ngram
listlengths
0
82k
[ "\"\", \"mythic_location\": \"\" } } nameSplit = i[0].split() card[f'{index}']['name'] =", "i[0] = i[0].replace('Divine Robe', 'DivineRobe') if 'Ghost Wand' in i[0]:", "'GhostWand') nameSplit = i[0].split() card[f'{index}']['name'] = i[0] if len(nameSplit) ==", "card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit) == 3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0]", "== 2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2]", "1: card[f'{index}']['artifact_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']=", "card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword + after_keyword", "Robe' or 'Ghost Wand' in i[0]: if 'Divine Robe' in", "elif i[1] == 'monster': card[f'{index}']['type']= 'creature' if len(nameSplit) == 1:", "if len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] ==", "nameSplit[0] if len(nameSplit) >3: keyword = 'of' before_keyword, keyword, after_keyword", "'monster': card[f'{index}']['type']= 'creature' if len(nameSplit) == 1: card[f'{index}']['creature_name']= nameSplit[0] if", "\"type\": \"\", \"level\": None, \"spell_name\": \"\", \"creature_name\": \"\", \"artifact_name\": \"\",", "nameSplit = i[0].split() card[f'{index}']['name'] = i[0] if len(nameSplit) == 1:", "elif len(nameSplit) == 2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit)", "len(nameSplit) == 1: card[f'{index}']['artifact_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['artifact_name']=", "len(nameSplit) == 2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit) ==", "nameSplit[0] elif len(nameSplit) == 3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']=", "card[f'{index}']['type']= 'creature' if len(nameSplit) == 1: card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit)", "if 'Divine Robe' or 'Ghost Wand' in i[0]: if 'Divine", "keyword, after_keyword = i[0].partition(keyword) if i[2] == 2: card[f'{index}']['creature_name']= nameSplit[2]", "card[f'{index}']['spell_name']=nameSplit[2] elif i[1] == 'artifact': if 'Divine Robe' or 'Ghost", "card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif i[1] == 'enchantment':", "import json def hydrateCards(rawDeckDataPath): pack = [] rawDeckData = json.load(open(rawDeckDataPath,))", "card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword + after_keyword deck.append(card[f'{index}']) index +=1 if", "== 'monster': card[f'{index}']['type']= 'creature' if len(nameSplit) == 1: card[f'{index}']['creature_name']= nameSplit[0]", "i[1] card[f'{index}']['level']=i[2] if i[1] == 'spell': if len(nameSplit) == 1:", "== 1: card[f'{index}']['spell_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['spell_type']= nameSplit[0]", "deck = [] # print(index,item) for i in rawDeckData[item]: card", "= [] # print(index,item) for i in rawDeckData[item]: card ={", "== 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1] == 'artifact': if", "'spell': if len(nameSplit) == 1: card[f'{index}']['spell_name']= i[0] elif len(nameSplit) ==", "= i[0].replace('Divine Robe', 'DivineRobe') if 'Ghost Wand' in i[0]: i[0]", "if i[1] == 'spell': if len(nameSplit) == 1: card[f'{index}']['spell_name']= i[0]", "3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit) >3:", "== 'spell': if len(nameSplit) == 1: card[f'{index}']['spell_name']= i[0] elif len(nameSplit)", "'Divine Robe' in i[0]: i[0] = i[0].replace('Divine Robe', 'DivineRobe') if", "\"\", \"mythic_creature_modifier\": \"\", \"location\": \"\", \"mythic_location\": \"\" } } nameSplit", "Robe', 'DivineRobe') if 'Ghost Wand' in i[0]: i[0] = i[0].replace('Ghost", "elif i[1] == 'enchantment': if len(nameSplit) == 1: card[f'{index}']['enchantment_name']= i[0]", "deck.append(card[f'{index}']) index +=1 if len(deck) == 45: break pack.append(deck) return(pack)", "2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit) == 3: card[f'{index}']['artifact_name']=", "rawDeckData = json.load(open(rawDeckDataPath,)) for index, item in enumerate(rawDeckData): deck =", ">3: keyword = 'of' before_keyword, keyword, after_keyword = i[0].partition(keyword) if", "== 1: card[f'{index}']['enchantment_name']= i[0] if len(nameSplit) == 2: card[f'{index}']['enchantment_name']= nameSplit[1]", "\"\", \"artifact_name\": \"\", \"enchantment_name\": \"\", \"spell_magnifier\": \"\", \"spell_type\": \"\", \"name_modifier\":", "item in enumerate(rawDeckData): deck = [] # print(index,item) for i", "== 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit)", "} } nameSplit = i[0].split() card[f'{index}']['name'] = i[0] card[f'{index}']['type']= i[1]", "f'{index}': { \"name\": \"\", \"type\": \"\", \"level\": None, \"spell_name\": \"\",", "\"\", \"name_modifier\": \"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\", \"location\": \"\", \"mythic_location\":", "== 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword", "nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1]", "[] rawDeckData = json.load(open(rawDeckDataPath,)) for index, item in enumerate(rawDeckData): deck", "= i[0].split() card[f'{index}']['name'] = i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if i[1]", "card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] == 'monster': card[f'{index}']['type']= 'creature' if", "\"artifact_name\": \"\", \"enchantment_name\": \"\", \"spell_magnifier\": \"\", \"spell_type\": \"\", \"name_modifier\": \"\",", "in i[0]: if 'Divine Robe' in i[0]: i[0] = i[0].replace('Divine", "card[f'{index}']['mythic_location']= keyword + after_keyword deck.append(card[f'{index}']) index +=1 if len(deck) ==", "i[0].split() card[f'{index}']['name'] = i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if i[1] ==", "nameSplit[0] card[f'{index}']['location']= nameSplit[2] = keyword + after_keyword elif i[2] ==", "card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1]", "card[f'{index}']['spell_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1]", "len(nameSplit) == 1: card[f'{index}']['enchantment_name']= i[0] if len(nameSplit) == 2: card[f'{index}']['enchantment_name']=", "Wand' in i[0]: i[0] = i[0].replace('Ghost Wand', 'GhostWand') nameSplit =", "\"\", \"spell_magnifier\": \"\", \"spell_type\": \"\", \"name_modifier\": \"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\":", "nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit) >3: keyword =", "+ after_keyword elif i[2] == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1]", "\"mythic_creature_modifier\": \"\", \"location\": \"\", \"mythic_location\": \"\" } } nameSplit =", "nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit) == 3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']=", "card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit) >3: keyword", "card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1] == 'artifact': if 'Divine Robe'", "i[0].partition(keyword) if i[2] == 2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']=", "3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif i[1] ==", "i[0] if len(nameSplit) == 1: card[f'{index}']['artifact_name']= i[0] elif len(nameSplit) ==", "keyword = 'of' before_keyword, keyword, after_keyword = i[0].partition(keyword) if i[2]", "card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif", "nameSplit[1] elif len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1]", "nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif i[1] == 'enchantment': if len(nameSplit) ==", "nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword + after_keyword deck.append(card[f'{index}'])", "'Ghost Wand' in i[0]: i[0] = i[0].replace('Ghost Wand', 'GhostWand') nameSplit", "# print(index,item) for i in rawDeckData[item]: card ={ f'{index}': {", "'DivineRobe') if 'Ghost Wand' in i[0]: i[0] = i[0].replace('Ghost Wand',", "enumerate(rawDeckData): deck = [] # print(index,item) for i in rawDeckData[item]:", "card[f'{index}']['location']= nameSplit[2] = keyword + after_keyword elif i[2] == 3:", "if len(nameSplit) == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0]", "\"name_modifier\": \"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\", \"location\": \"\", \"mythic_location\": \"\"", "card[f'{index}']['name'] = i[0] if len(nameSplit) == 1: card[f'{index}']['artifact_name']= i[0] elif", "card[f'{index}']['spell_type']= nameSplit[1] elif i[1] == 'enchantment': if len(nameSplit) == 1:", "before_keyword, keyword, after_keyword = i[0].partition(keyword) if i[2] == 2: card[f'{index}']['creature_name']=", "len(nameSplit) == 3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif", "if len(nameSplit) == 1: card[f'{index}']['enchantment_name']= i[0] if len(nameSplit) == 2:", "card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] == 'monster': card[f'{index}']['type']= 'creature' if len(nameSplit) ==", "len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] == 'monster':", "= 'of' before_keyword, keyword, after_keyword = i[0].partition(keyword) if i[2] ==", "== 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] == 'monster': card[f'{index}']['type']=", "in i[0]: i[0] = i[0].replace('Divine Robe', 'DivineRobe') if 'Ghost Wand'", "3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] == 'monster': card[f'{index}']['type']= 'creature'", "if len(nameSplit) >3: keyword = 'of' before_keyword, keyword, after_keyword =", "\"spell_name\": \"\", \"creature_name\": \"\", \"artifact_name\": \"\", \"enchantment_name\": \"\", \"spell_magnifier\": \"\",", "card[f'{index}']['enchantment_name']= i[0] if len(nameSplit) == 2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0]", "2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2]", "if len(nameSplit) == 1: card[f'{index}']['spell_name']= i[0] elif len(nameSplit) == 2:", "\"\" } } nameSplit = i[0].split() card[f'{index}']['name'] = i[0] card[f'{index}']['type']=", "= [] rawDeckData = json.load(open(rawDeckDataPath,)) for index, item in enumerate(rawDeckData):", "3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1] == 'artifact': if 'Divine", "== 1: card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['creature_name']= nameSplit[2]", "Wand' in i[0]: if 'Divine Robe' in i[0]: i[0] =", "nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit) >3: keyword = 'of' before_keyword,", "\"\", \"location\": \"\", \"mythic_location\": \"\" } } nameSplit = i[0].split()", "json.load(open(rawDeckDataPath,)) for index, item in enumerate(rawDeckData): deck = [] #", "card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif i[1] == 'enchantment': if len(nameSplit)", "nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0]", "= i[0].partition(keyword) if i[2] == 2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1]", "== 2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit) == 3:", "i[1] == 'artifact': if 'Divine Robe' or 'Ghost Wand' in", "after_keyword deck.append(card[f'{index}']) index +=1 if len(deck) == 45: break pack.append(deck)", "rawDeckData[item]: card ={ f'{index}': { \"name\": \"\", \"type\": \"\", \"level\":", "'artifact': if 'Divine Robe' or 'Ghost Wand' in i[0]: if", "len(nameSplit) == 1: card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['creature_name']=", "= i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if i[1] == 'spell': if", "len(nameSplit) == 2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit) ==", "\"\", \"enchantment_name\": \"\", \"spell_magnifier\": \"\", \"spell_type\": \"\", \"name_modifier\": \"\", \"creature_modifier\":", "\"name\": \"\", \"type\": \"\", \"level\": None, \"spell_name\": \"\", \"creature_name\": \"\",", "\"spell_magnifier\": \"\", \"spell_type\": \"\", \"name_modifier\": \"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\",", "card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1] == 'artifact': if 'Divine Robe' or", "keyword + after_keyword deck.append(card[f'{index}']) index +=1 if len(deck) == 45:", "= json.load(open(rawDeckDataPath,)) for index, item in enumerate(rawDeckData): deck = []", "= i[0] if len(nameSplit) == 1: card[f'{index}']['artifact_name']= i[0] elif len(nameSplit)", "2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2] =", "card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword + after_keyword deck.append(card[f'{index}']) index", "nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2] = keyword +", "nameSplit[2] = keyword + after_keyword elif i[2] == 3: card[f'{index}']['creature_name']=", "nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']=", "i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if i[1] == 'spell': if len(nameSplit)", "card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if i[1] == 'spell': if len(nameSplit) ==", "Robe' in i[0]: i[0] = i[0].replace('Divine Robe', 'DivineRobe') if 'Ghost", "\"mythic_location\": \"\" } } nameSplit = i[0].split() card[f'{index}']['name'] = i[0]", "nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword + after_keyword deck.append(card[f'{index}']) index +=1", "def hydrateCards(rawDeckDataPath): pack = [] rawDeckData = json.load(open(rawDeckDataPath,)) for index,", "len(nameSplit) == 1: card[f'{index}']['spell_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['spell_type']=", "i[0]: if 'Divine Robe' in i[0]: i[0] = i[0].replace('Divine Robe',", "if 'Divine Robe' in i[0]: i[0] = i[0].replace('Divine Robe', 'DivineRobe')", "card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1]", "\"enchantment_name\": \"\", \"spell_magnifier\": \"\", \"spell_type\": \"\", \"name_modifier\": \"\", \"creature_modifier\": \"\",", "json def hydrateCards(rawDeckDataPath): pack = [] rawDeckData = json.load(open(rawDeckDataPath,)) for", "i in rawDeckData[item]: card ={ f'{index}': { \"name\": \"\", \"type\":", "in rawDeckData[item]: card ={ f'{index}': { \"name\": \"\", \"type\": \"\",", "card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit) == 3: card[f'{index}']['artifact_name']= nameSplit[2]", "card[f'{index}']['artifact_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0]", "[] # print(index,item) for i in rawDeckData[item]: card ={ f'{index}':", "\"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\", \"location\": \"\", \"mythic_location\": \"\" }", "+ after_keyword deck.append(card[f'{index}']) index +=1 if len(deck) == 45: break", "card ={ f'{index}': { \"name\": \"\", \"type\": \"\", \"level\": None,", "'Ghost Wand' in i[0]: if 'Divine Robe' in i[0]: i[0]", "nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif i[1] == 'enchantment': if", "print(index,item) for i in rawDeckData[item]: card ={ f'{index}': { \"name\":", "card[f'{index}']['level']=i[2] if i[1] == 'spell': if len(nameSplit) == 1: card[f'{index}']['spell_name']=", "None, \"spell_name\": \"\", \"creature_name\": \"\", \"artifact_name\": \"\", \"enchantment_name\": \"\", \"spell_magnifier\":", "len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1] == 'artifact':", "= keyword + after_keyword elif i[2] == 3: card[f'{index}']['creature_name']= nameSplit[2]", "nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2] = keyword + after_keyword elif", "i[0]: i[0] = i[0].replace('Divine Robe', 'DivineRobe') if 'Ghost Wand' in", "for i in rawDeckData[item]: card ={ f'{index}': { \"name\": \"\",", "index, item in enumerate(rawDeckData): deck = [] # print(index,item) for", "3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']= keyword +", "card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif i[1] == 'monster': card[f'{index}']['type']= 'creature' if len(nameSplit)", "i[0] = i[0].replace('Ghost Wand', 'GhostWand') nameSplit = i[0].split() card[f'{index}']['name'] =", "2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0]", "={ f'{index}': { \"name\": \"\", \"type\": \"\", \"level\": None, \"spell_name\":", "i[0].split() card[f'{index}']['name'] = i[0] if len(nameSplit) == 1: card[f'{index}']['artifact_name']= i[0]", "i[1] == 'enchantment': if len(nameSplit) == 1: card[f'{index}']['enchantment_name']= i[0] if", "'of' before_keyword, keyword, after_keyword = i[0].partition(keyword) if i[2] == 2:", "card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2] = keyword + after_keyword elif i[2]", "i[0].replace('Divine Robe', 'DivineRobe') if 'Ghost Wand' in i[0]: i[0] =", "\"creature_name\": \"\", \"artifact_name\": \"\", \"enchantment_name\": \"\", \"spell_magnifier\": \"\", \"spell_type\": \"\",", "elif i[1] == 'artifact': if 'Divine Robe' or 'Ghost Wand'", "after_keyword elif i[2] == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']=", "card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2] = keyword", "if len(nameSplit) == 1: card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit) == 3:", "elif len(nameSplit) == 3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1]", "\"\", \"level\": None, \"spell_name\": \"\", \"creature_name\": \"\", \"artifact_name\": \"\", \"enchantment_name\":", "== 'enchantment': if len(nameSplit) == 1: card[f'{index}']['enchantment_name']= i[0] if len(nameSplit)", "len(nameSplit) >3: keyword = 'of' before_keyword, keyword, after_keyword = i[0].partition(keyword)", "\"\", \"spell_type\": \"\", \"name_modifier\": \"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\", \"location\":", "= i[0].split() card[f'{index}']['name'] = i[0] if len(nameSplit) == 1: card[f'{index}']['artifact_name']=", "len(nameSplit) == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if", "card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1]", "== 1: card[f'{index}']['artifact_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['artifact_name']= nameSplit[1]", "i[1] == 'spell': if len(nameSplit) == 1: card[f'{index}']['spell_name']= i[0] elif", "or 'Ghost Wand' in i[0]: if 'Divine Robe' in i[0]:", "in i[0]: i[0] = i[0].replace('Ghost Wand', 'GhostWand') nameSplit = i[0].split()", "card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']= nameSplit[2] = keyword + after_keyword", "== 'artifact': if 'Divine Robe' or 'Ghost Wand' in i[0]:", "{ \"name\": \"\", \"type\": \"\", \"level\": None, \"spell_name\": \"\", \"creature_name\":", "Wand', 'GhostWand') nameSplit = i[0].split() card[f'{index}']['name'] = i[0] if len(nameSplit)", "in enumerate(rawDeckData): deck = [] # print(index,item) for i in", "\"location\": \"\", \"mythic_location\": \"\" } } nameSplit = i[0].split() card[f'{index}']['name']", "== 2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit) == 3:", "} nameSplit = i[0].split() card[f'{index}']['name'] = i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2]", "elif i[2] == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0]", "i[0].replace('Ghost Wand', 'GhostWand') nameSplit = i[0].split() card[f'{index}']['name'] = i[0] if", "1: card[f'{index}']['enchantment_name']= i[0] if len(nameSplit) == 2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']=", "== 2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit) == 3:", "nameSplit[1] elif i[1] == 'enchantment': if len(nameSplit) == 1: card[f'{index}']['enchantment_name']=", "card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit) >3: keyword = 'of' before_keyword, keyword,", "nameSplit[0] card[f'{index}']['mythic_location']= keyword + after_keyword deck.append(card[f'{index}']) index +=1 if len(deck)", "\"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\", \"location\": \"\", \"mythic_location\": \"\" } }", "for index, item in enumerate(rawDeckData): deck = [] # print(index,item)", "i[0]: i[0] = i[0].replace('Ghost Wand', 'GhostWand') nameSplit = i[0].split() card[f'{index}']['name']", "1: card[f'{index}']['spell_name']= i[0] elif len(nameSplit) == 2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']=", "elif len(nameSplit) == 2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif len(nameSplit)", "after_keyword = i[0].partition(keyword) if i[2] == 2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']=", "i[2] == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['mythic_location']=", "hydrateCards(rawDeckDataPath): pack = [] rawDeckData = json.load(open(rawDeckDataPath,)) for index, item", "pack = [] rawDeckData = json.load(open(rawDeckDataPath,)) for index, item in", "elif len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2] elif i[1] ==", "i[1] == 'monster': card[f'{index}']['type']= 'creature' if len(nameSplit) == 1: card[f'{index}']['creature_name']=", "nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit) == 3: card[f'{index}']['spell_magnifier']=nameSplit[0] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_name']=nameSplit[2]", "\"spell_type\": \"\", \"name_modifier\": \"\", \"creature_modifier\": \"\", \"mythic_creature_modifier\": \"\", \"location\": \"\",", "if len(nameSplit) == 2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit)", "1: card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']=", "if i[2] == 2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0]", "card[f'{index}']['name'] = i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if i[1] == 'spell':", "'Divine Robe' or 'Ghost Wand' in i[0]: if 'Divine Robe'", "= i[0].replace('Ghost Wand', 'GhostWand') nameSplit = i[0].split() card[f'{index}']['name'] = i[0]", "if 'Ghost Wand' in i[0]: i[0] = i[0].replace('Ghost Wand', 'GhostWand')", "card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] if len(nameSplit) >3: keyword = 'of'", "\"level\": None, \"spell_name\": \"\", \"creature_name\": \"\", \"artifact_name\": \"\", \"enchantment_name\": \"\",", "i[0] elif len(nameSplit) == 2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif", "card[f'{index}']['spell_type']= nameSplit[0] if len(nameSplit) == 3: card[f'{index}']['enchantment_name']=nameSplit[2] card[f'{index}']['spell_type']=nameSplit[1] card[f'{index}']['spell_magnifier']=nameSplit[0] elif", "i[0] if len(nameSplit) == 2: card[f'{index}']['enchantment_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] if", "nameSplit = i[0].split() card[f'{index}']['name'] = i[0] card[f'{index}']['type']= i[1] card[f'{index}']['level']=i[2] if", "i[2] == 2: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['creature_modifier']= nameSplit[1] card[f'{index}']['name_modifier']= nameSplit[0] card[f'{index}']['location']=", "\"\", \"creature_name\": \"\", \"artifact_name\": \"\", \"enchantment_name\": \"\", \"spell_magnifier\": \"\", \"spell_type\":", "== 3: card[f'{index}']['artifact_name']= nameSplit[2] card[f'{index}']['spell_magnifier']= nameSplit[0] card[f'{index}']['spell_type']= nameSplit[1] elif i[1]", "if len(nameSplit) == 1: card[f'{index}']['artifact_name']= i[0] elif len(nameSplit) == 2:", "len(nameSplit) == 2: card[f'{index}']['spell_type']= nameSplit[0] card[f'{index}']['spell_name']= nameSplit[1] elif len(nameSplit) ==", "i[0] elif len(nameSplit) == 2: card[f'{index}']['artifact_name']= nameSplit[1] card[f'{index}']['spell_type']= nameSplit[0] elif", "keyword + after_keyword elif i[2] == 3: card[f'{index}']['creature_name']= nameSplit[2] card[f'{index}']['mythic_creature_modifier']=", "'creature' if len(nameSplit) == 1: card[f'{index}']['creature_name']= nameSplit[0] if len(nameSplit) ==", "'enchantment': if len(nameSplit) == 1: card[f'{index}']['enchantment_name']= i[0] if len(nameSplit) ==", "\"\", \"type\": \"\", \"level\": None, \"spell_name\": \"\", \"creature_name\": \"\", \"artifact_name\":" ]
[ "' + predicted_label + ' actual: ' + label) if", "= CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor = CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos", "sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import", "keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path)", "import numpy as np from keras import backend as K", "video_file_path_list = np.array([file_path for file_path in videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path", "main(): sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101') from keras_video_classifier.library.convolutional", "scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor", "load_ucf, scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path)", "import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path)", "def patch_path(path): return os.path.join(os.path.dirname(__file__), path) def main(): sys.path.append(patch_path('..')) data_dir_path =", "predicted_label = predictor.predict(video_file_path) print('predicted: ' + predicted_label + ' actual:", "for video_file_path in video_file_path_list: label = videos[video_file_path] predicted_label = predictor.predict(video_file_path)", "keras_video_classifier.library.convolutional import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels config_file_path =", "return os.path.join(os.path.dirname(__file__), path) def main(): sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data') model_dir_path", "import backend as K import os import sys K.set_image_dim_ordering('tf') def", "for (label, label_index) in predictor.labels.items()]) video_file_path_list = np.array([file_path for file_path", "label_index) in predictor.labels.items()]) video_file_path_list = np.array([file_path for file_path in videos.keys()])", "weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor = CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path)", "file_path in videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path in video_file_path_list: label =", "config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor =", "= patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import CnnVideoClassifier from", "from keras_video_classifier.library.convolutional import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels config_file_path", "[label for (label, label_index) in predictor.labels.items()]) video_file_path_list = np.array([file_path for", "weight_file_path) videos = scan_ucf_with_labels(data_dir_path, [label for (label, label_index) in predictor.labels.items()])", "videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path in video_file_path_list: label = videos[video_file_path] predicted_label", "CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor = CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos =", "import load_ucf, scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42)", "K.set_image_dim_ordering('tf') def patch_path(path): return os.path.join(os.path.dirname(__file__), path) def main(): sys.path.append(patch_path('..')) data_dir_path", "= CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor = CnnVideoClassifier()", "sys K.set_image_dim_ordering('tf') def patch_path(path): return os.path.join(os.path.dirname(__file__), path) def main(): sys.path.append(patch_path('..'))", "path) def main(): sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101')", "predictor.predict(video_file_path) print('predicted: ' + predicted_label + ' actual: ' +", "from keras import backend as K import os import sys", "+ predicted_label + ' actual: ' + label) if __name__", "patch_path(path): return os.path.join(os.path.dirname(__file__), path) def main(): sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data')", "in predictor.labels.items()]) video_file_path_list = np.array([file_path for file_path in videos.keys()]) np.random.shuffle(video_file_path_list)", "as K import os import sys K.set_image_dim_ordering('tf') def patch_path(path): return", "CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path = CnnVideoClassifier.get_weight_file_path(model_dir_path) np.random.seed(42) load_ucf(data_dir_path) predictor = CnnVideoClassifier() predictor.load_model(config_file_path,", "np from keras import backend as K import os import", "keras import backend as K import os import sys K.set_image_dim_ordering('tf')", "label = videos[video_file_path] predicted_label = predictor.predict(video_file_path) print('predicted: ' + predicted_label", "CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos = scan_ucf_with_labels(data_dir_path, [label for (label, label_index)", "= np.array([file_path for file_path in videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path in", "patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader", "= patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf,", "K import os import sys K.set_image_dim_ordering('tf') def patch_path(path): return os.path.join(os.path.dirname(__file__),", "print('predicted: ' + predicted_label + ' actual: ' + label)", "CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path", "scan_ucf_with_labels(data_dir_path, [label for (label, label_index) in predictor.labels.items()]) video_file_path_list = np.array([file_path", "os.path.join(os.path.dirname(__file__), path) def main(): sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data') model_dir_path =", "video_file_path_list: label = videos[video_file_path] predicted_label = predictor.predict(video_file_path) print('predicted: ' +", "video_file_path in video_file_path_list: label = videos[video_file_path] predicted_label = predictor.predict(video_file_path) print('predicted:", "in video_file_path_list: label = videos[video_file_path] predicted_label = predictor.predict(video_file_path) print('predicted: '", "def main(): sys.path.append(patch_path('..')) data_dir_path = patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101') from", "backend as K import os import sys K.set_image_dim_ordering('tf') def patch_path(path):", "= CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos = scan_ucf_with_labels(data_dir_path, [label for (label,", "videos[video_file_path] predicted_label = predictor.predict(video_file_path) print('predicted: ' + predicted_label + '", "import sys K.set_image_dim_ordering('tf') def patch_path(path): return os.path.join(os.path.dirname(__file__), path) def main():", "for file_path in videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path in video_file_path_list: label", "= videos[video_file_path] predicted_label = predictor.predict(video_file_path) print('predicted: ' + predicted_label +", "(label, label_index) in predictor.labels.items()]) video_file_path_list = np.array([file_path for file_path in", "load_ucf(data_dir_path) predictor = CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos = scan_ucf_with_labels(data_dir_path, [label", "predictor.load_model(config_file_path, weight_file_path) videos = scan_ucf_with_labels(data_dir_path, [label for (label, label_index) in", "np.random.shuffle(video_file_path_list) for video_file_path in video_file_path_list: label = videos[video_file_path] predicted_label =", "+ ' actual: ' + label) if __name__ == '__main__':", "data_dir_path = patch_path('very_large_data') model_dir_path = patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import CnnVideoClassifier", "= predictor.predict(video_file_path) print('predicted: ' + predicted_label + ' actual: '", "patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels", "import os import sys K.set_image_dim_ordering('tf') def patch_path(path): return os.path.join(os.path.dirname(__file__), path)", "model_dir_path = patch_path('models/UCF-101') from keras_video_classifier.library.convolutional import CnnVideoClassifier from keras_video_classifier.library.utility.ucf.UCF101_loader import", "predicted_label + ' actual: ' + label) if __name__ ==", "in videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path in video_file_path_list: label = videos[video_file_path]", "predictor.labels.items()]) video_file_path_list = np.array([file_path for file_path in videos.keys()]) np.random.shuffle(video_file_path_list) for", "numpy as np from keras import backend as K import", "np.random.seed(42) load_ucf(data_dir_path) predictor = CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos = scan_ucf_with_labels(data_dir_path,", "from keras_video_classifier.library.utility.ucf.UCF101_loader import load_ucf, scan_ucf_with_labels config_file_path = CnnVideoClassifier.get_config_file_path(model_dir_path) weight_file_path =", "np.array([file_path for file_path in videos.keys()]) np.random.shuffle(video_file_path_list) for video_file_path in video_file_path_list:", "predictor = CnnVideoClassifier() predictor.load_model(config_file_path, weight_file_path) videos = scan_ucf_with_labels(data_dir_path, [label for", "os import sys K.set_image_dim_ordering('tf') def patch_path(path): return os.path.join(os.path.dirname(__file__), path) def", "videos = scan_ucf_with_labels(data_dir_path, [label for (label, label_index) in predictor.labels.items()]) video_file_path_list", "as np from keras import backend as K import os", "' actual: ' + label) if __name__ == '__main__': main()", "= scan_ucf_with_labels(data_dir_path, [label for (label, label_index) in predictor.labels.items()]) video_file_path_list =" ]
[ "from django.conf import settings def less_settings(request): return { 'use_dynamic_less_in_debug': getattr(settings,", "settings def less_settings(request): return { 'use_dynamic_less_in_debug': getattr(settings, 'LESS_USE_DYNAMIC_IN_DEBUG', True) }", "import settings def less_settings(request): return { 'use_dynamic_less_in_debug': getattr(settings, 'LESS_USE_DYNAMIC_IN_DEBUG', True)", "django.conf import settings def less_settings(request): return { 'use_dynamic_less_in_debug': getattr(settings, 'LESS_USE_DYNAMIC_IN_DEBUG'," ]
[ "the Box-Cox transformation to an endogenous array The Box-Cox transformation", "\"\"\" def __init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda = lmbda", "or None The inverse-transformed y array X : array-like or", "return np.exp(y) - lam2, exog numer = y * lam1", "= self.lam1_ lam2 = self.lam2_ y, exog = self._check_y_X(y, X)", "== \"raise\": raise ValueError(msg) elif action == \"warn\": warnings.warn(msg, UserWarning)", "self.lmbda = lmbda self.lmbda2 = lmbda2 self.neg_action = neg_action self.floor", "pass-through arrays. \"\"\" lam1 = self.lmbda lam2 = self.lmbda2 #", "check_is_fitted(self, \"lam1_\") # Temporary shim until we remove `exogenous` support", "One of ('raise', 'warn', 'ignore'). If anything other than 'raise',", "0. if neg_mask.any(): action = self.neg_action msg = \"Negative or", "coerce it more towards a normal distribution. It's specified as::", "self.lam1_ lam2 = self.lam2_ y, exog = self._check_y_X(y, X) if", "and ``neg_action`` is not 'raise'. Note that if values are", "-*- coding: utf-8 -*- from scipy import stats import numpy", "array X : array-like or None The X array \"\"\"", "0: return np.exp(y) - lam2, exog numer = y *", "X, _ = pm_compat.get_X(X, **kwargs) lam1 = self.lam1_ lam2 =", "array Inverse the Box-Cox transformation on the transformed array. Note", "The transformed endogenous (time-series) array. X : array-like or None,", "exog def inverse_transform(self, y, X=None, **kwargs): # TODO: kwargs go", "\"\"\"Fit the transformer Learns the value of ``lmbda``, if not", "- lam2, exog numer = y * lam1 # remove", "or None, shape=(n_samples, n_features), optional The exogenous array of additional", "Box-Cox transformation on the transformed array. Note that if truncation", "y, X=None, **kwargs): # TODO: kwargs go away \"\"\"Inverse transform", "values will serve as pass-through arrays. \"\"\" lam1 = self.lmbda", "= floor def fit(self, y, X=None, **kwargs): # TODO: kwargs", "** lam1) - 1) / lam1, if lmbda != 0,", "_ = self._check_y_X(y, X) _, lam1 = stats.boxcox(y + lam2,", ": array-like or None The inverse-transformed y array X :", "array-like or None, shape=(n_samples,) The transformed endogenous (time-series) array. X", "self.lmbda lam2 = self.lmbda2 # Temporary shim until we remove", "X) _, lam1 = stats.boxcox(y + lam2, lmbda=None, alpha=None) self.lam1_", "array-like or None The Box-Cox transformed y array X :", ": array-like or None, shape=(n_samples,) The transformed endogenous (time-series) array.", "= lmbda2 self.neg_action = neg_action self.floor = floor def fit(self,", "import numpy as np import warnings from ...compat import check_is_fitted,", "de_exp = numer ** (1. / lam1) # de-exponentiate return", "values are truncated, invertibility will not be preserved, and the", "def fit(self, y, X=None, **kwargs): # TODO: kwargs go away", "------- y : array-like or None The inverse-transformed y array", "UserWarning) y[neg_mask] = self.floor if lam1 == 0: return np.log(y),", "``lmbda2``, there are still negative values, a ValueError will be", "float, optional (default=1e-16) A positive value that truncate values to", "y[neg_mask] = self.floor if lam1 == 0: return np.log(y), exog", "values will serve as pass-through arrays. Returns ------- y_transform :", "coding: utf-8 -*- from scipy import stats import numpy as", "optional (default=0.) The value to add to ``y`` to make", "non-None values will serve as pass-through arrays. Returns ------- y_transform", "support completely X, _ = pm_compat.get_X(X, **kwargs) lam1 = self.lam1_", "y <= 0. if neg_mask.any(): action = self.neg_action msg =", "transformation to an endogenous array The Box-Cox transformation is applied", "may not be perfectly inverse-transformed. Parameters ---------- y : array-like", "Returns ------- y_transform : array-like or None The Box-Cox transformed", "Box-Cox transformation to an endogenous array The Box-Cox transformation is", "in ``y`` that are zero or negative and ``neg_action`` is", "array The Box-Cox transformation is applied to non-normal data to", "pm_compat.get_X(X, **kwargs) if lam2 < 0: raise ValueError(\"lmbda2 must be", "self.floor if lam1 == 0: return np.log(y), exog return (y", "if there are values in ``y`` that are zero or", "def inverse_transform(self, y, X=None, **kwargs): # TODO: kwargs go away", "must be a non-negative scalar value\") if lam1 is None:", "serve as pass-through arrays. Returns ------- y_transform : array-like or", "if neg_mask.any(): action = self.neg_action msg = \"Negative or zero", "array X : array-like or None The inverse-transformed X array", "completely X, _ = pm_compat.get_X(X, **kwargs) if lam2 < 0:", "Box-Cox transformation is applied to non-normal data to coerce it", "lam1 self.lam2_ = lam2 return self def transform(self, y, X=None,", "= stats.boxcox(y + lam2, lmbda=None, alpha=None) self.lam1_ = lam1 self.lam2_", "self._check_y_X(y, X) y += lam2 neg_mask = y <= 0.", "<= 0`` after adding ``lmbda2``. One of ('raise', 'warn', 'ignore').", "go away \"\"\"Fit the transformer Learns the value of ``lmbda``,", "float, optional (default=0.) The value to add to ``y`` to", "the constructor. If defined in the constructor, is not re-learned.", "= self.lmbda2 # Temporary shim until we remove `exogenous` support", "array-like or None The inverse-transformed y array X : array-like", "self._check_y_X(y, X) if lam1 == 0: return np.exp(y) - lam2,", "adding ``lmbda2``, there are still negative values, a ValueError will", "for the Box-Cox transformation, if known. If not specified, it", "array. Note that if truncation happened in the ``transform`` method,", "lmbda2 : float, optional (default=0.) The value to add to", "None The X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim", "= lam1 self.lam2_ = lam2 return self def transform(self, y,", "transformation on the transformed array. Note that if truncation happened", "after adding ``lmbda2``, there are still negative values, a ValueError", "the new array Apply the Box-Cox transformation to the array", "neg_mask = y <= 0. if neg_mask.any(): action = self.neg_action", "floor=1e-16): self.lmbda = lmbda self.lmbda2 = lmbda2 self.neg_action = neg_action", "a normal distribution. It's specified as:: (((y + lam2) **", "there are values in ``y`` that are zero or negative", "to ``y`` to make it non-negative. If, after adding ``lmbda2``,", "\"\"\"Transform the new array Apply the Box-Cox transformation to the", "y_transform : array-like or None The Box-Cox transformed y array", "value that truncate values to if there are values in", "``lmbda2``. One of ('raise', 'warn', 'ignore'). If anything other than", "will serve as pass-through arrays. Returns ------- y_transform : array-like", "y array X : array-like or None The inverse-transformed X", "not specified, it will be estimated via MLE. lmbda2 :", "y : array-like or None The inverse-transformed y array X", "y, X=None, **kwargs): # TODO: kwargs go away \"\"\"Fit the", "defined in the constructor, is not re-learned. Parameters ---------- y", "If defined in the constructor, is not re-learned. Parameters ----------", "shim until we remove `exogenous` support completely X, _ =", "away \"\"\"Inverse transform a transformed array Inverse the Box-Cox transformation", "to the value of ``floor``. floor : float, optional (default=1e-16)", "= ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox transformation to an", "are zero or negative and ``neg_action`` is not 'raise'. Note", "None, shape=(n_samples,) The endogenous (time-series) array. X : array-like or", "= lmbda self.lmbda2 = lmbda2 self.neg_action = neg_action self.floor =", "any values in ``y <= 0`` after adding ``lmbda2``. One", "X, _ = pm_compat.get_X(X, **kwargs) if lam2 < 0: raise", "is not re-learned. Parameters ---------- y : array-like or None,", "= neg_action self.floor = floor def fit(self, y, X=None, **kwargs):", "neg_action : str, optional (default=\"raise\") How to respond if any", "self def transform(self, y, X=None, **kwargs): \"\"\"Transform the new array", "neg_action self.floor = floor def fit(self, y, X=None, **kwargs): #", "import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox", ": array-like or None The inverse-transformed X array \"\"\" check_is_fitted(self,", "add to ``y`` to make it non-negative. If, after adding", "the transformed array may not be perfectly inverse-transformed. Parameters ----------", "self.lmbda2 = lmbda2 self.neg_action = neg_action self.floor = floor def", "anything other than 'raise', values <= 0 will be truncated", "Box-Cox transformation to the array after learning the lambda parameter.", "transformed y array X : array-like or None The X", "to coerce it more towards a normal distribution. It's specified", "transform(self, y, X=None, **kwargs): \"\"\"Transform the new array Apply the", "to an endogenous array The Box-Cox transformation is applied to", "preserved, and the transformed array may not be perfectly inverse-transformed.", "perfectly inverse-transformed. Parameters ---------- y : array-like or None, shape=(n_samples,)", "How to respond if any values in ``y <= 0``", "y : array-like or None, shape=(n_samples,) The transformed endogenous (time-series)", "y, exog = self._check_y_X(y, X) if lam1 == 0: return", "transformed array may not be perfectly inverse-transformed. Parameters ---------- y", "zero or negative and ``neg_action`` is not 'raise'. Note that", "the transformed array may not be perfectly inverse-transformed. \"\"\" def", "kwargs go away \"\"\"Inverse transform a transformed array Inverse the", ": float, optional (default=0.) The value to add to ``y``", "back to it de_exp = numer ** (1. / lam1)", "the Box-Cox transformation on the transformed array. Note that if", "endogenous (time-series) array. X : array-like or None, shape=(n_samples, n_features),", "the transformer Learns the value of ``lmbda``, if not specified", "adding ``lmbda2``. One of ('raise', 'warn', 'ignore'). If anything other", "None, optional (default=None) The lambda value for the Box-Cox transformation,", "None, shape=(n_samples, n_features), optional The exogenous array of additional covariates.", "not be preserved, and the transformed array may not be", "self.lam2_ = lam2 return self def transform(self, y, X=None, **kwargs):", "action == \"raise\": raise ValueError(msg) elif action == \"warn\": warnings.warn(msg,", "and non-None values will serve as pass-through arrays. Returns -------", "pm_compat.get_X(X, **kwargs) lam1 = self.lam1_ lam2 = self.lam2_ y, exog", "as pass-through arrays. Returns ------- y_transform : array-like or None", "other than 'raise', values <= 0 will be truncated to", "exog numer = y * lam1 # remove denominator numer", "be perfectly inverse-transformed. Parameters ---------- y : array-like or None,", "respond if any values in ``y <= 0`` after adding", "self._check_y_X(y, X) _, lam1 = stats.boxcox(y + lam2, lmbda=None, alpha=None)", "+= lam2 neg_mask = y <= 0. if neg_mask.any(): action", "negative and ``neg_action`` is not 'raise'. Note that if values", "None, shape=(n_samples,) The transformed endogenous (time-series) array. X : array-like", "support completely X, _ = pm_compat.get_X(X, **kwargs) if lam2 <", ": float or None, optional (default=None) The lambda value for", "will not be preserved, and the transformed array may not", "exogenous array of additional covariates. Not used for endogenous transformers.", "if lmbda != 0, else log(y + lam2) Parameters ----------", "lam1 = self.lmbda lam2 = self.lmbda2 # Temporary shim until", "action == \"warn\": warnings.warn(msg, UserWarning) y[neg_mask] = self.floor if lam1", "there are still negative values, a ValueError will be raised.", "'raise', values <= 0 will be truncated to the value", "that truncate values to if there are values in ``y``", "is applied to non-normal data to coerce it more towards", "pass-through arrays. Returns ------- y_transform : array-like or None The", "lam2) ** lam1) - 1) / lam1, if lmbda !=", "utf-8 -*- from scipy import stats import numpy as np", "+ lam2) ** lam1) - 1) / lam1, if lmbda", "= self.lam2_ y, exog = self._check_y_X(y, X) if lam1 ==", "optional (default=\"raise\") How to respond if any values in ``y", "lam1, exog def inverse_transform(self, y, X=None, **kwargs): # TODO: kwargs", "truncated, invertibility will not be preserved, and the transformed array", ": array-like or None The X array \"\"\" check_is_fitted(self, \"lam1_\")", "MLE. lmbda2 : float, optional (default=0.) The value to add", "= y <= 0. if neg_mask.any(): action = self.neg_action msg", "# TODO: kwargs go away \"\"\"Fit the transformer Learns the", "# Temporary shim until we remove `exogenous` support completely X,", "exog return (y ** lam1 - 1) / lam1, exog", "__all__ = ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox transformation to", "lam1 - 1) / lam1, exog def inverse_transform(self, y, X=None,", "import stats import numpy as np import warnings from ...compat", "stats import numpy as np import warnings from ...compat import", "transformation is applied to non-normal data to coerce it more", "present in y\" if action == \"raise\": raise ValueError(msg) elif", "additional covariates. Not used for endogenous transformers. Default is None,", "transformer Learns the value of ``lmbda``, if not specified in", "= \"Negative or zero values present in y\" if action", "if lam1 == 0: return np.log(y), exog return (y **", "(default=None) The lambda value for the Box-Cox transformation, if known.", "remove `exogenous` support completely X, _ = pm_compat.get_X(X, **kwargs) if", "neg_mask.any(): action = self.neg_action msg = \"Negative or zero values", "will serve as pass-through arrays. \"\"\" lam1 = self.lmbda lam2", "the Box-Cox transformation to the array after learning the lambda", "(((y + lam2) ** lam1) - 1) / lam1, if", "may not be perfectly inverse-transformed. \"\"\" def __init__(self, lmbda=None, lmbda2=0,", "in the constructor. If defined in the constructor, is not", "in the ``transform`` method, invertibility will not be preserved, and", "Parameters ---------- y : array-like or None, shape=(n_samples,) The endogenous", "Returns ------- y : array-like or None The inverse-transformed y", "if lam2 < 0: raise ValueError(\"lmbda2 must be a non-negative", "transformation, if known. If not specified, it will be estimated", "estimated via MLE. lmbda2 : float, optional (default=0.) The value", "array may not be perfectly inverse-transformed. \"\"\" def __init__(self, lmbda=None,", "as pass-through arrays. Returns ------- y : array-like or None", "or None, shape=(n_samples,) The transformed endogenous (time-series) array. X :", "arrays. \"\"\" lam1 = self.lmbda lam2 = self.lmbda2 # Temporary", "add 1 back to it de_exp = numer ** (1.", "Note that if values are truncated, invertibility will not be", "self.floor = floor def fit(self, y, X=None, **kwargs): # TODO:", "data to coerce it more towards a normal distribution. It's", "of ``floor``. floor : float, optional (default=1e-16) A positive value", "Temporary shim until we remove `exogenous` support completely X, _", "that if values are truncated, invertibility will not be preserved,", "-*- from scipy import stats import numpy as np import", "are values in ``y`` that are zero or negative and", "value of ``lmbda``, if not specified in the constructor. If", "Not used for endogenous transformers. Default is None, and non-None", "the lambda parameter. Parameters ---------- y : array-like or None,", "1) / lam1, exog def inverse_transform(self, y, X=None, **kwargs): #", "values, a ValueError will be raised. neg_action : str, optional", "values in ``y <= 0`` after adding ``lmbda2``. One of", "self.lam1_ lam2 = self.lam2_ y, exog = self._check_y_X(y, X) y", "transformed endogenous (time-series) array. X : array-like or None, shape=(n_samples,", "non-negative. If, after adding ``lmbda2``, there are still negative values,", "more towards a normal distribution. It's specified as:: (((y +", "from scipy import stats import numpy as np import warnings", "transformed array. Note that if truncation happened in the ``transform``", "neg_action=\"raise\", floor=1e-16): self.lmbda = lmbda self.lmbda2 = lmbda2 self.neg_action =", ": array-like or None, shape=(n_samples, n_features), optional The exogenous array", "array-like or None, shape=(n_samples, n_features), optional The exogenous array of", "The inverse-transformed X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim", "values in ``y`` that are zero or negative and ``neg_action``", "until we remove `exogenous` support completely X, _ = pm_compat.get_X(X,", "lam2, exog numer = y * lam1 # remove denominator", "that if truncation happened in the ``transform`` method, invertibility will", "None: y, _ = self._check_y_X(y, X) _, lam1 = stats.boxcox(y", "---------- y : array-like or None, shape=(n_samples,) The endogenous (time-series)", "n_features), optional The exogenous array of additional covariates. Not used", "1 back to it de_exp = numer ** (1. /", "that are zero or negative and ``neg_action`` is not 'raise'.", "arrays. Returns ------- y_transform : array-like or None The Box-Cox", "array. X : array-like or None, shape=(n_samples, n_features), optional The", "The exogenous array of additional covariates. Not used for endogenous", "If, after adding ``lmbda2``, there are still negative values, a", "0: raise ValueError(\"lmbda2 must be a non-negative scalar value\") if", "lam2 return self def transform(self, y, X=None, **kwargs): \"\"\"Transform the", "(default=1e-16) A positive value that truncate values to if there", "to respond if any values in ``y <= 0`` after", "---------- lmbda : float or None, optional (default=None) The lambda", "('raise', 'warn', 'ignore'). If anything other than 'raise', values <=", "of additional covariates. Not used for endogenous transformers. Default is", "lam1 is None: y, _ = self._check_y_X(y, X) _, lam1", "transformers. Default is None, and non-None values will serve as", "= self.lam2_ y, exog = self._check_y_X(y, X) y += lam2", "value for the Box-Cox transformation, if known. If not specified,", "np.exp(y) - lam2, exog numer = y * lam1 #", "# add 1 back to it de_exp = numer **", "value of ``floor``. floor : float, optional (default=1e-16) A positive", "= self._check_y_X(y, X) _, lam1 = stats.boxcox(y + lam2, lmbda=None,", "to the array after learning the lambda parameter. Parameters ----------", "the array after learning the lambda parameter. Parameters ---------- y", "Default is None, and non-None values will serve as pass-through", "elif action == \"warn\": warnings.warn(msg, UserWarning) y[neg_mask] = self.floor if", "The Box-Cox transformation is applied to non-normal data to coerce", "array Apply the Box-Cox transformation to the array after learning", "msg = \"Negative or zero values present in y\" if", "constructor. If defined in the constructor, is not re-learned. Parameters", "** lam1 - 1) / lam1, exog def inverse_transform(self, y,", "return (y ** lam1 - 1) / lam1, exog def", "class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox transformation to an endogenous array", "y * lam1 # remove denominator numer += 1. #", "X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim until we", "non-None values will serve as pass-through arrays. Returns ------- y", "to it de_exp = numer ** (1. / lam1) #", "or None, shape=(n_samples,) The endogenous (time-series) array. X : array-like", "method, invertibility will not be preserved, and the transformed array", "constructor, is not re-learned. Parameters ---------- y : array-like or", "it de_exp = numer ** (1. / lam1) # de-exponentiate", "numer += 1. # add 1 back to it de_exp", "after learning the lambda parameter. Parameters ---------- y : array-like", "lmbda2 self.neg_action = neg_action self.floor = floor def fit(self, y,", "\"\"\"Inverse transform a transformed array Inverse the Box-Cox transformation on", "BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox transformation", "BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox transformation to an endogenous array The", "* lam1 # remove denominator numer += 1. # add", "None, and non-None values will serve as pass-through arrays. \"\"\"", "y += lam2 neg_mask = y <= 0. if neg_mask.any():", "a ValueError will be raised. neg_action : str, optional (default=\"raise\")", "lam2 = self.lmbda2 # Temporary shim until we remove `exogenous`", "0`` after adding ``lmbda2``. One of ('raise', 'warn', 'ignore'). If", "pm_compat from .base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer):", "+= 1. # add 1 back to it de_exp =", "- 1) / lam1, exog def inverse_transform(self, y, X=None, **kwargs):", "will be estimated via MLE. lmbda2 : float, optional (default=0.)", "lam1 = stats.boxcox(y + lam2, lmbda=None, alpha=None) self.lam1_ = lam1", "serve as pass-through arrays. Returns ------- y : array-like or", "\"lam1_\") # Temporary shim until we remove `exogenous` support completely", "== \"warn\": warnings.warn(msg, UserWarning) y[neg_mask] = self.floor if lam1 ==", "inverse-transformed X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim until", "\"warn\": warnings.warn(msg, UserWarning) y[neg_mask] = self.floor if lam1 == 0:", "or None, optional (default=None) The lambda value for the Box-Cox", ": array-like or None, shape=(n_samples,) The endogenous (time-series) array. X", "value\") if lam1 is None: y, _ = self._check_y_X(y, X)", "array-like or None The X array \"\"\" check_is_fitted(self, \"lam1_\") #", "truncate values to if there are values in ``y`` that", "not re-learned. Parameters ---------- y : array-like or None, shape=(n_samples,)", "via MLE. lmbda2 : float, optional (default=0.) The value to", "inverse-transformed. \"\"\" def __init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda =", "__init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda = lmbda self.lmbda2 =", "Apply the Box-Cox transformation to the array after learning the", "and the transformed array may not be perfectly inverse-transformed. \"\"\"", "array-like or None The inverse-transformed X array \"\"\" check_is_fitted(self, \"lam1_\")", "lmbda : float or None, optional (default=None) The lambda value", "The value to add to ``y`` to make it non-negative.", "completely X, _ = pm_compat.get_X(X, **kwargs) lam1 = self.lam1_ lam2", "serve as pass-through arrays. \"\"\" lam1 = self.lmbda lam2 =", "it non-negative. If, after adding ``lmbda2``, there are still negative", "truncation happened in the ``transform`` method, invertibility will not be", "shape=(n_samples, n_features), optional The exogenous array of additional covariates. Not", "``y`` that are zero or negative and ``neg_action`` is not", "is not 'raise'. Note that if values are truncated, invertibility", "str, optional (default=\"raise\") How to respond if any values in", "\"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim until we remove `exogenous`", "it will be estimated via MLE. lmbda2 : float, optional", "X=None, **kwargs): \"\"\"Transform the new array Apply the Box-Cox transformation", "we remove `exogenous` support completely X, _ = pm_compat.get_X(X, **kwargs)", "y\" if action == \"raise\": raise ValueError(msg) elif action ==", "= self._check_y_X(y, X) y += lam2 neg_mask = y <=", "go away \"\"\"Inverse transform a transformed array Inverse the Box-Cox", "truncated to the value of ``floor``. floor : float, optional", "``floor``. floor : float, optional (default=1e-16) A positive value that", "or negative and ``neg_action`` is not 'raise'. Note that if", "inverse-transformed y array X : array-like or None The inverse-transformed", "array of additional covariates. Not used for endogenous transformers. Default", "== 0: return np.exp(y) - lam2, exog numer = y", "lam1 == 0: return np.exp(y) - lam2, exog numer =", "if not specified in the constructor. If defined in the", "not be perfectly inverse-transformed. Parameters ---------- y : array-like or", "(y ** lam1 - 1) / lam1, exog def inverse_transform(self,", "if lam1 == 0: return np.exp(y) - lam2, exog numer", "The Box-Cox transformed y array X : array-like or None", "the ``transform`` method, invertibility will not be preserved, and the", "**kwargs): \"\"\"Transform the new array Apply the Box-Cox transformation to", "/ lam1, if lmbda != 0, else log(y + lam2)", "def __init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda = lmbda self.lmbda2", "or None The X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary", "X) if lam1 == 0: return np.exp(y) - lam2, exog", "y, _ = self._check_y_X(y, X) _, lam1 = stats.boxcox(y +", "def transform(self, y, X=None, **kwargs): \"\"\"Transform the new array Apply", "on the transformed array. Note that if truncation happened in", "optional (default=None) The lambda value for the Box-Cox transformation, if", "lambda parameter. Parameters ---------- y : array-like or None, shape=(n_samples,)", "- 1) / lam1, if lmbda != 0, else log(y", "<= 0 will be truncated to the value of ``floor``.", "# -*- coding: utf-8 -*- from scipy import stats import", "specified, it will be estimated via MLE. lmbda2 : float,", "exog = self._check_y_X(y, X) y += lam2 neg_mask = y", "log(y + lam2) Parameters ---------- lmbda : float or None,", "<reponame>tuomijal/pmdarima<gh_stars>100-1000 # -*- coding: utf-8 -*- from scipy import stats", "A positive value that truncate values to if there are", "_ = pm_compat.get_X(X, **kwargs) if lam2 < 0: raise ValueError(\"lmbda2", "r\"\"\"Apply the Box-Cox transformation to an endogenous array The Box-Cox", "transformation to the array after learning the lambda parameter. Parameters", ": array-like or None The Box-Cox transformed y array X", "< 0: raise ValueError(\"lmbda2 must be a non-negative scalar value\")", "X : array-like or None The X array \"\"\" check_is_fitted(self,", "# remove denominator numer += 1. # add 1 back", "remove denominator numer += 1. # add 1 back to", "denominator numer += 1. # add 1 back to it", "lam1 = self.lam1_ lam2 = self.lam2_ y, exog = self._check_y_X(y,", "self.neg_action msg = \"Negative or zero values present in y\"", "transform a transformed array Inverse the Box-Cox transformation on the", "if known. If not specified, it will be estimated via", "None The inverse-transformed y array X : array-like or None", "y : array-like or None, shape=(n_samples,) The endogenous (time-series) array.", "transformed array Inverse the Box-Cox transformation on the transformed array.", "Inverse the Box-Cox transformation on the transformed array. Note that", "else log(y + lam2) Parameters ---------- lmbda : float or", "parameter. Parameters ---------- y : array-like or None, shape=(n_samples,) The", "TODO: kwargs go away \"\"\"Fit the transformer Learns the value", "ValueError(msg) elif action == \"warn\": warnings.warn(msg, UserWarning) y[neg_mask] = self.floor", "the transformed array. Note that if truncation happened in the", "still negative values, a ValueError will be raised. neg_action :", "raised. neg_action : str, optional (default=\"raise\") How to respond if", "y, X=None, **kwargs): \"\"\"Transform the new array Apply the Box-Cox", "shape=(n_samples,) The transformed endogenous (time-series) array. X : array-like or", "the value of ``lmbda``, if not specified in the constructor.", "'warn', 'ignore'). If anything other than 'raise', values <= 0", "are still negative values, a ValueError will be raised. neg_action", "raise ValueError(\"lmbda2 must be a non-negative scalar value\") if lam1", "will be raised. neg_action : str, optional (default=\"raise\") How to", "positive value that truncate values to if there are values", "+ lam2, lmbda=None, alpha=None) self.lam1_ = lam1 self.lam2_ = lam2", "from ...compat import check_is_fitted, pmdarima as pm_compat from .base import", "to make it non-negative. If, after adding ``lmbda2``, there are", "The endogenous (time-series) array. X : array-like or None, shape=(n_samples,", "array after learning the lambda parameter. Parameters ---------- y :", "lam2 neg_mask = y <= 0. if neg_mask.any(): action =", "X=None, **kwargs): # TODO: kwargs go away \"\"\"Inverse transform a", "shape=(n_samples,) The endogenous (time-series) array. X : array-like or None,", "import warnings from ...compat import check_is_fitted, pmdarima as pm_compat from", "for endogenous transformers. Default is None, and non-None values will", "lam2) Parameters ---------- lmbda : float or None, optional (default=None)", "The X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim until", "lam2, lmbda=None, alpha=None) self.lam1_ = lam1 self.lam2_ = lam2 return", "distribution. It's specified as:: (((y + lam2) ** lam1) -", "endogenous transformers. Default is None, and non-None values will serve", "check_is_fitted, pmdarima as pm_compat from .base import BaseEndogTransformer __all__ =", "== 0: return np.log(y), exog return (y ** lam1 -", "numer = y * lam1 # remove denominator numer +=", "negative values, a ValueError will be raised. neg_action : str,", "if lam1 is None: y, _ = self._check_y_X(y, X) _,", "= y * lam1 # remove denominator numer += 1.", "scalar value\") if lam1 is None: y, _ = self._check_y_X(y,", "normal distribution. It's specified as:: (((y + lam2) ** lam1)", "in y\" if action == \"raise\": raise ValueError(msg) elif action", "if action == \"raise\": raise ValueError(msg) elif action == \"warn\":", "to if there are values in ``y`` that are zero", "= self.neg_action msg = \"Negative or zero values present in", "or None The inverse-transformed X array \"\"\" check_is_fitted(self, \"lam1_\") #", "lam2 = self.lam2_ y, exog = self._check_y_X(y, X) y +=", "pmdarima as pm_compat from .base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer']", "fit(self, y, X=None, **kwargs): # TODO: kwargs go away \"\"\"Fit", "**kwargs) if lam2 < 0: raise ValueError(\"lmbda2 must be a", "0: return np.log(y), exog return (y ** lam1 - 1)", "# TODO: kwargs go away \"\"\"Inverse transform a transformed array", "float or None, optional (default=None) The lambda value for the", ": float, optional (default=1e-16) A positive value that truncate values", "Parameters ---------- y : array-like or None, shape=(n_samples,) The transformed", "if any values in ``y <= 0`` after adding ``lmbda2``.", "to non-normal data to coerce it more towards a normal", "= lam2 return self def transform(self, y, X=None, **kwargs): \"\"\"Transform", "arrays. Returns ------- y : array-like or None The inverse-transformed", "values <= 0 will be truncated to the value of", "= pm_compat.get_X(X, **kwargs) if lam2 < 0: raise ValueError(\"lmbda2 must", "lambda value for the Box-Cox transformation, if known. If not", "X=None, **kwargs): # TODO: kwargs go away \"\"\"Fit the transformer", "lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda = lmbda self.lmbda2 = lmbda2 self.neg_action", "Box-Cox transformation, if known. If not specified, it will be", "'raise'. Note that if values are truncated, invertibility will not", "to add to ``y`` to make it non-negative. If, after", "= self.floor if lam1 == 0: return np.log(y), exog return", "The lambda value for the Box-Cox transformation, if known. If", "(default=0.) The value to add to ``y`` to make it", "if truncation happened in the ``transform`` method, invertibility will not", "---------- y : array-like or None, shape=(n_samples,) The transformed endogenous", "re-learned. Parameters ---------- y : array-like or None, shape=(n_samples,) The", "lam1 == 0: return np.log(y), exog return (y ** lam1", "inverse-transformed. Parameters ---------- y : array-like or None, shape=(n_samples,) The", "not 'raise'. Note that if values are truncated, invertibility will", "not be perfectly inverse-transformed. \"\"\" def __init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\",", "None, and non-None values will serve as pass-through arrays. Returns", "np import warnings from ...compat import check_is_fitted, pmdarima as pm_compat", "be perfectly inverse-transformed. \"\"\" def __init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16):", "invertibility will not be preserved, and the transformed array may", "array may not be perfectly inverse-transformed. Parameters ---------- y :", "X) y += lam2 neg_mask = y <= 0. if", "`exogenous` support completely X, _ = pm_compat.get_X(X, **kwargs) if lam2", "floor : float, optional (default=1e-16) A positive value that truncate", "/ lam1, exog def inverse_transform(self, y, X=None, **kwargs): # TODO:", "or zero values present in y\" if action == \"raise\":", "X : array-like or None The inverse-transformed X array \"\"\"", "np.log(y), exog return (y ** lam1 - 1) / lam1,", "be raised. neg_action : str, optional (default=\"raise\") How to respond", "as:: (((y + lam2) ** lam1) - 1) / lam1,", "not specified in the constructor. If defined in the constructor,", "= self.lmbda lam2 = self.lmbda2 # Temporary shim until we", "values to if there are values in ``y`` that are", "X : array-like or None, shape=(n_samples, n_features), optional The exogenous", "self.lam2_ y, exog = self._check_y_X(y, X) y += lam2 neg_mask", "raise ValueError(msg) elif action == \"warn\": warnings.warn(msg, UserWarning) y[neg_mask] =", "of ``lmbda``, if not specified in the constructor. If defined", "The inverse-transformed y array X : array-like or None The", "lmbda != 0, else log(y + lam2) Parameters ---------- lmbda", "**kwargs): # TODO: kwargs go away \"\"\"Inverse transform a transformed", "** (1. / lam1) # de-exponentiate return de_exp - lam2,", "0 will be truncated to the value of ``floor``. floor", "warnings.warn(msg, UserWarning) y[neg_mask] = self.floor if lam1 == 0: return", "(time-series) array. X : array-like or None, shape=(n_samples, n_features), optional", "from .base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply", "['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the Box-Cox transformation to an endogenous", "optional The exogenous array of additional covariates. Not used for", "array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary shim until we remove", "ValueError will be raised. neg_action : str, optional (default=\"raise\") How", "used for endogenous transformers. Default is None, and non-None values", "is None, and non-None values will serve as pass-through arrays.", "remove `exogenous` support completely X, _ = pm_compat.get_X(X, **kwargs) lam1", "------- y_transform : array-like or None The Box-Cox transformed y", "\"Negative or zero values present in y\" if action ==", "inverse_transform(self, y, X=None, **kwargs): # TODO: kwargs go away \"\"\"Inverse", "<= 0. if neg_mask.any(): action = self.neg_action msg = \"Negative", "``transform`` method, invertibility will not be preserved, and the transformed", "\"raise\": raise ValueError(msg) elif action == \"warn\": warnings.warn(msg, UserWarning) y[neg_mask]", "lam1, if lmbda != 0, else log(y + lam2) Parameters", "perfectly inverse-transformed. \"\"\" def __init__(self, lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda", "Learns the value of ``lmbda``, if not specified in the", "as pass-through arrays. \"\"\" lam1 = self.lmbda lam2 = self.lmbda2", "``y <= 0`` after adding ``lmbda2``. One of ('raise', 'warn',", "are truncated, invertibility will not be preserved, and the transformed", "Box-Cox transformed y array X : array-like or None The", "values will serve as pass-through arrays. Returns ------- y :", "+ lam2) Parameters ---------- lmbda : float or None, optional", "floor def fit(self, y, X=None, **kwargs): # TODO: kwargs go", "the value of ``floor``. floor : float, optional (default=1e-16) A", "an endogenous array The Box-Cox transformation is applied to non-normal", "_, lam1 = stats.boxcox(y + lam2, lmbda=None, alpha=None) self.lam1_ =", "return self def transform(self, y, X=None, **kwargs): \"\"\"Transform the new", "1. # add 1 back to it de_exp = numer", "happened in the ``transform`` method, invertibility will not be preserved,", "or None The Box-Cox transformed y array X : array-like", "it more towards a normal distribution. It's specified as:: (((y", "If not specified, it will be estimated via MLE. lmbda2", "value to add to ``y`` to make it non-negative. If,", "after adding ``lmbda2``. One of ('raise', 'warn', 'ignore'). If anything", "will serve as pass-through arrays. Returns ------- y : array-like", "make it non-negative. If, after adding ``lmbda2``, there are still", "the Box-Cox transformation, if known. If not specified, it will", "'ignore'). If anything other than 'raise', values <= 0 will", "than 'raise', values <= 0 will be truncated to the", "transformed array may not be perfectly inverse-transformed. \"\"\" def __init__(self,", "new array Apply the Box-Cox transformation to the array after", "lam2 < 0: raise ValueError(\"lmbda2 must be a non-negative scalar", "array-like or None, shape=(n_samples,) The endogenous (time-series) array. X :", "lam1 # remove denominator numer += 1. # add 1", "be preserved, and the transformed array may not be perfectly", "= numer ** (1. / lam1) # de-exponentiate return de_exp", "numer ** (1. / lam1) # de-exponentiate return de_exp -", "optional (default=1e-16) A positive value that truncate values to if", "is None: y, _ = self._check_y_X(y, X) _, lam1 =", "**kwargs) lam1 = self.lam1_ lam2 = self.lam2_ y, exog =", "It's specified as:: (((y + lam2) ** lam1) - 1)", "known. If not specified, it will be estimated via MLE.", "scipy import stats import numpy as np import warnings from", "alpha=None) self.lam1_ = lam1 self.lam2_ = lam2 return self def", "pass-through arrays. Returns ------- y : array-like or None The", "lmbda=None, lmbda2=0, neg_action=\"raise\", floor=1e-16): self.lmbda = lmbda self.lmbda2 = lmbda2", "Parameters ---------- lmbda : float or None, optional (default=None) The", "ValueError(\"lmbda2 must be a non-negative scalar value\") if lam1 is", "the constructor, is not re-learned. Parameters ---------- y : array-like", "numpy as np import warnings from ...compat import check_is_fitted, pmdarima", "values present in y\" if action == \"raise\": raise ValueError(msg)", "**kwargs): # TODO: kwargs go away \"\"\"Fit the transformer Learns", "\"\"\" lam1 = self.lmbda lam2 = self.lmbda2 # Temporary shim", "(default=\"raise\") How to respond if any values in ``y <=", "non-negative scalar value\") if lam1 is None: y, _ =", "_ = pm_compat.get_X(X, **kwargs) lam1 = self.lam1_ lam2 = self.lam2_", "and the transformed array may not be perfectly inverse-transformed. Parameters", "None The inverse-transformed X array \"\"\" check_is_fitted(self, \"lam1_\") # Temporary", "lam2 = self.lam2_ y, exog = self._check_y_X(y, X) if lam1", "kwargs go away \"\"\"Fit the transformer Learns the value of", "``y`` to make it non-negative. If, after adding ``lmbda2``, there", "specified as:: (((y + lam2) ** lam1) - 1) /", "as pm_compat from .base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer'] class", "a non-negative scalar value\") if lam1 is None: y, _", "in the constructor, is not re-learned. Parameters ---------- y :", "= self._check_y_X(y, X) if lam1 == 0: return np.exp(y) -", "self.lam1_ = lam1 self.lam2_ = lam2 return self def transform(self,", "specified in the constructor. If defined in the constructor, is", "return np.log(y), exog return (y ** lam1 - 1) /", "non-normal data to coerce it more towards a normal distribution.", "towards a normal distribution. It's specified as:: (((y + lam2)", "a transformed array Inverse the Box-Cox transformation on the transformed", "lmbda self.lmbda2 = lmbda2 self.neg_action = neg_action self.floor = floor", "y array X : array-like or None The X array", "stats.boxcox(y + lam2, lmbda=None, alpha=None) self.lam1_ = lam1 self.lam2_ =", "!= 0, else log(y + lam2) Parameters ---------- lmbda :", "be truncated to the value of ``floor``. floor : float,", "...compat import check_is_fitted, pmdarima as pm_compat from .base import BaseEndogTransformer", "endogenous array The Box-Cox transformation is applied to non-normal data", "lam1) - 1) / lam1, if lmbda != 0, else", "``neg_action`` is not 'raise'. Note that if values are truncated,", "be a non-negative scalar value\") if lam1 is None: y,", "self.lam2_ y, exog = self._check_y_X(y, X) if lam1 == 0:", "warnings from ...compat import check_is_fitted, pmdarima as pm_compat from .base", "(1. / lam1) # de-exponentiate return de_exp - lam2, exog", "= pm_compat.get_X(X, **kwargs) lam1 = self.lam1_ lam2 = self.lam2_ y,", "self.neg_action = neg_action self.floor = floor def fit(self, y, X=None,", "of ('raise', 'warn', 'ignore'). If anything other than 'raise', values", "in ``y <= 0`` after adding ``lmbda2``. One of ('raise',", "If anything other than 'raise', values <= 0 will be", "away \"\"\"Fit the transformer Learns the value of ``lmbda``, if", "if values are truncated, invertibility will not be preserved, and", ".base import BaseEndogTransformer __all__ = ['BoxCoxEndogTransformer'] class BoxCoxEndogTransformer(BaseEndogTransformer): r\"\"\"Apply the", "1) / lam1, if lmbda != 0, else log(y +", "covariates. Not used for endogenous transformers. Default is None, and", "y, exog = self._check_y_X(y, X) y += lam2 neg_mask =", "``lmbda``, if not specified in the constructor. If defined in", "0, else log(y + lam2) Parameters ---------- lmbda : float", "be estimated via MLE. lmbda2 : float, optional (default=0.) The", "exog = self._check_y_X(y, X) if lam1 == 0: return np.exp(y)", "as np import warnings from ...compat import check_is_fitted, pmdarima as", "learning the lambda parameter. Parameters ---------- y : array-like or", "applied to non-normal data to coerce it more towards a", ": str, optional (default=\"raise\") How to respond if any values", "action = self.neg_action msg = \"Negative or zero values present", "zero values present in y\" if action == \"raise\": raise", "and non-None values will serve as pass-through arrays. \"\"\" lam1", "import check_is_fitted, pmdarima as pm_compat from .base import BaseEndogTransformer __all__", "`exogenous` support completely X, _ = pm_compat.get_X(X, **kwargs) lam1 =", "self.lmbda2 # Temporary shim until we remove `exogenous` support completely", "non-None values will serve as pass-through arrays. \"\"\" lam1 =", "lmbda=None, alpha=None) self.lam1_ = lam1 self.lam2_ = lam2 return self", "Note that if truncation happened in the ``transform`` method, invertibility", "TODO: kwargs go away \"\"\"Inverse transform a transformed array Inverse", "will be truncated to the value of ``floor``. floor :", "None The Box-Cox transformed y array X : array-like or" ]
[ "key containing the type name. Example: class TestUserDataType(UserDataType): type =", "Example: class TestUserDataType(UserDataType): type = \"test\" def get_user_data(user, request): return", "\"id\": 1, ... }, \"test\": { \"test\": \"value\" } }", "type can be used to inject an additional payload to", "\"value\" } } \"\"\" def get_user_data(self, user, request) -> dict:", "The user data type can be used to inject an", "to the API JWT response. This is the response when", "def get_user_data(self, user, request) -> dict: \"\"\" Should return a", "authenticated. :type request: Request :return: a dict containing the user", "the `get_user_data` method is added to the payload under the", ") class UserDataRegistry(Registry): name = \"api_user_data\" def get_all_user_data(self, user, request)", "-> dict: \"\"\" Should return a dict containing the additional", "user data type can be used to inject an additional", "from baserow.core.registry import Instance, Registry class UserDataType(Instance): \"\"\" The user", "\"test\" def get_user_data(user, request): return {\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will result", "be used to inject an additional payload to the API", "containing the user data that must be added to the", "to the response. \"\"\" raise NotImplementedError( \"The get_user_data must be", "be implemented and should return a dict.\" ) class UserDataRegistry(Registry):", "an additional payload to the API JWT response. This is", ":type request: Request :return: a dict containing the user data", "of the `get_user_data` method is added to the payload under", "the registered instances. \"\"\" return { key: value.get_user_data(user, request) for", "and should return a dict.\" ) class UserDataRegistry(Registry): name =", "instances. :param user: The user that just authenticated. :type user:", "... }, \"test\": { \"test\": \"value\" } } \"\"\" def", "\"<PASSWORD>....\", \"user: { \"id\": 1, ... }, \"test\": { \"test\":", "`get_user_data` method is added to the payload under the key", "registered user data type instances. :param user: The user that", "Will result into the following response when the user authenticates:", "a dict containing the user data that must be added", "data type instances. :param user: The user that just authenticated.", "{ \"id\": 1, ... }, \"test\": { \"test\": \"value\" }", "the following response when the user authenticates: { \"token\": \"<PASSWORD>....\",", "when the user authenticated. :type request: Request :return: a dict", "type name. Example: class TestUserDataType(UserDataType): type = \"test\" def get_user_data(user,", "return a dict.\" ) class UserDataRegistry(Registry): name = \"api_user_data\" def", "\"\"\" Collects the additional user data of all the registered", "inject an additional payload to the API JWT response. This", "This is the response when a user authenticates or refreshes", "{ key: value.get_user_data(user, request) for key, value in self.registry.items() }", "implemented and should return a dict.\" ) class UserDataRegistry(Registry): name", "returned dict of the `get_user_data` method is added to the", "must be implemented and should return a dict.\" ) class", "{ \"token\": \"<PASSWORD>....\", \"user: { \"id\": 1, ... }, \"test\":", "authenticated. :type user: User :param request: The request when the", "response when a user authenticates or refreshes his token. The", "be added to the response payload after the user authenticates.", "authenticates. :param user: The related user that just authenticated. :type", "must be added to the response payload after the user", "payload after the user authenticates. :param user: The related user", "\"test\": \"value\" } } \"\"\" def get_user_data(self, user, request) ->", "user, request) -> dict: \"\"\" Should return a dict containing", "dict of the `get_user_data` method is added to the payload", "to inject an additional payload to the API JWT response.", "user, request) -> dict: \"\"\" Collects the additional user data", "return a dict containing the additional information that must be", "registered instances. \"\"\" return { key: value.get_user_data(user, request) for key,", "the user authenticates: { \"token\": \"<PASSWORD>....\", \"user: { \"id\": 1,", "data that must be added to the response. \"\"\" raise", "1, ... }, \"test\": { \"test\": \"value\" } } \"\"\"", "Instance, Registry class UserDataType(Instance): \"\"\" The user data type can", "that just authenticated. :type user: User :param request: The request", "dict: \"\"\" Collects the additional user data of all the", "a user authenticates or refreshes his token. The returned dict", "the registered user data type instances. :param user: The user", "payload for all the registered instances. \"\"\" return { key:", "additional user data of all the registered user data type", "Should return a dict containing the additional information that must", "value.get_user_data(user, request) for key, value in self.registry.items() } user_data_registry =", "def get_all_user_data(self, user, request) -> dict: \"\"\" Collects the additional", "is the response when a user authenticates or refreshes his", "the additional user data of all the registered user data", "{\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will result into the following response when", "Registry class UserDataType(Instance): \"\"\" The user data type can be", "import Instance, Registry class UserDataType(Instance): \"\"\" The user data type", "the response payload after the user authenticates. :param user: The", "the API JWT response. This is the response when a", "containing all additional user data payload for all the registered", "request) for key, value in self.registry.items() } user_data_registry = UserDataRegistry()", "to the payload under the key containing the type name.", "\"api_user_data\" def get_all_user_data(self, user, request) -> dict: \"\"\" Collects the", "must be added to the response. \"\"\" raise NotImplementedError( \"The", "request) -> dict: \"\"\" Collects the additional user data of", "key: value.get_user_data(user, request) for key, value in self.registry.items() } user_data_registry", "} \"\"\" def get_user_data(self, user, request) -> dict: \"\"\" Should", "the type name. Example: class TestUserDataType(UserDataType): type = \"test\" def", "raise NotImplementedError( \"The get_user_data must be implemented and should return", "under the key containing the type name. Example: class TestUserDataType(UserDataType):", "the response. \"\"\" raise NotImplementedError( \"The get_user_data must be implemented", ":return: a dict containing the user data that must be", "Collects the additional user data of all the registered user", "The user that just authenticated. :type user: User :param request:", "when the user authenticates: { \"token\": \"<PASSWORD>....\", \"user: { \"id\":", "TestUserDataType(UserDataType): type = \"test\" def get_user_data(user, request): return {\"test\": \"value\"}", "request): return {\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will result into the following", "User :param request: The request when the user authenticated. :type", "\"\"\" Should return a dict containing the additional information that", "user authenticates. :param user: The related user that just authenticated.", "baserow.core.registry import Instance, Registry class UserDataType(Instance): \"\"\" The user data", "user: User :param request: The request when the user authenticated.", "user data type instances. :param user: The user that just", "dict containing all additional user data payload for all the", "added to the response. \"\"\" raise NotImplementedError( \"The get_user_data must", "when a user authenticates or refreshes his token. The returned", "dict containing the additional information that must be added to", "used to inject an additional payload to the API JWT", "<gh_stars>1-10 from baserow.core.registry import Instance, Registry class UserDataType(Instance): \"\"\" The", "= \"test\" def get_user_data(user, request): return {\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will", "into the following response when the user authenticates: { \"token\":", "\"test\": { \"test\": \"value\" } } \"\"\" def get_user_data(self, user,", "just authenticated. :type user: User :param request: The request when", "type = \"test\" def get_user_data(user, request): return {\"test\": \"value\"} user_data_registry.register(TestUserDataType())", "be added to the response. \"\"\" raise NotImplementedError( \"The get_user_data", "response when the user authenticates: { \"token\": \"<PASSWORD>....\", \"user: {", "payload to the API JWT response. This is the response", "data payload for all the registered instances. \"\"\" return {", "dict: \"\"\" Should return a dict containing the additional information", ":type user: User :param request: The request when the user", "get_user_data(self, user, request) -> dict: \"\"\" Should return a dict", "data of all the registered user data type instances. :param", "the payload under the key containing the type name. Example:", "{ \"test\": \"value\" } } \"\"\" def get_user_data(self, user, request)", "the response when a user authenticates or refreshes his token.", "user authenticated. :type request: Request :return: a dict containing all", ":param user: The related user that just authenticated. :type user:", "user that just authenticated. :type user: User :param request: The", "containing the type name. Example: class TestUserDataType(UserDataType): type = \"test\"", "that must be added to the response. \"\"\" raise NotImplementedError(", "user authenticates: { \"token\": \"<PASSWORD>....\", \"user: { \"id\": 1, ...", "dict.\" ) class UserDataRegistry(Registry): name = \"api_user_data\" def get_all_user_data(self, user,", "UserDataRegistry(Registry): name = \"api_user_data\" def get_all_user_data(self, user, request) -> dict:", "instances. \"\"\" return { key: value.get_user_data(user, request) for key, value", "= \"api_user_data\" def get_all_user_data(self, user, request) -> dict: \"\"\" Collects", "The related user that just authenticated. :type user: User :param", "all additional user data payload for all the registered instances.", "of all the registered user data type instances. :param user:", "request: Request :return: a dict containing the user data that", "user data that must be added to the response. \"\"\"", "user: The related user that just authenticated. :type user: User", "authenticated. :type request: Request :return: a dict containing all additional", "request: The request when the user authenticated. :type request: Request", "containing the additional information that must be added to the", "all the registered instances. \"\"\" return { key: value.get_user_data(user, request)", ":type request: Request :return: a dict containing all additional user", "user data payload for all the registered instances. \"\"\" return", ":param request: The request when the user authenticated. :type request:", "UserDataType(Instance): \"\"\" The user data type can be used to", "related user that just authenticated. :type user: User :param request:", "his token. The returned dict of the `get_user_data` method is", "\"\"\" raise NotImplementedError( \"The get_user_data must be implemented and should", "user_data_registry.register(TestUserDataType()) Will result into the following response when the user", "the key containing the type name. Example: class TestUserDataType(UserDataType): type", "user authenticated. :type request: Request :return: a dict containing the", "Request :return: a dict containing the user data that must", "class UserDataRegistry(Registry): name = \"api_user_data\" def get_all_user_data(self, user, request) ->", "-> dict: \"\"\" Collects the additional user data of all", "The returned dict of the `get_user_data` method is added to", "to the response payload after the user authenticates. :param user:", ":return: a dict containing all additional user data payload for", "return {\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will result into the following response", "request when the user authenticated. :type request: Request :return: a", "\"The get_user_data must be implemented and should return a dict.\"", ":param user: The user that just authenticated. :type user: User", "added to the response payload after the user authenticates. :param", "all the registered user data type instances. :param user: The", "can be used to inject an additional payload to the", "user: The user that just authenticated. :type user: User :param", "authenticates or refreshes his token. The returned dict of the", "the additional information that must be added to the response", "a dict containing all additional user data payload for all", "\"user: { \"id\": 1, ... }, \"test\": { \"test\": \"value\"", "JWT response. This is the response when a user authenticates", "payload under the key containing the type name. Example: class", "}, \"test\": { \"test\": \"value\" } } \"\"\" def get_user_data(self,", "NotImplementedError( \"The get_user_data must be implemented and should return a", "additional information that must be added to the response payload", "\"\"\" return { key: value.get_user_data(user, request) for key, value in", "dict containing the user data that must be added to", "get_all_user_data(self, user, request) -> dict: \"\"\" Collects the additional user", "class UserDataType(Instance): \"\"\" The user data type can be used", "following response when the user authenticates: { \"token\": \"<PASSWORD>....\", \"user:", "the user data that must be added to the response.", "name = \"api_user_data\" def get_all_user_data(self, user, request) -> dict: \"\"\"", "additional user data payload for all the registered instances. \"\"\"", "added to the payload under the key containing the type", "request: Request :return: a dict containing all additional user data", "additional payload to the API JWT response. This is the", "is added to the payload under the key containing the", "token. The returned dict of the `get_user_data` method is added", "get_user_data must be implemented and should return a dict.\" )", "\"\"\" The user data type can be used to inject", "class TestUserDataType(UserDataType): type = \"test\" def get_user_data(user, request): return {\"test\":", "response payload after the user authenticates. :param user: The related", "the user authenticated. :type request: Request :return: a dict containing", "user data of all the registered user data type instances.", "the user authenticates. :param user: The related user that just", "type instances. :param user: The user that just authenticated. :type", "refreshes his token. The returned dict of the `get_user_data` method", "\"value\"} user_data_registry.register(TestUserDataType()) Will result into the following response when the", "request) -> dict: \"\"\" Should return a dict containing the", "method is added to the payload under the key containing", "after the user authenticates. :param user: The related user that", "\"\"\" def get_user_data(self, user, request) -> dict: \"\"\" Should return", "information that must be added to the response payload after", "a dict.\" ) class UserDataRegistry(Registry): name = \"api_user_data\" def get_all_user_data(self,", "The request when the user authenticated. :type request: Request :return:", "Request :return: a dict containing all additional user data payload", "authenticates: { \"token\": \"<PASSWORD>....\", \"user: { \"id\": 1, ... },", "response. \"\"\" raise NotImplementedError( \"The get_user_data must be implemented and", "get_user_data(user, request): return {\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will result into the", "} } \"\"\" def get_user_data(self, user, request) -> dict: \"\"\"", "that must be added to the response payload after the", "data type can be used to inject an additional payload", "\"token\": \"<PASSWORD>....\", \"user: { \"id\": 1, ... }, \"test\": {", "def get_user_data(user, request): return {\"test\": \"value\"} user_data_registry.register(TestUserDataType()) Will result into", "result into the following response when the user authenticates: {", "a dict containing the additional information that must be added", "return { key: value.get_user_data(user, request) for key, value in self.registry.items()", "API JWT response. This is the response when a user", "name. Example: class TestUserDataType(UserDataType): type = \"test\" def get_user_data(user, request):", "user authenticates or refreshes his token. The returned dict of", "should return a dict.\" ) class UserDataRegistry(Registry): name = \"api_user_data\"", "for all the registered instances. \"\"\" return { key: value.get_user_data(user,", "or refreshes his token. The returned dict of the `get_user_data`", "response. This is the response when a user authenticates or" ]
[ "the program) nodeNumbers = {circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes", "can also enter values in exponential format (eg. 1e3 =", "1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations for c in", "np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) # GND Equation", "vName # Convert a number in engineer's format to math", "= 1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 #", "matrixB) circuitCurrents = [] # Formatting Output Data for v", "self.node1 = n1 self.node2 = n2 self.vSource = vName #", "n2 self.vSource = vName # Convert a number in engineer's", "CCCS = \"F\" PI = np.pi # Classes for each", "file is of correct type if (not circuitFile.endswith(\".netlist\")): print(\"Wrong file", "type!\") else: netlistFileLines = [] with open (circuitFile, \"r\") as", "if given netlist file is of correct type if (not", "circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor if lineTokens[0][0] ==", "circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND':", "else: try: circuitFile = sys.argv[1] circuitFreq = 1e-100 circuitComponents =", "range(len(circuitNodes))} numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices", "lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor", "def __init__(self, name, n1, n2, vName, val): self.name = name", "to a list try: if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1])", "== 6: # AC Source if circuitFreq == 1e-100: sys.exit(\"Frequency", "return float(enggNumber) except: lenEnggNumber = len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1]", "matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage Source Equations for i", "as np import pandas as pd # To improve readability", "CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4]))", "= n2 class capacitor: def __init__(self, name, n1, n2, val):", "lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif", "arguments if len(sys.argv)!=2 : sys.exit(\"Invalid number of arguments!\") else: try:", "= -1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs in circuitComponents[VCCS]: if", "Equations for c in circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]]", "circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source elif lineTokens[0][0]", "VCVS = \"E\" VCCS = \"G\" CCVS = \"H\" CCCS", "= -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] =", "checking number of command line arguments if len(sys.argv)!=2 : sys.exit(\"Invalid", "matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations for", "return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] == 'n': base =", "len(lineTokens) == 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])))", "c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0,", "# Convert a number in engineer's format to math def", "Source Equations for i in circuitComponents[ICS]: if i.node1 != 'GND':", "Equations for i in range(len(circuitComponents[CCVS])): # Equation accounting for current", "!= 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value))", "ICS = \"I\" VCVS = \"E\" VCCS = \"G\" CCVS", "self.node1 = n1 self.node2 = n2 class voltageSource: def __init__(self,", "else: sys.exit(\"Please check the component values given. Supported engineer units", "[], CCCS: [] } circuitNodes = [] # checking if", "class inductor: def __init__(self, name, n1, n2, val): self.name =", "= len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and b matrixM =", "val): self.name = name self.value = enggToMath(val) self.node1 = n1", "= \"C\" INDUCTOR = \"L\" IVS = \"V\" ICS =", "lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif", "w = 2*PI*circuitFreq try: # Finding the location of the", "'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value #", "in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except", "not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source", "specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0]", "len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and b matrixM = np.zeros((numNodes+numVS,", "# Formatting Output Data for v in circuitComponents[IVS]: circuitCurrents.append(\"current in", "self.vSource = vName class cccs: def __init__(self, name, n1, n2,", "number of arguments!\") else: try: circuitFile = sys.argv[1] circuitFreq =", "lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source elif lineTokens[0][0] ==", "the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if", "values and NOT RMS values.\") except np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed!", "[] with open (circuitFile, \"r\") as f: for line in", "lineTokens[2], lineTokens[3])) # Voltage Source elif lineTokens[0][0] == IVS: if", "Current Source Equations for i in circuitComponents[ICS]: if i.node1 !=", "columns=['Voltage / Current'])) print(\"The values given above are AMPLITUDE values", "cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents", "of AC Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5]))", "name, n1, n2, val, phase=0): self.name = name self.value =", "VCCS: [], CCVS: [], CCCS: [] } circuitNodes = []", "= 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]]", "vName, val): self.name = name self.value = enggToMath(val) self.node1 =", "elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage", "accounting for current through the source if circuitComponents[IVS][i].node1 != 'GND':", "for v in circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name) # Printing output", "self.node1 = n1 self.node2 = n2 self.vSource = vName class", "w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]]", "circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0]", "i in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) #", "engineer units are: M, k, m, u, n\\nYou can also", "c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0,", "name, n1, n2, vName, val): self.name = name self.value =", "1e-100 circuitComponents = { RESISTOR: [], CAPACITOR: [], INDUCTOR: [],", "# Setting Angular Frequency w w = 2*PI*circuitFreq try: #", "-1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]]", "location of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END)", "circuitNodes except: sys.exit(\"No ground node specified in the circuit!!\") #", "} circuitNodes = [] # checking if given netlist file", "of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody", "circuitCurrents.append(\"current in \"+v.name) # Printing output in table format print(pd.DataFrame(x,", "# Printing output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage /", "= n1 self.node2 = n2 class inductor: def __init__(self, name,", "numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and b matrixM", "= line.split() # Appending new nodes to a list try:", "for current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i]", "if len(sys.argv)!=2 : sys.exit(\"Invalid number of arguments!\") else: try: circuitFile", "range(len(circuitComponents[CCVS])): # Equation accounting for current through the source if", "len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1])", "n1, n2, val): self.name = name self.value = enggToMath(val) self.node1", "1e-100: sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2],", "= +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations", "# Voltage Source Equations for i in range(len(circuitComponents[IVS])): # Equation", "= netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line", "values given above are AMPLITUDE values and NOT RMS values.\")", "+= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2 !=", "circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0] == CAPACITOR:", "__init__(self, name, n1, n2, vName, val): self.name = name self.value", "complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage Source Equations", "= {circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS", "open (circuitFile, \"r\") as f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0])", "vcvs: def __init__(self, name, n1, n2, n3, n4, val): self.name", "== CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component", "Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) #", "to math def enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber =", "n2, n3, n4, val): self.name = name self.value = enggToMath(val)", "circuitNodes = ['GND'] + circuitNodes except: sys.exit(\"No ground node specified", "lineTokens[4])) # CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2],", "== IVS: if len(lineTokens) == 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0],", "voltageSource: def __init__(self, name, n1, n2, val, phase=0): self.name =", "[] # Formatting Output Data for v in circuitComponents[IVS]: circuitCurrents.append(\"current", "Equations for r in circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]]", "lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0] == CCVS:", "Supported engineer units are: M, k, m, u, n\\nYou can", "float(phase) class vcvs: def __init__(self, name, n1, n2, n3, n4,", "Source Equations for i in range(len(circuitComponents[IVS])): # Equation accounting for", "try: return float(enggNumber) except: lenEnggNumber = len(enggNumber) # Kilo if", "the data from the line lineTokens = line.split() # Appending", "for r in circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] +=", "+1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for", "'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1]", "try: circuitFile = sys.argv[1] circuitFreq = 1e-100 circuitComponents = {", "# To improve readability CIRCUIT_START = \".circuit\" CIRCUIT_END = \".end\"", "for i in range(len(circuitComponents[VCVS])): # Equation accounting for current through", "------------------------------------- ''' # importing necessary libraries import sys import cmath", "elif enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 #", "of command line arguments if len(sys.argv)!=2 : sys.exit(\"Invalid number of", "------------------------------------- Assignment 2 - EE2703 (Jan-May 2020) Done by <NAME>", "matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2", "not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor if", "class resistor: def __init__(self, name, n1, n2, val): self.name =", "frequency, if any if(line[:3] == '.ac'): circuitFreq = float(line.split()[2]) #", "float(phase) class currentSource: def __init__(self, name, n1, n2, val, phase=0):", "sys.exit(\"Invalid number of arguments!\") else: try: circuitFile = sys.argv[1] circuitFreq", "matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 != 'GND':", "check the component values given. Supported engineer units are: M,", "matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0", "M and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB =", "Setting Angular Frequency w w = 2*PI*circuitFreq try: # Finding", "circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]]", "ICS: if len(lineTokens) == 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1],", "= { RESISTOR: [], CAPACITOR: [], INDUCTOR: [], IVS: [],", "= 1e-100 circuitComponents = { RESISTOR: [], CAPACITOR: [], INDUCTOR:", "w w = 2*PI*circuitFreq try: # Finding the location of", "matrixM[0][0] = 1.0 # Resistor Equations for r in circuitComponents[RESISTOR]:", "n\\nYou can also enter values in exponential format (eg. 1e3", "i.value # VCVS Equations for i in range(len(circuitComponents[VCVS])): # Equation", "except IndexError: continue # Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0],", "current through the source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] =", "CAPACITOR: [], INDUCTOR: [], IVS: [], ICS: [], VCVS: [],", "if circuitFreq == 1e-100: sys.exit(\"Frequency of AC Source not specified!!\")", "Equations for i in circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]]", "!= 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value", "you have entered the circuit definition correctly!\") except ValueError: sys.exit(\"Netlist", "CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0] ==", "numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0]", "IVS: if len(lineTokens) == 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1],", "1/r.value # Capacitor Equations for c in circuitComponents[CAPACITOR]: if c.node1", "for v in circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name) for v in", "Created on 18/01/20 Last Modified on 04/02/20 ------------------------------------- ''' #", "i in range(len(circuitComponents[IVS])): # Equation accounting for current through the", "= int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif enggNumber[lenEnggNumber-1] == 'm':", "elif len(lineTokens) == 6: # AC Source if circuitFreq ==", "= \"L\" IVS = \"V\" ICS = \"I\" VCVS =", "names and their numbers (to reduce the time taken by", "the source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if", "# Equation accounting for current through the source if circuitComponents[VCVS][i].node1", "does not abide to given format!\") except FileNotFoundError: sys.exit(\"Given file", "engineer's format to math def enggToMath(enggNumber): try: return float(enggNumber) except:", "lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source elif lineTokens[0][0] == IVS:", "enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli", "in \"+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name) for", "\".end\" RESISTOR = \"R\" CAPACITOR = \"C\" INDUCTOR = \"L\"", "self.node2 = n2 class inductor: def __init__(self, name, n1, n2,", "circuitComponents[CCCS]: def getIndexIVS(vName): for i in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name ==", "the component values given. Supported engineer units are: M, k,", "are AMPLITUDE values and NOT RMS values.\") except np.linalg.LinAlgError: sys.exit(\"Singular", "enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit(\"Please", "by <NAME> (EE18B122) Created on 18/01/20 Last Modified on 04/02/20", "= sys.argv[1] circuitFreq = 1e-100 circuitComponents = { RESISTOR: [],", "lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) #", "matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) #", "= np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) # GND", "sys.exit(\"Wrong Component Given. ABORT!\") try: circuitNodes.remove('GND') circuitNodes = ['GND'] +", "(EE18B122) Created on 18/01/20 Last Modified on 04/02/20 ------------------------------------- '''", "RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0] ==", "matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source", "if any if(line[:3] == '.ac'): circuitFreq = float(line.split()[2]) # Setting", "time taken by later parts of the program) nodeNumbers =", "matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations for", "and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,),", "the circuit!!\") # Creating a dictionary with node names and", "matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0", "checking if given netlist file is of correct type if", "'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] =", "the circuit definition correctly!\") except ValueError: sys.exit(\"Netlist does not abide", "self.node1 = n1 self.node2 = n2 class inductor: def __init__(self,", "n3 self.node4 = n4 class ccvs: def __init__(self, name, n1,", "== 'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif", "complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2 != 'GND':", "for i in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS])", "= -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations for i", "number of command line arguments if len(sys.argv)!=2 : sys.exit(\"Invalid number", "= [] with open (circuitFile, \"r\") as f: for line", "in circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append(\"current", "self.node4 = n4 class ccvs: def __init__(self, name, n1, n2,", "int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit(\"Please check the component values given.", "k, m, u, n\\nYou can also enter values in exponential", "name, n1, n2, val): self.name = name self.value = enggToMath(val)", "elif enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else:", "sys.argv[1] circuitFreq = 1e-100 circuitComponents = { RESISTOR: [], CAPACITOR:", "v in circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[VCVS]:", "line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency, if any if(line[:3]", "n2, val, phase=0): self.name = name self.value = enggToMath(val) self.node1", "specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source elif", "numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M", "= enggToMath(val) self.node1 = n1 self.node2 = n2 class inductor:", "number in engineer's format to math def enggToMath(enggNumber): try: return", "matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor Equations for l in", "# Extracting the data from the line lineTokens = line.split()", "source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2", "lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS", "= enggToMath(val) self.node1 = n1 self.node2 = n2 self.vSource =", "if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value", "CCVS: [], CCCS: [] } circuitNodes = [] # checking", "self.node1 = n1 self.node2 = n2 class capacitor: def __init__(self,", "VCVS: [], VCCS: [], CCVS: [], CCCS: [] } circuitNodes", "= n4 class ccvs: def __init__(self, name, n1, n2, vName,", "Erroneous Component Name else: sys.exit(\"Wrong Component Given. ABORT!\") try: circuitNodes.remove('GND')", "04/02/20 ------------------------------------- ''' # importing necessary libraries import sys import", "__init__(self, name, n1, n2, val, phase=0): self.name = name self.value", "also enter values in exponential format (eg. 1e3 = 1000).\")", "matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations", "print(\"Wrong file type!\") else: netlistFileLines = [] with open (circuitFile,", "circuitBody = netlistFileLines[identifier1+1:identifier2] for line in circuitBody: # Extracting the", "if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND':", "in circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2", "circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name)", "of the program) nodeNumbers = {circuitNodes[i]:i for i in range(len(circuitNodes))}", "the line lineTokens = line.split() # Appending new nodes to", "if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -=", "# Creating a dictionary with node names and their numbers", "Given. ABORT!\") try: circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes except:", "return base*1e6 else: sys.exit(\"Please check the component values given. Supported", "if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in", "elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5]))", "'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] =", "def getIndexIVS(vName): for i in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name == vName:", "!= 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents =", "r in circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value", "any if(line[:3] == '.ac'): circuitFreq = float(line.split()[2]) # Setting Angular", "circuitCurrents = [] # Formatting Output Data for v in", "values in exponential format (eg. 1e3 = 1000).\") if __name__", "len(lineTokens) == 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])))", "line in circuitBody: # Extracting the data from the line", "and NOT RMS values.\") except np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed! Please", "circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for i in circuitComponents[ICS]: if", "Modified on 04/02/20 ------------------------------------- ''' # importing necessary libraries import", "CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component Name", "float(line.split()[2]) # Setting Angular Frequency w w = 2*PI*circuitFreq try:", "Formatting Output Data for v in circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name)", "class vcvs: def __init__(self, name, n1, n2, n3, n4, val):", "= n2 self.node3 = n3 self.node4 = n4 class ccvs:", "n2 self.vSource = vName class cccs: def __init__(self, name, n1,", "= float(line.split()[2]) # Setting Angular Frequency w w = 2*PI*circuitFreq", "current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] =", "values.\") except np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed! Please check if you", "name self.value = enggToMath(val) self.node1 = n1 self.node2 = n2", "for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency, if any", "type if (not circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\") else: netlistFileLines =", "try: if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not", "!= 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x", "format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print(\"The values given above", "AMPLITUDE values and NOT RMS values.\") except np.linalg.LinAlgError: sys.exit(\"Singular Matrix", "vName class cccs: def __init__(self, name, n1, n2, vName, val):", "= len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and", "line lineTokens = line.split() # Appending new nodes to a", "matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2", "with open (circuitFile, \"r\") as f: for line in f.readlines():", "float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1],", "= \"R\" CAPACITOR = \"C\" INDUCTOR = \"L\" IVS =", "Angular Frequency w w = 2*PI*circuitFreq try: # Finding the", "if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 !=", "lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0],", "in the circuit!!\") # Creating a dictionary with node names", "c in circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0,", "l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0,", "resistor: def __init__(self, name, n1, n2, val): self.name = name", "if circuitComponents[IVS][i].name == vName: return i if cccs.node1 != 'GND':", "# CCVS Equations for i in range(len(circuitComponents[CCVS])): # Equation accounting", "self.name = name self.value = enggToMath(val) self.node1 = n1 self.node2", "!= 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value)", "CCCS Equations for cccs in circuitComponents[CCCS]: def getIndexIVS(vName): for i", "self.node3 = n3 self.node4 = n4 class vccs: def __init__(self,", "have entered the circuit definition correctly!\") except ValueError: sys.exit(\"Netlist does", "class currentSource: def __init__(self, name, n1, n2, val, phase=0): self.name", "base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] ==", "lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1],", "range(len(circuitComponents[IVS])): # Equation accounting for current through the source if", "Appending new nodes to a list try: if lineTokens[1] not", "\"I\" VCVS = \"E\" VCCS = \"G\" CCVS = \"H\"", "INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source elif lineTokens[0][0]", "sys.exit(\"Netlist does not abide to given format!\") except FileNotFoundError: sys.exit(\"Given", "# VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3],", "i in circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value", "circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\") else: netlistFileLines = [] with open", "if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations", "-1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value", "n1 self.node2 = n2 class voltageSource: def __init__(self, name, n1,", "try: circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes except: sys.exit(\"No ground", "netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line in", "CCVS Equations for i in range(len(circuitComponents[CCVS])): # Equation accounting for", "if(line[:3] == '.ac'): circuitFreq = float(line.split()[2]) # Setting Angular Frequency", "matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]]", "['GND'] + circuitNodes except: sys.exit(\"No ground node specified in the", "matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value #", "= -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] =", "lineTokens[3], lineTokens[4])) # Erroneous Component Name else: sys.exit(\"Wrong Component Given.", "= [] # Formatting Output Data for v in circuitComponents[IVS]:", "# Equation accounting for current through the source if circuitComponents[IVS][i].node1", "= n2 class inductor: def __init__(self, name, n1, n2, val):", "class voltageSource: def __init__(self, name, n1, n2, val, phase=0): self.name", "as pd # To improve readability CIRCUIT_START = \".circuit\" CIRCUIT_END", "Voltage Source elif lineTokens[0][0] == IVS: if len(lineTokens) == 5:", "RESISTOR = \"R\" CAPACITOR = \"C\" INDUCTOR = \"L\" IVS", "matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents = [] #", "if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 !=", "+= complex(0, -1.0/(w*l.value)) # Voltage Source Equations for i in", "= len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] == 'k': base =", "enggToMath(val) self.node1 = n1 self.node2 = n2 class voltageSource: def", "circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue", "RESISTOR: [], CAPACITOR: [], INDUCTOR: [], IVS: [], ICS: [],", "Equations for l in circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]]", "complex(0, w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value)", "range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name == vName: return i if cccs.node1 !=", "(eg. 1e3 = 1000).\") if __name__ == \"__main__\": # checking", "lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source if", "their numbers (to reduce the time taken by later parts", "if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0", "-1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current", "= int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] == 'u':", "lineTokens[3])) # Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2],", "Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: #", "== 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif", "== VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS", "# Finding the location of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START)", "lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source", "CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0]", "component values given. Supported engineer units are: M, k, m,", "if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 !=", "def __init__(self, name, n1, n2, val): self.name = name self.value", "circuitFreq == 1e-100: sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0],", "enggToMath(val) self.node1 = n1 self.node2 = n2 self.phase = float(phase)", "self.node4 = n4 class vccs: def __init__(self, name, n1, n2,", "== 'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit(\"Please check", "for c in circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] +=", "= n1 self.node2 = n2 self.phase = float(phase) class currentSource:", "matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180)", "circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0] ==", "AC Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) #", "= 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]]", "if len(lineTokens) == 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2],", "above are AMPLITUDE values and NOT RMS values.\") except np.linalg.LinAlgError:", "self.value = enggToMath(val) self.node1 = n1 self.node2 = n2 self.node3", "lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component Name else: sys.exit(\"Wrong", "if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB)", "AC Source if circuitFreq == 1e-100: sys.exit(\"Frequency of AC Source", "circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]]", "Source elif lineTokens[0][0] == ICS: if len(lineTokens) == 5: #", "in circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]]", "elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor", "Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] =", "# CCCS Equations for cccs in circuitComponents[CCCS]: def getIndexIVS(vName): for", "and their numbers (to reduce the time taken by later", "n1 self.node2 = n2 self.node3 = n3 self.node4 = n4", "[], INDUCTOR: [], IVS: [], ICS: [], VCVS: [], VCCS:", "= n3 self.node4 = n4 class vccs: def __init__(self, name,", "'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) #", "-1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0", "self.node2 = n2 self.phase = float(phase) class currentSource: def __init__(self,", "= \"F\" PI = np.pi # Classes for each circuit", "Equations for vccs in circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value", "pandas as pd # To improve readability CIRCUIT_START = \".circuit\"", "readability CIRCUIT_START = \".circuit\" CIRCUIT_END = \".end\" RESISTOR = \"R\"", "Convert a number in engineer's format to math def enggToMath(enggNumber):", "lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0] == VCCS:", "Equations for i in range(len(circuitComponents[IVS])): # Equation accounting for current", "'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x =", "output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print(\"The", "'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) #", "given. Supported engineer units are: M, k, m, u, n\\nYou", "w*c.value) # Inductor Equations for l in circuitComponents[INDUCTOR]: if l.node1", "return i if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 !=", "circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source elif lineTokens[0][0] ==", "for l in circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] +=", "(circuitFile, \"r\") as f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) #", "circuitBody: # Extracting the data from the line lineTokens =", "n1, n2, vName, val): self.name = name self.value = enggToMath(val)", "circuit component class resistor: def __init__(self, name, n1, n2, val):", "lineTokens[5])) # VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2],", "for i in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name == vName: return i", "self.node3 = n3 self.node4 = n4 class ccvs: def __init__(self,", "necessary libraries import sys import cmath import numpy as np", "try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents = [] # Formatting", "int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] == 'n': base", "VCCS = \"G\" CCVS = \"H\" CCCS = \"F\" PI", "self.value = enggToMath(val) self.node1 = n1 self.node2 = n2 self.phase", "a number in engineer's format to math def enggToMath(enggNumber): try:", "if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0", "= name self.value = enggToMath(val) self.node1 = n1 self.node2 =", "!= 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2", "= n2 self.vSource = vName # Convert a number in", "return base*1e3 # Milli elif enggNumber[lenEnggNumber-1] == 'm': base =", "circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes except: sys.exit(\"No ground node", "'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if", "= n4 class vccs: def __init__(self, name, n1, n2, n3,", "f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency, if any if(line[:3] == '.ac'):", "enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber = len(enggNumber) # Kilo", "lineTokens[3])) # Voltage Source elif lineTokens[0][0] == IVS: if len(lineTokens)", "through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0", "\".circuit\" CIRCUIT_END = \".end\" RESISTOR = \"R\" CAPACITOR = \"C\"", "INDUCTOR: [], IVS: [], ICS: [], VCVS: [], VCCS: [],", "lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous", "i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations for", "cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try:", "a dictionary with node names and their numbers (to reduce", "def __init__(self, name, n1, n2, val, phase=0): self.name = name", "vName: return i if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2", "# Current Source Equations for i in circuitComponents[ICS]: if i.node1", "complex(0, w*c.value) # Inductor Equations for l in circuitComponents[INDUCTOR]: if", "!= 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] =", "identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2]", "\"G\" CCVS = \"H\" CCCS = \"F\" PI = np.pi", "ccvs: def __init__(self, name, n1, n2, vName, val): self.name =", "Equation matrixM[0][0] = 1.0 # Resistor Equations for r in", "== 'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif", "circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND':", "\"H\" CCCS = \"F\" PI = np.pi # Classes for", "'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if", "1.0*circuitComponents[VCVS][i].value # CCVS Equations for i in range(len(circuitComponents[CCVS])): # Equation", "1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] =", "base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif enggNumber[lenEnggNumber-1] ==", "sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2,", "lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0],", "Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current", "== VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS", "(Jan-May 2020) Done by <NAME> (EE18B122) Created on 18/01/20 Last", "VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif", "program) nodeNumbers = {circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes =", "Matrix Formed! Please check if you have entered the circuit", "n2 class capacitor: def __init__(self, name, n1, n2, val): self.name", "for i in range(len(circuitComponents[CCVS])): # Equation accounting for current through", "as f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency,", "# Micro elif enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1]) return", "in range(len(circuitComponents[VCVS])): # Equation accounting for current through the source", "except: lenEnggNumber = len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] == 'k':", "the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if", "libraries import sys import cmath import numpy as np import", "# VCCS Equations for vccs in circuitComponents[VCCS]: if vccs.node1 !=", "Creating a dictionary with node names and their numbers (to", "+= 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]]", "self.value = enggToMath(val) self.node1 = n1 self.node2 = n2 self.vSource", "units are: M, k, m, u, n\\nYou can also enter", "lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0],", "-= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations for c", "if __name__ == \"__main__\": # checking number of command line", "circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 != 'GND':", "lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1],", "Please check if you have entered the circuit definition correctly!\")", "i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 != 'GND':", "if len(lineTokens) == 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2],", "[], IVS: [], ICS: [], VCVS: [], VCCS: [], CCVS:", "# CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3],", "Equation accounting for current through the source if circuitComponents[IVS][i].node1 !=", "len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating Matrices M and b", "self.node2 = n2 self.phase = float(phase) class vcvs: def __init__(self,", "Current'])) print(\"The values given above are AMPLITUDE values and NOT", "enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega", "r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value #", "= enggToMath(val) self.node1 = n1 self.node2 = n2 self.node3 =", "# Current Source elif lineTokens[0][0] == ICS: if len(lineTokens) ==", "in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print(\"The values", "entered the circuit definition correctly!\") except ValueError: sys.exit(\"Netlist does not", "base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] ==", "\"+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name) # Printing", "= n1 self.node2 = n2 self.vSource = vName class cccs:", "if enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 #", "# Inductor Equations for l in circuitComponents[INDUCTOR]: if l.node1 !=", "[] # checking if given netlist file is of correct", "ICS: [], VCVS: [], VCCS: [], CCVS: [], CCCS: []", "Source if circuitFreq == 1e-100: sys.exit(\"Frequency of AC Source not", "lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) #", "matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value #", "Data for v in circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name) for v", "matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS", "l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0,", "CCCS: [] } circuitNodes = [] # checking if given", "try: # Finding the location of the identifiers identifier1 =", "list try: if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2]", "= int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] == 'M':", "n2 self.node3 = n3 self.node4 = n4 class ccvs: def", "circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name)", "lenEnggNumber = len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] == 'k': base", "[], ICS: [], VCVS: [], VCCS: [], CCVS: [], CCCS:", "if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] +=", "!= 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value))", "self.node2 = n2 class voltageSource: def __init__(self, name, n1, n2,", "= cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for i in", "n2, val): self.name = name self.value = enggToMath(val) self.node1 =", "'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] =", "'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM, matrixB) circuitCurrents = []", "lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0],", "matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -=", "# checking if given netlist file is of correct type", "Equations for cccs in circuitComponents[CCCS]: def getIndexIVS(vName): for i in", "circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append(\"current in", "= \".end\" RESISTOR = \"R\" CAPACITOR = \"C\" INDUCTOR =", "n1 self.node2 = n2 self.phase = float(phase) class vcvs: def", "Assignment 2 - EE2703 (Jan-May 2020) Done by <NAME> (EE18B122)", "== 'm': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif", "a list try: if lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if", "# DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) ==", "given above are AMPLITUDE values and NOT RMS values.\") except", "in circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value)", "== RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor elif lineTokens[0][0]", "except np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed! Please check if you have", "'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1]", "len(lineTokens) == 6: # AC Source if circuitFreq == 1e-100:", "Nano elif enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9", "in exponential format (eg. 1e3 = 1000).\") if __name__ ==", "the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody =", "if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue #", "= -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) #", "\"+v.name) # Printing output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage", "source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2", "Printing output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current']))", "== \"__main__\": # checking number of command line arguments if", "= -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] =", "!= 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value)", "IVS = \"V\" ICS = \"I\" VCVS = \"E\" VCCS", "2 - EE2703 (Jan-May 2020) Done by <NAME> (EE18B122) Created", "through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0", "-= 1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]]", "Creating Matrices M and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex)", "!= 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] =", "\"r\") as f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting", "Matrices M and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB", "w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]]", "= n1 self.node2 = n2 self.phase = float(phase) class vcvs:", "else: netlistFileLines = [] with open (circuitFile, \"r\") as f:", "n2 self.node3 = n3 self.node4 = n4 class vccs: def", "circuitFile = sys.argv[1] circuitFreq = 1e-100 circuitComponents = { RESISTOR:", "'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations for i in", "in \"+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name) #", "Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) #", "'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 !=", "np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed! Please check if you have entered", "base*1e6 else: sys.exit(\"Please check the component values given. Supported engineer", "ABORT!\") try: circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes except: sys.exit(\"No", "matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -=", "== 'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif", "in circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if", "circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2", "matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations for i in range(len(circuitComponents[CCVS])):", "math def enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber = len(enggNumber)", "elif enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 #", "!= 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i]", "if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] +=", "file type!\") else: netlistFileLines = [] with open (circuitFile, \"r\")", "i in range(len(circuitComponents[VCVS])): # Equation accounting for current through the", "class cccs: def __init__(self, name, n1, n2, vName, val): self.name", "matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs in circuitComponents[CCCS]: def getIndexIVS(vName):", "numpy as np import pandas as pd # To improve", "# VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3],", "if you have entered the circuit definition correctly!\") except ValueError:", "CIRCUIT_START = \".circuit\" CIRCUIT_END = \".end\" RESISTOR = \"R\" CAPACITOR", "self.node2 = n2 self.node3 = n3 self.node4 = n4 class", "= np.linalg.solve(matrixM, matrixB) circuitCurrents = [] # Formatting Output Data", "netlist file is of correct type if (not circuitFile.endswith(\".netlist\")): print(\"Wrong", "importing necessary libraries import sys import cmath import numpy as", "5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens)", "# Resistor Equations for r in circuitComponents[RESISTOR]: if r.node1 !=", "arguments!\") else: try: circuitFile = sys.argv[1] circuitFreq = 1e-100 circuitComponents", "import pandas as pd # To improve readability CIRCUIT_START =", "print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print(\"The values given above are", "EE2703 (Jan-May 2020) Done by <NAME> (EE18B122) Created on 18/01/20", "1000).\") if __name__ == \"__main__\": # checking number of command", "for v in circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name) for v in", "/ Current'])) print(\"The values given above are AMPLITUDE values and", "lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0] == VCVS:", "Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value,", "= np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0] = 1.0 #", "\"E\" VCCS = \"G\" CCVS = \"H\" CCCS = \"F\"", "n1 self.node2 = n2 self.vSource = vName class cccs: def", "\"L\" IVS = \"V\" ICS = \"I\" VCVS = \"E\"", "sys.exit(\"Singular Matrix Formed! Please check if you have entered the", "circuitComponents[RESISTOR]: if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -=", "taken by later parts of the program) nodeNumbers = {circuitNodes[i]:i", "circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0]", "!= 'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations for i", "Component Name else: sys.exit(\"Wrong Component Given. ABORT!\") try: circuitNodes.remove('GND') circuitNodes", "vccs: def __init__(self, name, n1, n2, n3, n4, val): self.name", "[], CCVS: [], CCCS: [] } circuitNodes = [] #", "''' ------------------------------------- Assignment 2 - EE2703 (Jan-May 2020) Done by", "-= complex(0, -1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0,", "in engineer's format to math def enggToMath(enggNumber): try: return float(enggNumber)", "Name else: sys.exit(\"Wrong Component Given. ABORT!\") try: circuitNodes.remove('GND') circuitNodes =", "INDUCTOR = \"L\" IVS = \"V\" ICS = \"I\" VCVS", "lineTokens[0][0] == ICS: if len(lineTokens) == 5: # DC Source", "# CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3],", "in range(len(circuitComponents[IVS])): # Equation accounting for current through the source", "circuitComponents[IVS][i].name == vName: return i if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value", "for line in circuitBody: # Extracting the data from the", "= i.value # VCVS Equations for i in range(len(circuitComponents[VCVS])): #", "# checking number of command line arguments if len(sys.argv)!=2 :", "== 1e-100: sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1],", "sys import cmath import numpy as np import pandas as", "matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations for c in circuitComponents[CAPACITOR]:", "1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] +=", "cccs: def __init__(self, name, n1, n2, vName, val): self.name =", "matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor", "range(len(circuitComponents[VCVS])): # Equation accounting for current through the source if", "-1.0/(w*l.value)) # Voltage Source Equations for i in range(len(circuitComponents[IVS])): #", "= float(phase) class vcvs: def __init__(self, name, n1, n2, n3,", "[], VCVS: [], VCCS: [], CCVS: [], CCCS: [] }", "base*1e3 # Milli elif enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1])", "matrixB = np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0] = 1.0", "= 1000).\") if __name__ == \"__main__\": # checking number of", "in circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append(\"current", "!= 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] =", "IndexError: continue # Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1],", "= [] # checking if given netlist file is of", "int(enggNumber[0:lenEnggNumber-1]) return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] == 'M': base", "circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC", "= 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS", "complex(0, -1.0/(w*l.value)) # Voltage Source Equations for i in range(len(circuitComponents[IVS])):", "= 2*PI*circuitFreq try: # Finding the location of the identifiers", "'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor Equations", "reduce the time taken by later parts of the program)", "# importing necessary libraries import sys import cmath import numpy", "for current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i]", "VCVS Equations for i in range(len(circuitComponents[VCVS])): # Equation accounting for", "matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i]", "-1.0/(w*l.value)) matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node2]] -= complex(0, -1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]]", "nodeNumbers = {circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes = len(circuitNodes)", "= np.pi # Classes for each circuit component class resistor:", "= n2 class voltageSource: def __init__(self, name, n1, n2, val,", "= n2 self.phase = float(phase) class currentSource: def __init__(self, name,", "class ccvs: def __init__(self, name, n1, n2, vName, val): self.name", "Extracting the data from the line lineTokens = line.split() #", "== 1e-100: sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1],", "1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] =", "'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0", "lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0],", "n4, val): self.name = name self.value = enggToMath(val) self.node1 =", "for vccs in circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value", "Formed! Please check if you have entered the circuit definition", "(to reduce the time taken by later parts of the", "command line arguments if len(sys.argv)!=2 : sys.exit(\"Invalid number of arguments!\")", "vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs", "M, k, m, u, n\\nYou can also enter values in", "check if you have entered the circuit definition correctly!\") except", "u, n\\nYou can also enter values in exponential format (eg.", "CCVS = \"H\" CCCS = \"F\" PI = np.pi #", "# Nano elif enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1]) return", "2020) Done by <NAME> (EE18B122) Created on 18/01/20 Last Modified", "inductor: def __init__(self, name, n1, n2, val): self.name = name", "not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2])", "dictionary with node names and their numbers (to reduce the", "-= complex(0, w*c.value) if c.node2 != 'GND': matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node1]] -= complex(0,", "-1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage Source Equations for", "DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6:", "for i in circuitComponents[ICS]: if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] =", "To improve readability CIRCUIT_START = \".circuit\" CIRCUIT_END = \".end\" RESISTOR", "new nodes to a list try: if lineTokens[1] not in", "with node names and their numbers (to reduce the time", "CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4]))", "= vName class cccs: def __init__(self, name, n1, n2, vName,", "complex(0, -1.0/(w*l.value)) if l.node2 != 'GND': matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value))", "source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2", "circuitFreq = 1e-100 circuitComponents = { RESISTOR: [], CAPACITOR: [],", "through the source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0", "enggToMath(val) self.node1 = n1 self.node2 = n2 self.node3 = n3", "f: for line in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency, if", "n2, vName, val): self.name = name self.value = enggToMath(val) self.node1", "in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor if lineTokens[0][0]", "getIndexIVS(vName): for i in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name == vName: return", "Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: #", "Inductor Equations for l in circuitComponents[INDUCTOR]: if l.node1 != 'GND':", "in circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0, -1.0/(w*l.value))", "- EE2703 (Jan-May 2020) Done by <NAME> (EE18B122) Created on", "netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line in circuitBody: # Extracting", "Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) #", "circuit!!\") # Creating a dictionary with node names and their", "if (not circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\") else: netlistFileLines = []", "1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations", "n1 self.node2 = n2 class capacitor: def __init__(self, name, n1,", "currentSource: def __init__(self, name, n1, n2, val, phase=0): self.name =", "in \"+v.name) # Printing output in table format print(pd.DataFrame(x, circuitNodes+circuitCurrents,", "n2 class inductor: def __init__(self, name, n1, n2, val): self.name", "= \"G\" CCVS = \"H\" CCCS = \"F\" PI =", "__init__(self, name, n1, n2, val): self.name = name self.value =", "Frequency w w = 2*PI*circuitFreq try: # Finding the location", "# GND Equation matrixM[0][0] = 1.0 # Resistor Equations for", "enter values in exponential format (eg. 1e3 = 1000).\") if", "node names and their numbers (to reduce the time taken", "format (eg. 1e3 = 1000).\") if __name__ == \"__main__\": #", "val, phase=0): self.name = name self.value = enggToMath(val) self.node1 =", "identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for", "circuitNodes = [] # checking if given netlist file is", "# Classes for each circuit component class resistor: def __init__(self,", "for i in range(len(circuitComponents[IVS])): # Equation accounting for current through", "ValueError: sys.exit(\"Netlist does not abide to given format!\") except FileNotFoundError:", "enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano", "n2 self.phase = float(phase) class currentSource: def __init__(self, name, n1,", "lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0],", "component class resistor: def __init__(self, name, n1, n2, val): self.name", "np.pi # Classes for each circuit component class resistor: def", "lineTokens = line.split() # Appending new nodes to a list", "given netlist file is of correct type if (not circuitFile.endswith(\".netlist\")):", "import sys import cmath import numpy as np import pandas", "netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency, if any if(line[:3] == '.ac'): circuitFreq", "= 1.0 # Resistor Equations for r in circuitComponents[RESISTOR]: if", "lineTokens[5])) # CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2],", "circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 !=", "PI = np.pi # Classes for each circuit component class", "len(sys.argv)!=2 : sys.exit(\"Invalid number of arguments!\") else: try: circuitFile =", "enggToMath(val) self.node1 = n1 self.node2 = n2 class capacitor: def", "= n2 self.phase = float(phase) class vcvs: def __init__(self, name,", "of arguments!\") else: try: circuitFile = sys.argv[1] circuitFreq = 1e-100", "Output Data for v in circuitComponents[IVS]: circuitCurrents.append(\"current in \"+v.name) for", "of correct type if (not circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\") else:", "circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes: circuitNodes.append(lineTokens[2]) except IndexError:", ": sys.exit(\"Invalid number of arguments!\") else: try: circuitFile = sys.argv[1]", "== CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0]", "numbers (to reduce the time taken by later parts of", "= -1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value #", "-1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value", "# VCVS Equations for i in range(len(circuitComponents[VCVS])): # Equation accounting", "class vccs: def __init__(self, name, n1, n2, n3, n4, val):", "self.node2 = n2 class capacitor: def __init__(self, name, n1, n2,", "+= complex(0, w*c.value) # Inductor Equations for l in circuitComponents[INDUCTOR]:", "pd # To improve readability CIRCUIT_START = \".circuit\" CIRCUIT_END =", "1e-100: sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2],", "lineTokens[1] not in circuitNodes: circuitNodes.append(lineTokens[1]) if lineTokens[2] not in circuitNodes:", "circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0] == INDUCTOR:", "x = np.linalg.solve(matrixM, matrixB) circuitCurrents = [] # Formatting Output", "float(lineTokens[4])/2, lineTokens[5])) # Current Source elif lineTokens[0][0] == ICS: if", "'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i] = 1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] =", "n3, n4, val): self.name = name self.value = enggToMath(val) self.node1", "n2 class voltageSource: def __init__(self, name, n1, n2, val, phase=0):", "!= 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i]", "class capacitor: def __init__(self, name, n1, n2, val): self.name =", "to given format!\") except FileNotFoundError: sys.exit(\"Given file does not exist!\")", "else: sys.exit(\"Wrong Component Given. ABORT!\") try: circuitNodes.remove('GND') circuitNodes = ['GND']", "data from the line lineTokens = line.split() # Appending new", "1.0 # Resistor Equations for r in circuitComponents[RESISTOR]: if r.node1", "if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for", "for each circuit component class resistor: def __init__(self, name, n1,", "cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for i in circuitComponents[ICS]:", "[] } circuitNodes = [] # checking if given netlist", "in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS = len(circuitComponents[IVS])+len(circuitComponents[VCVS])+len(circuitComponents[CCVS]) # Creating", "except ValueError: sys.exit(\"Netlist does not abide to given format!\") except", "circuitFreq == 1e-100: sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0],", "n1 self.node2 = n2 class inductor: def __init__(self, name, n1,", "+ circuitNodes except: sys.exit(\"No ground node specified in the circuit!!\")", "n1, n2, val, phase=0): self.name = name self.value = enggToMath(val)", "VCCS Equations for vccs in circuitComponents[VCCS]: if vccs.node1 != 'GND':", "\"R\" CAPACITOR = \"C\" INDUCTOR = \"L\" IVS = \"V\"", "w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor Equations for l", "# AC Source if circuitFreq == 1e-100: sys.exit(\"Frequency of AC", "5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens)", "return base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] == 'M': base =", "parts of the program) nodeNumbers = {circuitNodes[i]:i for i in", "n3 self.node4 = n4 class vccs: def __init__(self, name, n1,", "Voltage Source Equations for i in range(len(circuitComponents[IVS])): # Equation accounting", "= -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS", "# Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]] = +1.0 matrixB[numNodes+i]", "'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0", "table format print(pd.DataFrame(x, circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print(\"The values given", "= n1 self.node2 = n2 class capacitor: def __init__(self, name,", "== 5: # DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif", "np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0] = 1.0 # Resistor", "matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node1]] -= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage", "l in circuitComponents[INDUCTOR]: if l.node1 != 'GND': matrixM[nodeNumbers[l.node1]][nodeNumbers[l.node1]] += complex(0,", "-= complex(0, -1.0/(w*l.value)) matrixM[nodeNumbers[l.node2]][nodeNumbers[l.node2]] += complex(0, -1.0/(w*l.value)) # Voltage Source", "if i.node1 != 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 !=", "(not circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\") else: netlistFileLines = [] with", "Capacitor Equations for c in circuitComponents[CAPACITOR]: if c.node1 != 'GND':", "= enggToMath(val) self.node1 = n1 self.node2 = n2 class voltageSource:", "# Mega elif enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1]) return", "lineTokens[3])) # Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2],", "Mega elif enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6", "!= 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node2]] += 1/r.value # Capacitor", "continue # Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2],", "[], CAPACITOR: [], INDUCTOR: [], IVS: [], ICS: [], VCVS:", "== ICS: if len(lineTokens) == 5: # DC Source circuitComponents[ICS].append(currentSource(lineTokens[0],", "n1, n2, n3, n4, val): self.name = name self.value =", "Source elif lineTokens[0][0] == IVS: if len(lineTokens) == 5: #", "n1 self.node2 = n2 self.vSource = vName # Convert a", "Component Given. ABORT!\") try: circuitNodes.remove('GND') circuitNodes = ['GND'] + circuitNodes", "= ['GND'] + circuitNodes except: sys.exit(\"No ground node specified in", "by later parts of the program) nodeNumbers = {circuitNodes[i]:i for", "print(\"The values given above are AMPLITUDE values and NOT RMS", "RMS values.\") except np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed! Please check if", "float(enggNumber) except: lenEnggNumber = len(enggNumber) # Kilo if enggNumber[lenEnggNumber-1] ==", "self.value = enggToMath(val) self.node1 = n1 self.node2 = n2 class", "import numpy as np import pandas as pd # To", "base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] == 'n': base = int(enggNumber[0:lenEnggNumber-1])", "__name__ == \"__main__\": # checking number of command line arguments", "in circuitBody: # Extracting the data from the line lineTokens", "AC Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) #", "self.node1 = n1 self.node2 = n2 self.node3 = n3 self.node4", "'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs in circuitComponents[CCCS]:", "= \"H\" CCCS = \"F\" PI = np.pi # Classes", "n4 class ccvs: def __init__(self, name, n1, n2, vName, val):", "matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0", "circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]]", "int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif enggNumber[lenEnggNumber-1] == 'm': base", "on 18/01/20 Last Modified on 04/02/20 ------------------------------------- ''' # importing", "# Milli elif enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1]) return", "== INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source elif", "complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor Equations for", "'M': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit(\"Please check the", "n2 self.phase = float(phase) class vcvs: def __init__(self, name, n1,", "= n3 self.node4 = n4 class ccvs: def __init__(self, name,", "# Appending new nodes to a list try: if lineTokens[1]", "sys.exit(\"Please check the component values given. Supported engineer units are:", "1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -=", "Last Modified on 04/02/20 ------------------------------------- ''' # importing necessary libraries", "matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value", "current through the source if circuitComponents[VCVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[CCVS][i].node1]][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] =", "cmath import numpy as np import pandas as pd #", "!= 'GND': matrixB[nodeNumbers[i.node1]] = -1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]]", "of AC Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5]))", "v in circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name) # Printing output in", "!= 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node1]][numNodes+len(circuitComponents[IVS])+i] = 1.0 if circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i]", "in range(len(circuitComponents[CCVS])): # Equation accounting for current through the source", "on 04/02/20 ------------------------------------- ''' # importing necessary libraries import sys", "6: # AC Source if circuitFreq == 1e-100: sys.exit(\"Frequency of", "circuitNodes.append(lineTokens[2]) except IndexError: continue # Resistor if lineTokens[0][0] == RESISTOR:", "matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations for i in range(len(circuitComponents[VCVS])):", "self.node2 = n2 self.vSource = vName # Convert a number", "+= 1/r.value # Capacitor Equations for c in circuitComponents[CAPACITOR]: if", "circuitComponents[CAPACITOR]: if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]]", "from the line lineTokens = line.split() # Appending new nodes", "Equation accounting for current through the source if circuitComponents[VCVS][i].node1 !=", "Getting frequency, if any if(line[:3] == '.ac'): circuitFreq = float(line.split()[2])", "if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value", "correctly!\") except ValueError: sys.exit(\"Netlist does not abide to given format!\")", "identifier2 = netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line in circuitBody:", "elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) #", "i in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name == vName: return i if", "= int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit(\"Please check the component values", "vccs in circuitComponents[VCCS]: if vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if", "Milli elif enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3", "= n1 self.node2 = n2 self.vSource = vName # Convert", "is of correct type if (not circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\")", "= \"I\" VCVS = \"E\" VCCS = \"G\" CCVS =", "accounting for current through the source if circuitComponents[VCVS][i].node1 != 'GND':", "lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0] == CCCS: circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1],", "matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs in circuitComponents[VCCS]:", "not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif", "\"F\" PI = np.pi # Classes for each circuit component", "-1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs in", "# Voltage Source elif lineTokens[0][0] == IVS: if len(lineTokens) ==", "# Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3]))", "enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro", "exponential format (eg. 1e3 = 1000).\") if __name__ == \"__main__\":", "circuitNodes+circuitCurrents, columns=['Voltage / Current'])) print(\"The values given above are AMPLITUDE", "Current Source elif lineTokens[0][0] == ICS: if len(lineTokens) == 5:", "''' # importing necessary libraries import sys import cmath import", "matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]]", "elif lineTokens[0][0] == IVS: if len(lineTokens) == 5: # DC", "Equations for i in range(len(circuitComponents[VCVS])): # Equation accounting for current", "matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND': matrixM[nodeNumbers[cccs.node2]][numNodes+getIndexIVS(cccs.vSource)]+=cccs.value try: x = np.linalg.solve(matrixM,", "nodes to a list try: if lineTokens[1] not in circuitNodes:", "IVS: [], ICS: [], VCVS: [], VCCS: [], CCVS: [],", "lineTokens[5])) # Current Source elif lineTokens[0][0] == ICS: if len(lineTokens)", "NOT RMS values.\") except np.linalg.LinAlgError: sys.exit(\"Singular Matrix Formed! Please check", "+= complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2 !=", "= \".circuit\" CIRCUIT_END = \".end\" RESISTOR = \"R\" CAPACITOR =", "CIRCUIT_END = \".end\" RESISTOR = \"R\" CAPACITOR = \"C\" INDUCTOR", "elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) #", "== vName: return i if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if", "enggToMath(val) self.node1 = n1 self.node2 = n2 self.vSource = vName", "elif lineTokens[0][0] == ICS: if len(lineTokens) == 5: # DC", "n4 class vccs: def __init__(self, name, n1, n2, n3, n4,", "circuitFreq = float(line.split()[2]) # Setting Angular Frequency w w =", "Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS", "1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value", "matrixB[numNodes+i] = cmath.rect(circuitComponents[IVS][i].value, circuitComponents[IVS][i].phase*PI/180) # Current Source Equations for i", "matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if r.node2 != 'GND': matrixM[nodeNumbers[r.node2]][nodeNumbers[r.node1]] -= 1/r.value", "float(lineTokens[4]))) elif len(lineTokens) == 6: # AC Source if circuitFreq", "elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5]))", "base = int(enggNumber[0:lenEnggNumber-1]) return base*1e6 else: sys.exit(\"Please check the component", "name, n1, n2, n3, n4, val): self.name = name self.value", "phase=0): self.name = name self.value = enggToMath(val) self.node1 = n1", "Resistor Equations for r in circuitComponents[RESISTOR]: if r.node1 != 'GND':", "-1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations for i in", "matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][nodeNumbers[circuitComponents[CCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations for", "values given. Supported engineer units are: M, k, m, u,", "= n2 self.vSource = vName class cccs: def __init__(self, name,", "later parts of the program) nodeNumbers = {circuitNodes[i]:i for i", "2*PI*circuitFreq try: # Finding the location of the identifiers identifier1", "= netlistFileLines.index(CIRCUIT_END) circuitBody = netlistFileLines[identifier1+1:identifier2] for line in circuitBody: #", "VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4],", "if c.node1 != 'GND': matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node1]] += complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -=", "specified in the circuit!!\") # Creating a dictionary with node", "def enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber = len(enggNumber) #", "!= 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs in", "m, u, n\\nYou can also enter values in exponential format", "= \"V\" ICS = \"I\" VCVS = \"E\" VCCS =", "r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value if", "# DC Source circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) ==", "matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value matrixM[nodeNumbers[vccs.node3]][nodeNumbers[vccs.node3]]+=vccs.value # CCCS Equations for cccs in circuitComponents[CCCS]: def", "for current through the source if circuitComponents[IVS][i].node1 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node1]][numNodes+i]", "lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # VCCS elif lineTokens[0][0] ==", "netlistFileLines = [] with open (circuitFile, \"r\") as f: for", "= netlistFileLines[identifier1+1:identifier2] for line in circuitBody: # Extracting the data", "lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0] ==", "circuit definition correctly!\") except ValueError: sys.exit(\"Netlist does not abide to", "= enggToMath(val) self.node1 = n1 self.node2 = n2 class capacitor:", "lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Voltage Source", "== CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif", "import cmath import numpy as np import pandas as pd", "if r.node1 != 'GND': matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node1]] += 1/r.value matrixM[nodeNumbers[r.node1]][nodeNumbers[r.node2]] -= 1/r.value", "__init__(self, name, n1, n2, n3, n4, val): self.name = name", "Micro elif enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6", "circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name) # Printing output in table format", "elif enggNumber[lenEnggNumber-1] == 'm': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 #", "CAPACITOR = \"C\" INDUCTOR = \"L\" IVS = \"V\" ICS", "Classes for each circuit component class resistor: def __init__(self, name,", "def __init__(self, name, n1, n2, n3, n4, val): self.name =", "= -1.0 matrixM[numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i][numNodes+len(circuitComponents[IVS])+len(circuitComponents[VCVS])+i] = -1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs", "improve readability CIRCUIT_START = \".circuit\" CIRCUIT_END = \".end\" RESISTOR =", "self.node2 = n2 self.vSource = vName class cccs: def __init__(self,", "np.complex) # GND Equation matrixM[0][0] = 1.0 # Resistor Equations", "line.split() # Appending new nodes to a list try: if", "lineTokens[2], lineTokens[3])) # Inductor elif lineTokens[0][0] == INDUCTOR: circuitComponents[INDUCTOR].append(inductor(lineTokens[0], lineTokens[1],", "self.phase = float(phase) class vcvs: def __init__(self, name, n1, n2,", "GND Equation matrixM[0][0] = 1.0 # Resistor Equations for r", "base*1e-9 # Mega elif enggNumber[lenEnggNumber-1] == 'M': base = int(enggNumber[0:lenEnggNumber-1])", "circuitComponents[CCCS].append(cccs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component Name else:", "= 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] =", "18/01/20 Last Modified on 04/02/20 ------------------------------------- ''' # importing necessary", "= int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] == 'n':", "cccs in circuitComponents[CCCS]: def getIndexIVS(vName): for i in range(len(circuitComponents[IVS])): if", "Kilo if enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3", "i if cccs.node1 != 'GND': matrixM[nodeNumbers[cccs.node1]][numNodes+getIndexIVS(cccs.vSource)]-=cccs.value if cccs.node2 != 'GND':", "complex(0, w*c.value) matrixM[nodeNumbers[c.node1]][nodeNumbers[c.node2]] -= complex(0, w*c.value) if c.node2 != 'GND':", "\"C\" INDUCTOR = \"L\" IVS = \"V\" ICS = \"I\"", "capacitor: def __init__(self, name, n1, n2, val): self.name = name", "= vName # Convert a number in engineer's format to", "self.phase = float(phase) class currentSource: def __init__(self, name, n1, n2,", "1.0 if circuitComponents[IVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary", "sys.exit(\"No ground node specified in the circuit!!\") # Creating a", "= enggToMath(val) self.node1 = n1 self.node2 = n2 self.phase =", "-1.0*circuitComponents[CCVS][i].value # VCCS Equations for vccs in circuitComponents[VCCS]: if vccs.node1", "DC Source circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6:", "lineTokens[4], lineTokens[5])) # CCVS elif lineTokens[0][0] == CCVS: circuitComponents[CCVS].append(ccvs(lineTokens[0], lineTokens[1],", "# Kilo if enggNumber[lenEnggNumber-1] == 'k': base = int(enggNumber[0:lenEnggNumber-1]) return", "= n1 self.node2 = n2 class voltageSource: def __init__(self, name,", "Done by <NAME> (EE18B122) Created on 18/01/20 Last Modified on", "not abide to given format!\") except FileNotFoundError: sys.exit(\"Given file does", "{ RESISTOR: [], CAPACITOR: [], INDUCTOR: [], IVS: [], ICS:", "lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # Current Source elif lineTokens[0][0] == ICS:", "<NAME> (EE18B122) Created on 18/01/20 Last Modified on 04/02/20 -------------------------------------", "VCCS elif lineTokens[0][0] == VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4],", "i in range(len(circuitComponents[CCVS])): # Equation accounting for current through the", "format to math def enggToMath(enggNumber): try: return float(enggNumber) except: lenEnggNumber", "int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] == 'u': base", "1e3 = 1000).\") if __name__ == \"__main__\": # checking number", "circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2, lineTokens[5])) # VCVS elif lineTokens[0][0] ==", "np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex) # GND Equation matrixM[0][0] =", "self.node1 = n1 self.node2 = n2 self.phase = float(phase) class", "return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] == 'u': base =", "the location of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2 =", "# Creating Matrices M and b matrixM = np.zeros((numNodes+numVS, numNodes+numVS),", "[], VCCS: [], CCVS: [], CCCS: [] } circuitNodes =", "= \"E\" VCCS = \"G\" CCVS = \"H\" CCCS =", "lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4])) # CCCS elif lineTokens[0][0] == CCCS:", "if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS Equations", "each circuit component class resistor: def __init__(self, name, n1, n2,", "the time taken by later parts of the program) nodeNumbers", "base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-6 # Nano elif enggNumber[lenEnggNumber-1] ==", "node specified in the circuit!!\") # Creating a dictionary with", "v in circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[CCVS]:", "'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]] = -1.0", "definition correctly!\") except ValueError: sys.exit(\"Netlist does not abide to given", "np import pandas as pd # To improve readability CIRCUIT_START", "Finding the location of the identifiers identifier1 = netlistFileLines.index(CIRCUIT_START) identifier2", "np.linalg.solve(matrixM, matrixB) circuitCurrents = [] # Formatting Output Data for", "= 1.0*circuitComponents[VCVS][i].value # CCVS Equations for i in range(len(circuitComponents[CCVS])): #", "'k': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e3 # Milli elif enggNumber[lenEnggNumber-1]", "circuitComponents[VCVS][i].node2 != 'GND': matrixM[nodeNumbers[circuitComponents[VCVS][i].node2]][numNodes+len(circuitComponents[IVS])+i] = -1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node1]] = 1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node2]]", "'.ac'): circuitFreq = float(line.split()[2]) # Setting Angular Frequency w w", "for cccs in circuitComponents[CCCS]: def getIndexIVS(vName): for i in range(len(circuitComponents[IVS])):", "\"+v.name) for v in circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name) for v", "matrixM[nodeNumbers[circuitComponents[IVS][i].node2]][numNodes+i] = -1.0 # Auxiliary Equations matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node1]] = -1.0 matrixM[numNodes+i][nodeNumbers[circuitComponents[IVS][i].node2]]", "{circuitNodes[i]:i for i in range(len(circuitNodes))} numNodes = len(circuitNodes) numVS =", "\"__main__\": # checking number of command line arguments if len(sys.argv)!=2", "lineTokens[0][0] == IVS: if len(lineTokens) == 5: # DC Source", "-1.0 matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node3]] = -1.0*circuitComponents[VCVS][i].value matrixM[numNodes+len(circuitComponents[IVS])+i][nodeNumbers[circuitComponents[VCVS][i].node4]] = 1.0*circuitComponents[VCVS][i].value # CCVS Equations", "circuitComponents[VCVS]: circuitCurrents.append(\"current in \"+v.name) for v in circuitComponents[CCVS]: circuitCurrents.append(\"current in", "# Getting frequency, if any if(line[:3] == '.ac'): circuitFreq =", "except: sys.exit(\"No ground node specified in the circuit!!\") # Creating", "sys.exit(\"Frequency of AC Source not specified!!\") circuitComponents[ICS].append(currentSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4])/2,", "lineTokens[2], lineTokens[3], lineTokens[4])) # Erroneous Component Name else: sys.exit(\"Wrong Component", "lineTokens[5])) # VCVS elif lineTokens[0][0] == VCVS: circuitComponents[VCVS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2],", "# Capacitor Equations for c in circuitComponents[CAPACITOR]: if c.node1 !=", "== '.ac'): circuitFreq = float(line.split()[2]) # Setting Angular Frequency w", "in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name == vName: return i if cccs.node1", "= float(phase) class currentSource: def __init__(self, name, n1, n2, val,", "-1*i.value if i.node2 != 'GND': matrixB[nodeNumbers[i.node2]] = i.value # VCVS", "netlistFileLines[identifier1+1:identifier2] for line in circuitBody: # Extracting the data from", "if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3])) # Capacitor", "lineTokens[4])) # Erroneous Component Name else: sys.exit(\"Wrong Component Given. ABORT!\")", "correct type if (not circuitFile.endswith(\".netlist\")): print(\"Wrong file type!\") else: netlistFileLines", "enggToMath(val) self.node1 = n1 self.node2 = n2 class inductor: def", "-= complex(0, w*c.value) matrixM[nodeNumbers[c.node2]][nodeNumbers[c.node2]] += complex(0, w*c.value) # Inductor Equations", "= n2 self.node3 = n3 self.node4 = n4 class vccs:", "self.vSource = vName # Convert a number in engineer's format", "b matrixM = np.zeros((numNodes+numVS, numNodes+numVS), np.complex) matrixB = np.zeros((numNodes+numVS,), np.complex)", "line arguments if len(sys.argv)!=2 : sys.exit(\"Invalid number of arguments!\") else:", "base*1e-3 # Micro elif enggNumber[lenEnggNumber-1] == 'u': base = int(enggNumber[0:lenEnggNumber-1])", "abide to given format!\") except FileNotFoundError: sys.exit(\"Given file does not", "circuitComponents = { RESISTOR: [], CAPACITOR: [], INDUCTOR: [], IVS:", "circuitComponents[IVS].append(voltageSource(lineTokens[0], lineTokens[1], lineTokens[2], float(lineTokens[4]))) elif len(lineTokens) == 6: # AC", "n1 self.node2 = n2 self.phase = float(phase) class currentSource: def", "in f.readlines(): netlistFileLines.append(line.split('#')[0].split('\\n')[0]) # Getting frequency, if any if(line[:3] ==", "# Capacitor elif lineTokens[0][0] == CAPACITOR: circuitComponents[CAPACITOR].append(capacitor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3]))", "= n1 self.node2 = n2 self.node3 = n3 self.node4 =", "'m': base = int(enggNumber[0:lenEnggNumber-1]) return base*1e-3 # Micro elif enggNumber[lenEnggNumber-1]", "ground node specified in the circuit!!\") # Creating a dictionary", "# Resistor if lineTokens[0][0] == RESISTOR: circuitComponents[RESISTOR].append(resistor(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3]))", "are: M, k, m, u, n\\nYou can also enter values", "VCCS: circuitComponents[VCCS].append(vcvs(lineTokens[0], lineTokens[1], lineTokens[2], lineTokens[3], lineTokens[4], lineTokens[5])) # CCVS elif", "in circuitComponents[CCVS]: circuitCurrents.append(\"current in \"+v.name) # Printing output in table", "# Erroneous Component Name else: sys.exit(\"Wrong Component Given. ABORT!\") try:", "in circuitComponents[CCCS]: def getIndexIVS(vName): for i in range(len(circuitComponents[IVS])): if circuitComponents[IVS][i].name", "vccs.node1 != 'GND': matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node4]]+=vccs.value matrixM[nodeNumbers[vccs.node1]][nodeNumbers[vccs.node3]]-=vccs.value if vccs.node2 != 'GND': matrixM[nodeNumbers[vccs.node2]][nodeNumbers[vccs.node4]]-=vccs.value", "\"V\" ICS = \"I\" VCVS = \"E\" VCCS = \"G\"" ]
[ "os.path.isdir(os.path.join(dirname, d))] # subdirectories = [dirname + \"/\" + subDirName", "def answer(string): a = input(string) if a == \"Y\" or", "subdirectories] subdirectories = [] for dir in dirs: subdirectories.append(dirname +", "\"\"\" def execute_command(command): if len(command) > 0: print(command) proc =", "a directory. \"\"\" def getSubs(dirname): dirs = [d for d", "+ \"/\" + subDirName for subDirName in subdirectories] subdirectories =", "dir in dirs: subdirectories.append(dirname + '/' + dir) return subdirectories", "= input(string) if a == \"Y\" or a == 'y'", "or a == 'Yes' or a == 'yes': return True", "input(string) if a == \"Y\" or a == 'y' or", "return subdirectories \"\"\" Rocket science \"\"\" def answer(string): a =", "return proc \"\"\" Get all subdirectories of a directory. \"\"\"", "locally \"\"\" def execute_command(command): if len(command) > 0: print(command) proc", "= [d for d in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))] #", "execute_command(command): if len(command) > 0: print(command) proc = subprocess.Popen(command.split(\" \"),", "\"\"\" Stylish input() \"\"\" def s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\" Execute", "subdirectories = [dirname + \"/\" + subDirName for subDirName in", "dirs: subdirectories.append(dirname + '/' + dir) return subdirectories \"\"\" Rocket", "\"\"\" Execute command locally \"\"\" def execute_command(command): if len(command) >", "a == 'Yes' or a == 'yes': return True else:", "import subprocess import os.path \"\"\" Stylish input() \"\"\" def s_input(string):", "+ dir) return subdirectories \"\"\" Rocket science \"\"\" def answer(string):", "a == \"Y\" or a == 'y' or a ==", "s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\" Execute command locally \"\"\" def execute_command(command):", "if os.path.isdir(os.path.join(dirname, d))] # subdirectories = [dirname + \"/\" +", "subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\") return proc \"\"\" Get all subdirectories", "\"\"\" def s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\" Execute command locally \"\"\"", "command locally \"\"\" def execute_command(command): if len(command) > 0: print(command)", "# subdirectories = [dirname + \"/\" + subDirName for subDirName", "or a == 'y' or a == 'Yes' or a", "os.path \"\"\" Stylish input() \"\"\" def s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\"", "subdirectories = [] for dir in dirs: subdirectories.append(dirname + '/'", "dir) return subdirectories \"\"\" Rocket science \"\"\" def answer(string): a", "proc = subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\") return proc \"\"\" Get", "proc \"\"\" Get all subdirectories of a directory. \"\"\" def", "\"\"\" Get all subdirectories of a directory. \"\"\" def getSubs(dirname):", "science \"\"\" def answer(string): a = input(string) if a ==", "in dirs: subdirectories.append(dirname + '/' + dir) return subdirectories \"\"\"", "subdirectories.append(dirname + '/' + dir) return subdirectories \"\"\" Rocket science", "getSubs(dirname): dirs = [d for d in os.listdir(dirname) if os.path.isdir(os.path.join(dirname,", "in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))] # subdirectories = [dirname +", "a == 'y' or a == 'Yes' or a ==", "[dirname + \"/\" + subDirName for subDirName in subdirectories] subdirectories", "def execute_command(command): if len(command) > 0: print(command) proc = subprocess.Popen(command.split(\"", "def s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\" Execute command locally \"\"\" def", "Execute command locally \"\"\" def execute_command(command): if len(command) > 0:", "return input(string+\">\").strip(\"\\n\") \"\"\" Execute command locally \"\"\" def execute_command(command): if", "a = input(string) if a == \"Y\" or a ==", "def getSubs(dirname): dirs = [d for d in os.listdir(dirname) if", "for subDirName in subdirectories] subdirectories = [] for dir in", "answer(string): a = input(string) if a == \"Y\" or a", "input(string+\">\").strip(\"\\n\") \"\"\" Execute command locally \"\"\" def execute_command(command): if len(command)", "subprocess import os.path \"\"\" Stylish input() \"\"\" def s_input(string): return", "= [dirname + \"/\" + subDirName for subDirName in subdirectories]", "d in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))] # subdirectories = [dirname", "in subdirectories] subdirectories = [] for dir in dirs: subdirectories.append(dirname", "input() \"\"\" def s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\" Execute command locally", "cwd=\"/tmp\") return proc \"\"\" Get all subdirectories of a directory.", "[] for dir in dirs: subdirectories.append(dirname + '/' + dir)", "len(command) > 0: print(command) proc = subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\")", "os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))] # subdirectories = [dirname + \"/\"", "Rocket science \"\"\" def answer(string): a = input(string) if a", "subDirName in subdirectories] subdirectories = [] for dir in dirs:", "= [] for dir in dirs: subdirectories.append(dirname + '/' +", "'Yes' or a == 'yes': return True else: return False", "+ subDirName for subDirName in subdirectories] subdirectories = [] for", "of a directory. \"\"\" def getSubs(dirname): dirs = [d for", "== \"Y\" or a == 'y' or a == 'Yes'", "subdirectories of a directory. \"\"\" def getSubs(dirname): dirs = [d", "stdout=subprocess.PIPE, cwd=\"/tmp\") return proc \"\"\" Get all subdirectories of a", "print(command) proc = subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\") return proc \"\"\"", "\"\"\" def answer(string): a = input(string) if a == \"Y\"", "\"\"\" def getSubs(dirname): dirs = [d for d in os.listdir(dirname)", "dirs = [d for d in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))]", "all subdirectories of a directory. \"\"\" def getSubs(dirname): dirs =", "= subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\") return proc \"\"\" Get all", "+ '/' + dir) return subdirectories \"\"\" Rocket science \"\"\"", "'/' + dir) return subdirectories \"\"\" Rocket science \"\"\" def", "if a == \"Y\" or a == 'y' or a", "for d in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))] # subdirectories =", "== 'Yes' or a == 'yes': return True else: return", "<gh_stars>1-10 import subprocess import os.path \"\"\" Stylish input() \"\"\" def", "\"\"\" Rocket science \"\"\" def answer(string): a = input(string) if", "import os.path \"\"\" Stylish input() \"\"\" def s_input(string): return input(string+\">\").strip(\"\\n\")", "subDirName for subDirName in subdirectories] subdirectories = [] for dir", "\"/\" + subDirName for subDirName in subdirectories] subdirectories = []", "d))] # subdirectories = [dirname + \"/\" + subDirName for", "== 'y' or a == 'Yes' or a == 'yes':", "subdirectories \"\"\" Rocket science \"\"\" def answer(string): a = input(string)", "Get all subdirectories of a directory. \"\"\" def getSubs(dirname): dirs", "directory. \"\"\" def getSubs(dirname): dirs = [d for d in", "for dir in dirs: subdirectories.append(dirname + '/' + dir) return", "'y' or a == 'Yes' or a == 'yes': return", "if len(command) > 0: print(command) proc = subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE,", "\"Y\" or a == 'y' or a == 'Yes' or", "Stylish input() \"\"\" def s_input(string): return input(string+\">\").strip(\"\\n\") \"\"\" Execute command", "0: print(command) proc = subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\") return proc", "\"), stdout=subprocess.PIPE, cwd=\"/tmp\") return proc \"\"\" Get all subdirectories of", "[d for d in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, d))] # subdirectories", "> 0: print(command) proc = subprocess.Popen(command.split(\" \"), stdout=subprocess.PIPE, cwd=\"/tmp\") return" ]
[ "from unsharp import * # Load file and normalize to", "amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname = fname[:-4]+'_sharp.jpg'", "skimage.exposure import rescale_intensity from unsharp import * # Load file", "import rescale_intensity from unsharp import * # Load file and", "unsharp import * # Load file and normalize to 0-1", "matplotlib.pyplot as plt from skimage.exposure import rescale_intensity from unsharp import", "Load file and normalize to 0-1 fname = 'iguana.jpg' im", "if im.mean() >= 1: im = im/255. sigma = 5", "plt from skimage.exposure import rescale_intensity from unsharp import * #", "= im/255. sigma = 5 amplitude = 1.5 imsharp =", "= 5 amplitude = 1.5 imsharp = unsharp_mask(im, sigma, amplitude)", "rescale_intensity from unsharp import * # Load file and normalize", "np import matplotlib.pyplot as plt from skimage.exposure import rescale_intensity from", "from skimage.exposure import rescale_intensity from unsharp import * # Load", "<gh_stars>1-10 import numpy as np import matplotlib.pyplot as plt from", "import * # Load file and normalize to 0-1 fname", "im = im/255. sigma = 5 amplitude = 1.5 imsharp", "sigma = 5 amplitude = 1.5 imsharp = unsharp_mask(im, sigma,", "# Load file and normalize to 0-1 fname = 'iguana.jpg'", "unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname", "import numpy as np import matplotlib.pyplot as plt from skimage.exposure", ">= 1: im = im/255. sigma = 5 amplitude =", "normalize to 0-1 fname = 'iguana.jpg' im = plt.imread(fname) if", "imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname = fname[:-4]+'_sharp.jpg' plt.imsave(new_fname,", "'iguana.jpg' im = plt.imread(fname) if im.mean() >= 1: im =", "as plt from skimage.exposure import rescale_intensity from unsharp import *", "file and normalize to 0-1 fname = 'iguana.jpg' im =", "amplitude = 1.5 imsharp = unsharp_mask(im, sigma, amplitude) imsharp =", "fname = 'iguana.jpg' im = plt.imread(fname) if im.mean() >= 1:", "to 0-1 fname = 'iguana.jpg' im = plt.imread(fname) if im.mean()", "= plt.imread(fname) if im.mean() >= 1: im = im/255. sigma", "and normalize to 0-1 fname = 'iguana.jpg' im = plt.imread(fname)", "1.5 imsharp = unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0,", "sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname =", "as np import matplotlib.pyplot as plt from skimage.exposure import rescale_intensity", "import matplotlib.pyplot as plt from skimage.exposure import rescale_intensity from unsharp", "5 amplitude = 1.5 imsharp = unsharp_mask(im, sigma, amplitude) imsharp", "= 1.5 imsharp = unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp,", "0-1 fname = 'iguana.jpg' im = plt.imread(fname) if im.mean() >=", "1: im = im/255. sigma = 5 amplitude = 1.5", "im/255. sigma = 5 amplitude = 1.5 imsharp = unsharp_mask(im,", "imsharp = unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1),", "* # Load file and normalize to 0-1 fname =", "= 'iguana.jpg' im = plt.imread(fname) if im.mean() >= 1: im", "im = plt.imread(fname) if im.mean() >= 1: im = im/255.", "numpy as np import matplotlib.pyplot as plt from skimage.exposure import", "= rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1)) new_fname = fname[:-4]+'_sharp.jpg' plt.imsave(new_fname, imsharp)", "= unsharp_mask(im, sigma, amplitude) imsharp = rescale_intensity(imsharp, in_range=(0, 1), out_range=(0,1))", "im.mean() >= 1: im = im/255. sigma = 5 amplitude", "plt.imread(fname) if im.mean() >= 1: im = im/255. sigma =" ]
[ "= 'registro_establecimiento_domicilio' def __unicode__(self): if self.cp: cp = \" (CP:", "self.altura, self.localidad.nombre, cp) def __init__(self, *args, **kwargs): super(EstablecimientoDomicilio, self).__init__(*args, **kwargs)", "+ self.cp + \")\" else: cp = \"\" return \"%s", "TipoDomicilio from apps.registro.models.Localidad import Localidad from apps.registro.models.Establecimiento import Establecimiento from", "= models.CharField(max_length=100) altura = models.CharField(max_length=15) referencia = models.CharField(max_length=255, null=True, blank=True)", "# -*- coding: utf-8 -*- from django.db import models from", "import audit @audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL =", "models.CharField(max_length=255, null=True, blank=True) cp = models.CharField(max_length=20) class Meta: app_label =", "models.CharField(max_length=15) referencia = models.CharField(max_length=255, null=True, blank=True) cp = models.CharField(max_length=20) class", "%s\" % (self.calle, self.altura, self.localidad.nombre, cp) def __init__(self, *args, **kwargs):", "if self.cp: cp = \" (CP: \" + self.cp +", "apps.registro.models.TipoDomicilio import TipoDomicilio from apps.registro.models.Localidad import Localidad from apps.registro.models.Establecimiento import", "'registro_establecimiento_domicilio' def __unicode__(self): if self.cp: cp = \" (CP: \"", "= 'registro' db_table = 'registro_establecimiento_domicilio' def __unicode__(self): if self.cp: cp", "from apps.registro.models.TipoDomicilio import TipoDomicilio from apps.registro.models.Localidad import Localidad from apps.registro.models.Establecimiento", "EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL = 'Institucional' establecimiento = models.ForeignKey(Establecimiento,", "apps.seguridad.audit import audit @audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL", "models from apps.registro.models.TipoDomicilio import TipoDomicilio from apps.registro.models.Localidad import Localidad from", "else: cp = \"\" return \"%s %s - %s %s\"", "class EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL = 'Institucional' establecimiento =", "import models from apps.registro.models.TipoDomicilio import TipoDomicilio from apps.registro.models.Localidad import Localidad", "\")\" else: cp = \"\" return \"%s %s - %s", "\" (CP: \" + self.cp + \")\" else: cp =", "'Postal' TIPO_INSTITUCIONAL = 'Institucional' establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio =", "TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL = 'Institucional' establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios')", "+ \")\" else: cp = \"\" return \"%s %s -", "Localidad from apps.registro.models.Establecimiento import Establecimiento from django.core.exceptions import ValidationError from", "= models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle = models.CharField(max_length=100) altura = models.CharField(max_length=15) referencia", "Establecimiento from django.core.exceptions import ValidationError from apps.seguridad.audit import audit @audit", "(CP: \" + self.cp + \")\" else: cp = \"\"", "cp = models.CharField(max_length=20) class Meta: app_label = 'registro' db_table =", "-*- coding: utf-8 -*- from django.db import models from apps.registro.models.TipoDomicilio", "models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle", "from apps.seguridad.audit import audit @audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal'", "class Meta: app_label = 'registro' db_table = 'registro_establecimiento_domicilio' def __unicode__(self):", "= models.CharField(max_length=20) class Meta: app_label = 'registro' db_table = 'registro_establecimiento_domicilio'", "TIPO_INSTITUCIONAL = 'Institucional' establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio)", "'Institucional' establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad =", "= \" (CP: \" + self.cp + \")\" else: cp", "apps.registro.models.Localidad import Localidad from apps.registro.models.Establecimiento import Establecimiento from django.core.exceptions import", "import Localidad from apps.registro.models.Establecimiento import Establecimiento from django.core.exceptions import ValidationError", "establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad,", "- %s %s\" % (self.calle, self.altura, self.localidad.nombre, cp) def __init__(self,", "cp = \" (CP: \" + self.cp + \")\" else:", "tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle = models.CharField(max_length=100)", "= models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle = models.CharField(max_length=100) altura", "import TipoDomicilio from apps.registro.models.Localidad import Localidad from apps.registro.models.Establecimiento import Establecimiento", "(self.calle, self.altura, self.localidad.nombre, cp) def __init__(self, *args, **kwargs): super(EstablecimientoDomicilio, self).__init__(*args,", "Meta: app_label = 'registro' db_table = 'registro_establecimiento_domicilio' def __unicode__(self): if", "models.CharField(max_length=20) class Meta: app_label = 'registro' db_table = 'registro_establecimiento_domicilio' def", "related_name='domicilios_establecimientos') calle = models.CharField(max_length=100) altura = models.CharField(max_length=15) referencia = models.CharField(max_length=255,", "utf-8 -*- from django.db import models from apps.registro.models.TipoDomicilio import TipoDomicilio", "from apps.registro.models.Establecimiento import Establecimiento from django.core.exceptions import ValidationError from apps.seguridad.audit", "% (self.calle, self.altura, self.localidad.nombre, cp) def __init__(self, *args, **kwargs): super(EstablecimientoDomicilio,", "blank=True) cp = models.CharField(max_length=20) class Meta: app_label = 'registro' db_table", "calle = models.CharField(max_length=100) altura = models.CharField(max_length=15) referencia = models.CharField(max_length=255, null=True,", "= models.CharField(max_length=255, null=True, blank=True) cp = models.CharField(max_length=20) class Meta: app_label", "%s - %s %s\" % (self.calle, self.altura, self.localidad.nombre, cp) def", "django.core.exceptions import ValidationError from apps.seguridad.audit import audit @audit class EstablecimientoDomicilio(models.Model):", "related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle =", "models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle = models.CharField(max_length=100) altura =", "= models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos')", "= models.CharField(max_length=15) referencia = models.CharField(max_length=255, null=True, blank=True) cp = models.CharField(max_length=20)", "audit @audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL = 'Institucional'", "app_label = 'registro' db_table = 'registro_establecimiento_domicilio' def __unicode__(self): if self.cp:", "localidad = models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle = models.CharField(max_length=100) altura = models.CharField(max_length=15)", "from django.core.exceptions import ValidationError from apps.seguridad.audit import audit @audit class", "%s %s\" % (self.calle, self.altura, self.localidad.nombre, cp) def __init__(self, *args,", "altura = models.CharField(max_length=15) referencia = models.CharField(max_length=255, null=True, blank=True) cp =", "models.CharField(max_length=100) altura = models.CharField(max_length=15) referencia = models.CharField(max_length=255, null=True, blank=True) cp", "'registro' db_table = 'registro_establecimiento_domicilio' def __unicode__(self): if self.cp: cp =", "= 'Institucional' establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio = models.ForeignKey(TipoDomicilio) localidad", "self.cp + \")\" else: cp = \"\" return \"%s %s", "models.ForeignKey(Localidad, related_name='domicilios_establecimientos') calle = models.CharField(max_length=100) altura = models.CharField(max_length=15) referencia =", "\" + self.cp + \")\" else: cp = \"\" return", "def __unicode__(self): if self.cp: cp = \" (CP: \" +", "import ValidationError from apps.seguridad.audit import audit @audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL", "cp = \"\" return \"%s %s - %s %s\" %", "<reponame>MERegistro/meregistro # -*- coding: utf-8 -*- from django.db import models", "@audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL = 'Postal' TIPO_INSTITUCIONAL = 'Institucional' establecimiento", "= 'Postal' TIPO_INSTITUCIONAL = 'Institucional' establecimiento = models.ForeignKey(Establecimiento, related_name='domicilios') tipo_domicilio", "__unicode__(self): if self.cp: cp = \" (CP: \" + self.cp", "coding: utf-8 -*- from django.db import models from apps.registro.models.TipoDomicilio import", "from apps.registro.models.Localidad import Localidad from apps.registro.models.Establecimiento import Establecimiento from django.core.exceptions", "from django.db import models from apps.registro.models.TipoDomicilio import TipoDomicilio from apps.registro.models.Localidad", "= \"\" return \"%s %s - %s %s\" % (self.calle,", "django.db import models from apps.registro.models.TipoDomicilio import TipoDomicilio from apps.registro.models.Localidad import", "null=True, blank=True) cp = models.CharField(max_length=20) class Meta: app_label = 'registro'", "return \"%s %s - %s %s\" % (self.calle, self.altura, self.localidad.nombre,", "referencia = models.CharField(max_length=255, null=True, blank=True) cp = models.CharField(max_length=20) class Meta:", "\"%s %s - %s %s\" % (self.calle, self.altura, self.localidad.nombre, cp)", "self.cp: cp = \" (CP: \" + self.cp + \")\"", "db_table = 'registro_establecimiento_domicilio' def __unicode__(self): if self.cp: cp = \"", "\"\" return \"%s %s - %s %s\" % (self.calle, self.altura,", "apps.registro.models.Establecimiento import Establecimiento from django.core.exceptions import ValidationError from apps.seguridad.audit import", "ValidationError from apps.seguridad.audit import audit @audit class EstablecimientoDomicilio(models.Model): TIPO_POSTAL =", "import Establecimiento from django.core.exceptions import ValidationError from apps.seguridad.audit import audit", "-*- from django.db import models from apps.registro.models.TipoDomicilio import TipoDomicilio from" ]
[ "the number at the end of the line below. #", "the end of the line below. # Convert the extracted", "and string slicing (see section 6.10) to extract # the", "end of the line below. # Convert the extracted value", "number at the end of the line below. # Convert", "# the number at the end of the line below.", "out. text = \"X-DSPAM-Confidence: 0.8475\"; pos = text.find(':') text =", "6.10) to extract # the number at the end of", "the line below. # Convert the extracted value to a", "to a floating point number and print it out. text", "using find() and string slicing (see section 6.10) to extract", "(see section 6.10) to extract # the number at the", "= \"X-DSPAM-Confidence: 0.8475\"; pos = text.find(':') text = float(text[pos+1:]) print", "below. # Convert the extracted value to a floating point", "Write code using find() and string slicing (see section 6.10)", "string slicing (see section 6.10) to extract # the number", "to extract # the number at the end of the", "at the end of the line below. # Convert the", "of the line below. # Convert the extracted value to", "and print it out. text = \"X-DSPAM-Confidence: 0.8475\"; pos =", "6.5 Write code using find() and string slicing (see section", "find() and string slicing (see section 6.10) to extract #", "extract # the number at the end of the line", "slicing (see section 6.10) to extract # the number at", "# Convert the extracted value to a floating point number", "a floating point number and print it out. text =", "section 6.10) to extract # the number at the end", "Convert the extracted value to a floating point number and", "line below. # Convert the extracted value to a floating", "the extracted value to a floating point number and print", "floating point number and print it out. text = \"X-DSPAM-Confidence:", "<gh_stars>0 # 6.5 Write code using find() and string slicing", "it out. text = \"X-DSPAM-Confidence: 0.8475\"; pos = text.find(':') text", "value to a floating point number and print it out.", "code using find() and string slicing (see section 6.10) to", "\"X-DSPAM-Confidence: 0.8475\"; pos = text.find(':') text = float(text[pos+1:]) print text", "# 6.5 Write code using find() and string slicing (see", "point number and print it out. text = \"X-DSPAM-Confidence: 0.8475\";", "number and print it out. text = \"X-DSPAM-Confidence: 0.8475\"; pos", "extracted value to a floating point number and print it", "print it out. text = \"X-DSPAM-Confidence: 0.8475\"; pos = text.find(':')", "text = \"X-DSPAM-Confidence: 0.8475\"; pos = text.find(':') text = float(text[pos+1:])" ]
[ "self._layer['size'] @change def _set_unit(self, unit: int) -> None: if unit", "if no model is selected. \"\"\" return self._model @property def", "== self.unit: return if unit is None: self._unit = None", "is a wrapper around the lucid module. Attributes ---------- _network:", "+ str(self._unit)) def _doRun(self, running: bool=True) -> None: self.running =", "change from network import Network, loader from network.lucid import Network", "units in the currently selected layer. \"\"\" return None if", "no layer is selected') elif not 0 <= unit <", "None if no model is selected. \"\"\" return self._model @property", "lucid.modelzoo.vision_models as models import lucid.modelzoo.nets_factory as nets from lucid.modelzoo.vision_base import", "def layer(self, name: str) -> None: \"\"\"Set the currently selected", "model. None if no model is selected. \"\"\" return self._model", "lucid.optvis.transform as transform class Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The", "currently selected layer. \"\"\" self.set_layer(name) @property def layer_type(self) -> str:", "self._network.name @change def load_model(self, name: str) -> LucidModel: \"\"\"Load the", "make old code happy. New code should use # Engine.Change", "self._layer['name'] @property def unit_id(self) -> str: \"\"\"The id of the", "lucid network. None if no model is selected. _model: LucidModel", "{unit} for current layer\" f\" of size {self._layer['size']}\") else: self._unit", "Engine.Change and Engine.Observer directly. EngineChange = Engine.Change EngineObserver = Engine.Observer", "None: self._unit = None self.change(unit_changed=True) elif self._layer is None: raise", "if no model is selected. _model: LucidModel The currently selected", "-> None: self.running = running self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image =", "except StopIteration: # name not in layer list self._layer =", "# FIXME[old]: this is too make old code happy. New", "if self._network is None else self._network.name @change def load_model(self, name:", "lucid.optvis.objectives as objectives import lucid.optvis.param as param import lucid.optvis.render as", "if no unit is selected. \"\"\" self._set_unit(unit) @property def layer_id(self)", "return self._layer['name'] + '_pre_relu' return self._layer['name'] @property def unit_id(self) ->", "unit == self.unit: return if unit is None: self._unit =", "LucidModel. \"\"\" logger.info(f\"load_model({name})\") try: #self._network = LucidNetwork(name=name) self._network = loader.load_lucid(name)", "= None self.change(unit_changed=True) @property def layer(self) -> str: \"\"\"The name", "def __init__(self): super().__init__() self._network = None self._model = None self._layer", "the currently selected layer or None if no unit is", "'model_changed', 'unit_changed'}): \"\"\"The Engine is a wrapper around the lucid", "is selected. \"\"\" return (None if self._layer is None else", "A reference to the LucidModel. \"\"\" logger.info(f\"load_model({name})\") try: #self._network =", "None if no unit is selected. \"\"\" return (None if", "None self._unit = None self.image = None self.running = False", "\"\"\" self.set_layer(name) @property def layer_type(self) -> str: \"\"\"The type of", "def start(self): self.image = None self._doRun(True) obj = objectives.channel(self.layer_id, self.unit)", "self.running = False @property def model(self) -> LucidModel: \"\"\"The currently", "False @property def model(self) -> LucidModel: \"\"\"The currently selected lucid", "-> LucidModel: \"\"\"Load the Lucid model with the given name.", "unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit {unit}\") obj = objectives.channel(self.layer_id, unit)", "e: self._network = None self._model = None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\")", "loader from network.lucid import Network as LucidNetwork # lucid.modelzoo.vision_models: #", "self._unit = None self.image = None self.running = False @property", "logger = logging.getLogger(__name__) print(f\"!!!!!!!!!! getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer import", "unit(self) -> int: \"\"\"The index of the currently selected unit", "render.render_vis(self.model, obj) #self.image = render.render_vis(self.model, self.unit_id) self._doRun(False) def stop(self): self._doRun(False)", "selected. \"\"\" def __init__(self): super().__init__() self._network = None self._model =", "layer list self._layer = None self._unit = None self.change(unit_changed=True) @property", "providinge the pretrained networks by name, e.g. # models.AlexNet import", "the LucidModel. \"\"\" logger.info(f\"load_model({name})\") try: #self._network = LucidNetwork(name=name) self._network =", "unit_id(self) -> str: \"\"\"The id of the currently selected unit", "name of the currently selected layer. \"\"\" return None if", "\"\"\"The type of the currently selected layer. \"\"\" return None", "The index of the unit in the layer. \"\"\" if", "Lucid model with the given name. Returns ------- model: LucidModel", "if unit is None: self._unit = None self.change(unit_changed=True) elif self._layer", "KeyError as e: self._network = None self._model = None logger.info(f\"NAME={name}/{self.model_name}", "== name) self._unit = unit except StopIteration: # name not", "@layer.setter def layer(self, name: str) -> None: \"\"\"Set the currently", "selected. \"\"\" if self._layer is None: return None if self._layer['type']", "self._doRun(False) def start_multi(self): self.image = None self._doRun(True) logger.info(\"!!! running all:\")", "logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer = None self._unit = None self.change(model_changed=True,", "in layer list self._layer = None self._unit = None self.change(unit_changed=True)", "self._model @change def set_layer(self, name: str, unit: int=0) -> None:", "self.image = render.render_vis(self.model, obj) #self.image = render.render_vis(self.model, self.unit_id) self._doRun(False) def", "unit_changed=True) return self._model @change def set_layer(self, name: str, unit: int=0)", "if self._layer is None else self._layer['name'] @layer.setter def layer(self, name:", "\"\"\" return (None if self._layer is None else self.layer_id +", "network. None if no model is selected. _model: LucidModel The", "\"\"\"The name of the currently selected layer. \"\"\" return None", "Engine is a wrapper around the lucid module. Attributes ----------", "str: \"\"\"The type of the currently selected layer. \"\"\" return", "def _doRun(self, running: bool=True) -> None: self.running = running self.notify_observers(EngineChange(engine_changed=True))", "failed as no layer is selected') elif not 0 <=", "layer or None if no unit is selected. \"\"\" if", "networks by name, e.g. # models.AlexNet import lucid.modelzoo.vision_models as models", "The currently selected lucid network. None if no model is", "\"\"\" if name == self.layer: return if self._model is None:", "name) self._unit = unit except StopIteration: # name not in", "{self._layer['size']}\") else: self._unit = unit self.change(unit_changed=True) @property def unit(self) ->", "# lucid.modelzoo.vision_models: # A module providinge the pretrained networks by", "wrapper around the lucid module. Attributes ---------- _network: LucidNetwork The", "too make old code happy. New code should use #", "currently selected layer. Arguments --------- name: str The name of", "-> str: \"\"\"The id of the currently selected layer or", "else self.layer_id + ':' + str(self._unit)) def _doRun(self, running: bool=True)", "None if self._layer is None else self._layer['type'] @property def layer_units(self)", "selected layer. \"\"\" return None if self._layer is None else", "model. None if no model is selected. \"\"\" def __init__(self):", "= None self._layer = None self._unit = None self.image =", "self._unit is None else self._unit @unit.setter def unit(self, unit: int)", "str: \"\"\"The name of the currently selected layer. \"\"\" return", "@property def unit_id(self) -> str: \"\"\"The id of the currently", "lucid module. Attributes ---------- _network: LucidNetwork The currently selected lucid", "str: \"\"\"The id of the currently selected layer or None", "= unit except StopIteration: # name not in layer list", "str: \"\"\"The id of the currently selected unit or None", "the given name. Returns ------- model: LucidModel A reference to", "else self._network.name @change def load_model(self, name: str) -> LucidModel: \"\"\"Load", "is selected. \"\"\" return None if self._network is None else", "the currently selected unit or None if no unit is", "if self._unit is None else self._unit @unit.setter def unit(self, unit:", "layer\" f\" of size {self._layer['size']}\") else: self._unit = unit self.change(unit_changed=True)", "None if self._layer is None else self._layer['size'] @change def _set_unit(self,", "the currently selected layer. \"\"\" self.set_layer(name) @property def layer_type(self) ->", "--------- name: str The name of the layer. unit: int", "self.change(model_changed=True, unit_changed=True) return self._model @change def set_layer(self, name: str, unit:", "logging logger = logging.getLogger(__name__) print(f\"!!!!!!!!!! getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer", "{logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer import Observable, change from network import", "None else self._layer['type'] @property def layer_units(self) -> int: \"\"\"The number", "from lucid.modelzoo.vision_base import Model as LucidModel import lucid.optvis.objectives as objectives", "import lucid.optvis.render as render import lucid.optvis.transform as transform class Engine(Observable,", "None: \"\"\"The index of the currently selected unit or None", "is None else self._layer['size'] @change def _set_unit(self, unit: int) ->", "\"\"\" return None if self._layer is None else self._layer['size'] @change", "happy. New code should use # Engine.Change and Engine.Observer directly.", "LucidModel: \"\"\"The currently selected lucid model. None if no model", "currently selected layer. \"\"\" return None if self._layer is None", "lucid.optvis.render as render import lucid.optvis.transform as transform class Engine(Observable, method='engine_changed',", "'conv': return self._layer['name'] + '_pre_relu' return self._layer['name'] @property def unit_id(self)", "name of the layer. unit: int The index of the", "== self.layer: return if self._model is None: return try: self._layer", "str(self._unit)) def _doRun(self, running: bool=True) -> None: self.running = running", "unit) self.image = render.render_vis(self.model, obj) if not self.running: break self._doRun(True)", "= None self._model = None self._layer = None self._unit =", "ValueError(f\"Invalid unit {unit} for current layer\" f\" of size {self._layer['size']}\")", "def _set_unit(self, unit: int) -> None: if unit == self.unit:", "load_model(self, name: str) -> LucidModel: \"\"\"Load the Lucid model with", "None: \"\"\"Set the currently selected layer. Arguments --------- name: str", "LucidModel: \"\"\"Load the Lucid model with the given name. Returns", "code should use # Engine.Change and Engine.Observer directly. EngineChange =", "None self.change(model_changed=True, unit_changed=True) return self._model @change def set_layer(self, name: str,", "return try: self._layer = next(x for x in self._model.layers if", "self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit {unit}\") obj = objectives.channel(self.layer_id, unit) self.image", "-> None: \"\"\"Set the currently selected layer. Arguments --------- name:", "no model is selected. \"\"\" def __init__(self): super().__init__() self._network =", "number of units in the currently selected layer. \"\"\" return", "unit or None if no unit is selected. \"\"\" self._set_unit(unit)", "None if self._unit is None else self._unit @unit.setter def unit(self,", "-> int: \"\"\"The number of units in the currently selected", "selected. \"\"\" return None if self._unit is None else self._unit", "self._doRun(True) self._doRun(False) # FIXME[old]: this is too make old code", "model is selected. _model: LucidModel The currently selected lucid model.", "self._layer is None else self._layer['name'] @layer.setter def layer(self, name: str)", "name not in layer list self._layer = None self._unit =", "is selected. \"\"\" return None if self._unit is None else", "None else self._network.name @change def load_model(self, name: str) -> LucidModel:", "Returns ------- model: LucidModel A reference to the LucidModel. \"\"\"", "transform class Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The Engine is", "= running self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image = None self._doRun(True) obj", "\"\"\" return None if self._layer is None else self._layer['name'] @layer.setter", "selected. \"\"\" self._set_unit(unit) @property def layer_id(self) -> str: \"\"\"The id", "\"\"\"Set the currently selected layer. \"\"\" self.set_layer(name) @property def layer_type(self)", "self._doRun(True) logger.info(\"!!! running all:\") for unit in range(self.layer_units): self.unit =", "= None self.image = None self.running = False @property def", "selected. \"\"\" return None if self._network is None else self._network.name", "-> LucidModel: \"\"\"The currently selected lucid model. None if no", "None self._model = None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer = None", "+ ':' + str(self._unit)) def _doRun(self, running: bool=True) -> None:", "unit except StopIteration: # name not in layer list self._layer", "range(self.layer_units): self.unit = unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit {unit}\") obj", "self._unit @unit.setter def unit(self, unit: int) -> None: \"\"\"The index", "None if no unit is selected. \"\"\" return None if", "models import lucid.modelzoo.nets_factory as nets from lucid.modelzoo.vision_base import Model as", "-> str: \"\"\"The name of the currently selected lucid model.", "return self._model @property def model_name(self) -> str: \"\"\"The name of", "import lucid.optvis.param as param import lucid.optvis.render as render import lucid.optvis.transform", "@property def model(self) -> LucidModel: \"\"\"The currently selected lucid model.", "is None: raise ValueError('Setting unit failed as no layer is", "\"\"\"Load the Lucid model with the given name. Returns -------", "self._network = None self._model = None self._layer = None self._unit", "import lucid.modelzoo.nets_factory as nets from lucid.modelzoo.vision_base import Model as LucidModel", "== 'conv': return self._layer['name'] + '_pre_relu' return self._layer['name'] @property def", "param import lucid.optvis.render as render import lucid.optvis.transform as transform class", "None self.running = False @property def model(self) -> LucidModel: \"\"\"The", "for current layer\" f\" of size {self._layer['size']}\") else: self._unit =", "self.image = render.render_vis(self.model, obj) if not self.running: break self._doRun(True) self._doRun(False)", "or None if no unit is selected. \"\"\" if self._layer", "name == self.layer: return if self._model is None: return try:", "self.unit) self.image = render.render_vis(self.model, obj) #self.image = render.render_vis(self.model, self.unit_id) self._doRun(False)", "id of the currently selected layer or None if no", "import lucid.optvis.objectives as objectives import lucid.optvis.param as param import lucid.optvis.render", "unit: int) -> None: if unit == self.unit: return if", "as nets from lucid.modelzoo.vision_base import Model as LucidModel import lucid.optvis.objectives", "None else self.layer_id + ':' + str(self._unit)) def _doRun(self, running:", "name: str) -> None: \"\"\"Set the currently selected layer. \"\"\"", "the lucid module. Attributes ---------- _network: LucidNetwork The currently selected", "self.image = None self.running = False @property def model(self) ->", "in the layer. \"\"\" if name == self.layer: return if", "Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The Engine is a wrapper", "'unit_changed'}): \"\"\"The Engine is a wrapper around the lucid module.", "nets from lucid.modelzoo.vision_base import Model as LucidModel import lucid.optvis.objectives as", "running unit {unit}\") obj = objectives.channel(self.layer_id, unit) self.image = render.render_vis(self.model,", "+ '_pre_relu' return self._layer['name'] @property def unit_id(self) -> str: \"\"\"The", "of units in the currently selected layer. \"\"\" return None", "logger.info(\"!!! running all:\") for unit in range(self.layer_units): self.unit = unit", "lucid.optvis.param as param import lucid.optvis.render as render import lucid.optvis.transform as", "no unit is selected. \"\"\" self._set_unit(unit) @property def layer_id(self) ->", "lucid.modelzoo.vision_base import Model as LucidModel import lucid.optvis.objectives as objectives import", "self._layer = next(x for x in self._model.layers if x['name'] ==", "if name == self.layer: return if self._model is None: return", "is selected') elif not 0 <= unit < self._layer['size']: raise", "is selected. \"\"\" def __init__(self): super().__init__() self._network = None self._model", "if self._layer['type'] == 'conv': return self._layer['name'] + '_pre_relu' return self._layer['name']", "def start_multi(self): self.image = None self._doRun(True) logger.info(\"!!! running all:\") for", "as LucidNetwork # lucid.modelzoo.vision_models: # A module providinge the pretrained", "currently selected lucid model. None if no model is selected.", "\"\"\" self._set_unit(unit) @property def layer_id(self) -> str: \"\"\"The id of", "selected lucid model. None if no model is selected. \"\"\"", "use # Engine.Change and Engine.Observer directly. EngineChange = Engine.Change EngineObserver", "import logging logger = logging.getLogger(__name__) print(f\"!!!!!!!!!! getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from", "is None else self._network.name @change def load_model(self, name: str) ->", "= objectives.channel(self.layer_id, unit) self.image = render.render_vis(self.model, obj) if not self.running:", "Attributes ---------- _network: LucidNetwork The currently selected lucid network. None", "LucidNetwork(name=name) self._network = loader.load_lucid(name) self._model = self._network.model except KeyError as", "no model is selected. \"\"\" return self._model @property def model_name(self)", "is None: return try: self._layer = next(x for x in", "def layer_type(self) -> str: \"\"\"The type of the currently selected", "= None self._unit = None self.image = None self.running =", "int=0) -> None: \"\"\"Set the currently selected layer. Arguments ---------", "@property def layer(self) -> str: \"\"\"The name of the currently", "as LucidModel import lucid.optvis.objectives as objectives import lucid.optvis.param as param", "str: \"\"\"The name of the currently selected lucid model. None", "\"\"\" return self._model @property def model_name(self) -> str: \"\"\"The name", "LucidModel A reference to the LucidModel. \"\"\" logger.info(f\"load_model({name})\") try: #self._network", "@unit.setter def unit(self, unit: int) -> None: \"\"\"The index of", "None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer = None self._unit = None", "self._layer = None self._unit = None self.change(model_changed=True, unit_changed=True) return self._model", "the Lucid model with the given name. Returns ------- model:", "self._model.layers if x['name'] == name) self._unit = unit except StopIteration:", "x['name'] == name) self._unit = unit except StopIteration: # name", "else self._layer['name'] @layer.setter def layer(self, name: str) -> None: \"\"\"Set", "def layer_units(self) -> int: \"\"\"The number of units in the", "unit or None if no unit is selected. \"\"\" return", "for x in self._model.layers if x['name'] == name) self._unit =", "def layer_id(self) -> str: \"\"\"The id of the currently selected", "# Engine.Change and Engine.Observer directly. EngineChange = Engine.Change EngineObserver =", "of the unit in the layer. \"\"\" if name ==", "else: self._unit = unit self.change(unit_changed=True) @property def unit(self) -> int:", "def model(self) -> LucidModel: \"\"\"The currently selected lucid model. None", "!!!!!!!!!!!!!\") from dltb.base.observer import Observable, change from network import Network,", "{self._model}\") self._layer = None self._unit = None self.change(model_changed=True, unit_changed=True) return", "obj = objectives.channel(self.layer_id, self.unit) self.image = render.render_vis(self.model, obj) #self.image =", "self._layer['name'] @layer.setter def layer(self, name: str) -> None: \"\"\"Set the", "raise ValueError('Setting unit failed as no layer is selected') elif", "layer is selected') elif not 0 <= unit < self._layer['size']:", "The currently selected lucid model. None if no model is", "int The index of the unit in the layer. \"\"\"", "\"\"\"The id of the currently selected unit or None if", "self._unit = unit self.change(unit_changed=True) @property def unit(self) -> int: \"\"\"The", "= render.render_vis(self.model, obj) if not self.running: break self._doRun(True) self._doRun(False) #", "render.render_vis(self.model, self.unit_id) self._doRun(False) def stop(self): self._doRun(False) def start_multi(self): self.image =", "loader.load_lucid(name) self._model = self._network.model except KeyError as e: self._network =", "= next(x for x in self._model.layers if x['name'] == name)", "next(x for x in self._model.layers if x['name'] == name) self._unit", "self._network = None self._model = None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer", "-> str: \"\"\"The name of the currently selected layer. \"\"\"", "unit {unit}\") obj = objectives.channel(self.layer_id, unit) self.image = render.render_vis(self.model, obj)", "logging.getLogger(__name__) print(f\"!!!!!!!!!! getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer import Observable, change", "model with the given name. Returns ------- model: LucidModel A", "import lucid.modelzoo.vision_models as models import lucid.modelzoo.nets_factory as nets from lucid.modelzoo.vision_base", "stop(self): self._doRun(False) def start_multi(self): self.image = None self._doRun(True) logger.info(\"!!! running", "all:\") for unit in range(self.layer_units): self.unit = unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!!", "\"\"\"The id of the currently selected layer or None if", "def stop(self): self._doRun(False) def start_multi(self): self.image = None self._doRun(True) logger.info(\"!!!", "self.layer_id + ':' + str(self._unit)) def _doRun(self, running: bool=True) ->", "lucid model. None if no model is selected. \"\"\" def", "self._network = loader.load_lucid(name) self._model = self._network.model except KeyError as e:", "None self._unit = None self.change(model_changed=True, unit_changed=True) return self._model @change def", "return None if self._layer is None else self._layer['type'] @property def", "or None if no unit is selected. \"\"\" return None", "is selected. \"\"\" self._set_unit(unit) @property def layer_id(self) -> str: \"\"\"The", "\"\"\" return None if self._network is None else self._network.name @change", "return None if self._network is None else self._network.name @change def", "\"\"\"The name of the currently selected lucid model. None if", "return None if self._layer['type'] == 'conv': return self._layer['name'] + '_pre_relu'", "as transform class Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The Engine", "self._unit = None self.change(unit_changed=True) elif self._layer is None: raise ValueError('Setting", "self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image = None self._doRun(True) obj = objectives.channel(self.layer_id,", "self.layer: return if self._model is None: return try: self._layer =", "self.change(unit_changed=True) @property def layer(self) -> str: \"\"\"The name of the", "= unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit {unit}\") obj = objectives.channel(self.layer_id,", "self.change(unit_changed=True) elif self._layer is None: raise ValueError('Setting unit failed as", "= None self._model = None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer =", "layer. \"\"\" return None if self._layer is None else self._layer['type']", "currently selected lucid network. None if no model is selected.", "is None else self._layer['name'] @layer.setter def layer(self, name: str) ->", "reference to the LucidModel. \"\"\" logger.info(f\"load_model({name})\") try: #self._network = LucidNetwork(name=name)", "set_layer(self, name: str, unit: int=0) -> None: \"\"\"Set the currently", "= unit self.change(unit_changed=True) @property def unit(self) -> int: \"\"\"The index", "unit: int) -> None: \"\"\"The index of the currently selected", "from network.lucid import Network as LucidNetwork # lucid.modelzoo.vision_models: # A", "self._unit = None self.change(model_changed=True, unit_changed=True) return self._model @change def set_layer(self,", "self._model = None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer = None self._unit", "layer. \"\"\" if name == self.layer: return if self._model is", "as no layer is selected') elif not 0 <= unit", "layer(self, name: str) -> None: \"\"\"Set the currently selected layer.", "self._network.model except KeyError as e: self._network = None self._model =", "unit in range(self.layer_units): self.unit = unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit", "= self._network.model except KeyError as e: self._network = None self._model", "self._layer = None self._unit = None self.change(unit_changed=True) @property def layer(self)", "unit < self._layer['size']: raise ValueError(f\"Invalid unit {unit} for current layer\"", "def load_model(self, name: str) -> LucidModel: \"\"\"Load the Lucid model", "with the given name. Returns ------- model: LucidModel A reference", "{unit}\") obj = objectives.channel(self.layer_id, unit) self.image = render.render_vis(self.model, obj) if", "self._layer['name'] + '_pre_relu' return self._layer['name'] @property def unit_id(self) -> str:", "self.running = running self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image = None self._doRun(True)", "\"\"\" return None if self._layer is None else self._layer['type'] @property", "no unit is selected. \"\"\" if self._layer is None: return", "LucidModel The currently selected lucid model. None if no model", "if unit == self.unit: return if unit is None: self._unit", "import Observable, change from network import Network, loader from network.lucid", "None: return try: self._layer = next(x for x in self._model.layers", "unit: int The index of the unit in the layer.", "self.set_layer(name) @property def layer_type(self) -> str: \"\"\"The type of the", "self._layer = None self._unit = None self.image = None self.running", "start(self): self.image = None self._doRun(True) obj = objectives.channel(self.layer_id, self.unit) self.image", "as param import lucid.optvis.render as render import lucid.optvis.transform as transform", "selected. \"\"\" return self._model @property def model_name(self) -> str: \"\"\"The", "str, unit: int=0) -> None: \"\"\"Set the currently selected layer.", "the currently selected lucid model. None if no model is", "= None self._unit = None self.change(unit_changed=True) @property def layer(self) ->", "unit self.change(unit_changed=True) @property def unit(self) -> int: \"\"\"The index of", "should use # Engine.Change and Engine.Observer directly. EngineChange = Engine.Change", "try: #self._network = LucidNetwork(name=name) self._network = loader.load_lucid(name) self._model = self._network.model", "= None logger.info(f\"NAME={name}/{self.model_name} : {self._model}\") self._layer = None self._unit =", "@property def model_name(self) -> str: \"\"\"The name of the currently", "int: \"\"\"The index of the currently selected unit or None", "selected. _model: LucidModel The currently selected lucid model. None if", "= None self.running = False @property def model(self) -> LucidModel:", "self._doRun(False) def stop(self): self._doRun(False) def start_multi(self): self.image = None self._doRun(True)", "<= unit < self._layer['size']: raise ValueError(f\"Invalid unit {unit} for current", "obj) #self.image = render.render_vis(self.model, self.unit_id) self._doRun(False) def stop(self): self._doRun(False) def", "LucidNetwork The currently selected lucid network. None if no model", "e.g. # models.AlexNet import lucid.modelzoo.vision_models as models import lucid.modelzoo.nets_factory as", "= logging.getLogger(__name__) print(f\"!!!!!!!!!! getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer import Observable,", "self.image = None self._doRun(True) obj = objectives.channel(self.layer_id, self.unit) self.image =", "from network import Network, loader from network.lucid import Network as", "the unit in the layer. \"\"\" if name == self.layer:", "self._layer is None else self._layer['type'] @property def layer_units(self) -> int:", "< self._layer['size']: raise ValueError(f\"Invalid unit {unit} for current layer\" f\"", "'_pre_relu' return self._layer['name'] @property def unit_id(self) -> str: \"\"\"The id", "list self._layer = None self._unit = None self.change(unit_changed=True) @property def", "Observable, change from network import Network, loader from network.lucid import", "_set_unit(self, unit: int) -> None: if unit == self.unit: return", "as e: self._network = None self._model = None logger.info(f\"NAME={name}/{self.model_name} :", "The name of the layer. unit: int The index of", "the currently selected layer. \"\"\" return None if self._layer is", "models.AlexNet import lucid.modelzoo.vision_models as models import lucid.modelzoo.nets_factory as nets from", "_doRun(self, running: bool=True) -> None: self.running = running self.notify_observers(EngineChange(engine_changed=True)) def", "# name not in layer list self._layer = None self._unit", "of the currently selected unit or None if no unit", "layer. unit: int The index of the unit in the", "return self._layer['name'] @property def unit_id(self) -> str: \"\"\"The id of", "no unit is selected. \"\"\" return None if self._unit is", "unit is selected. \"\"\" return (None if self._layer is None", "model. None if no model is selected. \"\"\" return None", "logger.info(f\"load_model({name})\") try: #self._network = LucidNetwork(name=name) self._network = loader.load_lucid(name) self._model =", "self._layer is None: raise ValueError('Setting unit failed as no layer", "= None self.change(model_changed=True, unit_changed=True) return self._model @change def set_layer(self, name:", "selected layer. \"\"\" self.set_layer(name) @property def layer_type(self) -> str: \"\"\"The", "def unit_id(self) -> str: \"\"\"The id of the currently selected", "size {self._layer['size']}\") else: self._unit = unit self.change(unit_changed=True) @property def unit(self)", "return if self._model is None: return try: self._layer = next(x", "unit is selected. \"\"\" if self._layer is None: return None", "= None self._doRun(True) obj = objectives.channel(self.layer_id, self.unit) self.image = render.render_vis(self.model,", "None if self._layer['type'] == 'conv': return self._layer['name'] + '_pre_relu' return", "@change def _set_unit(self, unit: int) -> None: if unit ==", "unit: int=0) -> None: \"\"\"Set the currently selected layer. Arguments", "index of the unit in the layer. \"\"\" if name", "None if self._network is None else self._network.name @change def load_model(self,", "= None self._doRun(True) logger.info(\"!!! running all:\") for unit in range(self.layer_units):", "this is too make old code happy. New code should", "self._layer['size']: raise ValueError(f\"Invalid unit {unit} for current layer\" f\" of", "class Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The Engine is a", "unit is selected. \"\"\" return None if self._unit is None", "unit in the layer. \"\"\" if name == self.layer: return", "int: \"\"\"The number of units in the currently selected layer.", "f\" of size {self._layer['size']}\") else: self._unit = unit self.change(unit_changed=True) @property", "type of the currently selected layer. \"\"\" return None if", "\"\"\"The number of units in the currently selected layer. \"\"\"", "None: if unit == self.unit: return if unit is None:", "self._unit = None self.change(unit_changed=True) @property def layer(self) -> str: \"\"\"The", "self._set_unit(unit) @property def layer_id(self) -> str: \"\"\"The id of the", "None: raise ValueError('Setting unit failed as no layer is selected')", "return self._model @change def set_layer(self, name: str, unit: int=0) ->", "changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The Engine is a wrapper around the", "return if unit is None: self._unit = None self.change(unit_changed=True) elif", "model: LucidModel A reference to the LucidModel. \"\"\" logger.info(f\"load_model({name})\") try:", "else self._layer['size'] @change def _set_unit(self, unit: int) -> None: if", "the layer. unit: int The index of the unit in", "is too make old code happy. New code should use", "str) -> LucidModel: \"\"\"Load the Lucid model with the given", "is None else self._layer['type'] @property def layer_units(self) -> int: \"\"\"The", "\"\"\" logger.info(f\"load_model({name})\") try: #self._network = LucidNetwork(name=name) self._network = loader.load_lucid(name) self._model", "FIXME[old]: this is too make old code happy. New code", "if no unit is selected. \"\"\" return (None if self._layer", "lucid.modelzoo.nets_factory as nets from lucid.modelzoo.vision_base import Model as LucidModel import", "not 0 <= unit < self._layer['size']: raise ValueError(f\"Invalid unit {unit}", "unit(self, unit: int) -> None: \"\"\"The index of the currently", "None if self._layer is None else self._layer['name'] @layer.setter def layer(self,", "of the currently selected layer or None if no unit", "running: bool=True) -> None: self.running = running self.notify_observers(EngineChange(engine_changed=True)) def start(self):", "None if no model is selected. \"\"\" return None if", "@change def load_model(self, name: str) -> LucidModel: \"\"\"Load the Lucid", "@change def set_layer(self, name: str, unit: int=0) -> None: \"\"\"Set", "pretrained networks by name, e.g. # models.AlexNet import lucid.modelzoo.vision_models as", "the layer. \"\"\" if name == self.layer: return if self._model", "name: str, unit: int=0) -> None: \"\"\"Set the currently selected", "if no unit is selected. \"\"\" return None if self._unit", "\"\"\" if self._layer is None: return None if self._layer['type'] ==", "running all:\") for unit in range(self.layer_units): self.unit = unit self.notify_observers(EngineChange(unit_changed=True))", "str The name of the layer. unit: int The index", "@property def layer_id(self) -> str: \"\"\"The id of the currently", "selected layer or None if no unit is selected. \"\"\"", "code happy. New code should use # Engine.Change and Engine.Observer", "None: return None if self._layer['type'] == 'conv': return self._layer['name'] +", "of size {self._layer['size']}\") else: self._unit = unit self.change(unit_changed=True) @property def", "if no model is selected. \"\"\" return None if self._network", "import Model as LucidModel import lucid.optvis.objectives as objectives import lucid.optvis.param", "is None: self._unit = None self.change(unit_changed=True) elif self._layer is None:", "in range(self.layer_units): self.unit = unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit {unit}\")", "is selected. _model: LucidModel The currently selected lucid model. None", "None self.change(unit_changed=True) @property def layer(self) -> str: \"\"\"The name of", "self._model = None self._layer = None self._unit = None self.image", "else self._layer['type'] @property def layer_units(self) -> int: \"\"\"The number of", "id of the currently selected unit or None if no", "the pretrained networks by name, e.g. # models.AlexNet import lucid.modelzoo.vision_models", "if no model is selected. \"\"\" def __init__(self): super().__init__() self._network", "name of the currently selected lucid model. None if no", "is None else self.layer_id + ':' + str(self._unit)) def _doRun(self,", "= render.render_vis(self.model, self.unit_id) self._doRun(False) def stop(self): self._doRun(False) def start_multi(self): self.image", "from dltb.base.observer import Observable, change from network import Network, loader", "def model_name(self) -> str: \"\"\"The name of the currently selected", "\"\"\" def __init__(self): super().__init__() self._network = None self._model = None", "#self.image = render.render_vis(self.model, self.unit_id) self._doRun(False) def stop(self): self._doRun(False) def start_multi(self):", "if self._layer is None else self._layer['size'] @change def _set_unit(self, unit:", "@property def layer_units(self) -> int: \"\"\"The number of units in", "elif self._layer is None: raise ValueError('Setting unit failed as no", "model is selected. \"\"\" return None if self._network is None", "given name. Returns ------- model: LucidModel A reference to the", "index of the currently selected unit or None if no", "None self._model = None self._layer = None self._unit = None", "-> str: \"\"\"The type of the currently selected layer. \"\"\"", "Arguments --------- name: str The name of the layer. unit:", "':' + str(self._unit)) def _doRun(self, running: bool=True) -> None: self.running", "model is selected. \"\"\" return self._model @property def model_name(self) ->", "of the currently selected lucid model. None if no model", "around the lucid module. Attributes ---------- _network: LucidNetwork The currently", "is selected. \"\"\" return self._model @property def model_name(self) -> str:", "-> None: \"\"\"Set the currently selected layer. \"\"\" self.set_layer(name) @property", "self.unit_id) self._doRun(False) def stop(self): self._doRun(False) def start_multi(self): self.image = None", "Model as LucidModel import lucid.optvis.objectives as objectives import lucid.optvis.param as", "# models.AlexNet import lucid.modelzoo.vision_models as models import lucid.modelzoo.nets_factory as nets", "if self._layer is None else self._layer['type'] @property def layer_units(self) ->", "self.running: break self._doRun(True) self._doRun(False) # FIXME[old]: this is too make", "= render.render_vis(self.model, obj) #self.image = render.render_vis(self.model, self.unit_id) self._doRun(False) def stop(self):", "as objectives import lucid.optvis.param as param import lucid.optvis.render as render", "None else self._layer['size'] @change def _set_unit(self, unit: int) -> None:", "self._network is None else self._network.name @change def load_model(self, name: str)", "import Network as LucidNetwork # lucid.modelzoo.vision_models: # A module providinge", "x in self._model.layers if x['name'] == name) self._unit = unit", "\"\"\"The currently selected lucid model. None if no model is", "raise ValueError(f\"Invalid unit {unit} for current layer\" f\" of size", "unit is None: self._unit = None self.change(unit_changed=True) elif self._layer is", "StopIteration: # name not in layer list self._layer = None", "else self._unit @unit.setter def unit(self, unit: int) -> None: \"\"\"The", "None: self.running = running self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image = None", "if self._model is None: return try: self._layer = next(x for", "in the currently selected layer. \"\"\" return None if self._layer", "is None else self._unit @unit.setter def unit(self, unit: int) ->", "dltb.base.observer import Observable, change from network import Network, loader from", "= None self._unit = None self.change(model_changed=True, unit_changed=True) return self._model @change", "print(f\"!!!!!!!!!! getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer import Observable, change from", "elif not 0 <= unit < self._layer['size']: raise ValueError(f\"Invalid unit", "def set_layer(self, name: str, unit: int=0) -> None: \"\"\"Set the", "None else self._layer['name'] @layer.setter def layer(self, name: str) -> None:", "is selected. \"\"\" if self._layer is None: return None if", "if self._layer is None: return None if self._layer['type'] == 'conv':", "old code happy. New code should use # Engine.Change and", "unit failed as no layer is selected') elif not 0", "#self._network = LucidNetwork(name=name) self._network = loader.load_lucid(name) self._model = self._network.model except", "self._layer['type'] == 'conv': return self._layer['name'] + '_pre_relu' return self._layer['name'] @property", "currently selected layer or None if no unit is selected.", "name: str) -> LucidModel: \"\"\"Load the Lucid model with the", "= objectives.channel(self.layer_id, self.unit) self.image = render.render_vis(self.model, obj) #self.image = render.render_vis(self.model,", "render import lucid.optvis.transform as transform class Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed',", "-> int: \"\"\"The index of the currently selected unit or", "self._doRun(True) obj = objectives.channel(self.layer_id, self.unit) self.image = render.render_vis(self.model, obj) #self.image", "0 <= unit < self._layer['size']: raise ValueError(f\"Invalid unit {unit} for", "layer. \"\"\" return None if self._layer is None else self._layer['size']", "super().__init__() self._network = None self._model = None self._layer = None", "None if no model is selected. _model: LucidModel The currently", "def layer(self) -> str: \"\"\"The name of the currently selected", "selected unit or None if no unit is selected. \"\"\"", "if x['name'] == name) self._unit = unit except StopIteration: #", "return None if self._layer is None else self._layer['name'] @layer.setter def", "lucid model. None if no model is selected. \"\"\" return", "import Network, loader from network.lucid import Network as LucidNetwork #", "self._layer is None else self.layer_id + ':' + str(self._unit)) def", "if not self.running: break self._doRun(True) self._doRun(False) # FIXME[old]: this is", "not in layer list self._layer = None self._unit = None", "\"\"\"The Engine is a wrapper around the lucid module. Attributes", "selected lucid network. None if no model is selected. _model:", "network import Network, loader from network.lucid import Network as LucidNetwork", "getEffectiveLevel: {logger.getEffectiveLevel()} !!!!!!!!!!!!!\") from dltb.base.observer import Observable, change from network", "name: str The name of the layer. unit: int The", "as render import lucid.optvis.transform as transform class Engine(Observable, method='engine_changed', changes={'engine_changed',", "self.unit = unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running unit {unit}\") obj =", "return None if self._layer is None else self._layer['size'] @change def", "unit {unit} for current layer\" f\" of size {self._layer['size']}\") else:", "self._layer['type'] @property def layer_units(self) -> int: \"\"\"The number of units", "-> str: \"\"\"The id of the currently selected unit or", "or None if no unit is selected. \"\"\" self._set_unit(unit) @property", "LucidModel import lucid.optvis.objectives as objectives import lucid.optvis.param as param import", "_model: LucidModel The currently selected lucid model. None if no", "Network, loader from network.lucid import Network as LucidNetwork # lucid.modelzoo.vision_models:", "None self.change(unit_changed=True) elif self._layer is None: raise ValueError('Setting unit failed", "current layer\" f\" of size {self._layer['size']}\") else: self._unit = unit", "# A module providinge the pretrained networks by name, e.g.", "self._layer is None else self._layer['size'] @change def _set_unit(self, unit: int)", "model_name(self) -> str: \"\"\"The name of the currently selected lucid", "no model is selected. \"\"\" return None if self._network is", "@property def unit(self) -> int: \"\"\"The index of the currently", "no unit is selected. \"\"\" return (None if self._layer is", "layer(self) -> str: \"\"\"The name of the currently selected layer.", "self._model @property def model_name(self) -> str: \"\"\"The name of the", "logger.info(f\"!!! running unit {unit}\") obj = objectives.channel(self.layer_id, unit) self.image =", "@property def layer_type(self) -> str: \"\"\"The type of the currently", "(None if self._layer is None else self.layer_id + ':' +", "for unit in range(self.layer_units): self.unit = unit self.notify_observers(EngineChange(unit_changed=True)) logger.info(f\"!!! running", "ValueError('Setting unit failed as no layer is selected') elif not", "None self._layer = None self._unit = None self.image = None", "start_multi(self): self.image = None self._doRun(True) logger.info(\"!!! running all:\") for unit", "self.image = None self._doRun(True) logger.info(\"!!! running all:\") for unit in", "self.change(unit_changed=True) @property def unit(self) -> int: \"\"\"The index of the", "obj) if not self.running: break self._doRun(True) self._doRun(False) # FIXME[old]: this", "New code should use # Engine.Change and Engine.Observer directly. EngineChange", "\"\"\"The index of the currently selected unit or None if", "layer. \"\"\" return None if self._layer is None else self._layer['name']", "None self._unit = None self.change(unit_changed=True) @property def layer(self) -> str:", "None: \"\"\"Set the currently selected layer. \"\"\" self.set_layer(name) @property def", "name. Returns ------- model: LucidModel A reference to the LucidModel.", "None if no model is selected. \"\"\" def __init__(self): super().__init__()", "objectives.channel(self.layer_id, unit) self.image = render.render_vis(self.model, obj) if not self.running: break", "as models import lucid.modelzoo.nets_factory as nets from lucid.modelzoo.vision_base import Model", "import lucid.optvis.transform as transform class Engine(Observable, method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}):", "\"\"\" return None if self._unit is None else self._unit @unit.setter", "unit is selected. \"\"\" self._set_unit(unit) @property def layer_id(self) -> str:", "self._model is None: return try: self._layer = next(x for x", "self._doRun(False) # FIXME[old]: this is too make old code happy.", "the currently selected layer. Arguments --------- name: str The name", "self._unit = unit except StopIteration: # name not in layer", "None self.image = None self.running = False @property def model(self)", "module providinge the pretrained networks by name, e.g. # models.AlexNet", "is None: return None if self._layer['type'] == 'conv': return self._layer['name']", "= LucidNetwork(name=name) self._network = loader.load_lucid(name) self._model = self._network.model except KeyError", "selected') elif not 0 <= unit < self._layer['size']: raise ValueError(f\"Invalid", "def unit(self) -> int: \"\"\"The index of the currently selected", "None self._doRun(True) logger.info(\"!!! running all:\") for unit in range(self.layer_units): self.unit", "bool=True) -> None: self.running = running self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image", "or None if no unit is selected. \"\"\" return (None", "self.unit: return if unit is None: self._unit = None self.change(unit_changed=True)", "a wrapper around the lucid module. Attributes ---------- _network: LucidNetwork", "to the LucidModel. \"\"\" logger.info(f\"load_model({name})\") try: #self._network = LucidNetwork(name=name) self._network", "layer. \"\"\" self.set_layer(name) @property def layer_type(self) -> str: \"\"\"The type", "obj = objectives.channel(self.layer_id, unit) self.image = render.render_vis(self.model, obj) if not", "running self.notify_observers(EngineChange(engine_changed=True)) def start(self): self.image = None self._doRun(True) obj =", "layer_id(self) -> str: \"\"\"The id of the currently selected layer", "= None self.change(unit_changed=True) elif self._layer is None: raise ValueError('Setting unit", "render.render_vis(self.model, obj) if not self.running: break self._doRun(True) self._doRun(False) # FIXME[old]:", "_network: LucidNetwork The currently selected lucid network. None if no", "---------- _network: LucidNetwork The currently selected lucid network. None if", "layer_type(self) -> str: \"\"\"The type of the currently selected layer.", "in self._model.layers if x['name'] == name) self._unit = unit except", "objectives import lucid.optvis.param as param import lucid.optvis.render as render import", "try: self._layer = next(x for x in self._model.layers if x['name']", "not self.running: break self._doRun(True) self._doRun(False) # FIXME[old]: this is too", "except KeyError as e: self._network = None self._model = None", "of the layer. unit: int The index of the unit", "module. Attributes ---------- _network: LucidNetwork The currently selected lucid network.", "lucid.modelzoo.vision_models: # A module providinge the pretrained networks by name,", "\"\"\"Set the currently selected layer. Arguments --------- name: str The", "method='engine_changed', changes={'engine_changed', 'model_changed', 'unit_changed'}): \"\"\"The Engine is a wrapper around", "model(self) -> LucidModel: \"\"\"The currently selected lucid model. None if", "self._model = self._network.model except KeyError as e: self._network = None", "layer_units(self) -> int: \"\"\"The number of units in the currently", "Network as LucidNetwork # lucid.modelzoo.vision_models: # A module providinge the", "A module providinge the pretrained networks by name, e.g. #", "layer. Arguments --------- name: str The name of the layer.", "of the currently selected layer. \"\"\" return None if self._layer", "-> None: if unit == self.unit: return if unit is", "model is selected. \"\"\" def __init__(self): super().__init__() self._network = None", "int) -> None: \"\"\"The index of the currently selected unit", "network.lucid import Network as LucidNetwork # lucid.modelzoo.vision_models: # A module", "LucidNetwork # lucid.modelzoo.vision_models: # A module providinge the pretrained networks", "return None if self._unit is None else self._unit @unit.setter def", "selected. \"\"\" return (None if self._layer is None else self.layer_id", "None self._doRun(True) obj = objectives.channel(self.layer_id, self.unit) self.image = render.render_vis(self.model, obj)", "self._layer is None: return None if self._layer['type'] == 'conv': return", "by name, e.g. # models.AlexNet import lucid.modelzoo.vision_models as models import", "if no unit is selected. \"\"\" if self._layer is None:", "name, e.g. # models.AlexNet import lucid.modelzoo.vision_models as models import lucid.modelzoo.nets_factory", "------- model: LucidModel A reference to the LucidModel. \"\"\" logger.info(f\"load_model({name})\")", "int) -> None: if unit == self.unit: return if unit", "-> None: \"\"\"The index of the currently selected unit or", "None if no unit is selected. \"\"\" if self._layer is", ": {self._model}\") self._layer = None self._unit = None self.change(model_changed=True, unit_changed=True)", "str) -> None: \"\"\"Set the currently selected layer. \"\"\" self.set_layer(name)", "__init__(self): super().__init__() self._network = None self._model = None self._layer =", "objectives.channel(self.layer_id, self.unit) self.image = render.render_vis(self.model, obj) #self.image = render.render_vis(self.model, self.unit_id)", "None else self._unit @unit.setter def unit(self, unit: int) -> None:", "None if no unit is selected. \"\"\" self._set_unit(unit) @property def", "return (None if self._layer is None else self.layer_id + ':'", "= False @property def model(self) -> LucidModel: \"\"\"The currently selected", "if self._layer is None else self.layer_id + ':' + str(self._unit))", "selected layer. Arguments --------- name: str The name of the", "no model is selected. _model: LucidModel The currently selected lucid", "currently selected unit or None if no unit is selected.", "def unit(self, unit: int) -> None: \"\"\"The index of the", "= loader.load_lucid(name) self._model = self._network.model except KeyError as e: self._network", "break self._doRun(True) self._doRun(False) # FIXME[old]: this is too make old" ]
[ "already been persisted. Returns: Deferred[set[str]] \"\"\" # The set of", "def _calculate_state_delta(self, room_id, current_state): \"\"\"Calculate the new state deltas for", "room. For each room, a list of the event ids", "twice should_delete_params += (\"%:\" + self.hs.hostname, \"%:\" + self.hs.hostname) should_delete_params", "\"SELECT event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \"", "): txn.executemany( \"DELETE FROM %s WHERE event_id = ?\" %", "VALUES (?,?)\", (event.event_id, event.redacts), ) @defer.inlineCallbacks def count_daily_messages(self): \"\"\" Returns", "to resolve our state sets. state_groups = {sg: state_groups_map[sg] for", "room Args: room_id (str): room to which the events are", "delta from the existing to new current state, # so", "should_delete_expr += \" AND event_id NOT LIKE ?\" # We", "event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\", None) return d self._simple_insert_many_txn( txn, table=\"event_json\",", "each new event\", buckets=(1, 2, 3, 5, 7, 10, 15,", "BackgroundUpdateStore, ): def __init__(self, db_conn, hs): super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue", "the minimum depth of the backwards # extremities. However, the", "the prev-event graph until it finds no more soft-failed/rejected events.", "can be deleted and the set of state groups that", "events_and_contexts: # nothing to do here return def event_dict(event): d", "delete_existing (bool): True to purge existing table rows for the", "= yield self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids = yield self._calculate_new_extremities( room_id,", "# Insert into the redactions table. self._store_redaction(txn, event) elif event.type", "def _update_metadata_tables_txn( self, txn, events_and_contexts, all_events_and_contexts, backfilled ): \"\"\"Update all", "table. Things reading from those table will need to check", "where to_delete are the type/state_keys to remove from current_state_events and", "new_events_and_contexts.get(event.event_id) if prev_event_context: if not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): # To", "def event_dict(event): d = event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\", None) return", "txn.call_after(prefill) def _store_redaction(self, txn, event): # invalidate the cache for", "queue = self._event_persist_queues.setdefault(room_id, deque()) try: while True: yield queue.popleft() except", "USING (event_id)\" \" WHERE ? > stream_ordering AND stream_ordering >=", "from synapse.util.logutils import log_function from synapse.util.metrics import Measure logger =", "state_group_id, }, ) sql = \"UPDATE events SET outlier =", "= txn.fetchall() if len(new_event_updates) == limit: upper_bound = new_event_updates[-1][0] else:", "be invoked with for each item in the queue, of", "\" AND event_stream_ordering >= ?\" \" ORDER BY event_stream_ordering DESC\"", "allows us to later efficiently look up the forward extremeties", "block event # persistence. # # We do this by", "% (\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id for event, _ in events_and_contexts],", "_ in events_and_contexts ], ) def _store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add", "which aren't # being rejected. new_events = [ event for", "that the database transactions # have a logcontext to report", "do know the delta then the new current state is", "if event_id == ev.event_id and ctx.state_group is not None: event_id_to_state_group[event_id]", "sg, in txn) logger.info( \"[purge] found %i referenced state groups\",", "self.hs.hostname) should_delete_params += (room_id, token.topological) # Note that we insert", "the same event twice. Pick the earliest non-outlier if there", "-= referenced rows = self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={},", "License for the specific language governing permissions and # limitations", "these events. # This is simply used to prefill the", "forward extremities result = set(latest_event_ids) # add all the new", "state_key for ev_type, state_key in itertools.chain(to_delete, to_insert) if ev_type ==", "# Insert into the event_search table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event)", "get_all_new_events_txn(txn): sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \"", "Prefill the event cache self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self, txn, events_and_contexts):", "event, ctx in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds = []", "to ensure we don't delete all the events from the", "events so that they can be persisted in bulk with", "in itertools.chain(to_delete, to_insert) ), ) self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[ {", "(room_id,), ) # Mark all state and own events as", "values=[ {\"event_id\": ev_id, \"room_id\": room_id} for room_id, new_extrem in iteritems(new_forward_extremities)", "to fetch groups for. (We know none of the old", "the send_join # results, in which case there will be", "the forward extremeties txn.execute( \"SELECT e.event_id, e.depth FROM events as", "for key, state_id in iteritems(curr_state) ], ) logger.info(\"[purge] removing redundant", "Read the extrems every 60 minutes def read_forward_extremities(): # run", "synapse.util.logutils import log_function from synapse.util.metrics import Measure logger = logging.getLogger(__name__)", "don't care if the event # was an outlier or", "the latest extremities # were the same when we created", "\"\"\" Returns an estimate of the number of messages sent", "the txn in sqlite, # so make sure to keep", "e\" \" INNER JOIN ex_outlier_stream USING (event_id)\" \" LEFT JOIN", "# now. When this server creates a new event (as", "len(state_groups_to_delete) ) logger.info( \"[purge] de-delta-ing %i remaining state groups\", len(remaining_state_groups),", "Pick the earliest non-outlier if there is one, else the", "list[str]]): The new forward extremities for each room. For each", "as well as the new. stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number", "check if the event is one we're persisting, in which", "SynapseError( 400, \"topological_ordering is greater than forward extremeties\" ) logger.info(\"[purge]", "forward extremity state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\", \"\" ) # The", "and not context.rejected: depth_updates[event.room_id] = max( event.depth, depth_updates.get(event.room_id, event.depth) )", "Measure(self._clock, \"persist_events\"): yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error", "we turn the state groups that reference to-be-deleted state #", "self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id, \"room_id\": room_id} for room_id,", "Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. # #", "is only a # single forward extremity state_delta_single_event_counter = Counter(", "# Ok, we need to defer to the state handler", "in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) ) @defer.inlineCallbacks def _calculate_new_extremities(self, room_id,", "= ( \"SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts,", "referenced. current_search -= referenced rows = self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\",", "OF ANY KIND, either express or implied. # See the", "that are going to be deleted. Returns: tuple[set[int], set[int]]: The", "from twisted.internet import defer import synapse.metrics from synapse.api.constants import EventTypes", "for room_id, current_state_tuple in iteritems(state_delta_by_room): to_delete, to_insert = current_state_tuple #", "= [] sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\"", "\" e.event_id as event_id, \" \" r.redacts as redacts,\" \"", "values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict() ),", "out class _EventPeristenceQueue(object): \"\"\"Queues up events so that they can", ") def _purge_history_txn(self, txn, room_id, token_str, delete_local_events): token = RoomStreamToken.parse(token_str)", "get_all_updated_current_state_deltas_txn(txn): sql = \"\"\" SELECT stream_id, room_id, type, state_key, event_id", "we are persisting all_events_and_contexts (list[(EventBase, EventContext)]): all events that we", "# state_groups # state_groups_state # we will build a temporary", "dangling extremities. existing_prevs = yield self._get_prevs_before_rejected( e_id for event in", "{e[0].event_id: e[0] for e in events_and_contexts[i : i + N]}", "# First we add entries to the current_state_delta_stream. We #", "self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self): def _count_messages(txn): # This", "event.type == EventTypes.Topic: # Insert into the topics table and", "self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, ) if not event.internal_metadata.is_outlier() and not context.rejected:", "( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \"", "room at a time. \"\"\" # we're only interested in", "USING (event_id) WHERE state_group IN (%s) AND ep.event_id IS NULL", "\"\"\" SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM events WHERE type =", "while True: yield queue.popleft() except IndexError: # Queue has been", ") txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, ) # Invalidate the various", "# NB: Assumes that we are only persisting events for", "break if not room_version: room_version = yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups", "state groups are referenced sql = \"\"\" SELECT DISTINCT state_group", "\" INNER JOIN ex_outlier_stream USING (event_id)\" \" LEFT JOIN redactions", "\"SELECT \" \" e.event_id as event_id, \" \" r.redacts as", "FROM events_to_purge INNER JOIN event_to_state_groups USING (event_id) \"\"\" ) referenced_state_groups", "at a time. Returns: tuple[list, dict] (to_delete, to_insert): where to_delete", "(event_id)\" \" LEFT JOIN redactions USING (event_id)\" \" LEFT JOIN", "pull out the state groups for any missing events from", "?, ?, ?, ?, ( SELECT event_id FROM current_state_events WHERE", "self._store_history_visibility_txn(txn, event) elif event.type == EventTypes.GuestAccess: # Insert into the", "NOT events.outlier \"\"\" % ( \",\".join(\"?\" for _ in to_recursively_check),", "state groups that can be deleted\") _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups)", "those that have been soft-failed or rejected. Returns those soft", "messages sent in the last day. If it has been", "not use this file except in compliance with the License.", "current_state_delta_stream. We # do this before updating the current_state_events table", "event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE ? > event_stream_ordering\"", "rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk in batch_iter(event_ids, 100): yield self.runInteraction(", "(event_id) LEFT JOIN rejections USING (event_id) LEFT JOIN event_json USING", "ancestors of new events, but are separated by soft failed", "and ev.state_key == \"\": room_version = ev.content.get(\"room_version\", \"1\") break if", ") txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id, \"room_id\":", "# create an index on should_delete because later we'll be", "in state_groups_map: continue # We're only interested in pulling out", "self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups = _ logger.info( \"[purge] found %i", "against events_to_purge for e.g. calculating state # groups to purge,", "an index on event_id, and has one on # (room_id,", "token (str): A topological token to delete events before delete_local_events", "are going to be deleted. Returns: tuple[set[int], set[int]]: The set", "in events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id) if prev_event_context: if not event.internal_metadata.is_outlier():", "deferred is ready. Args: room_id (str): events_and_contexts (list[(EventBase, EventContext)]): backfilled", "# The stream_id for the update is chosen to be", "# If there is only one state group, then we", "delta_ids = res # If either are not None then", "group can have at most one prev group graph[row[\"state_group\"]] =", "if not json.loads(r[1]).get(\"soft_failed\")) for chunk in batch_iter(event_ids, 100): yield self.runInteraction(", "one concurrent transaction per room. \"\"\" _EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\",", "into the event_search table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event) # Insert", "etc. Returns: Deferred[int]: the stream ordering of the latest persisted", "or not the returned deferred is ready. Args: room_id (str):", "(stream_id, room_id, type, state_key, event_id, prev_event_id) SELECT ?, ?, ?,", "purge attempt, so let's drop the table first. txn.execute(\"DROP TABLE", "we need to remove them and their prev events, #", "in txn) logger.info( \"[purge] found %i referenced state groups\", len(referenced_state_groups)", "the new forward # extremities in each room new_forward_extremeties =", "updates. # sql = \"\"\" INSERT INTO current_state_delta_stream (stream_id, room_id,", "FROM event_backward_extremities WHERE room_id = ?\", (room_id,) ) # Update", "if not res: raise SynapseError(404, \"Could not find event %s\"", "events have reached\"\"\" return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id, current_id, limit):", "we delete them. txn.execute( \"\"\" SELECT DISTINCT state_group FROM events_to_purge", "# backfilled events have negative stream orderings, so we don't", "events we are persisting all_events_and_contexts (list[(EventBase, EventContext)]): all events that", "BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers = txn.fetchall()", "to be # deleted. We then go and check if", "min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) # Ensure that we", "should_delete BOOLEAN NOT NULL\" \")\" ) # First ensure that", "events are persisted. Runs its callbacks *without* a logcontext. \"\"\"", "a single state set. missing_state = new_state_groups - set(state_groups_map) if", "max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order,", "\"auth_id\": auth_id, } for event, _ in events_and_contexts for auth_id", "event_ids): \"\"\"Get soft-failed ancestors to remove from the extremities. Given", "event ids to filter Returns: Deferred[List[str]]: filtered event ids \"\"\"", "are only persisting events for one room # at a", "# events to be purged that are pointed to by", "res = yield func(self, *args, delete_existing=True, **kwargs) defer.returnValue(res) return f", "= ev.content.get(\"room_version\", \"1\") break if not room_version: room_version = yield", "all events that we were going to persist. This includes", "event, _ in events_and_contexts: if event.type == EventTypes.Name: # Insert", "and once we run this update, we # will block", "iterating up the state group graphs for state # groups", "only persisting events for one room at a time. \"\"\"", "\"type\": event.type, \"state_key\": event.state_key, } # TODO: How does this", "[key for key in existing_state if key not in current_state]", "in ev_ctx_rm ) # Don't bother calculating state if they're", "and the events_json table. to_remove = set() for event, context", "the rejected events. \"\"\" # Remove the rejected events from", "] for chunk in chunks: # We can't easily parallelize", "self._store_room_members_txn( txn, [ event for event, _ in events_and_contexts if", "events_to_purge \" \" WHERE NOT should_delete\" \")\", (True,), ) #", "forward extremities for the room. new_latest_event_ids (iterable[str]): the new forward", "to db Args: events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): delete_existing (bool):", "we've already persisted, etc, that wouldn't appear in events_and_context. backfilled", "for ec in events_and_contexts if ec[0].is_state() ] state_values = []", ") txn.execute(sql, batch) results.extend(r[0] for r in txn if not", "there has been no change. If there has been a", "\"event_id\": state_id, } for key, state_id in iteritems(curr_state) ], )", "== limit: upper_bound = new_forward_events[-1][0] else: upper_bound = current_forward_id sql", "# current_state_delta updates. # sql = \"\"\" INSERT INTO current_state_delta_stream", "events to the database Args: events_and_contexts: list of tuples of", "from current_state_events and `to_insert` are the updates to current_state_events. \"\"\"", "state map state_groups_map = {} # Map from (prev state", "which are already in the events table. \"\"\" txn.execute( \"SELECT", "{ key: ev_id for key, ev_id in iteritems(current_state) if ev_id", "self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids ) latest_event_ids = set(latest_event_ids) if new_latest_event_ids", "AND event_id = ?\" % (table,), [(ev.room_id, ev.event_id) for ev,", "previous set of extremities as well as the new. stale_forward_extremities_counter", "_add_to_cache(self, txn, events_and_contexts): to_prefill = [] rows = [] N", "= ? AND event_id = ?\" % (table,), [(ev.room_id, ev.event_id)", "and their prev events. existing_prevs = set() def _get_prevs_before_rejected_txn(txn, batch):", "events to be purged that are pointed to by events", "deleted, as nothing will happen to them. txn.execute( \"INSERT INTO", "txn, events_and_contexts): \"\"\"Insert new events into the event and event_json", "event_backward_extremities table now that this # event isn't an outlier", "backfilled events have negative stream orderings, so we don't #", "FROM event_to_state_groups LEFT JOIN events_to_purge AS ep USING (event_id) WHERE", "is ready. Args: room_id (str): events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool):", "== prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state delta for room %s\",", "the events are being added. Used for logging etc events_context", "WHERE room_id = ? AND type = ? AND state_key", "txn.execute(sql, to_recursively_check) to_recursively_check = [] for event_id, prev_event_id, metadata, rejected", "SynapseError from synapse.events import EventBase # noqa: F401 from synapse.events.snapshot", "event. Stale extremities # are those that were in the", "= txn.fetchone() logger.info(\"[purge] updating room_depth to %d\", min_depth) txn.execute( \"UPDATE", "self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self): def _count(txn): sql =", "[] N = 200 for i in range(0, len(events_and_contexts), N):", "\"DELETE FROM state_groups WHERE id = ?\", ((sg,) for sg", "latest persisted event \"\"\" partitioned = {} for event, ctx", "need to ensure we don't delete all the events from", "e_id for event in new_events for e_id in event.prev_event_ids() )", "chosen to be the minimum of the stream_ids # for", "the `prev_event_id`. (This # allows us to not have to", "= ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts,", "= state_group_deltas.get((old_state_group, new_state_group), None) if delta_ids is not None: #", "forward extremeties # for a room before a given stream_ordering", "existing events. existing_prevs = yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally handle", "first being the full new current state and the second", "else: new_forward_events = [] forward_ex_outliers = [] sql = (", "number of extremities to count self._current_forward_extremities_amount = c_counter() BucketCollector( \"synapse_forward_extremities\",", ") txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers = txn.fetchall() else: new_forward_events =", "AND stream_ordering >= ?\" \" ORDER BY stream_ordering DESC\" \"", "COALESCE(MIN(depth), 0) FROM event_backward_extremities AS eb INNER JOIN event_edges AS", "e.event_id, e.depth FROM events as e \" \"INNER JOIN event_forward_extremities", "\"INSERT INTO redactions (event_id, redacts) VALUES (?,?)\", (event.event_id, event.redacts), )", "= current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids # We", "(last_forward_id, upper_bound)) forward_ex_outliers = txn.fetchall() else: new_forward_events = [] forward_ex_outliers", "\" FROM events as e\" \" LEFT JOIN rejections as", "e.event_id = eg.event_id WHERE eb.room_id = ? \"\"\", (room_id,), )", "groups to delete\", len(state_groups_to_delete) ) logger.info( \"[purge] de-delta-ing %i remaining", "+ self.hs.hostname) should_delete_params += (room_id, token.topological) # Note that we", "the temp table. this will commit the txn in sqlite,", "room_id, ev_ctx_rm in iteritems(events_by_room): latest_event_ids = yield self.get_latest_event_ids_in_room( room_id )", "# event_json # event_push_actions # event_reference_hashes # event_search # event_to_state_groups", "in state_groups_to_delete), ) logger.info(\"[purge] removing events from event_to_state_groups\") txn.execute( \"DELETE", "current_search = next_to_search next_to_search = set() else: current_search = set(itertools.islice(next_to_search,", "not event.internal_metadata.is_outlier() and not ctx.rejected and not event.internal_metadata.is_soft_failed() ] latest_event_ids", "% (should_delete_expr, should_delete_expr), should_delete_params, ) # We create the indices", "this point onwards the events are only events that we", "which are prev_events of existing (non-outlier/rejected) events. Args: event_ids (Iterable[str]):", "to the ex_outlier_stream table to replicate the # change in", "\"\"\" deferred = self._event_persist_queue.add_to_queue( event.room_id, [(event, context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id)", "\" LEFT JOIN state_events USING (event_id)\" \" LEFT JOIN event_relations", "the database missing_event_ids.add(event_id) if missing_event_ids: # Now pull out the", "F401 from synapse.events.snapshot import EventContext # noqa: F401 from synapse.metrics", "six import iteritems, text_type from six.moves import range from canonicaljson", "is one, else the earliest one. Args: events_and_contexts (list[(EventBase, EventContext)]):", "storage compared to storing the entire event # anyway). self._simple_insert_many_txn(", "of type/state keys to be removed from the current state,", "= ? WHERE room_id = ?\", (min_depth, room_id), ) #", "event_json USING (event_id) WHERE prev_event_id IN (%s) AND NOT events.outlier", "updates to current_state_events. \"\"\" existing_state = yield self.get_current_state_ids(room_id) to_delete =", "WHERE room_id = ? AND event_id = ?\" % (table,),", "backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert some number of room", "continue outlier_persisted = have_persisted[event.event_id] if not event.internal_metadata.is_outlier() and outlier_persisted: #", "persisted event \"\"\" partitioned = {} for event, ctx in", "to prefill the get_current_state_ids # cache current_state_for_room = {} #", "will be no existing # extremities, so we'll `continue` above", "extremities are going to be in events_context). missing_event_ids = set(old_latest_event_ids)", "in chunk: if context.app_service: origin_type = \"local\" origin_entity = context.app_service.id", "if not delete_local_events: should_delete_expr += \" AND event_id NOT LIKE", "forward extremities for the room. Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]:", "# This is a fairly handwavey check to see if", "backfilled=backfilled, ) def _update_current_state_txn(self, txn, state_delta_by_room, stream_id): for room_id, current_state_tuple", "from synapse.api.errors import SynapseError from synapse.events import EventBase # noqa:", "in to_delete # We sanity check that we're deleting rather", "state_delta_single_event_counter.inc() # This is a fairly handwavey check to see", "deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, )", "table=\"events\", values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\": event.depth, \"event_id\":", "out the changes of membership to invalidate the # `get_rooms_for_user`", "in events_and_contexts], ) def _store_event_txn(self, txn, events_and_contexts): \"\"\"Insert new events", "(event_id)\" \" WHERE ? < stream_ordering AND stream_ordering <= ?\"", "in ( \"events\", \"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\",", "internal_metadata = ?\" \" WHERE event_id = ?\" ) txn.execute(sql,", "depth of the backwards # extremities. However, the events in", "state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" ) # The number of", "stream_id, room_id, etype, state_key, ev_id, room_id, etype, state_key, ) for", "to new current state, # so lets just return that.", "we happen to already have # the current state in", "but its easier for now just to store them (and", "if len(new_backfill_events) == limit: upper_bound = new_backfill_events[-1][0] else: upper_bound =", "context in events_and_contexts: if event.event_id not in have_persisted: continue to_remove.add(event)", "logcontext. \"\"\" queue = self._event_persist_queues.setdefault(room_id, deque()) if queue: # if", "# Collect metrics on the number of forward extremities that", "events from the database. This is useful when retrying due", "be deleted\") _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups = _", "ev, _ in ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids()) if latest_event_ids ==", "event_id_to_state_group = {} for event_id in new_latest_event_ids: # First search", "state when there is only a # single forward extremity", "self._store_event_state_mappings_txn(txn, ((event, context),)) except Exception: logger.exception(\"\") raise metadata_json = encode_json(event.internal_metadata.get_dict())", "implied. # See the License for the specific language governing", "get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self, last_id, current_id, limit): if last_id ==", "ORDER BY stream_id ASC LIMIT ? \"\"\" txn.execute(sql, (from_token, to_token,", "\"+Inf\"), ) # The number of stale forward extremities for", "greater than forward extremeties\" ) logger.info(\"[purge] looking for events to", "(instead of just marking them as outliers and deleting their", "not going to # purge. txn.execute( \"SELECT DISTINCT e.event_id FROM", "# there should always be at least one forward extremity.", "r in txn if not json.loads(r[1]).get(\"soft_failed\")) for chunk in batch_iter(event_ids,", "background process to make sure that the database transactions #", "\"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\", ): logger.info(\"[purge] removing events", "self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) == 1: # If there is", "keys entirely. state_delta_for_room[room_id] = ([], delta_ids) elif current_state is not", "= last_backfill_id != current_backfill_id have_forward_events = last_forward_id != current_forward_id if", "that are outliers and aren't going to be # deleted,", "at the events that # point to it via event_edges", "find extremities that are ancestors of new events, but are", "Insert event_reference_hashes table. self._store_event_reference_hashes_txn( txn, [event for event, _ in", "[] forward_ex_outliers = [] sql = ( \"SELECT -e.stream_ordering, e.event_id,", "to_recursively_check), ) txn.execute(sql, to_recursively_check) to_recursively_check = [] for event_id, prev_event_id,", "hostname then thats your own fault. like_clause = \"%:\" +", "): def __init__(self, db_conn, hs): super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue =", "_ in events_and_contexts], ) have_persisted = {event_id: outlier for event_id,", "room_id->list[event_ids] giving the new forward # extremities in each room", "this first. # # furthermore, we might already have the", "500, \"+Inf\"], ) # Read the extrems every 60 minutes", "rej.event_id as rejects \" \" FROM events as e\" \"", "set. missing_state = new_state_groups - set(state_groups_map) if missing_state: group_to_state =", "we are recalculating state when there is only a #", "_count_messages(txn): # This is good enough as if you have", "update is chosen to be the minimum of the stream_ids", "room_version, state_groups, events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None)) @defer.inlineCallbacks def _calculate_state_delta(self,", "we'll be looking for # the should_delete / shouldn't_delete subsets", "\"group\" % (ev.event_id,) ) continue if ctx.state_group in state_groups_map: continue", "txn, [event for event, _ in events_and_contexts] ) state_events_and_contexts =", "state maps, the first being the full new current state", "event_id2 in the stream \"\"\" to_1, so_1 = yield self._get_event_ordering(event_id1)", "== ev.event_id and ctx.state_group is not None: event_id_to_state_group[event_id] = ctx.state_group", "and the set of state groups that need to be", "the specific language governing permissions and # limitations under the", "not ev.internal_metadata.is_outlier(): raise Exception( \"Context for new event %s has", "have reached\"\"\" return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id, current_id, limit): if", "for event, ctx in event_contexts if not event.internal_metadata.is_outlier() and not", "return defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql = ( \"SELECT -e.stream_ordering, e.event_id,", "reinsert them. # This gets around any problems with some", "logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter = Counter( \"synapse_storage_events_persisted_events_sep\", \"\",", "redacts, relates_to_id\" \" FROM events AS e\" \" LEFT JOIN", "from that. events_by_room = {} for event, context in chunk:", "functools import wraps from six import iteritems, text_type from six.moves", "outliers into ex-outliers (unless the new event was rejected). Args:", "self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit, ): \"\"\"Get all the", "= set(state_groups) # Set of state groups to handle next.", "already been calculated. Conversely if we do know the delta", "current_backfill_id, current_forward_id, limit, ): \"\"\"Get all the new events that", "the # SQL query getting too big if len(next_to_search) <", "events that are to be # deleted. We then go", "them (and # it doesn't take much storage compared to", "at the server either as new events or as backfilled", "in events_and_contexts for auth_id in event.auth_event_ids() if event.is_state() ], )", "event_counter = Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\", \"origin_entity\"], ) #", "to new forward extremeties in the room. # This allows", "\"\"\"Used when purging history to figure out which state groups", "to our workers. stream_order = event.internal_metadata.stream_ordering state_group_id = context.state_group self._simple_insert_txn(", "elif event.type == EventTypes.Topic: # Insert into the topics table", "to later efficiently look up the forward extremeties # for", "= self._event_persist_queues.setdefault(room_id, deque()) if queue: # if the last item", "persisted, etc, that wouldn't appear in events_and_context. backfilled (bool): True", "group %s\", sg) curr_state = self._get_state_groups_from_groups_txn(txn, [sg]) curr_state = curr_state[sg]", "have silly characters in your own # hostname then thats", "?\", ( (room_id, etype, state_key) for etype, state_key in itertools.chain(to_delete,", "self.hs.is_mine_id(event.sender): origin_type = \"local\" origin_entity = \"*client*\" else: origin_type =", "guessed what the delta would have been when # processing", "events into the event and event_json tables Args: txn (twisted.enterprise.adbapi.Connection):", "EventTypes from synapse.api.errors import SynapseError from synapse.events import EventBase #", "de-delta-ing remaining state group %s\", sg) curr_state = self._get_state_groups_from_groups_txn(txn, [sg])", "-> delta state dict state_group_deltas = {} for ev, ctx", "state handler to resolve our state sets. state_groups = {sg:", "chunk: events_by_room.setdefault(event.room_id, []).append( (event, context) ) for room_id, ev_ctx_rm in", "invoked with for each item in the queue, of type", ") # Mark all state and own events as outliers", "being scheduled for deletion). Args: txn state_groups (set[int]): Set of", "if the last item in the queue has the same", "Queue has been drained. pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\"))", "event_id = ?\" txn.execute(sql, (False, event.event_id)) # Update the event_backward_extremities", "\"\"\" # map from state_group to ((type, key) -> event_id)", "@defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter the supplied list of event_ids", "only a # single forward extremity state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\",", "from functools import wraps from six import iteritems, text_type from", "event \"\"\" partitioned = {} for event, ctx in events_and_contexts:", "if not event.internal_metadata.is_outlier() and not context.rejected: depth_updates[event.room_id] = max( event.depth,", "doesn't take much storage compared to storing the entire event", "new \"current state\" for each room. # We do this", "(dict[str, list[str]]): The new forward extremities for each room. For", ") def _store_event_txn(self, txn, events_and_contexts): \"\"\"Insert new events into the", "for ev, _ in events_context} # We need to get", "backfilled delete_existing (bool): True to purge existing table rows for", "LEFT JOIN events_to_purge AS ep2 ON ed.event_id = ep2.event_id\" \"", "e in event_rows if e[1]), ) logger.info(\"[purge] Finding new backward", "event_id, \"stream_ordering\": max_stream_order, } for room_id, new_extrem in iteritems(new_forward_extremities) for", "current_search -= referenced rows = self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search,", "type, state_key, event_id FROM current_state_delta_stream WHERE ? < stream_id AND", "the current_state_events table so # that we can use it", "referenced by events that are going to be deleted. Returns:", "self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def persist_event(self, event, context, backfilled=False): \"\"\"", "of just marking them as outliers and deleting their state", "event_id, \" \" r.redacts as redacts,\" \" rej.event_id as rejects", "all the existing entries # for these events so we", "new_state) for room_id, latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) )", "yield func(self, *args, delete_existing=True, **kwargs) defer.returnValue(res) return f # inherits", "the queue becomnes empty. The return value of the function", "we couldn't find it, then we'll need to pull #", "= yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups of old_latest_event_ids old_state_groups", "the queue. If another callback is currently handling the queue", "already having # entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert", "filters out any events which were # rejected, and returns", "replicate the # change in outlier status to our workers.", "a set of events, find all those that have been", "latest_event_ids: # No change in extremities, so no change in", "event_id FROM current_state_delta_stream WHERE ? < stream_id AND stream_id <=", "for an event we were # persisting. state_delta_reuse_delta_counter = Counter(", "for the update is chosen to be the minimum of", "checking # if they match the current forward extremities. for", "events are only events that we haven't # seen before.", "depth) def _update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update any outliers with new", "prev_event_id, metadata, rejected in txn: if prev_event_id in existing_prevs: continue", "group graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete = state_groups_seen - referenced_groups to_dedelta", "case where the new events have soft-failed prev # events.", "new current state, # so lets just return that. If", "= txn.fetchall() max_depth = max(row[1] for row in rows) if", "evid in new_latest_event_ids ) # If they old and new", "need to fetch groups for. (We know none of the", "new_events = [ event for event, ctx in event_contexts if", "run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000)", "get_all_new_events( self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit, ): \"\"\"Get all", "sure to keep this actually last. txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge]", "yield self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None))", "type = ? AND state_key = ?\", ( (room_id, etype,", "Set of state groups referenced by events that are going", "< 100: current_search = next_to_search next_to_search = set() else: current_search", "EventContext)] new list, without events which are already in the", "to replicate the # change in outlier status to our", "( \"SELECT -event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE", "new_latest_event_ids new_state_groups = set( event_id_to_state_group[evid] for evid in new_latest_event_ids )", "PreserveLoggingContext(): item.deferred.callback(ret) finally: queue = self._event_persist_queues.pop(room_id, None) if queue: self._event_persist_queues[room_id]", "\"\"\"Returns True if event_id1 is after event_id2 in the stream", "is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok, we need to defer to", "any missing events from DB event_to_groups = yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups)", "TABLE IF EXISTS events_to_purge\") txn.execute( \"CREATE TEMPORARY TABLE events_to_purge (\"", "[sg]) curr_state = curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg} )", "for event_id in new_extrem ], ) @classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts):", "retrieved from federation via backfill or not. Used to determine", "defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self, from_token, to_token, limit): def", "= ?\" \" WHERE event_id = ?\" ) txn.execute(sql, (metadata_json,", "import EventBase # noqa: F401 from synapse.events.snapshot import EventContext #", "rows: # Note: Each state group can have at most", "\" WHERE ep2.event_id IS NULL\" ) new_backwards_extrems = txn.fetchall() logger.info(\"[purge]", "self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop off in the", "change then we only return the delta if its already", "getting too big if len(next_to_search) < 100: current_search = next_to_search", "txn.execute( \"\"\" select count(*) c from event_forward_extremities group by room_id", "the context. We'll pull stuff out of the DB later", "backward extremeties by finding # events to be purged that", "groups for any missing events from DB event_to_groups = yield", "<= ? ORDER BY stream_id ASC LIMIT ? \"\"\" txn.execute(sql,", "subsets txn.execute( \"CREATE INDEX events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\" ) #", "\"event_id\": event.event_id, \"state_group\": state_group_id, }, ) sql = \"UPDATE events", "logger.info( \"[purge] found %i events before cutoff, of which %i", "group from the database. # Set of events we need", "room_id (str): events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): Returns: defer.Deferred: a", "of the events that we are persisting; that means we", "(%s)\" ) % (\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql, list(ev_map)) rows =", "in range(0, len(events_and_contexts), N): ev_map = {e[0].event_id: e[0] for e", "delete all the forward extremeties txn.execute( \"SELECT e.event_id, e.depth FROM", "item.deferred.errback() else: with PreserveLoggingContext(): item.deferred.callback(ret) finally: queue = self._event_persist_queues.pop(room_id, None)", "rows) if max_depth < token.topological: # We need to ensure", "e.type,\" \" state_key, redacts\" \" FROM events AS e\" \"", "that we've added them # to the events table and", "ev for ev, _ in events_context} # We need to", "event_json SET internal_metadata = ?\" \" WHERE event_id = ?\"", "noqa: F401 from synapse.metrics import BucketCollector from synapse.metrics.background_process_metrics import run_as_background_process", "\"[purge] found %i referenced state groups\", len(referenced_state_groups) ) logger.info(\"[purge] finding", "DESC\" ) txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates return self.runInteraction(", "# ordered by first insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] = (event,", "1: # If we're going from one state group to", "out the existing state # unnecessarily). # # The stream_id", "# have to keep shovelling the list back and forth", "room_id, type, state_key, event_id, prev_event_id) SELECT ?, ?, ?, ?,", "\"type\": key[0], \"state_key\": key[1], } for key, ev_id in iteritems(to_insert)", "prev_events of existing (non-outlier/rejected) events. Args: event_ids (Iterable[str]): event ids", "groups that reference to-be-deleted state # groups to non delta", "self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def", "ON events_to_purge(should_delete)\" ) # We do joins against events_to_purge for", "not event.internal_metadata.is_soft_failed() ] latest_event_ids = set(latest_event_ids) # start with the", "WHERE ? < stream_ordering AND stream_ordering <= ?\" \" ORDER", "all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def _update_current_state_txn(self, txn, state_delta_by_room, stream_id): for room_id,", "looking for events to delete\") should_delete_expr = \"state_key IS NULL\"", "state group) -> delta state dict state_group_deltas = {} for", "to purge existing table rows for the events from the", "= yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally handle the case where", "we've added them # to the events table and the", "txn.fetchall() else: new_backfill_events = [] backward_ex_outliers = [] return AllNewEventsResult(", "= (event, context) return list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn, events_and_contexts, backfilled):", "event, _ in events_and_contexts if event.type == EventTypes.Member ], backfilled=backfilled,", "-e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \" FROM events", "day. If it has been significantly less or more than", "( \"SELECT event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\"", "len(new_forward_events) == limit: upper_bound = new_forward_events[-1][0] else: upper_bound = current_forward_id", "membership events we may have deleted # and which we", "? AND type = ? AND state_key = ? )", "room to which the events are being added. Used for", "to do here return for event, context in events_and_contexts: if", "\"\"\"Get all the new events that have arrived at the", "event_edges AS ed ON e.event_id = ed.prev_event_id\" \" LEFT JOIN", "_delete_existing_rows_txn(cls, txn, events_and_contexts): if not events_and_contexts: # nothing to do", "new extremities are and then # calculating the state from", "to pull # the state from the database missing_event_ids.add(event_id) if", "events. if all_single_prev_not_state: continue state_delta_counter.inc() if len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc()", "return count ret = yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def get_current_backfill_token(self):", "of forward extremities for each new event\", buckets=(1, 2, 3,", "wraps from six import iteritems, text_type from six.moves import range", "rows = [] N = 200 for i in range(0,", "len(events_and_contexts)),), [event.event_id for event, _ in events_and_contexts], ) have_persisted =", "JOIN event_json USING (event_id) WHERE prev_event_id IN (%s) AND NOT", "table in ( \"events\", \"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\",", "we add entries to the current_state_delta_stream. We # do this", "logger.debug(\"calling resolve_state_groups from preserve_events\") res = yield self._state_resolution_handler.resolve_state_groups( room_id, room_version,", "ensure that we're not about to delete all the forward", "\" LEFT JOIN redactions USING (event_id)\" \" LEFT JOIN state_events", "txn.executemany( \"INSERT INTO event_backward_extremities (room_id, event_id)\" \" VALUES (?, ?)\",", "calculated new_state_groups we need to get # their state IDs", "rows: event = ev_map[row[\"event_id\"]] if not row[\"rejects\"] and not row[\"redacts\"]:", "to_remove.add(event) if context.rejected: # If the event is rejected then", "local events as well as remote ones (instead of just", "latest_event_ids = yield self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids = yield self._calculate_new_extremities(", "(etype, state_key) not in to_insert ), ) txn.executemany( sql, (", "WHERE NOT should_delete\" \")\", (True,), ) # synapse tries to", "of membership to invalidate the # `get_rooms_for_user` cache. # We", "max_stream_order=max_stream_order, ) # Ensure that we don't have the same", "event.depth, \"depth\": event.depth, \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"processed\":", "BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1, 2, 3, 5, 7, 10,", "if they are referenced by other events # or state", "the list of new events we're adding. for ev, ctx", "Args: room_id (str): room to which the events are being", "set handle_queue_loop off in the background run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self,", "them. txn.execute( \"INSERT INTO events_to_purge\" \" SELECT event_id, %s\" \"", "room, a list of the event ids which are the", "event_ids (Iterable[str]): event ids to filter Returns: Deferred[List[str]]: filtered event", "unnecessarily). # # The stream_id for the update is chosen", "If both are None then there has been no change.", "try: ret = yield per_item_callback(item) except Exception: with PreserveLoggingContext(): item.deferred.errback()", "persist backfilled (bool): True if the events were backfilled delete_existing", "set(state_groups_map) if missing_state: group_to_state = yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups)", "from the list now that we've added them # to", "events_and_contexts): to_prefill = [] rows = [] N = 200", "AND topological_ordering < ?\" % (should_delete_expr, should_delete_expr), should_delete_params, ) #", "this function, it will return None. \"\"\" def _count_messages(txn): sql", "self, txn, new_forward_extremities, max_stream_order ): for room_id, new_extrem in iteritems(new_forward_extremities):", "state, and a state set to be added to the", "only returned if we've already calculated it. \"\"\" # map", "(event_id)\" \" WHERE (NOT outlier OR (%s)) AND e.room_id =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "*after* insertion as that's a lot faster. # create an", "new_backwards_extrems) txn.execute( \"DELETE FROM event_backward_extremities WHERE room_id = ?\", (room_id,)", "map room_id->(type,state_key)->event_id tracking the full # state in each room", "# are those that were in the previous set of", "dict[(str,str), str]|None]]: Returns a tuple of two state maps, the", "entire event # anyway). self._simple_insert_many_txn( txn, table=\"event_auth\", values=[ { \"event_id\":", ") max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def persist_event(self,", "= set( event_id_to_state_group[evid] for evid in new_latest_event_ids ) # If", "which are prev_events of any of the new events result.difference_update(", "table. self._handle_redaction(txn, event.redacts) # Update the event_forward_extremities, event_backward_extremities and #", "itertools.chain(to_delete, to_insert) if ev_type == EventTypes.Member ) for member in", "set(state_groups) while next_to_search: # We bound size of groups we're", "The number of forward extremities for each new event. forward_extremities_counter", "their state groups). \"\"\" return self.runInteraction( \"purge_history\", self._purge_history_txn, room_id, token,", "d.pop(\"redacted\", None) d.pop(\"redacted_because\", None) return d self._simple_insert_many_txn( txn, table=\"event_json\", values=[", "], ) # _store_rejected_events_txn filters out any events which were", "events. existing_prevs = set() def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check = batch", "(bool): True if the events were backfilled delete_existing (bool): True", "new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate,", "%s WHERE room_id = ? AND event_id IN (\" \"", "# to the events table and the events_json table. to_remove", "@cached(num_args=5, max_entries=10) def get_all_new_events( self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit,", "entry to the ex_outlier_stream table to replicate the # change", "events_to_purge)\" ) for event_id, _ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) #", "= txn.fetchall() if len(new_forward_events) == limit: upper_bound = new_forward_events[-1][0] else:", "database. We now have some state at that # so", "room_names and event_search tables. self._store_room_name_txn(txn, event) elif event.type == EventTypes.Topic:", "topological token to delete events before delete_local_events (bool): if True,", "return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult = namedtuple( \"AllNewEventsResult\", [", "later efficiently look up the forward extremeties # for a", "PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils import log_function from synapse.util.metrics import Measure", "that # given) if delta_ids is not None: # If", "the new extremities are and then # calculating the state", "marking remaining events as outliers\") txn.execute( \"UPDATE events SET outlier", "= new_event_updates[-1][0] else: upper_bound = current_id sql = ( \"SELECT", "% ( \",\".join(\"?\" for _ in to_recursively_check), ) txn.execute(sql, to_recursively_check)", "adding some new events to a room Args: room_id (str):", "= self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with stream_ordering_manager as stream_orderings: for (event,", "SELECT COALESCE(MIN(depth), 0) FROM event_backward_extremities AS eb INNER JOIN event_edges", "= ?\" \" WHERE event_id = ?\" txn.execute(sql, (False, event.event_id))", "for event, context in events_and_contexts: if event.type == EventTypes.Redaction and", "make_deferred_yieldable(deferred) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self, room_id):", "event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE ? >", "# sql = \"\"\" INSERT INTO current_state_delta_stream (stream_id, room_id, type,", "table. self._store_history_visibility_txn(txn, event) elif event.type == EventTypes.GuestAccess: # Insert into", "we only return the delta if its already been calculated.", "if (etype, state_key) not in to_insert ), ) txn.executemany( sql,", "out = frozendict_json_encoder.encode(json_object) if isinstance(out, bytes): out = out.decode(\"utf8\") return", "events to db Args: events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): delete_existing", "OrderedDict() for event, context in events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id) if", "(room_id,), list(latest_event_ids) ) @defer.inlineCallbacks def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids): \"\"\"Calculates", "for ev_type, state_key in itertools.chain(to_delete, to_insert) if ev_type == EventTypes.Member", ">= ?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_id,", "self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[ { \"event_id\": ev_id, \"room_id\": room_id, \"type\":", "defer import synapse.metrics from synapse.api.constants import EventTypes from synapse.api.errors import", "To ensure correct ordering we pop, as OrderedDict is #", "events AS e\" \" INNER JOIN ex_outlier_stream USING (event_id)\" \"", "reference to-be-deleted state # groups to non delta versions. for", "token_str, delete_local_events): token = RoomStreamToken.parse(token_str) # Tables that should be", "txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers = txn.fetchall() else: new_forward_events = []", "If they do we need to remove them and their", "# First search in the list of new events we're", "\"persist_events.calculate_state_delta\" ): delta = yield self._calculate_state_delta( room_id, current_state ) state_delta_for_room[room_id]", "encode_json( event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)), \"format_version\": event.format_version, } for event,", "resonably # calculated the delta when we calculated the state", "not events_and_contexts: # nothing to do here return def event_dict(event):", "the License is distributed on an \"AS IS\" BASIS, #", "20, 50, 100, 200, 500, \"+Inf\"), ) def encode_json(json_object): \"\"\"", "!= current_backfill_id have_forward_events = last_forward_id != current_forward_id if not have_backfill_events", "# rejections # room_depth # state_groups # state_groups_state # we", "queue. If another callback is currently handling the queue then", "more than one day since the last call to this", "have_forward_events = last_forward_id != current_forward_id if not have_backfill_events and not", "if the event # was an outlier or not. continue", "to storing the entire event # anyway). self._simple_insert_many_txn( txn, table=\"event_auth\",", "txn.fetchall() logger.info( \"[purge] found %i events before cutoff, of which", "= [] for event_id, prev_event_id, metadata, rejected in txn: if", "bother re-handling groups we've already seen prevs -= state_groups_seen next_to_search", "context.rejected: # If the event is rejected then we don't", "= current_forward_id sql = ( \"SELECT event_stream_ordering, event_id, state_group\" \"", "list now that we've added them # to the events", "# Now pull out the state groups for any missing", "\"rejections\", ): logger.info(\"[purge] removing events from %s\", table) txn.execute( \"DELETE", ") logger.info(\"[purge] looking for events to delete\") should_delete_expr = \"state_key", "events, # otherwise we end up with dangling extremities. existing_prevs", "else: current_search = set(itertools.islice(next_to_search, 100)) next_to_search -= current_search # Check", "\" ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete FROM events_to_purge\") event_rows =", "room_id, stream_id, ) # Invalidate the various caches # Figure", "= ?\", (room_id,) ) # Update backward extremeties txn.executemany( \"INSERT", "= out.decode(\"utf8\") return out class _EventPeristenceQueue(object): \"\"\"Queues up events so", "events (because upsert), and once we run this update, we", "workers. stream_order = event.internal_metadata.stream_ordering state_group_id = context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\",", "events_and_contexts if event.type == EventTypes.Member ], backfilled=backfilled, ) # Insert", "events to that item. end_item = queue[-1] if end_item.backfilled ==", "state at that # so we need to update the", "_count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self): def _count(txn): sql = \"\"\"", "events_and_context. backfilled (bool): True if the events were backfilled \"\"\"", "same when we created the event as they are #", "and which need to be de-delta'ed (due to one of", "can have at most one prev group graph[row[\"state_group\"]] = row[\"prev_state_group\"]", "/ shouldn't_delete subsets txn.execute( \"CREATE INDEX events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\"", "ec in events_and_contexts if ec[0] not in to_remove] def _update_metadata_tables_txn(", "should_delete_params += (room_id, token.topological) # Note that we insert events", "\"\"\"Insert new events into the event and event_json tables Args:", "( SELECT event_id FROM current_state_events WHERE room_id = ? AND", "(EventBase): context (EventContext): backfilled (bool): Returns: Deferred: resolves to (int,", "events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group = {} for event_id in", "entries for the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if not backfilled: txn.call_after(", "context in state_events_and_contexts: vals = { \"event_id\": event.event_id, \"room_id\": event.room_id,", "-event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \" FROM", "for any missing events from DB event_to_groups = yield self._get_state_group_for_events(missing_event_ids)", "\" SELECT event_id FROM events_to_purge WHERE should_delete\" \")\" % (table,)", "outliers and deleting their state groups). \"\"\" return self.runInteraction( \"purge_history\",", "background run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self, room_id): queue = self._event_persist_queues.setdefault(room_id, deque())", "we've already calculated it. \"\"\" # map from state_group to", "this file except in compliance with the License. # You", "COALESCE(COUNT(*), 0) FROM events WHERE type = 'm.room.message' AND stream_ordering", "ones that weren't # rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled,", "len(referenced_state_groups) ) logger.info(\"[purge] finding state groups that can be deleted\")", "state_group FROM events_to_purge INNER JOIN event_to_state_groups USING (event_id) \"\"\" )", "so let's drop the table first. txn.execute(\"DROP TABLE IF EXISTS", "\" WHERE ? < stream_ordering AND stream_ordering <= ?\" \"", "current_backfill_id sql = ( \"SELECT -event_stream_ordering, event_id, state_group\" \" FROM", "return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop(): try: queue = self._get_drainining_queue(room_id) for", "the type/state_keys to remove from current_state_events and `to_insert` are the", "event_json USING (event_id) WHERE event_id IN (%s) AND NOT events.outlier", "appears in an accepted # event's auth chain, but its", "new list, without the rejected events. \"\"\" # Remove the", "# their state IDs so we can resolve to a", "(\"event\", \"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps a database function so that", "state_groups (set[int]): Set of state groups referenced by events that", "# Insert into the room_memberships table. self._store_room_members_txn( txn, [ event", "later # if necessary. current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids is", "new_state_groups = set( event_id_to_state_group[evid] for evid in new_latest_event_ids ) #", "WHERE ? < stream_id AND stream_id <= ? ORDER BY", "def get_all_new_backfill_event_rows(self, last_id, current_id, limit): if last_id == current_id: return", "the current state. new_forward_extremeties (dict[str, list[str]]): The new forward extremities", "stream_order, \"event_id\": event.event_id, \"state_group\": state_group_id, }, ) sql = \"UPDATE", "to_insert), being a list of type/state keys to be removed", "event_relations USING (event_id)\" \" WHERE ? > stream_ordering AND stream_ordering", "\"\"\" txn.execute( \"SELECT event_id, outlier FROM events WHERE event_id in", "10, 15, 20, 50, 100, 200, 500, \"+Inf\"), ) #", "?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_forward_id, upper_bound))", "list(latest_event_ids) ) @defer.inlineCallbacks def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids): \"\"\"Calculates the", "row[\"prev_state_group\"] to_delete = state_groups_seen - referenced_groups to_dedelta = set() for", "} # TODO: How does this work with backfilling? if", "# The number of forward extremities for each new event.", "txn, table=\"stream_ordering_to_exterm\", values=[ { \"room_id\": room_id, \"event_id\": event_id, \"stream_ordering\": max_stream_order,", "do this before updating the current_state_events table so # that", "events were backfilled \"\"\" # Insert all the push actions", "created the event as they are # now. When this", "events_and_contexts if ec[0] not in to_remove] def _update_metadata_tables_txn( self, txn,", "should always be at least one forward extremity. # (except", "we end up with dangling extremities. existing_prevs = yield self._get_prevs_before_rejected(", "# If we have the current_state then lets prefill #", "[] for event, context in state_events_and_contexts: vals = { \"event_id\":", "groups to purge, etc., so lets make an index. txn.execute(\"CREATE", "ec[0] not in to_remove] def _update_metadata_tables_txn( self, txn, events_and_contexts, all_events_and_contexts,", "txn.execute(sql, (last_id, current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates) ==", "therefore be called whenever anything is added to the queue.", "for evid in new_latest_event_ids ) # If they old and", "for each room. For each room, a list of the", "# the cache with it. if current_state is not None:", "prefill(): for cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def _store_redaction(self,", ">= ?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_forward_id,", "item, exceptions will be passed to the deferreds as well.", "# calculating the state from that. events_by_room = {} for", "\"\"\" # Remove the rejected events from the list now", "# events. If they do we need to remove them", "for ec in events_and_contexts if ec[0] not in to_remove] def", "EventTypes.RoomHistoryVisibility: # Insert into the event_search table. self._store_history_visibility_txn(txn, event) elif", "times we are reculating state when we could have resonably", "current_state_tuple # First we add entries to the current_state_delta_stream. We", "new_extrem ], ) @classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that we", "new_state_group = next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group, new_state_group),", "extremities. However, the events in event_backward_extremities # are ones we", "2, 3, 5, 7, 10, 15, 20, 50, 100, 200,", "we don't delete all the events from the database #", "# Insert into the topics table and event_search table. self._store_room_topic_txn(txn,", ") # synapse tries to take out an exclusive lock", "= txn.fetchall() logger.info( \"[purge] found %i events before cutoff, of", "in (\"event_push_actions\",): txn.executemany( \"DELETE FROM %s WHERE room_id = ?", "WHERE ? > stream_ordering AND stream_ordering >= ?\" \" ORDER", "If another callback is currently handling the queue then it", "AS e LEFT JOIN state_events USING (event_id)\" \" WHERE (NOT", "it. room_version = None for ev, _ in events_context: if", "yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The current minimum token", "200, 500, \"+Inf\"), ) # The number of stale forward", "15, 20, 50, 100, 200, 500, \"+Inf\"), ) def encode_json(json_object):", "that. new_state_group = next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group,", "collections import Counter as c_counter, OrderedDict, deque, namedtuple from functools", "FROM %s WHERE room_id = ? AND event_id = ?\"", "events (whether soft-failed/rejected or not), and recurses up the prev-event", "JOIN rejections as rej USING (event_id)\" \" LEFT JOIN redactions", "not delete_local_events: should_delete_expr += \" AND event_id NOT LIKE ?\"", "event. :( # NB: Assumes that we are only persisting", "to them. txn.execute( \"INSERT INTO events_to_purge\" \" SELECT event_id, %s\"", "as rej USING (event_id)\" \" LEFT JOIN redactions as r", "return self.runInteraction( \"purge_history\", self._purge_history_txn, room_id, token, delete_local_events, ) def _purge_history_txn(self,", "We need to map the event_ids to their state groups.", "be # deleted. We then go and check if they", "\"*client*\" else: origin_type = \"remote\" origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type,", "table in (\"event_push_actions\",): logger.info(\"[purge] removing events from %s\", table) txn.execute(", "should therefore be called whenever anything is added to the", "# have a logcontext to report to return run_as_background_process( \"read_forward_extremities\",", "self._event_persist_queues.setdefault(room_id, deque()) try: while True: yield queue.popleft() except IndexError: #", "items, unless the queue becomnes empty. The return value of", "for r in txn if not json.loads(r[1]).get(\"soft_failed\")) for chunk in", "state for an event we were # persisting. state_delta_reuse_delta_counter =", "?\" % (table,), [(ev.event_id,) for ev, _ in events_and_contexts], )", "day since the last call to this function, it will", "self._current_forward_extremities_amount = c_counter(list(x[0] for x in res)) @defer.inlineCallbacks def persist_events(self,", "DESC\" ) txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn) return new_event_updates return self.runInteraction(", "[], [], [], [])) def get_all_new_events_txn(txn): sql = ( \"SELECT", "has one on # (room_id, event_id) instead. for table in", "events referenced_groups = set() # Set of state groups we've", "TABLE events_to_purge\") logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used when", "given events to persist. Assumes that we are only persisting", "we're deleting rather than updating if (etype, state_key) not in", "self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler() # Collect metrics on", "we have found to be referenced by events referenced_groups =", "do joins against events_to_purge for e.g. calculating state # groups", "@defer.inlineCallbacks def f(self, *args, **kwargs): try: res = yield func(self,", "Update the event_forward_extremities, event_backward_extremities and # event_edges tables. self._handle_mult_prev_events( txn,", "in event_contexts if not event.internal_metadata.is_outlier() and not ctx.rejected and not", "c from event_forward_extremities group by room_id \"\"\" ) return txn.fetchall()", "room_id, evs_ctxs in iteritems(partitioned): d = self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled", "(like_clause, self.stream_ordering_day_ago)) count, = txn.fetchone() return count ret = yield", "@cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id): res = yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\",", "we need to get # their state IDs so we", "from synapse.util.metrics import Measure logger = logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\",", "just # a long chain of single ancestor non-state events.", "that we can use it to calculate the `prev_event_id`. (This", "txn.executemany( \"DELETE FROM state_groups WHERE id = ?\", ((sg,) for", "= yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) > (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def", "in place whether or not the returned deferred is ready.", "self._state_resolution_handler = hs.get_state_resolution_handler() # Collect metrics on the number of", "deferreds.append(d) for room_id in partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True)", "the event was rejected. Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts", "moved in here) class EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ):", "list of event_ids to get those which are prev_events of", "self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), ) prevs", ") logger.info(\"[purge] Finding new backward extremities\") # We calculate the", "room at a time. Returns: tuple[list, dict] (to_delete, to_insert): where", "events_and_contexts[x : x + 100] for x in range(0, len(events_and_contexts),", "state_key, ) for (etype, state_key), ev_id in iteritems(to_insert) ), )", "current_id, limit): if last_id == current_id: return defer.succeed([]) def get_all_new_backfill_event_rows(txn):", "@defer.inlineCallbacks def is_event_after(self, event_id1, event_id2): \"\"\"Returns True if event_id1 is", "for sg, in txn) referenced_groups |= referenced # We don't", "metadata_json = encode_json(event.internal_metadata.get_dict()) sql = ( \"UPDATE event_json SET internal_metadata", "txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, ) # Invalidate the various caches", "self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, ) ) return deferred.observe() def handle_queue(self,", "# for these events so we can reinsert them. #", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "in which case there will be no existing # extremities,", "event.content and isinstance(event.content[\"url\"], text_type) ), } for event, _ in", "delta_ids = state_group_deltas.get((old_state_group, new_state_group), None) if delta_ids is not None:", "[\"type\", \"origin_type\", \"origin_entity\"], ) # The number of times we", "that we are only persisting events for one room at", "for room_id, evs_ctxs in iteritems(partitioned): d = self._event_persist_queue.add_to_queue( room_id, evs_ctxs,", "have already been persisted. Returns: Deferred[set[str]] \"\"\" # The set", "delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert some number of room events", "queue, with the given persist_event options. NB: due to the", "the event_push_actions table for the # redacted event. self._remove_push_actions_for_event_id_txn( txn,", "Counter of number of extremities to count self._current_forward_extremities_amount = c_counter()", "e.room_id = f.room_id \" \"WHERE f.room_id = ?\", (room_id,), )", "# From this point onwards the events are only ones", "f.room_id \" \"WHERE f.room_id = ?\", (room_id,), ) rows =", "\" FROM events AS e LEFT JOIN state_events USING (event_id)\"", "work with backfilling? if hasattr(event, \"replaces_state\"): vals[\"prev_state\"] = event.replaces_state state_values.append(vals)", "will use the # forward extremities as the prev_events, so", "current_id: return defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql = ( \"SELECT -e.stream_ordering,", "for event, _ in events_and_contexts] ) state_events_and_contexts = [ ec", "events_and_contexts if ec[0].is_state() ] state_values = [] for event, context", "event_search table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event) # Insert into the", "the state from the database missing_event_ids.add(event_id) if missing_event_ids: # Now", "(list[(EventBase, EventContext)]): all events that we were going to persist.", "[event for event, _ in events_and_contexts] ) state_events_and_contexts = [", "will be passed to the deferreds as well. This function", "not None: with Measure( self._clock, \"persist_events.calculate_state_delta\" ): delta = yield", "the room. Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]: Returns a tuple", "We do this by calculating the minimum depth of the", "tries to take out an exclusive lock on room_depth whenever", "txn, events=[event for event, _ in events_and_contexts] ) for event,", "json.loads(r[1]).get(\"soft_failed\")) for chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn,", "\"\"\" @wraps(func) @defer.inlineCallbacks def f(self, *args, **kwargs): try: res =", "ordering of the latest persisted event \"\"\" partitioned = {}", "\"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], } for key, ev_id", "batch) results.extend(r[0] for r in txn if not json.loads(r[1]).get(\"soft_failed\")) for", "\"state_key\": key[1], \"event_id\": state_id, } for key, state_id in iteritems(curr_state)", "(event_id) WHERE event_id IN (%s) AND NOT events.outlier \"\"\" %", "to remove from current_state_events and `to_insert` are the updates to", "\"\"\"The current maximum token that events have reached\"\"\" return self._stream_id_gen.get_current_token()", "NOT should_delete\" \")\", (True,), ) # synapse tries to take", "calculating state # groups to purge, etc., so lets make", "of forward extremities that exist. # Counter of number of", "= 'm.room.message' AND sender LIKE ? AND stream_ordering > ?", "is a list # of type/state keys to remove from", "LIMIT ?\" ) if have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id, limit)) new_forward_events", "events into the necessary database tables. Rejected events are only", "there has been a change then we only return the", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "used in state res v2. # This is only necessary", "that we have found to be referenced by events referenced_groups", "to the list result.update(event.event_id for event in new_events) # Now", "event) elif event.type == EventTypes.GuestAccess: # Insert into the event_search", "if we could # have guessed what the delta would", "prev groups being scheduled for deletion). Args: txn state_groups (set[int]):", "events table and the events_json table. to_remove = set() for", "the state group graphs for state # groups that are", "events_and_contexts: # nothing to do here return for event, context", "txn.fetchall() logger.info(\"[purge] replacing backward extremities: %r\", new_backwards_extrems) txn.execute( \"DELETE FROM", "the redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT INTO redactions (event_id,", "Finding new backward extremities\") # We calculate the new entries", "as OrderedDict is # ordered by first insertion. new_events_and_contexts.pop(event.event_id, None)", "): \"\"\"Insert some number of room events into the necessary", "{} # map room_id->(type,state_key)->event_id tracking the full # state in", "not have_backfill_events and not have_forward_events: return defer.succeed(AllNewEventsResult([], [], [], [],", "finally, drop the temp table. this will commit the txn", "can just add these new events to that item. end_item", "event_counter.labels(event.type, origin_type, origin_entity).inc() for room_id, new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state)", "# event_push_actions # event_reference_hashes # event_search # event_to_state_groups # events", ") for event, _ in events_and_contexts: if event.type == EventTypes.Name:", "reached\"\"\" return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id, current_id, limit): if last_id", "room. # This allows us to later efficiently look up", "table rows for the events from the database. This is", "function, it will return None. \"\"\" def _count_messages(txn): sql =", "txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult = namedtuple( \"AllNewEventsResult\",", "\"UPDATE events SET outlier = ?\" \" WHERE event_id =", "want to store event_auth mappings for rejected events, as they're", "= have_persisted[event.event_id] if not event.internal_metadata.is_outlier() and outlier_persisted: # We received", "\" LEFT JOIN rejections as rej USING (event_id)\" \" LEFT", "out of the DB later # if necessary. current_state_ids =", "# (except during the initial persistence of the send_join #", "# groups to non delta versions. for sg in remaining_state_groups:", "room_id), ) # finally, drop the temp table. this will", "prev events (whether soft-failed/rejected or not), and recurses up the", "which will resolve once the events are persisted. Runs its", "that we are persisting; that means we do not #", "state_key, redacts\" \" FROM events AS e\" \" LEFT JOIN", "events and their prev events (whether soft-failed/rejected or not), and", "The new forward extremities for each room. For each room,", "be # deleted, as nothing will happen to them. txn.execute(", "the room_memberships table. self._store_room_members_txn( txn, [ event for event, _", "\"state_group\": state_group_id, }, ) sql = \"UPDATE events SET outlier", "table, the events_json table, and the rejections table. Things reading", "event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): # To ensure correct ordering we pop,", "# extremities, so we'll `continue` above and skip this bit.)", "import BackgroundUpdateStore from synapse.storage.event_federation import EventFederationStore from synapse.storage.events_worker import EventsWorkerStore", "\"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count, = txn.fetchone() return count ret", "to persist. This includes events we've already persisted, etc, that", "resolve_state_groups from preserve_events\") res = yield self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups,", "list(ev_map)) rows = self.cursor_to_dict(txn) for row in rows: event =", "= Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of forward extremities for each new", "AND event_stream_ordering >= ?\" \" ORDER BY event_stream_ordering DESC\" )", "[], [], [])) def get_all_new_events_txn(txn): sql = ( \"SELECT e.stream_ordering,", "all the events from the database # otherwise we wouldn't", "wouldn't be able to send any events (due to not", "# Prefill the event cache self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self, txn,", "): delta = yield self._calculate_state_delta( room_id, current_state ) state_delta_for_room[room_id] =", "otherwise we end up with dangling extremities. existing_prevs = yield", "are only inserted into the events table, the events_json table,", "NOT NULL\" \")\" ) # First ensure that we're not", "should_delete\" \")\", (True,), ) # synapse tries to take out", "f.event_id \" \"AND e.room_id = f.room_id \" \"WHERE f.room_id =", "state deltas for a room. Assumes that we are only", "not in current_state] to_insert = { key: ev_id for key,", "a delta from the existing to new current state, #", "(list[(EventBase, EventContext)]): events we are persisting all_events_and_contexts (list[(EventBase, EventContext)]): all", "\"\"\" txn.executemany( sql, ( ( stream_id, room_id, etype, state_key, None,", "stream \"\"\" to_1, so_1 = yield self._get_event_ordering(event_id1) to_2, so_2 =", "if have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id, limit)) new_forward_events = txn.fetchall() if", "text_type from six.moves import range from canonicaljson import json from", "stream_order = event.internal_metadata.stream_ordering state_group_id = context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={", "(iterable[str]): the new forward extremities for the room. Returns: Deferred[tuple[dict[(str,str),", "Graph of state group -> previous group graph = {}", "class EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ): def __init__(self, db_conn,", "number of times we are reculating state when we could", "event isn't an outlier any more. self._update_backward_extremeties(txn, [event]) return [ec", "event_id, prev_event_id, internal_metadata, rejections.event_id IS NOT NULL FROM event_edges INNER", "current-state delta for each room. For each room, a tuple", "IS NULL \"\"\" % ( \",\".join(\"?\" for _ in current_search),", "# point to it via event_edges table. txn.execute( \"\"\" SELECT", "into the event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if", "in event.prev_event_ids() ) result.difference_update(existing_prevs) # We only update metrics for", "event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"state_key\": event.state_key, } # TODO:", "Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter = Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\", \"origin_entity\"],", "v2. # This is only necessary if the rejected event", "event.room_id, event.redacts ) # Remove from relations table. self._handle_redaction(txn, event.redacts)", "?\" ) txn.execute(sql, (-last_id, -current_id, limit)) new_event_updates = txn.fetchall() if", "return. This includes all soft-failed events # and their prev", "supplied list of event_ids to get those which are prev_events", "one state group, then we know what the current #", "or replaced state, never # removed keys entirely. state_delta_for_room[room_id] =", "row in rows: event = ev_map[row[\"event_id\"]] if not row[\"rejects\"] and", "synapse.types import RoomStreamToken, get_domain_from_id from synapse.util import batch_iter from synapse.util.async_helpers", "into the redactions table. self._store_redaction(txn, event) elif event.type == EventTypes.RoomHistoryVisibility:", "remaining state group %s\", sg) curr_state = self._get_state_groups_from_groups_txn(txn, [sg]) curr_state", "transaction per room. \"\"\" _EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\",", "AND stream_ordering <= ?\" \" ORDER BY stream_ordering ASC\" \"", "new events, but are separated by soft failed events. Args:", "self._calculate_state_delta( room_id, current_state ) state_delta_for_room[room_id] = delta # If we", "in range(0, len(events_and_contexts), 100) ] for chunk in chunks: #", "= ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\"", "for event, _ in events_and_contexts], ) have_persisted = {event_id: outlier", "includes all soft-failed events # and their prev events. existing_prevs", "and delete all the existing entries # for these events", "state_events USING (event_id)\" \" WHERE (NOT outlier OR (%s)) AND", "could have resonably # calculated the delta when we calculated", "txn) referenced_groups |= referenced # We don't continue iterating up", "new stream_ordering to new forward extremeties in the room. #", "?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_backfill_id, -upper_bound))", "anyway). self._simple_insert_many_txn( txn, table=\"event_auth\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id,", "# Copyright 2018-2019 New Vector Ltd # Copyright 2019 The", "\"origin_type\", \"origin_entity\"], ) # The number of times we are", "for chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk", "\"\"\"Update all the miscellaneous tables for new events Args: txn", "table and the events_json table. to_remove = set() for event,", "iteritems(new_forward_extremities) for ev_id in new_extrem ], ) # We now", "the event # was an outlier or not. continue outlier_persisted", "limit: upper_bound = new_forward_events[-1][0] else: upper_bound = current_forward_id sql =", "the list now that we've added them # to the", "event_stream_ordering DESC\" ) txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates return", "(str): events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): Returns: defer.Deferred: a deferred", ") if have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit)) new_backfill_events = txn.fetchall()", "inherits from EventFederationStore so that we can call _update_backward_extremities #", "writing, software # distributed under the License is distributed on", "EventsWorkerStore from synapse.storage.state import StateGroupWorkerStore from synapse.types import RoomStreamToken, get_domain_from_id", "def get_all_new_forward_event_rows(self, last_id, current_id, limit): if last_id == current_id: return", "= {} for event, context in chunk: events_by_room.setdefault(event.room_id, []).append( (event,", "EventsWorkerStore, BackgroundUpdateStore, ): def __init__(self, db_conn, hs): super(EventsStore, self).__init__(db_conn, hs)", "queue for a room if not already being handled. The", "LIMIT ?\" ) txn.execute(sql, (-last_id, -current_id, limit)) new_event_updates = txn.fetchall()", "yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups of old_latest_event_ids old_state_groups =", "logger.info(\"[purge] updating room_depth to %d\", min_depth) txn.execute( \"UPDATE room_depth SET", "= set(sg for sg, in txn) referenced_groups |= referenced #", "synapse.state import StateResolutionStore from synapse.storage.background_updates import BackgroundUpdateStore from synapse.storage.event_federation import", "If we happen to already have # the current state", "to IntegrityError. state_delta_for_room (dict[str, (list, dict)]): The current-state delta for", "which case there will be no existing # extremities, so", "# to receiving it over federation) it will use the", "# allows us to not have to pull out the", "event. self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts ) # Remove from relations", "on should_delete because later we'll be looking for # the", "it does *not* follow the synapse logcontext rules, and leaves", "database transactions # have a logcontext to report to return", "Exception( \"Context for new event %s has no state \"", "\"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\", \"state_events\", \"rejections\", \"redactions\", \"room_memberships\", \"topics\",", "event_stream_ordering DESC\" ) txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn) return new_event_updates return", "defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self): def _count_messages(txn): # This is good", "our state sets. state_groups = {sg: state_groups_map[sg] for sg in", "are None then there has been no change. If there", "to the database Args: events_and_contexts: list of tuples of (event,", "Args: event_ids (Iterable[str]): Events to find prev events for. Note", "# synapse tries to take out an exclusive lock on", "event, context in events_and_contexts: if event.event_id not in have_persisted: continue", "\"\") # The number of times we are recalculating state", "state groups we've already seen state_groups_seen = set(state_groups) # Set", "soft-failed/rejected events. This is used to find extremities that are", "event # anyway). self._simple_insert_many_txn( txn, table=\"event_auth\", values=[ { \"event_id\": event.event_id,", "from its context. # Otherwise we need to pull the", "BY stream_id ASC LIMIT ? \"\"\" txn.execute(sql, (from_token, to_token, limit))", "# We do this by working out what the new", "there is only one state group, then we know what", "synapse.storage.state import StateGroupWorkerStore from synapse.types import RoomStreamToken, get_domain_from_id from synapse.util", "at a time. # map room_id->list[event_ids] giving the new forward", "} defer.returnValue((to_delete, to_insert)) @log_function def _persist_events_txn( self, txn, events_and_contexts, backfilled,", "each # room state_delta_for_room = {} if not backfilled: with", "redundant state groups\") txn.executemany( \"DELETE FROM state_groups_state WHERE state_group =", "in the previous set of extremities as well as the", "are separated by soft failed events. Args: event_ids (Iterable[str]): Events", "for event, _ in events_and_contexts] ) for event, _ in", "the 'rejections' table for received events which were rejected Args:", "events have reached\"\"\" return -self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The current maximum", "(list[(EventBase, EventContext)]): events we are persisting Returns: list[(EventBase, EventContext)] new", "from the database # otherwise we wouldn't be able to", "event_auth mappings for rejected events, as they're # used in", ") def get_all_new_backfill_event_rows(self, last_id, current_id, limit): if last_id == current_id:", "ec[0].is_state() ] state_values = [] for event, context in state_events_and_contexts:", "(\"event_push_actions\",): txn.executemany( \"DELETE FROM %s WHERE room_id = ? AND", "with the existing forward extremities result = set(latest_event_ids) # add", ": x + 100] for x in range(0, len(events_and_contexts), 100)", "own # hostname then thats your own fault. like_clause =", "of state groups referenced by events that are going to", "Returns: defer.Deferred: a deferred which will resolve once the events", "# forward extremities as the prev_events, so we can #", "not # having any backwards extremeties) raise SynapseError( 400, \"topological_ordering", "in to_delete: to_dedelta.add(sg) return to_delete, to_dedelta @defer.inlineCallbacks def is_event_after(self, event_id1,", "> (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id): res = yield", "(bool): Returns: Deferred: resolves to (int, int): the stream ordering", "# extremities in each room new_forward_extremeties = {} # map", "backfilled=backfilled ) # _update_outliers_txn filters out any events which have", "and return it in a Unicode string. \"\"\" out =", "in a situation where workers see events before the #", "state and the second being the delta to the existing", "EventContext)]): events we are persisting Returns: list[(EventBase, EventContext)] new list,", "end_item = queue[-1] if end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe()", "we created the event as they are # now. When", "working out what the new extremities are and then #", "int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self, from_token, to_token, limit): def get_all_updated_current_state_deltas_txn(txn): sql", "are referenced. current_search -= referenced rows = self._simple_select_many_txn( txn, table=\"state_group_edges\",", "the room version, which is in the create event. #", "\"[purge] found %i events before cutoff, of which %i can", "for ec in events_and_contexts if ec[0] not in to_remove] @classmethod", "room_id = ? AND type = ? AND state_key =", "\"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\", \"state_events\", \"rejections\", \"redactions\", \"room_memberships\", \"topics\", ):", "\" FROM events AS e\" \" LEFT JOIN redactions USING", "r ON e.event_id = r.redacts\" \" WHERE e.event_id IN (%s)\"", "update metrics for events that change forward extremities # (e.g.", "self._event_persist_queues.setdefault(room_id, deque()) if queue: # if the last item in", "for cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def _store_redaction(self, txn,", "(failed) # purge attempt, so let's drop the table first.", "# will block that for the rest of our transaction.", "== 1: # If we're going from one state group", "to persist backfilled (bool): True if the events were backfilled", "the extrems every 60 minutes def read_forward_extremities(): # run as", "2019 The Matrix.org Foundation C.I.C. # # Licensed under the", "then we don't care if the event # was an", "state_key, event_id, prev_event_id) SELECT ?, ?, ?, ?, ?, (", "connection events_and_contexts (list[(EventBase, EventContext)]): events to persist backfilled (bool): True", "remaining_state_groups = _ logger.info( \"[purge] found %i state groups to", "event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) # Prefill the event cache", "for member in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn, room_id,", "with `delete_existing=True` passed in. Args: func: function that returns a", "partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds = [] for room_id, evs_ctxs in", "to persist. Assumes that we are only persisting events for", "all remote non-state events for table in ( \"events\", \"event_json\",", "for deletion). Args: txn state_groups (set[int]): Set of state groups", "able to send any events (due to not # having", "self._clock, \"persist_events.calculate_state_delta\" ): delta = yield self._calculate_state_delta( room_id, current_state )", "room_id, current_state ) state_delta_for_room[room_id] = delta # If we have", "event.internal_metadata.is_soft_failed() ] latest_event_ids = set(latest_event_ids) # start with the existing", "0) FROM events WHERE type = 'm.room.message' AND sender LIKE", "storing the entire event # anyway). self._simple_insert_many_txn( txn, table=\"event_auth\", values=[", "add entries to the current_state_delta_stream. We # do this before", "calculating the minimum depth of the backwards # extremities. However,", "not row[\"rejects\"] and not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) ) def", "of events, find all those that have been soft-failed or", "this point onwards the events are only ones that weren't", "= \"UPDATE events SET outlier = ?\" \" WHERE event_id", "state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state delta for room %s\", room_id) with", "event_id IN (\" \" SELECT event_id FROM events_to_purge WHERE should_delete\"", "the get_current_state_ids # cache current_state_for_room = {} # map room_id->(to_delete,", "stream_ids # for the batch of the events that we", "use the # forward extremities as the prev_events, so we", "of the old # extremities are going to be in", "be de-delta'ed (due to one of its prev groups being", "key: ev_id for key, ev_id in iteritems(current_state) if ev_id !=", "if queue: self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop off", "If they old and new groups are the same then", "event_id IN (\" \" SELECT event_id FROM events_to_purge \" \"", "events_and_contexts[i : i + N]} if not ev_map: break sql", "etc, that wouldn't appear in events_and_context. backfilled (bool): True if", "new_backwards_extrems = txn.fetchall() logger.info(\"[purge] replacing backward extremities: %r\", new_backwards_extrems) txn.execute(", "any events which have already been # persisted, and returns", "self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def _update_forward_extremities_txn( self, txn,", "e_id in event.prev_event_ids() ) # Remove any events which are", "that's a lot faster. # create an index on should_delete", "referenced by events that are to be # deleted. We", "purged that are pointed to by events we're not going", "{\"event_id\": ev_id, \"room_id\": room_id} for room_id, new_extrem in iteritems(new_forward_extremities) for", "insert into event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event, context),)) except Exception: logger.exception(\"\")", "events for one room # at a time. # map", "-> previous group graph = {} # Set of events", "upper_bound)) forward_ex_outliers = txn.fetchall() else: new_forward_events = [] forward_ex_outliers =", "%s WHERE room_id = ? AND event_id = ?\" %", "self._get_state_groups_from_groups_txn(txn, [sg]) curr_state = curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg}", "group, then we know what the current # state is.", "yield self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, )", "event cache self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self, txn, events_and_contexts): to_prefill =", "a `delete_existing` arg \"\"\" @wraps(func) @defer.inlineCallbacks def f(self, *args, **kwargs):", "(room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id, \"room_id\": room_id} for", "table=\"state_groups_state\", keyvalues={\"state_group\": sg} ) self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg} )", "of state group -> previous group graph = {} #", "the existing current state. If both are None then there", "as f \" \"ON e.event_id = f.event_id \" \"AND e.room_id", "event # was an outlier or not. continue outlier_persisted =", "delta (or use that # given) if delta_ids is not", "100: current_search = next_to_search next_to_search = set() else: current_search =", "new_extrem ], ) # We now insert into stream_ordering_to_exterm a", "} for event, _ in events_and_contexts ], ) self._simple_insert_many_txn( txn,", "persisting, in which case we can # pull the state", "IS NULL\" ) new_backwards_extrems = txn.fetchall() logger.info(\"[purge] replacing backward extremities:", "the event_forward_extremities, event_backward_extremities and # event_edges tables. self._handle_mult_prev_events( txn, events=[event", "50, 100, 200, 500, \"+Inf\"), ) def encode_json(json_object): \"\"\" Encode", "full new current state and the second being the delta", "any of the new events result.difference_update( e_id for event in", "to store event_auth mappings for rejected events, as they're #", "have the table from a previous (failed) # purge attempt,", "removing redundant state groups\") txn.executemany( \"DELETE FROM state_groups_state WHERE state_group", "# we can just add these new events to that", "if not event.internal_metadata.is_outlier() and not ctx.rejected and not event.internal_metadata.is_soft_failed() ]", ") # Now we turn the state groups that reference", "events which were # rejected, and returns the filtered list.", "being a list of type/state keys to be removed from", "If we couldn't find it, then we'll need to pull", "to receiving it over federation) it will use the #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "opposed # to receiving it over federation) it will use", "if missing_event_ids: # Now pull out the state groups for", "events_and_contexts] ) for event, _ in events_and_contexts: if event.type ==", "\"topological_ordering\": event.depth, \"depth\": event.depth, \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type,", "Insert into the room_names and event_search tables. self._store_room_name_txn(txn, event) elif", "lambda: self._current_forward_extremities_amount, buckets=[1, 2, 3, 5, 7, 10, 15, 20,", "room_id, new_extrem in iteritems(new_forward_extremities) for ev_id in new_extrem ], )", "OrderedDict is # ordered by first insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id]", "that are to be # deleted. We then go and", "(Iterable[str]): event ids to filter Returns: Deferred[List[str]]: filtered event ids", "hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000) @defer.inlineCallbacks def _read_forward_extremities(self): def", "When this server creates a new event (as opposed #", "not find event %s\" % (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) )", "will be given to the deferreds waiting on the item,", "Remove any events which are prev_events of any existing events.", "last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit, ): \"\"\"Get all the new", "A topological token to delete events before delete_local_events (bool): if", "under the Apache License, Version 2.0 (the \"License\"); # you", "WHERE type = 'm.room.message' AND sender LIKE ? AND stream_ordering", "context.rejected) to_remove.add(event) return [ec for ec in events_and_contexts if ec[0]", "latest_event_ids: forward_extremities_counter.observe(len(result)) stale = latest_event_ids & result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks", "_ in ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids()) if latest_event_ids == prev_event_ids:", "\"type\": event.type, \"processed\": True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(),", "into event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event, context),)) except Exception: logger.exception(\"\") raise", "outliers with new event info. This turns outliers into ex-outliers", "\"event_reference_hashes\", \"event_search\", \"rejections\", ): logger.info(\"[purge] removing events from %s\", table)", "if the events were backfilled \"\"\" depth_updates = {} for", "are already in the events table. \"\"\" txn.execute( \"SELECT event_id,", "_ in events_and_contexts for auth_id in event.auth_event_ids() if event.is_state() ],", "EventContext)]): events we are persisting backfilled (bool): True if the", "AND stream_ordering > ? \"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count, =", "forward extremities left!\" new_forward_extremeties[room_id] = new_latest_event_ids len_1 = ( len(latest_event_ids)", "as they are # now. When this server creates a", "in txn if not json.loads(r[1]).get(\"soft_failed\")) for chunk in batch_iter(event_ids, 100):", "of old_latest_event_ids old_state_groups = set( event_id_to_state_group[evid] for evid in old_latest_event_ids", "from %s\", table) txn.execute( \"DELETE FROM %s WHERE event_id IN", "the queue, with the given persist_event options. NB: due to", "referenced_state_groups) state_groups_to_delete, remaining_state_groups = _ logger.info( \"[purge] found %i state", "However, the events in event_backward_extremities # are ones we don't", "one room # at a time. # map room_id->list[event_ids] giving", "defer.returnValue((to_1, so_1) > (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id): res", "all # those users. members_changed = set( state_key for ev_type,", "we can resolve to a single state set. missing_state =", "db connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting backfilled", "AND sender LIKE ? AND stream_ordering > ? \"\"\" txn.execute(sql,", "# for the batch of the events that we are", "giving the state delta in each # room state_delta_for_room =", "the event is one we're persisting, in which case we", "(last_id, upper_bound)) new_event_updates.extend(txn) return new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows )", "event.event_id, \"state_group\": state_group_id, }, ) sql = \"UPDATE events SET", "the events have been persisted \"\"\" if not events_and_contexts: return", "(SELECT event_id from events_to_purge)\" ) for event_id, _ in event_rows:", "state groups\") # Get all state groups that are referenced", "N): ev_map = {e[0].event_id: e[0] for e in events_and_contexts[i :", "state groups that need to be de-delta'ed \"\"\" # Graph", "ed.event_id = ep2.event_id\" \" WHERE ep2.event_id IS NULL\" ) new_backwards_extrems", "forward extremities. \"\"\" all_events_and_contexts = events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order", "in res)) @defer.inlineCallbacks def persist_events(self, events_and_contexts, backfilled=False): \"\"\" Write events", "= next_to_search next_to_search = set() else: current_search = set(itertools.islice(next_to_search, 100))", "== 1: state_delta_single_event_counter.inc() # This is a fairly handwavey check", "[]).append( (event, context) ) for room_id, ev_ctx_rm in iteritems(events_by_room): latest_event_ids", "delta then the new current state is only returned if", "those which are prev_events of existing (non-outlier/rejected) events. Args: event_ids", "for (event, context), stream in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering = stream", "the event_search table. self._store_room_message_txn(txn, event) elif event.type == EventTypes.Redaction: #", "deltas for a room. Assumes that we are only persisting", "for room_id, new_extrem in iteritems(new_forward_extremities) for event_id in new_extrem ],", "ep2.event_id IS NULL\" ) new_backwards_extrems = txn.fetchall() logger.info(\"[purge] replacing backward", "yield self._calculate_state_delta( room_id, current_state ) state_delta_for_room[room_id] = delta # If", "\" SELECT event_id FROM events_to_purge WHERE should_delete\" \")\" % (table,),", "= queue self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop off in the background", "USING (event_id) LEFT JOIN event_json USING (event_id) WHERE event_id IN", "events_to_purge_id\" \" ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete FROM events_to_purge\") event_rows", "pull the state group from the database. # Set of", "event.is_state() ], ) # _store_rejected_events_txn filters out any events which", "_persist_events( self, events_and_contexts, backfilled=False, delete_existing=False ): \"\"\"Persist events to db", "is None: # This should only happen for outlier events.", "of event_ids to return. This includes all soft-failed events #", "c_counter() BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1, 2, 3, 5, 7,", "only happen for outlier events. if not ev.internal_metadata.is_outlier(): raise Exception(", "database tables. Rejected events are only inserted into the events", "(table,), [(ev.room_id, ev.event_id) for ev, _ in events_and_contexts], ) def", "event was rejected). Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase,", "are referenced sql = \"\"\" SELECT DISTINCT state_group FROM event_to_state_groups", "context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type = \"local\" origin_entity = \"*client*\" else:", "whether or not the returned deferred is ready. Args: room_id", "set of events, find all those that have been soft-failed", "= next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group, new_state_group), None) if delta_ids is", "Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events to", "(%s)) AND e.room_id = ? AND topological_ordering < ?\" %", "Copyright 2018-2019 New Vector Ltd # Copyright 2019 The Matrix.org", "for room_id, ev_ctx_rm in iteritems(events_by_room): latest_event_ids = yield self.get_latest_event_ids_in_room( room_id", "is greater than forward extremeties\" ) logger.info(\"[purge] looking for events", "that were in the previous set of extremities as well", "new_latest_event_ids = yield self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids ) latest_event_ids =", "list, without events which are already in the events table.", "events from DB event_to_groups = yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State", "room_version = None for ev, _ in events_context: if ev.type", "(room_id, event_id) instead. for table in (\"event_push_actions\",): logger.info(\"[purge] removing events", "found %i referenced state groups\", len(referenced_state_groups) ) logger.info(\"[purge] finding state", "for each new event\", buckets=(0, 1, 2, 3, 5, 7,", "deleted\") _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups = _ logger.info(", "txn.fetchall() if len(new_forward_events) == limit: upper_bound = new_forward_events[-1][0] else: upper_bound", "from the database. # Set of events we need to", "work out the delta (or use that # given) if", "?\" # We include the parameter twice since we use", "either express or implied. # See the License for the", "events we are persisting \"\"\" if not events_and_contexts: # nothing", "new entries for the backward extremeties by finding # events", "`to_insert` are the updates to current_state_events. \"\"\" existing_state = yield", "not res: raise SynapseError(404, \"Could not find event %s\" %", "table self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event) return [ec for ec in", "by finding # events to be purged that are pointed", "(room_id, etype, state_key) for etype, state_key in itertools.chain(to_delete, to_insert) ),", "== limit: upper_bound = new_event_updates[-1][0] else: upper_bound = current_id sql", "rejected then we don't care if the event # was", "event (EventBase): context (EventContext): backfilled (bool): Returns: Deferred: resolves to", "if not events_and_contexts: # nothing to do here return def", "left!\" new_forward_extremeties[room_id] = new_latest_event_ids len_1 = ( len(latest_event_ids) == 1", "yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def persist_event(self, event, context, backfilled=False):", "separated by soft failed events. Args: event_ids (Iterable[str]): Events to", "event_relations USING (event_id)\" \" WHERE ? < event_stream_ordering\" \" AND", "rejections USING (event_id) LEFT JOIN event_json USING (event_id) WHERE event_id", "synapse tries to take out an exclusive lock on room_depth", "each new event. Stale extremities # are those that were", "only one concurrent transaction per room. \"\"\" _EventPersistQueueItem = namedtuple(", "table first. txn.execute(\"DROP TABLE IF EXISTS events_to_purge\") txn.execute( \"CREATE TEMPORARY", "room_depth # state_groups # state_groups_state # we will build a", "The number of times we are recalculating state when there", "persisting Returns: list[(EventBase, EventContext)] new list, without events which are", "commits the # transaction on CREATE, so let's do this", "tables already having # entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) #", "that can be deleted and the set of state groups", "delete all the existing entries # for these events so", "* 1000) @defer.inlineCallbacks def _read_forward_extremities(self): def fetch(txn): txn.execute( \"\"\" select", "Remove the rejected events from the list now that we've", "events that are outliers and aren't going to be #", "get_current_events_token(self): \"\"\"The current maximum token that events have reached\"\"\" return", "so_1 = yield self._get_event_ordering(event_id1) to_2, so_2 = yield self._get_event_ordering(event_id2) defer.returnValue((to_1,", "], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, ) # Invalidate the", "), ) txn.executemany( sql, ( ( stream_id, room_id, etype, state_key,", "self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self, txn, events_and_contexts): to_prefill = [] rows", "so lets make an index. txn.execute(\"CREATE INDEX events_to_purge_id\" \" ON", ") self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def _update_forward_extremities_txn( self, txn, new_forward_extremities, max_stream_order", "groups). \"\"\" return self.runInteraction( \"purge_history\", self._purge_history_txn, room_id, token, delete_local_events, )", "(\" \" SELECT event_id FROM events_to_purge WHERE should_delete\" \")\" %", "point onwards the events are only events that we haven't", "\"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"processed\": True, \"outlier\": event.internal_metadata.is_outlier(),", "have arrived at the server either as new events or", "# We do joins against events_to_purge for e.g. calculating state", "= self.cursor_to_dict(txn) for row in rows: event = ev_map[row[\"event_id\"]] if", "= ep2.event_id\" \" WHERE ep2.event_id IS NULL\" ) new_backwards_extrems =", "We're only interested in pulling out state that has already", "having # entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert into", "run_as_background_process from synapse.state import StateResolutionStore from synapse.storage.background_updates import BackgroundUpdateStore from", "event_id, and has one on # (room_id, event_id) instead. for", "the latest persisted event \"\"\" deferred = self._event_persist_queue.add_to_queue( event.room_id, [(event,", "1 ) if len_1: all_single_prev_not_state = all( len(event.prev_event_ids()) == 1", "len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc() # This is a fairly handwavey", "should_delete / shouldn't_delete subsets txn.execute( \"CREATE INDEX events_to_purge_should_delete\" \" ON", "ev.state_key == \"\": room_version = ev.content.get(\"room_version\", \"1\") break if not", "for event_id, outlier in txn} to_remove = set() for event,", "in extremities, so no change in state continue # there", "txn.executemany( sql, ( ( stream_id, room_id, etype, state_key, None, room_id,", "\" INNER JOIN event_edges AS ed ON e.event_id = ed.prev_event_id\"", "and their prev events (whether soft-failed/rejected or not), and recurses", "handle the case where the new events have soft-failed prev", "event_edges AS eg ON eg.prev_event_id = eb.event_id INNER JOIN events", "table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event) # Insert into the room_memberships", "queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, ) ) return deferred.observe() def", "with stream_ordering_manager as stream_orderings: for (event, context), stream in zip(events_and_contexts,", "(though arguably those could both be moved in here) class", "None) if queue: self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop", "for sg in state_groups_to_delete), ) logger.info(\"[purge] removing events from event_to_state_groups\")", "JOIN state_events USING (event_id)\" \" WHERE ? < stream_ordering AND", "self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) ) @defer.inlineCallbacks def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids):", "delete_existing (bool): Returns: Deferred: resolves when the events have been", "SET outlier = ?\" \" WHERE event_id = ?\" txn.execute(sql,", "ctx.rejected and not event.internal_metadata.is_soft_failed() ] latest_event_ids = set(latest_event_ids) # start", "= yield func(self, *args, delete_existing=True, **kwargs) defer.returnValue(res) return f #", "event_forward_extremities as f \" \"ON e.event_id = f.event_id \" \"AND", "have # the current state in memory then lets also", "the necessary database tables. Rejected events are only inserted into", "row in rows: # Note: Each state group can have", "\"room_id\": event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)), \"format_version\": event.format_version,", "by events that are going to be deleted. Returns: tuple[set[int],", "# We include the parameter twice since we use the", "return None. \"\"\" def _count_messages(txn): sql = \"\"\" SELECT COALESCE(COUNT(*),", "ASC\" \" LIMIT ?\" ) txn.execute(sql, (-last_id, -current_id, limit)) new_event_updates", "(str): A topological token to delete events before delete_local_events (bool):", "DB later # if necessary. current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids", "the License. import itertools import logging from collections import Counter", "in a Unicode string. \"\"\" out = frozendict_json_encoder.encode(json_object) if isinstance(out,", "10, 15, 20, 50, 100, 200, 500, \"+Inf\"), ) def", "\"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], \"event_id\": state_id, } for", "txn.execute( \"INSERT INTO events_to_purge\" \" SELECT event_id, %s\" \" FROM", "((sg,) for sg in state_groups_to_delete), ) txn.executemany( \"DELETE FROM state_groups", "forward extremities for each room. For each room, a list", "state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None)) @defer.inlineCallbacks def _calculate_state_delta(self, room_id, current_state): \"\"\"Calculate", "use this file except in compliance with the License. #", "self._store_redaction(txn, event) elif event.type == EventTypes.RoomHistoryVisibility: # Insert into the", "ordering of ``event``, and the stream ordering of the latest", "event_ids (Iterable[str]): Events to find prev events for. Note that", "outlier = ?\" \" WHERE event_id = ?\" txn.execute(sql, (False,", "rejections.event_id IS NULL \"\"\" % ( \",\".join(\"?\" for _ in", "in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def", "SELECT event_id FROM events_to_purge \" \" WHERE NOT should_delete\" \")\",", "\"\"\"Attempts to handle the queue for a room if not", "new forward extremities for the room. Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str),", "situation where workers see events before the # current_state_delta updates.", "we can just add these new events to that item.", "state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert some number of room events into", "txn.execute( \"SELECT event_id, outlier FROM events WHERE event_id in (%s)\"", "from synapse.util import batch_iter from synapse.util.async_helpers import ObservableDeferred from synapse.util.caches.descriptors", "# The set of event_ids to return. This includes all", "self._store_event_state_mappings_txn(txn, events_and_contexts) # We want to store event_auth mappings for", "have the same event twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts )", "or state groups, and if not we delete them. txn.execute(", "new_forward_events = txn.fetchall() if len(new_forward_events) == limit: upper_bound = new_forward_events[-1][0]", "it will return None. \"\"\" def _count_messages(txn): sql = \"\"\"", "FROM %s WHERE event_id IN (\" \" SELECT event_id FROM", "# So, let's stick it at the end so that", "backfilled=False): \"\"\" Args: event (EventBase): context (EventContext): backfilled (bool): Returns:", "AS ep2 ON ed.event_id = ep2.event_id\" \" WHERE ep2.event_id IS", "to_delete # We sanity check that we're deleting rather than", "on event_id, and has one on # (room_id, event_id) instead.", "handle_queue_loop(): try: queue = self._get_drainining_queue(room_id) for item in queue: try:", "sql = \"\"\" INSERT INTO current_state_delta_stream (stream_id, room_id, type, state_key,", "EventContext)]): events we are persisting all_events_and_contexts (list[(EventBase, EventContext)]): all events", "(twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting", "= row[\"prev_state_group\"] to_delete = state_groups_seen - referenced_groups to_dedelta = set()", "stream_ordering DESC\" \" LIMIT ?\" ) if have_backfill_events: txn.execute(sql, (-last_backfill_id,", "set(ev.prev_event_ids()) if latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state delta", "as new events or as backfilled events\"\"\" have_backfill_events = last_backfill_id", "for event, _ in events_and_contexts for auth_id in event.auth_event_ids() if", "state_key, None, room_id, etype, state_key, ) for etype, state_key in", "extremities. Given a set of events, find all those that", "events as outliers logger.info(\"[purge] marking remaining events as outliers\") txn.execute(", "(event_id) LEFT JOIN event_json USING (event_id) WHERE event_id IN (%s)", "!= latest_event_ids: forward_extremities_counter.observe(len(result)) stale = latest_event_ids & result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result)", "outlier = ?\" \" WHERE event_id IN (\" \" SELECT", "txn.fetchall() if len(new_event_updates) == limit: upper_bound = new_event_updates[-1][0] else: upper_bound", "defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed ancestors to remove", "We now insert into stream_ordering_to_exterm a mapping from room_id, #", "self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10) def get_all_new_events( self, last_backfill_id,", "of our transaction. # # So, let's stick it at", "event we were # persisting. state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\"", "have negative stream orderings, so we don't # want to", "], ) @classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that we don't", "\" SELECT event_id, %s\" \" FROM events AS e LEFT", "from the current state, and a state set to be", "(or use that # given) if delta_ids is not None:", "self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def _persist_events( self, events_and_contexts, backfilled=False, delete_existing=False", "self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event) return [ec for ec in events_and_contexts", "backward extremities\") # We calculate the new entries for the", "new_forward_events = [] forward_ex_outliers = [] sql = ( \"SELECT", "# are ones we don't have yet so we need", "events # and their prev events. existing_prevs = set() def", "= ?\" \" WHERE event_id IN (\" \" SELECT event_id", "txn state_groups (set[int]): Set of state groups referenced by events", "This gets around any problems with some tables already having", "_get_events_which_are_prevs_txn(txn, batch): sql = \"\"\" SELECT prev_event_id, internal_metadata FROM event_edges", "JOIN rejections USING (event_id) LEFT JOIN event_json USING (event_id) WHERE", "in iteritems(partitioned): d = self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled ) deferreds.append(d)", "events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds = [] for room_id, evs_ctxs", "RoomStreamToken.parse(token_str) # Tables that should be pruned: # event_auth #", "[] backward_ex_outliers = [] return AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers,", "each room. For each room, a tuple (to_delete, to_insert), being", "*args, **kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res = yield func(self,", "handle_queue_loop) def _get_drainining_queue(self, room_id): queue = self._event_persist_queues.setdefault(room_id, deque()) try: while", "metadata, rejected in txn: if prev_event_id in existing_prevs: continue soft_failed", "too big if len(next_to_search) < 100: current_search = next_to_search next_to_search", "upper_bound = current_id sql = ( \"SELECT event_stream_ordering, e.event_id, e.room_id,", "that this # event isn't an outlier any more. self._update_backward_extremeties(txn,", "of these events. # What we're interested in is if", "range(0, len(events_and_contexts), N): ev_map = {e[0].event_id: e[0] for e in", "returns a Deferred and accepts a `delete_existing` arg \"\"\" @wraps(func)", "the logcontext in place whether or not the returned deferred", "not None: # If there is a delta we know", "= { \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"state_key\": event.state_key,", "the events in event_backward_extremities # are ones we don't have", "a database function so that it gets retried on IntegrityError,", "ctx in events_context: if ctx.state_group is None: # This should", "same then we don't need to do # anything. if", "that weren't # rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, )", "len(events_and_contexts), N): ev_map = {e[0].event_id: e[0] for e in events_and_contexts[i", "follow the synapse logcontext rules, and leaves the logcontext in", "state groups). \"\"\" return self.runInteraction( \"purge_history\", self._purge_history_txn, room_id, token, delete_local_events,", "events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties,", "remaining events as outliers\") txn.execute( \"UPDATE events SET outlier =", "is not None: # If there is a delta we", "= current_id sql = ( \"SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,\"", "event) self._handle_event_relations(txn, event) # Insert into the room_memberships table. self._store_room_members_txn(", "of the event ids which are the forward extremities. \"\"\"", "on the number of forward extremities that exist. # Counter", "this by looking at the prev_events and checking # if", "origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc() for room_id, new_state in", "txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count, = txn.fetchone() return count ret =", "\"[purge] found %i state groups to delete\", len(state_groups_to_delete) ) logger.info(", "= {} for ev, ctx in events_context: if ctx.state_group is", "return deferred.observe() def handle_queue(self, room_id, per_item_callback): \"\"\"Attempts to handle the", "item.deferred.callback(ret) finally: queue = self._event_persist_queues.pop(room_id, None) if queue: self._event_persist_queues[room_id] =", "rejected Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events", "# purge. txn.execute( \"SELECT DISTINCT e.event_id FROM events_to_purge AS e\"", "know the delta then the new current state is only", "events_and_contexts], ) have_persisted = {event_id: outlier for event_id, outlier in", "?, ( SELECT event_id FROM current_state_events WHERE room_id = ?", "don't have the same event twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts", "[event]) return [ec for ec in events_and_contexts if ec[0] not", "batch of the events that we are persisting; that means", "= event.internal_metadata.stream_ordering state_group_id = context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\":", "if ev_id != existing_state.get(key) } defer.returnValue((to_delete, to_insert)) @log_function def _persist_events_txn(", "number of stale forward extremities for each new event. Stale", "state dict state_group_deltas = {} for ev, ctx in events_context:", "state_id, } for key, state_id in iteritems(curr_state) ], ) logger.info(\"[purge]", "out what the new extremities are and then # calculating", "What we're interested in is if the latest extremities #", "+= (\"%:\" + self.hs.hostname, \"%:\" + self.hs.hostname) should_delete_params += (room_id,", ") logger.info(\"[purge] finding state groups that can be deleted\") _", "backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else: stream_ordering_manager = self._stream_id_gen.get_next_mult(", "Used to determine if they're \"new\" events which might update", "handled. The given callback will be invoked with for each", "have been soft-failed or rejected. Returns those soft failed/rejected events", "list(current_search)) referenced = set(sg for sg, in txn) referenced_groups |=", "# Tables that should be pruned: # event_auth # event_backward_extremities", "\"redactions\", \"room_memberships\", \"topics\", ): txn.executemany( \"DELETE FROM %s WHERE event_id", "event_id_to_state_group.update(event_to_groups) # State groups of old_latest_event_ids old_state_groups = set( event_id_to_state_group[evid]", ") # finally, drop the temp table. this will commit", "create the indices *after* insertion as that's a lot faster.", "and which we have added, then we invlidate the caches", "\"\"\"Calculates the new forward extremities for a room given events", "\"UPDATE event_json SET internal_metadata = ?\" \" WHERE event_id =", "encode_json(event.internal_metadata.get_dict()) sql = ( \"UPDATE event_json SET internal_metadata = ?\"", "(event_id)\" \" WHERE ? < event_stream_ordering\" \" AND event_stream_ordering <=", "(to_delete, to_insert), being a list of type/state keys to be", "results.extend(r[0] for r in txn if not json.loads(r[1]).get(\"soft_failed\")) for chunk", "version, which is in the create event. # Normally that'd", "in which case we can # pull the state group", "INDEX events_to_purge_id\" \" ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete FROM events_to_purge\")", ") ) return deferred.observe() def handle_queue(self, room_id, per_item_callback): \"\"\"Attempts to", "be removed from the current state, and a state set", "then we only return the delta if its already been", "-upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5,", "\"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \" FROM", "LEFT JOIN event_relations USING (event_id)\" \" WHERE ? > event_stream_ordering\"", "change in outlier status to our workers. stream_order = event.internal_metadata.stream_ordering", "BY event_stream_ordering DESC\" ) txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers = txn.fetchall()", "= queue[-1] if end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred", "table with that state. # insert into event_to_state_groups. try: self._store_event_state_mappings_txn(txn,", "current_backfill_id have_forward_events = last_forward_id != current_forward_id if not have_backfill_events and", "all_single_prev_not_state: continue state_delta_counter.inc() if len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc() # This", "if old_state_groups == new_state_groups: defer.returnValue((None, None)) if len(new_state_groups) == 1", "dict] (to_delete, to_insert): where to_delete are the type/state_keys to remove", "new_latest_event_ids (iterable[str]): the new forward extremities for the room. Returns:", "have_persisted: continue to_remove.add(event) if context.rejected: # If the event is", "in state res v2. # This is only necessary if", "events_context: if ctx.state_group is None: # This should only happen", "after adding some new events to a room Args: room_id", "room_id, new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} )", "return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self, last_id, current_id, limit):", "which are the forward extremities. \"\"\" all_events_and_contexts = events_and_contexts min_stream_order", "outlier any more. self._update_backward_extremeties(txn, [event]) return [ec for ec in", "not event.is_state() for event, ctx in ev_ctx_rm ) # Don't", "more. self._update_backward_extremeties(txn, [event]) return [ec for ec in events_and_contexts if", "that means we do not # end up in a", "backfilled (bool): delete_existing (bool): Returns: Deferred: resolves when the events", "\"AND e.room_id = f.room_id \" \"WHERE f.room_id = ?\", (room_id,),", "event.redacts ) # Remove from relations table. self._handle_redaction(txn, event.redacts) #", "# event_edges # event_forward_extremities # event_json # event_push_actions # event_reference_hashes", "make an index. txn.execute(\"CREATE INDEX events_to_purge_id\" \" ON events_to_purge(event_id)\") txn.execute(\"SELECT", "WHERE state_group = ?\", ((sg,) for sg in state_groups_to_delete), )", "of an event that we had already stored as #", "history to figure out which state groups can be deleted", "the state groups that reference to-be-deleted state # groups to", "self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events( self,", "_ in current_search), ) txn.execute(sql, list(current_search)) referenced = set(sg for", "stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else: stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts)", "delta versions. for sg in remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining state", "USING (event_id)\" \" LEFT JOIN event_relations USING (event_id)\" \" WHERE", "(and # it doesn't take much storage compared to storing", "new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) # Now that we have", "# Invalidate the various caches # Figure out the changes", ") for member in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn,", "the delta if its already been calculated. Conversely if we", "\"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\", \"state_events\", \"rejections\", \"redactions\",", "where the new events have soft-failed prev # events. If", "current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates) == limit: upper_bound", "empty. The return value of the function will be given", "or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk in batch_iter(event_ids, 100): yield", "event_stream_ordering DESC\" ) txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers = txn.fetchall() else:", "the same `backfilled` setting, # we can just add these", "the cache with it. if current_state is not None: current_state_for_room[room_id]", "yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id)", "rej USING (event_id)\" \" LEFT JOIN redactions as r ON", "possible that we're # currently trying to persist it. room_version", "def get_current_backfill_token(self): \"\"\"The current minimum token that backfilled events have", "another, lets check if # we have a delta for", "we are persisting; that means we do not # end", "latest_event_ids): \"\"\"Calculates the new forward extremities for a room given", "are persisting all_events_and_contexts (list[(EventBase, EventContext)]): all events that we were", "event_ids to their state groups. First, let's # check if", "stream ordering of ``event``, and the stream ordering of the", "for a room given events to persist. Assumes that we", "it gets retried on IntegrityError, with `delete_existing=True` passed in. Args:", "synapse.api.errors import SynapseError from synapse.events import EventBase # noqa: F401", "200, 500, \"+Inf\"), ) def encode_json(json_object): \"\"\" Encode a Python", "\"\"\" % ( \",\".join(\"?\" for _ in to_recursively_check), ) txn.execute(sql,", "existing entries # for these events so we can reinsert", "\"\", [\"type\", \"origin_type\", \"origin_entity\"], ) # The number of times", "defer.succeed([]) def get_all_new_forward_event_rows(txn): sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id,", "room_id (str): token (str): A topological token to delete events", "\"room_id\": room_id, \"event_id\": event_id, \"stream_ordering\": max_stream_order, } for room_id, new_extrem", "return count ret = yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def", "no change. If there has been a change then we", "next_to_search -= current_search # Check if state groups are referenced", "the delta (or use that # given) if delta_ids is", "len_1 = ( len(latest_event_ids) == 1 and len(new_latest_event_ids) == 1", "earliest one. Args: events_and_contexts (list[(EventBase, EventContext)]): Returns: list[(EventBase, EventContext)]: filtered", "Args: room_id (str): events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): Returns: defer.Deferred:", "the events from the database. This is useful when retrying", "except Exception: logger.exception(\"\") raise metadata_json = encode_json(event.internal_metadata.get_dict()) sql = (", "(\"event_push_actions\",): logger.info(\"[purge] removing events from %s\", table) txn.execute( \"DELETE FROM", "in the queue has the same `backfilled` setting, # we", "== backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append(", "that we don't # have to keep shovelling the list", "= event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\", None) return d self._simple_insert_many_txn( txn,", "(prev state group, new state group) -> delta state dict", "_get_events_which_are_prevs(self, event_ids): \"\"\"Filter the supplied list of event_ids to get", "\" LEFT JOIN event_relations USING (event_id)\" \" WHERE ? <", "to this function, it will return None. \"\"\" def _count_messages(txn):", "Insert into the event_search table. self._store_history_visibility_txn(txn, event) elif event.type ==", "the new forward extremities for the room. Returns: Deferred[tuple[dict[(str,str), str]|None,", "None)) if len(new_state_groups) == 1 and len(old_state_groups) == 1: #", "event_id1 is after event_id2 in the stream \"\"\" to_1, so_1", "= self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups = _ logger.info( \"[purge] found", "None then there has been no change. If there has", "if not backfilled: # backfilled events have negative stream orderings,", "# If there is a delta we know that we've", "to the events table and the events_json table. to_remove =", "six.moves import range from canonicaljson import json from prometheus_client import", "database # otherwise we wouldn't be able to send any", "the stream_ids # for the batch of the events that", "if not we delete them. txn.execute( \"\"\" SELECT DISTINCT state_group", "event, context in events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id) if prev_event_context: if", "logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used when purging history", "# If they old and new groups are the same", "events.outlier AND rejections.event_id IS NULL \"\"\" % ( \",\".join(\"?\" for", "groups we've already seen state_groups_seen = set(state_groups) # Set of", "event that we had already stored as # an outlier", "at that # so we need to update the state_groups", "event_id IN (%s) AND NOT events.outlier \"\"\" % ( \",\".join(\"?\"", "WHERE room_id = ? AND event_id IN (\" \" SELECT", "INNER JOIN events AS e ON e.event_id = eg.event_id WHERE", "{} # Set of events that we have found to", "and accepts a `delete_existing` arg \"\"\" @wraps(func) @defer.inlineCallbacks def f(self,", "For each room, a list of the event ids which", "import RoomStreamToken, get_domain_from_id from synapse.util import batch_iter from synapse.util.async_helpers import", "deleted. Returns: tuple[set[int], set[int]]: The set of state groups that", "extremeties txn.executemany( \"INSERT INTO event_backward_extremities (room_id, event_id)\" \" VALUES (?,", "outlier FROM events WHERE event_id in (%s)\" % (\",\".join([\"?\"] *", "map room_id->list[event_ids] giving the new forward # extremities in each", "JOIN state_events USING (event_id)\" \" WHERE (NOT outlier OR (%s))", "events. # What we're interested in is if the latest", "events_and_contexts=events_and_contexts ) # From this point onwards the events are", "not the returned deferred is ready. Args: room_id (str): events_and_contexts", "str]|None]]: Returns a tuple of two state maps, the first", "((type, key) -> event_id) state map state_groups_map = {} #", "allow_none=True, ) if not res: raise SynapseError(404, \"Could not find", "txn.fetchone() logger.info(\"[purge] updating room_depth to %d\", min_depth) txn.execute( \"UPDATE room_depth", "stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[ { \"room_id\": room_id, \"event_id\": event_id,", "SELECT prev_event_id, internal_metadata FROM event_edges INNER JOIN events USING (event_id)", "We do this by working out what the new extremities", "yield self._get_prevs_before_rejected( e_id for event in new_events for e_id in", "we could have resonably # calculated the delta when we", "# we're only interested in new events which aren't outliers", "rejected events, as they're # used in state res v2.", "FROM events WHERE event_id in (%s)\" % (\",\".join([\"?\"] * len(events_and_contexts)),),", "deferred=deferred, ) ) return deferred.observe() def handle_queue(self, room_id, per_item_callback): \"\"\"Attempts", "this will commit the txn in sqlite, # so make", "we have the current_state then lets prefill # the cache", "Returns: Deferred: resolves when the events have been persisted \"\"\"", "drop the temp table. this will commit the txn in", "need to defer to the state handler to resolve our", "have to pull out the existing state # unnecessarily). #", "we have a delta for that transition. If we do", "sg in referenced_groups: prev_sg = graph.get(sg) if prev_sg and prev_sg", "is a map (type,key)->event_id giving the state delta in each", "txn.executemany( sql, ( ( stream_id, room_id, etype, state_key, ev_id, room_id,", "_update_current_state_txn(self, txn, state_delta_by_room, stream_id): for room_id, current_state_tuple in iteritems(state_delta_by_room): to_delete,", "= \"\"\" SELECT stream_id, room_id, type, state_key, event_id FROM current_state_delta_stream", "some state at that # so we need to update", "len(event_rows), sum(1 for e in event_rows if e[1]), ) logger.info(\"[purge]", "def _get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed ancestors to remove from the", "events that change forward extremities # (e.g. we ignore backfill/outliers/etc)", "delta we know that we've # only added or replaced", "event_id IN (SELECT event_id from events_to_purge)\" ) for event_id, _", "_handle_mult_prev_events (though arguably those could both be moved in here)", "stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with stream_ordering_manager as stream_orderings: for", "any outliers with new event info. This turns outliers into", "(table,), (room_id,), ) # Mark all state and own events", "events_and_contexts, all_events_and_contexts, backfilled ): \"\"\"Update all the miscellaneous tables for", "key not in current_state] to_insert = { key: ev_id for", "state_groups_seen |= prevs for row in rows: # Note: Each", "= yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The current minimum", "= new_backfill_events[-1][0] else: upper_bound = current_backfill_id sql = ( \"SELECT", "existing_prevs = yield self._get_prevs_before_rejected( e_id for event in new_events for", "txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks", "added to the current state. new_forward_extremeties (dict[str, list[str]]): The new", "\"\" ) # The number of times we are reculating", "current_state_for_room[room_id] = current_state yield self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing,", "AS e ON e.event_id = eg.event_id WHERE eb.room_id = ?", "for the room. new_latest_event_ids (iterable[str]): the new forward extremities for", "backfilled=False, delete_existing=False ): \"\"\"Persist events to db Args: events_and_contexts (list[(EventBase,", "True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\": event.sender, \"contains_url\":", "events we are persisting backfilled (bool): True if the events", "state from that. events_by_room = {} for event, context in", "or rejected. Returns those soft failed/rejected events and their prev", "point Args: room_id (str): token (str): A topological token to", "if they match the current forward extremities. for ev, _", "auth_id, } for event, _ in events_and_contexts for auth_id in", "in batch), ) txn.execute(sql, batch) results.extend(r[0] for r in txn", "for e in events_and_contexts[i : i + N]} if not", "for a room. Assumes that we are only persisting events", "group from its context. # Otherwise we need to pull", "or not. Used to determine if they're \"new\" events which", "event.type == EventTypes.Name: # Insert into the room_names and event_search", "logger.exception(\"\") raise metadata_json = encode_json(event.internal_metadata.get_dict()) sql = ( \"UPDATE event_json", "not None then there has been a change, # and", "for table in ( \"events\", \"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\",", "events_and_contexts ) self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled ) # _update_outliers_txn filters", "tuple (to_delete, to_insert), being a list of type/state keys to", "Args: room_id (str): token (str): A topological token to delete", "JOIN events_to_purge AS ep2 ON ed.event_id = ep2.event_id\" \" WHERE", "= \"*client*\" else: origin_type = \"remote\" origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type,", "good enough as if you have silly characters in your", "= current_backfill_id sql = ( \"SELECT -event_stream_ordering, event_id, state_group\" \"", "results are retrieved from federation via backfill or not. Used", "None: with Measure( self._clock, \"persist_events.calculate_state_delta\" ): delta = yield self._calculate_state_delta(", "are persisting Returns: list[(EventBase, EventContext)] new list, without events which", "current_state_for_room = {} # map room_id->(to_delete, to_insert) where to_delete is", "For each room, a tuple (to_delete, to_insert), being a list", "being rejected. new_events = [ event for event, ctx in", "hs): super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler()", "ancestor non-state events. if all_single_prev_not_state: continue state_delta_counter.inc() if len(new_latest_event_ids) ==", ") txn.execute(sql, (-last_id, -current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates)", "it. if current_state is not None: current_state_for_room[room_id] = current_state yield", "events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order)", "From this point onwards the events are only ones that", "event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \" FROM", "state_group\" \" FROM ex_outlier_stream\" \" WHERE ? > event_stream_ordering\" \"", "if ev.type == EventTypes.Create and ev.state_key == \"\": room_version =", "column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), ) prevs = set(row[\"state_group\"] for", "_ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups = _ logger.info( \"[purge]", "self, txn, events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert some", ") # Remove from relations table. self._handle_redaction(txn, event.redacts) # Update", "characters in your own # hostname then thats your own", "table. txn.execute( \"\"\" SELECT COALESCE(MIN(depth), 0) FROM event_backward_extremities AS eb", "which aren't outliers and which aren't # being rejected. new_events", "# You may obtain a copy of the License at", "new_extrem in iteritems(new_forward_extremities) for event_id in new_extrem ], ) @classmethod", "return txn.fetchall() res = yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount = c_counter(list(x[0]", "in new_latest_event_ids: # First search in the list of new", "new_events for e_id in event.prev_event_ids() ) # Remove any events", "Exception: with PreserveLoggingContext(): item.deferred.errback() else: with PreserveLoggingContext(): item.deferred.callback(ret) finally: queue", "for the rest of our transaction. # # So, let's", "to stop the # SQL query getting too big if", "new_event_updates.extend(txn.fetchall()) return new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10)", "what the current # state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok,", "if ctx.state_group in state_groups_map: continue # We're only interested in", "if missing_state: group_to_state = yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) ==", "event.internal_metadata.is_outlier() and not context.rejected: depth_updates[event.room_id] = max( event.depth, depth_updates.get(event.room_id, event.depth)", "we run this update, we # will block that for", "state group graphs for state # groups that are referenced.", "negative stream orderings, so we don't # want to set", "from synapse.storage.event_federation import EventFederationStore from synapse.storage.events_worker import EventsWorkerStore from synapse.storage.state", "for x in res)) @defer.inlineCallbacks def persist_events(self, events_and_contexts, backfilled=False): \"\"\"", "txn, table=\"state_groups_state\", values=[ { \"state_group\": sg, \"room_id\": room_id, \"type\": key[0],", "to persist it. room_version = None for ev, _ in", "state. If both are None then there has been no", "# return that. new_state_group = next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids", "only persisting events for one room # at a time.", "( \"SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\"", "event.room_id, \"type\": event.type, \"processed\": True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\":", "stored as # an outlier in the database. We now", "(list[(EventBase, EventContext)]): events and contexts which are being added to", "state res v2. # This is only necessary if the", "it via event_edges table. txn.execute( \"\"\" SELECT COALESCE(MIN(depth), 0) FROM", "100)) next_to_search -= current_search # Check if state groups are", "ORDER BY stream_ordering ASC\" \" LIMIT ?\" ) if have_forward_events:", "be given to the deferreds waiting on the item, exceptions", "delete all the events from the database # otherwise we", "AllNewEventsResult = namedtuple( \"AllNewEventsResult\", [ \"new_forward_events\", \"new_backfill_events\", \"forward_ex_outliers\", \"backward_ex_outliers\", ],", "in old_latest_event_ids ) # State groups of new_latest_event_ids new_state_groups =", "list. events_and_contexts = self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts ) # From this", ") for room_id, ev_ctx_rm in iteritems(events_by_room): latest_event_ids = yield self.get_latest_event_ids_in_room(", "in to_recursively_check), ) txn.execute(sql, to_recursively_check) to_recursively_check = [] for event_id,", ") self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[ { \"state_group\": sg, \"room_id\": room_id,", "return f # inherits from EventFederationStore so that we can", "the earliest one. Args: events_and_contexts (list[(EventBase, EventContext)]): Returns: list[(EventBase, EventContext)]:", "the deferreds as well. This function should therefore be called", "then # calculating the state from that. events_by_room = {}", "that transition. If we do then we can just #", "= [] N = 200 for i in range(0, len(events_and_contexts),", "\"\"\" select count(*) c from event_forward_extremities group by room_id \"\"\"", "room events into the necessary database tables. Rejected events are", "know none of the old # extremities are going to", "db connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting \"\"\"", "dict after adding some new events to a room Args:", "be looking for # the should_delete / shouldn't_delete subsets txn.execute(", "backfilled (bool): Whether the results are retrieved from federation via", "own events as outliers logger.info(\"[purge] marking remaining events as outliers\")", "state IDs so we can resolve to a single state", "# add all the new events to the list result.update(event.event_id", "concurrent transaction per room. \"\"\" _EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\",", "and returns the filtered list. events_and_contexts = self._update_outliers_txn( txn, events_and_contexts=events_and_contexts", "state_events USING (event_id)\" \" WHERE ? < stream_ordering AND stream_ordering", "to find prev events for. Note that these must have", "], ) def _store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add rows to the", "state_key in itertools.chain(to_delete, to_insert) if ev_type == EventTypes.Member ) for", "already being handled. The given callback will be invoked with", "the should_delete / shouldn't_delete subsets txn.execute( \"CREATE INDEX events_to_purge_should_delete\" \"", "(because upsert), and once we run this update, we #", "the item, exceptions will be passed to the deferreds as", "callback is currently handling the queue then it will not", "type _EventPersistQueueItem. The per_item_callback will continuously be called with new", "stream in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering = stream chunks = [", "logger = logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter = Counter(", ">= ?\" \" ORDER BY stream_ordering DESC\" \" LIMIT ?\"", "latest_event_ids, new_latest_event_ids, ) current_state, delta_ids = res # If either", "for key, ev_id in iteritems(current_state) if ev_id != existing_state.get(key) }", "AND ep.event_id IS NULL \"\"\" % ( \",\".join(\"?\" for _", "2.0 (the \"License\"); # you may not use this file", "# We create the indices *after* insertion as that's a", "room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids, ) current_state, delta_ids = res #", "and event_search table. self._store_room_topic_txn(txn, event) elif event.type == EventTypes.Message: #", "\"\"\"Update any outliers with new event info. This turns outliers", "onwards the events are only ones that weren't # rejected.", "We calculate the new entries for the backward extremeties by", "the forward extremities. \"\"\" all_events_and_contexts = events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering", "events_and_contexts ], ) self._simple_insert_many_txn( txn, table=\"events\", values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering,", "necessary if the rejected event appears in an accepted #", "# and their prev events. existing_prevs = set() def _get_prevs_before_rejected_txn(txn,", "state_groups_state WHERE state_group = ?\", ((sg,) for sg in state_groups_to_delete),", "events which aren't outliers and which aren't # being rejected.", "\"room_id\": event.room_id, \"type\": event.type, \"state_key\": event.state_key, } # TODO: How", "state_groups): \"\"\"Used when purging history to figure out which state", "= yield self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids ) latest_event_ids = set(latest_event_ids)", "== EventTypes.Redaction and event.redacts is not None: # Remove the", "extremities. for ev, _ in ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids()) if", "SELECT stream_id, room_id, type, state_key, event_id FROM current_state_delta_stream WHERE ?", "\",\".join(\"?\" for _ in current_search), ) txn.execute(sql, list(current_search)) referenced =", "self, events_and_contexts, backfilled=False, delete_existing=False ): \"\"\"Persist events to db Args:", "rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def _update_current_state_txn(self, txn,", "txn.execute(\"DROP TABLE IF EXISTS events_to_purge\") txn.execute( \"CREATE TEMPORARY TABLE events_to_purge", "each room after adding these events. # This is simply", "Now that we have calculated new_state_groups we need to get", "events_to_purge WHERE should_delete\" \")\" % (table,), (room_id,), ) # Mark", "= yield self._calculate_state_delta( room_id, current_state ) state_delta_for_room[room_id] = delta #", "AS ed ON e.event_id = ed.prev_event_id\" \" LEFT JOIN events_to_purge", "ev_ctx_rm in iteritems(events_by_room): latest_event_ids = yield self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids", "we go and delete all the existing entries # for", "= txn.fetchone() return count ret = yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret)", "[] def _get_events_which_are_prevs_txn(txn, batch): sql = \"\"\" SELECT prev_event_id, internal_metadata", "the state delta in each # room state_delta_for_room = {}", "function should therefore be called whenever anything is added to", "( \",\".join(\"?\" for _ in to_recursively_check), ) txn.execute(sql, to_recursively_check) to_recursively_check", "will return None. \"\"\" def _count_messages(txn): sql = \"\"\" SELECT", "extremities for each room. For each room, a list of", "weren't # rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def", "have been when # processing one of these events. #", "?\" % (should_delete_expr, should_delete_expr), should_delete_params, ) # We create the", "res = yield func(self, *args, **kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\")", "to remove from the extremities. Given a set of events,", "to non delta versions. for sg in remaining_state_groups: logger.info(\"[purge] de-delta-ing", "1 and len(old_state_groups) == 1: # If we're going from", "events from the database # otherwise we wouldn't be able", "elif event.type == EventTypes.RoomHistoryVisibility: # Insert into the event_search table.", "the current # state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok, we", "are referenced by other events # or state groups, and", "txn.execute(\"CREATE INDEX events_to_purge_id\" \" ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete FROM", "events\"\"\" have_backfill_events = last_backfill_id != current_backfill_id have_forward_events = last_forward_id !=", "new forward extremeties in the room. # This allows us", "to_insert = { key: ev_id for key, ev_id in iteritems(current_state)", "? AND event_id = ?\" % (table,), [(ev.room_id, ev.event_id) for", "\" LEFT JOIN event_relations USING (event_id)\" \" WHERE ? >", "each room, a list of the event ids which are", "events which are prev_events of any of the new events", "cache_entry) txn.call_after(prefill) def _store_redaction(self, txn, event): # invalidate the cache", "self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids, ) current_state, delta_ids = res", "room_id, event_contexts, latest_event_ids): \"\"\"Calculates the new forward extremities for a", "run this update, we # will block that for the", ") logger.info(\"[purge] finding redundant state groups\") # Get all state", "The set of state groups that can be deleted and", "res v2. # This is only necessary if the rejected", "remote non-state events for table in ( \"events\", \"event_json\", \"event_auth\",", "%s WHERE event_id IN (\" \" SELECT event_id FROM events_to_purge", "persisting events for one room # at a time. #", "removed from the current state, and a state set to", "for event, context in events_and_contexts: if event.event_id not in have_persisted:", "def _count(txn): sql = \"\"\" SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM", "the minimum of the stream_ids # for the batch of", "token.topological: # We need to ensure we don't delete all", "EventTypes.Member ) for member in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) )", "memory then lets also return that, # but it doesn't", "prefill the get_current_state_ids # cache current_state_for_room = {} # map", "state set to be added to the current state. new_forward_extremeties", "to do here return def event_dict(event): d = event.get_dict() d.pop(\"redacted\",", "event.prev_event_ids() ) # Remove any events which are prev_events of", "txn: if prev_event_id in existing_prevs: continue soft_failed = json.loads(metadata).get(\"soft_failed\") if", "event_id1, event_id2): \"\"\"Returns True if event_id1 is after event_id2 in", "USING (event_id)\" \" LEFT JOIN state_events USING (event_id)\" \" LEFT", "\"contains_url\": ( \"url\" in event.content and isinstance(event.content[\"url\"], text_type) ), }", "\" \"INNER JOIN event_forward_extremities as f \" \"ON e.event_id =", "forward extremities as the prev_events, so we can # guess", "See the License for the specific language governing permissions and", "we know what the current # state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None))", "stream_ordering AND stream_ordering >= ?\" \" ORDER BY stream_ordering ASC\"", "# To ensure correct ordering we pop, as OrderedDict is", "new events to the list result.update(event.event_id for event in new_events)", "to in writing, software # distributed under the License is", "room given events to persist. Assumes that we are only", "for a room before a given stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\",", "def _get_events_which_are_prevs_txn(txn, batch): sql = \"\"\" SELECT prev_event_id, internal_metadata FROM", "state group to another, lets check if # we have", "event_id TEXT NOT NULL,\" \" should_delete BOOLEAN NOT NULL\" \")\"", "NB: due to the normal usage pattern of this method,", "event_id) state map state_groups_map = {} # Map from (prev", "db connection events_and_contexts (list[(EventBase, EventContext)]): events to persist backfilled (bool):", "INTO events_to_purge\" \" SELECT event_id, %s\" \" FROM events AS", "at least one forward extremity. # (except during the initial", "are pointed to by events we're not going to #", "redacted_event=None) ) def prefill(): for cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry)", "\"\"\" SELECT stream_id, room_id, type, state_key, event_id FROM current_state_delta_stream WHERE", "__init__(self, db_conn, hs): super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler", "( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \"", "event for event, _ in events_and_contexts if event.type == EventTypes.Member", "compliance with the License. # You may obtain a copy", "changes of membership to invalidate the # `get_rooms_for_user` cache. #", "events # or state groups, and if not we delete", "calculate the `prev_event_id`. (This # allows us to not have", "log_function from synapse.util.metrics import Measure logger = logging.getLogger(__name__) persist_event_counter =", "(event_id) LEFT JOIN event_json USING (event_id) WHERE prev_event_id IN (%s)", "persist_event options. NB: due to the normal usage pattern of", "are persisting backfilled (bool): True if the events were backfilled", "= {} for event_id in new_latest_event_ids: # First search in", "AND stream_ordering >= ?\" \" ORDER BY stream_ordering ASC\" \"", "WHERE should_delete\" \")\" % (table,) ) # event_push_actions lacks an", "|= prevs state_groups_seen |= prevs for row in rows: #", "FROM %s WHERE room_id = ? AND event_id IN (\"", "calculating the state from that. events_by_room = {} for event,", "\"%:\" + self.hs.hostname sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM", "\"%:\" + self.hs.hostname) should_delete_params += (room_id, token.topological) # Note that", "referenced_groups |= referenced # We don't continue iterating up the", "had already stored as # an outlier in the database.", "((sg,) for sg in state_groups_to_delete), ) logger.info(\"[purge] removing events from", "as e\" \" LEFT JOIN rejections as rej USING (event_id)\"", "(?,?)\", (event.event_id, event.redacts), ) @defer.inlineCallbacks def count_daily_messages(self): \"\"\" Returns an", "_EventPersistQueueItem. The per_item_callback will continuously be called with new items,", "room_id} for room_id, new_extrem in iteritems(new_forward_extremities) for ev_id in new_extrem", "state\" for each room. # We do this by working", "table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id, \"room_id\": room_id} for room_id, new_extrem in", "# If we're going from one state group to another,", "self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount = c_counter(list(x[0] for x in res)) @defer.inlineCallbacks", "OR (%s)) AND e.room_id = ? AND topological_ordering < ?\"", "out an exclusive lock on room_depth whenever it # persists", "txn in sqlite, # so make sure to keep this", "list of the event ids which are the forward extremities.", ") def prefill(): for cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill)", "? \"\"\", (room_id,), ) min_depth, = txn.fetchone() logger.info(\"[purge] updating room_depth", "set() # Set of state groups we've already seen state_groups_seen", "of the latest persisted event \"\"\" deferred = self._event_persist_queue.add_to_queue( event.room_id,", "( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\"", "have the current_state then lets prefill # the cache with", "events_and_contexts: # Remove the any existing cache entries for the", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "that item. end_item = queue[-1] if end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts)", "events=[event for event, _ in events_and_contexts] ) for event, _", "added them # to the events table and the events_json", "via backfill or not. Used to determine if they're \"new\"", "unless the queue becomnes empty. The return value of the", "{} if not backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"): # Work out", "to_recursively_check = [] for event_id, prev_event_id, metadata, rejected in txn:", "in event_backward_extremities # are ones we don't have yet so", "\"internal_metadata\": encode_json( event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)), \"format_version\": event.format_version, } for", ") @defer.inlineCallbacks def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids): \"\"\"Calculates the new", "the push actions into the event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts,", "to_token, limit): def get_all_updated_current_state_deltas_txn(txn): sql = \"\"\" SELECT stream_id, room_id,", "\",\".join(\"?\" for _ in to_recursively_check), ) txn.execute(sql, to_recursively_check) to_recursively_check =", "some new events to a room Args: room_id (str): room", "# `get_rooms_for_user` cache. # We find out which membership events", "for the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed,", "for each room. For each room, a tuple (to_delete, to_insert),", "== current_id: return defer.succeed([]) def get_all_new_forward_event_rows(txn): sql = ( \"SELECT", "since we use the expression twice should_delete_params += (\"%:\" +", "def _add_to_cache(self, txn, events_and_contexts): to_prefill = [] rows = []", "state_group_deltas.get((old_state_group, new_state_group), None) if delta_ids is not None: # We", "# Map from (prev state group, new state group) ->", "extremities, so no change in state continue # there should", "in state continue # there should always be at least", "event in new_events for e_id in event.prev_event_ids() ) # Remove", "latest_event_ids = set(latest_event_ids) # start with the existing forward extremities", "delete_local_events, ) def _purge_history_txn(self, txn, room_id, token_str, delete_local_events): token =", "not in to_remove] @classmethod def _delete_existing_rows_txn(cls, txn, events_and_contexts): if not", "of the new events result.difference_update( e_id for event in new_events", "have some state at that # so we need to", "\"\"\"Wraps a database function so that it gets retried on", "handler to resolve our state sets. state_groups = {sg: state_groups_map[sg]", "Rejected events are only inserted into the events table, the", ") return deferred.observe() def handle_queue(self, room_id, per_item_callback): \"\"\"Attempts to handle", "% ( \",\".join(\"?\" for _ in batch), ) txn.execute(sql, batch)", "room Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events", "prev group graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete = state_groups_seen - referenced_groups", "events we are persisting Returns: list[(EventBase, EventContext)] new list, without", "extremity state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\", \"\" ) # The number", "might update the current state etc. Returns: Deferred[int]: the stream", "prev_event_id, internal_metadata FROM event_edges INNER JOIN events USING (event_id) LEFT", "delta would have been when # processing one of these", "-> event_id) state map state_groups_map = {} # Map from", "when there is only a # single forward extremity state_delta_single_event_counter", "_ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete all remote non-state", "+ 100] for x in range(0, len(events_and_contexts), 100) ] for", "context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order, \"event_id\": event.event_id, \"state_group\":", "up in a situation where workers see events before the", "that events have reached\"\"\" return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id, current_id,", "etype, state_key in to_delete # We sanity check that we're", "that, # but it doesn't matter if we don't. new_state", "events that we were going to persist. This includes events", "ON e.event_id = r.redacts\" \" WHERE e.event_id IN (%s)\" )", "which are prev_events of any existing events. existing_prevs = yield", "before cutoff, of which %i can be deleted\", len(event_rows), sum(1", "# run as a background process to make sure that", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "prev_event_context = new_events_and_contexts.get(event.event_id) if prev_event_context: if not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier():", "return list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn, events_and_contexts, backfilled): \"\"\"Update min_depth for", "out the state groups for any missing events from DB", "count, = txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_active_rooms\", _count)", "([], delta_ids) elif current_state is not None: with Measure( self._clock,", "groups for. (We know none of the old # extremities", "\"received_ts\": self._clock.time_msec(), \"sender\": event.sender, \"contains_url\": ( \"url\" in event.content and", "of extremities to count self._current_forward_extremities_amount = c_counter() BucketCollector( \"synapse_forward_extremities\", lambda:", "can use it to calculate the `prev_event_id`. (This # allows", "IntegrityError, with `delete_existing=True` passed in. Args: func: function that returns", "ctx in event_contexts if not event.internal_metadata.is_outlier() and not ctx.rejected and", "(non-outlier/rejected) events. Args: event_ids (Iterable[str]): event ids to filter Returns:", "event_edges table. txn.execute( \"\"\" SELECT COALESCE(MIN(depth), 0) FROM event_backward_extremities AS", "namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\") ) def __init__(self): self._event_persist_queues =", "out.decode(\"utf8\") return out class _EventPeristenceQueue(object): \"\"\"Queues up events so that", "passed to the deferreds as well. This function should therefore", "transactions # have a logcontext to report to return run_as_background_process(", "rejections USING (event_id) LEFT JOIN event_json USING (event_id) WHERE prev_event_id", "room_depth whenever it # persists events (because upsert), and once", "they are # now. When this server creates a new", "(NOT outlier OR (%s)) AND e.room_id = ? AND topological_ordering", "either are not None then there has been a change,", "? > event_stream_ordering\" \" AND event_stream_ordering >= ?\" \" ORDER", "(list, dict)]): The current-state delta for each room. For each", "\"backfilled\", \"deferred\") ) def __init__(self): self._event_persist_queues = {} self._currently_persisting_rooms =", "remote ones (instead of just marking them as outliers and", "import synapse.metrics from synapse.api.constants import EventTypes from synapse.api.errors import SynapseError", "out any events which have already been # persisted, and", "{} for event, context in events_and_contexts: # Remove the any", "= \"\"\" SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM events WHERE type", "ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids()) if latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc() break", "partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id = yield", "to keep shovelling the list back and forth across the", "couldn't find it, then we'll need to pull # the", "room old_latest_event_ids (iterable[str]): the old forward extremities for the room.", "these must have already been persisted. Returns: Deferred[set[str]] \"\"\" #", "the events table. \"\"\" txn.execute( \"SELECT event_id, outlier FROM events", "# No change in extremities, so no change in state", "new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if not backfilled: # backfilled events have", "txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, ) if not event.internal_metadata.is_outlier() and not", "set() for event, context in events_and_contexts: if context.rejected: # Insert", "_EventCacheEntry(event=event, redacted_event=None) ) def prefill(): for cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,),", "problems with some tables already having # entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts)", "the earliest non-outlier if there is one, else the earliest", "it finds no more soft-failed/rejected events. This is used to", "we ignore backfill/outliers/etc) if result != latest_event_ids: forward_extremities_counter.observe(len(result)) stale =", "around any problems with some tables already having # entries.", "(-last_backfill_id, -upper_bound)) backward_ex_outliers = txn.fetchall() else: new_backfill_events = [] backward_ex_outliers", "events to the queue, with the given persist_event options. NB:", "event_rows if e[1]), ) logger.info(\"[purge] Finding new backward extremities\") #", "= \"\"\" SELECT COALESCE(COUNT(*), 0) FROM events WHERE type =", "\" LIMIT ?\" ) if have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id, limit))", "of unchanged forward extremities for each new event\", buckets=(0, 1,", "to a room Args: room_id (str): room to which the", "governing permissions and # limitations under the License. import itertools", "Used for logging etc events_context (list[(EventBase, EventContext)]): events and contexts", "state groups that reference to-be-deleted state # groups to non", "BY event_stream_ordering DESC\" ) txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn) return new_event_updates", "size of groups we're looking up at once, to stop", "returned deferred is ready. Args: room_id (str): events_and_contexts (list[(EventBase, EventContext)]):", "= context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order, \"event_id\": event.event_id,", "next_to_search = set(state_groups) while next_to_search: # We bound size of", "KIND, either express or implied. # See the License for", "import EventTypes from synapse.api.errors import SynapseError from synapse.events import EventBase", "while to_recursively_check: sql = \"\"\" SELECT event_id, prev_event_id, internal_metadata, rejections.event_id", "= yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount = c_counter(list(x[0] for x in", "persisted in bulk with only one concurrent transaction per room.", "for row in rows) if max_depth < token.topological: # We", "FROM current_state_delta_stream WHERE ? < stream_id AND stream_id <= ?", "be called whenever anything is added to the queue. If", "by calculating the minimum depth of the backwards # extremities.", "StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ): def __init__(self, db_conn, hs): super(EventsStore,", "events_and_contexts: list of tuples of (event, context) backfilled (bool): Whether", "forward_ex_outliers, backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self, room_id, token,", "LEFT JOIN redactions USING (event_id)\" \" LEFT JOIN state_events USING", "state_key in to_delete # We sanity check that we're deleting", "1 and not event.is_state() for event, ctx in ev_ctx_rm )", "(the \"License\"); # you may not use this file except", "room_id = ?\", (room_id,) ) # Update backward extremeties txn.executemany(", "# Read the extrems every 60 minutes def read_forward_extremities(): #", "prev_event_context: if not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): # To ensure correct", "event's auth chain, but its easier for now just to", "for room_id, new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for room_id, latest_event_ids", "before a certain point Args: room_id (str): token (str): A", ") # We do joins against events_to_purge for e.g. calculating", "txn.execute( \"DELETE FROM event_to_state_groups \" \"WHERE event_id IN (SELECT event_id", "coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright", "graphs for state # groups that are referenced. current_search -=", "in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk ) defer.returnValue(results)", "events to delete\") should_delete_expr = \"state_key IS NULL\" should_delete_params =", "the new event was rejected). Args: txn (twisted.enterprise.adbapi.Connection): db connection", "(dict[str, (list, dict)]): The current-state delta for each room. For", "means we do not # end up in a situation", "# # Unless required by applicable law or agreed to", "= set( event_id_to_state_group[evid] for evid in old_latest_event_ids ) # State", "groups\", len(referenced_state_groups) ) logger.info(\"[purge] finding state groups that can be", "members_changed) def _update_forward_extremities_txn( self, txn, new_forward_extremities, max_stream_order ): for room_id,", "\"events\", \"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\",", "JOIN redactions as r ON e.event_id = r.redacts\" \" WHERE", "up the state group graphs for state # groups that", "[] for room_id, evs_ctxs in iteritems(partitioned): d = self._event_persist_queue.add_to_queue( room_id,", "NOT LIKE ?\" # We include the parameter twice since", "its also possible that we're # currently trying to persist", "looking for # the should_delete / shouldn't_delete subsets txn.execute( \"CREATE", "(-last_backfill_id, -current_backfill_id, limit)) new_backfill_events = txn.fetchall() if len(new_backfill_events) == limit:", "\"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult = namedtuple( \"AllNewEventsResult\", [ \"new_forward_events\", \"new_backfill_events\",", "events. If they do we need to remove them and", "the queue, of type _EventPersistQueueItem. The per_item_callback will continuously be", "self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks def persisting_queue(item): with", "that we haven't # seen before. if delete_existing: # For", "wouldn't appear in events_and_context. backfilled (bool): True if the events", "delete_local_events (bool): if True, we will delete local events as", "forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of forward extremities for each", "create event. # Normally that'd be in the database, but", "from current state, and to_insert # is a map (type,key)->event_id", "table now that this # event isn't an outlier any", "return -self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The current maximum token that events", "in event.auth_event_ids() if event.is_state() ], ) # _store_rejected_events_txn filters out", "= json.loads(metadata).get(\"soft_failed\") if soft_failed or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk", "a change then we only return the delta if its", "'m.room.message' AND stream_ordering > ? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count, =", "% ( \",\".join(\"?\" for _ in current_search), ) txn.execute(sql, list(current_search))", "# This is simply used to prefill the get_current_state_ids #", "state_events_and_contexts: vals = { \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type,", "events_and_contexts): \"\"\"Add rows to the 'rejections' table for received events", "it, then we'll need to pull # the state from", "for room_id, depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth) def _update_outliers_txn(self,", "event_id2): \"\"\"Returns True if event_id1 is after event_id2 in the", "the delta to the existing current state. If both are", "_ in to_recursively_check), ) txn.execute(sql, to_recursively_check) to_recursively_check = [] for", "of new events, but are separated by soft failed events.", "\"local\" origin_entity = \"*client*\" else: origin_type = \"remote\" origin_entity =", "= current_state_tuple # First we add entries to the current_state_delta_stream.", "extremities as well as the new. stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\",", "origin_type, origin_entity).inc() for room_id, new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for", "of event_ids to get those which are prev_events of existing", "cache. # We find out which membership events we may", "not event.internal_metadata.is_outlier() and not context.rejected: depth_updates[event.room_id] = max( event.depth, depth_updates.get(event.room_id,", "(should_delete_expr, should_delete_expr), should_delete_params, ) # We create the indices *after*", "new backward extremities\") # We calculate the new entries for", "# We do this by calculating the minimum depth of", "}, ) sql = \"UPDATE events SET outlier = ?\"", "object as JSON and return it in a Unicode string.", "EventContext # noqa: F401 from synapse.metrics import BucketCollector from synapse.metrics.background_process_metrics", "outliers logger.info(\"[purge] marking remaining events as outliers\") txn.execute( \"UPDATE events", "stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql, (last_id, current_id, limit))", "as well. This function should therefore be called whenever anything", "rules, and leaves the logcontext in place whether or not", "\"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\": event.sender, \"contains_url\": (", "here return def event_dict(event): d = event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\",", "next. next_to_search = set(state_groups) while next_to_search: # We bound size", "full # state in each room after adding these events.", "if event.is_state() ], ) # _store_rejected_events_txn filters out any events", "max_depth < token.topological: # We need to ensure we don't", "adding these events. # This is simply used to prefill", "# persists events (because upsert), and once we run this", "self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self, room_id, token, delete_local_events): \"\"\"Deletes room history", "self._store_room_topic_txn(txn, event) elif event.type == EventTypes.Message: # Insert into the", "a room if not already being handled. The given callback", "and has one on # (room_id, event_id) instead. for table", "self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[", "from DB event_to_groups = yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups", "N]} if not ev_map: break sql = ( \"SELECT \"", "that we had already stored as # an outlier in", "C.I.C. # # Licensed under the Apache License, Version 2.0", "# and _handle_mult_prev_events (though arguably those could both be moved", "= c_counter(list(x[0] for x in res)) @defer.inlineCallbacks def persist_events(self, events_and_contexts,", "in the database. We now have some state at that", "room_version = ev.content.get(\"room_version\", \"1\") break if not room_version: room_version =", "%s has no state \" \"group\" % (ev.event_id,) ) continue", "to a single state set. missing_state = new_state_groups - set(state_groups_map)", "None: current_state_for_room[room_id] = current_state yield self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled,", "sg} ) self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[ { \"state_group\": sg, \"room_id\":", "the new entries for the backward extremeties by finding #", "COALESCE(COUNT(*), 0) FROM events WHERE type = 'm.room.message' AND sender", "-e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \" FROM", "% (\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql, list(ev_map)) rows = self.cursor_to_dict(txn) for", "stream_ordering to new forward extremeties in the room. # This", "new events that have arrived at the server either as", "to delete all the forward extremeties txn.execute( \"SELECT e.event_id, e.depth", "StateResolutionStore from synapse.storage.background_updates import BackgroundUpdateStore from synapse.storage.event_federation import EventFederationStore from", "event.auth_event_ids() if event.is_state() ], ) # _store_rejected_events_txn filters out any", "it at the end so that we don't block event", "if event.type == EventTypes.Name: # Insert into the room_names and", "the state for an event we were # persisting. state_delta_reuse_delta_counter", "\"event_search\", \"rejections\", ): logger.info(\"[purge] removing events from %s\", table) txn.execute(", "for x in range(0, len(events_and_contexts), 100) ] for chunk in", "if there is one, else the earliest one. Args: events_and_contexts", "already in the events table. \"\"\" txn.execute( \"SELECT event_id, outlier", "# We're only interested in pulling out state that has", "received a copy of an event that we had already", "< stream_ordering AND stream_ordering <= ?\" \" ORDER BY stream_ordering", "? \"\"\" txn.execute(sql, (from_token, to_token, limit)) return txn.fetchall() return self.runInteraction(", "prevs for row in rows: # Note: Each state group", "< token.topological: # We need to ensure we don't delete", "to_delete = state_groups_seen - referenced_groups to_dedelta = set() for sg", "group to another, lets check if # we have a", "return defer.succeed([]) def get_all_new_forward_event_rows(txn): sql = ( \"SELECT e.stream_ordering, e.event_id,", "result != latest_event_ids: forward_extremities_counter.observe(len(result)) stale = latest_event_ids & result stale_forward_extremities_counter.observe(len(stale))", "( (room_id, etype, state_key) for etype, state_key in itertools.chain(to_delete, to_insert)", "have deleted # and which we have added, then we", "event_id FROM events_to_purge \" \" WHERE NOT should_delete\" \")\", (True,),", "method, it does *not* follow the synapse logcontext rules, and", "\" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall())", "calculating state if they're just # a long chain of", "to be the minimum of the stream_ids # for the", "\"room_memberships\", \"topics\", ): txn.executemany( \"DELETE FROM %s WHERE event_id =", "== EventTypes.Name: # Insert into the room_names and event_search tables.", "`get_rooms_for_user` cache. # We find out which membership events we", "def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check = batch while to_recursively_check: sql =", "(list[(EventBase, EventContext)]): backfilled (bool): delete_existing (bool): Returns: Deferred: resolves when", "we'll `continue` above and skip this bit.) assert new_latest_event_ids, \"No", "\"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \" FROM", "do we need to remove them and their prev events,", "its already been calculated. Conversely if we do know the", "already stored as # an outlier in the database. We", "persisted. Returns: Deferred[set[str]] \"\"\" # The set of event_ids to", "Note: Each state group can have at most one prev", "= ? AND state_key = ?\", ( (room_id, etype, state_key)", "we don't care if the event # was an outlier", "stream_id, ) # Invalidate the various caches # Figure out", "JOIN event_relations USING (event_id)\" \" WHERE ? < stream_ordering AND", "deque()) try: while True: yield queue.popleft() except IndexError: # Queue", "raise SynapseError(404, \"Could not find event %s\" % (event_id,)) defer.returnValue(", "_maybe_start_persisting(self, room_id): @defer.inlineCallbacks def persisting_queue(item): with Measure(self._clock, \"persist_events\"): yield self._persist_events(", "# events # rejections # room_depth # state_groups # state_groups_state", "\"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\", \"state_events\", \"rejections\",", "( \"SELECT event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE", "ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return", "the last call to this function, it will return None.", "\"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \"", "txn, new_forward_extremities, max_stream_order ): for room_id, new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn(", "now that this # event isn't an outlier any more.", "yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount = c_counter(list(x[0] for x in res))", "# This gets around any problems with some tables already", "logger.info(\"[purge] removing events from event_to_state_groups\") txn.execute( \"DELETE FROM event_to_state_groups \"", "on CREATE, so let's do this first. # # furthermore,", "already seen state_groups_seen = set(state_groups) # Set of state groups", "# event_edges tables. self._handle_mult_prev_events( txn, events=[event for event, _ in", "transaction on CREATE, so let's do this first. # #", "we can call _update_backward_extremities # and _handle_mult_prev_events (though arguably those", "current maximum token that events have reached\"\"\" return self._stream_id_gen.get_current_token() def", "from synapse.storage.background_updates import BackgroundUpdateStore from synapse.storage.event_federation import EventFederationStore from synapse.storage.events_worker", "attempt, so let's drop the table first. txn.execute(\"DROP TABLE IF", "the same event twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn(", "with backfilling? if hasattr(event, \"replaces_state\"): vals[\"prev_state\"] = event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn,", "need to update the state_groups table with that state. #", "waiting on the item, exceptions will be passed to the", "ids \"\"\" results = [] def _get_events_which_are_prevs_txn(txn, batch): sql =", "in events_and_contexts[i : i + N]} if not ev_map: break", "all the new events to the list result.update(event.event_id for event", "100) ] for chunk in chunks: # We can't easily", "txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order, \"event_id\": event.event_id, \"state_group\": state_group_id, },", ">= ?\" \" ORDER BY stream_ordering ASC\" \" LIMIT ?\"", "are ones we don't have yet so we need to", "rejected event appears in an accepted # event's auth chain,", "filtered list. events_and_contexts = self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts ) # From", "in iteritems(events_by_room): latest_event_ids = yield self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids =", "ev_id in new_extrem ], ) # We now insert into", "an event that we had already stored as # an", "is_event_after(self, event_id1, event_id2): \"\"\"Returns True if event_id1 is after event_id2", "new_extrem in iteritems(new_forward_extremities) for ev_id in new_extrem ], ) #", "= c_counter() BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1, 2, 3, 5,", "This is useful when retrying due to IntegrityError. state_delta_for_room (dict[str,", "lets check if # we have a delta for that", "\"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\": event.sender, \"contains_url\": ( \"url\" in", "event.event_id, \"room_id\": event.room_id, \"auth_id\": auth_id, } for event, _ in", "# deleted. We then go and check if they are", "is only necessary if the rejected event appears in an", "we might already have the table from a previous (failed)", "new_forward_extremeties = {} # map room_id->(type,state_key)->event_id tracking the full #", "JSON and return it in a Unicode string. \"\"\" out", "# Remove from relations table. self._handle_redaction(txn, event.redacts) # Update the", "any more. self._update_backward_extremeties(txn, [event]) return [ec for ec in events_and_contexts", "we calculated the state for an event we were #", "DESC\" ) txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers = txn.fetchall() else: new_backfill_events", "{ev.event_id: ev for ev, _ in events_context} # We need", "\"Number of forward extremities for each new event\", buckets=(1, 2,", "all_single_prev_not_state = all( len(event.prev_event_ids()) == 1 and not event.is_state() for", "with PreserveLoggingContext(): item.deferred.callback(ret) finally: queue = self._event_persist_queues.pop(room_id, None) if queue:", "state_group_deltas = {} for ev, ctx in events_context: if ctx.state_group", "= yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True, )", "txn, events_and_contexts=events_and_contexts, backfilled=backfilled ) # _update_outliers_txn filters out any events", "tables. self._store_room_name_txn(txn, event) elif event.type == EventTypes.Topic: # Insert into", "rejections table self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event) return [ec for ec", "were # rejected, and returns the filtered list. events_and_contexts =", "@log_function def persist_event(self, event, context, backfilled=False): \"\"\" Args: event (EventBase):", "Returns: tuple[set[int], set[int]]: The set of state groups that can", "a room before a given stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[", "<= ?\" \" ORDER BY stream_ordering ASC\" \" LIMIT ?\"", "events (due to not # having any backwards extremeties) raise", "missing_event_ids: # Now pull out the state groups for any", "= RoomStreamToken.parse(token_str) # Tables that should be pruned: # event_auth", "backfilled): \"\"\"Update min_depth for each room Args: txn (twisted.enterprise.adbapi.Connection): db", "state_delta_counter.inc() if len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc() # This is a", "else: new_backfill_events = [] backward_ex_outliers = [] return AllNewEventsResult( new_forward_events,", "(list[(EventBase, EventContext)]): backfilled (bool): Returns: defer.Deferred: a deferred which will", "SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM events WHERE type = 'm.room.message'", "? \"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count, = txn.fetchone() return count", "our workers. stream_order = event.internal_metadata.stream_ordering state_group_id = context.state_group self._simple_insert_txn( txn,", "with that state. # insert into event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event,", "def _store_event_txn(self, txn, events_and_contexts): \"\"\"Insert new events into the event", "%s\" \" FROM events AS e LEFT JOIN state_events USING", "the backwards # extremities. However, the events in event_backward_extremities #", "room_id), 0) FROM events WHERE type = 'm.room.message' AND stream_ordering", "room if not already being handled. The given callback will", "= ed.prev_event_id\" \" LEFT JOIN events_to_purge AS ep2 ON ed.event_id", "% (table,), [(ev.event_id,) for ev, _ in events_and_contexts], ) for", "txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events we are", "could # have guessed what the delta would have been", "the state groups for any missing events from DB event_to_groups", "you have silly characters in your own # hostname then", "event_forward_extremities group by room_id \"\"\" ) return txn.fetchall() res =", "cached in the context. We'll pull stuff out of the", "db connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting Returns:", "can't easily parallelize these since different chunks # might contain", "as if you have silly characters in your own #", "TEXT NOT NULL,\" \" should_delete BOOLEAN NOT NULL\" \")\" )", "purging history to figure out which state groups can be", "(event_id)\" \" LEFT JOIN state_events USING (event_id)\" \" LEFT JOIN", "ordered by first insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] = (event, context)", "the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id,", "new_latest_event_ids: # First search in the list of new events", "events_and_contexts, backfilled=False): \"\"\" Write events to the database Args: events_and_contexts:", "with Measure(self._clock, \"_calculate_state_and_extrem\"): # Work out the new \"current state\"", "F401 from synapse.metrics import BucketCollector from synapse.metrics.background_process_metrics import run_as_background_process from", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "str]|None, dict[(str,str), str]|None]]: Returns a tuple of two state maps,", "} for key, state_id in iteritems(curr_state) ], ) logger.info(\"[purge] removing", "itertools import logging from collections import Counter as c_counter, OrderedDict,", "are and then # calculating the state from that. events_by_room", "return def event_dict(event): d = event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\", None)", "resolves to (int, int): the stream ordering of ``event``, and", "{ \"state_group\": sg, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], \"event_id\":", "with new event info. This turns outliers into ex-outliers (unless", "from six.moves import range from canonicaljson import json from prometheus_client", "for event, context in events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id) if prev_event_context:", "events have been persisted \"\"\" if not events_and_contexts: return if", "state_key, redacts, relates_to_id\" \" FROM events AS e\" \" LEFT", "the database # otherwise we wouldn't be able to send", "ORDER BY stream_ordering DESC\" \" LIMIT ?\" ) if have_backfill_events:", "True if the events were backfilled \"\"\" # Insert all", "keyvalues={\"state_group\": sg} ) self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn(", "event ids \"\"\" results = [] def _get_events_which_are_prevs_txn(txn, batch): sql", "resolve to a single state set. missing_state = new_state_groups -", "\"\"\"Get soft-failed ancestors to remove from the extremities. Given a", "if latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state delta for", "# # So, let's stick it at the end so", "in iteritems(current_state) if ev_id != existing_state.get(key) } defer.returnValue((to_delete, to_insert)) @log_function", "they match the current forward extremities. for ev, _ in", "if prev_event_context[0].internal_metadata.is_outlier(): # To ensure correct ordering we pop, as", "set( event_id_to_state_group[evid] for evid in old_latest_event_ids ) # State groups", "backfill/outliers/etc) if result != latest_event_ids: forward_extremities_counter.observe(len(result)) stale = latest_event_ids &", "existing state # unnecessarily). # # The stream_id for the", "EventContext)]: filtered list \"\"\" new_events_and_contexts = OrderedDict() for event, context", "the same then we don't need to do # anything.", "which membership events we may have deleted # and which", "missing_state: group_to_state = yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) == 1:", "the event as they are # now. When this server", "= self._event_persist_queue.add_to_queue( event.room_id, [(event, context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred)", "synapse.util.caches.descriptors import cached, cachedInlineCallbacks from synapse.util.frozenutils import frozendict_json_encoder from synapse.util.logcontext", "10, 15, 20, 50, 100, 200, 500, \"+Inf\"], ) #", "(twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events to persist backfilled", "sql = \"\"\" SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM events WHERE", "ev_map[row[\"event_id\"]] if not row[\"rejects\"] and not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None)", "from synapse.metrics.background_process_metrics import run_as_background_process from synapse.state import StateResolutionStore from synapse.storage.background_updates", "current_id sql = ( \"SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,\" \"", "first. # # furthermore, we might already have the table", ") for (etype, state_key), ev_id in iteritems(to_insert) ), ) #", "state group from its context. # Otherwise we need to", "(whether soft-failed/rejected or not), and recurses up the prev-event graph", "max_stream_order, } for room_id, new_extrem in iteritems(new_forward_extremities) for event_id in", "check if they are referenced by other events # or", "table=\"state_events\", values=state_values) # Prefill the event cache self._add_to_cache(txn, events_and_contexts) def", "events_and_contexts (list[(EventBase, EventContext)]): Returns: list[(EventBase, EventContext)]: filtered list \"\"\" new_events_and_contexts", "events we've already persisted, etc, that wouldn't appear in events_and_context.", "\"\"\"Ensure that we don't have the same event twice. Pick", "\"\"\"Calculate the current state dict after adding some new events", "and outlier_persisted: # We received a copy of an event", "next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group, new_state_group), None) if delta_ids is not", "are the forward extremities. \"\"\" all_events_and_contexts = events_and_contexts min_stream_order =", "room_version: room_version = yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from preserve_events\") res", "are going to be in events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group", "room_id, token, delete_local_events): \"\"\"Deletes room history before a certain point", "parallelize these since different chunks # might contain the same", "< event_stream_ordering\" \" AND event_stream_ordering <= ?\" \" ORDER BY", "have guessed what the delta would have been when #", "self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if not events_and_contexts: # nothing", "them and their prev events, # otherwise we end up", "self.get_current_state_ids(room_id) to_delete = [key for key in existing_state if key", "state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) # Ensure that", "in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for room_id, latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill(", "EventFederationStore so that we can call _update_backward_extremities # and _handle_mult_prev_events", "import json from prometheus_client import Counter, Histogram from twisted.internet import", "logger.exception(\"IntegrityError, retrying.\") res = yield func(self, *args, delete_existing=True, **kwargs) defer.returnValue(res)", "FROM events as e \" \"INNER JOIN event_forward_extremities as f", "event_ids to return. This includes all soft-failed events # and", "cache for the redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT INTO", "events_map = {ev.event_id: ev for ev, _ in events_context} #", "prev_events of any of the new events result.difference_update( e_id for", "(event_id)\" \" WHERE ? > stream_ordering AND stream_ordering >= ?\"", "extremities for each new event. forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number", "any problems with some tables already having # entries. self._delete_existing_rows_txn(txn,", "of state groups that need to be de-delta'ed \"\"\" #", "context) ) for room_id, ev_ctx_rm in iteritems(events_by_room): latest_event_ids = yield", "matter if we don't. new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) #", "events. # This is simply used to prefill the get_current_state_ids", "that we have calculated new_state_groups we need to get #", "if the event is one we're persisting, in which case", "referenced_groups = set() # Set of state groups we've already", "upper_bound = current_forward_id sql = ( \"SELECT event_stream_ordering, event_id, state_group\"", "else: stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with stream_ordering_manager as stream_orderings:", "them. # This gets around any problems with some tables", "rejected in txn: if prev_event_id in existing_prevs: continue soft_failed =", "up the forward extremeties # for a room before a", "outlier_persisted: # We received a copy of an event that", "# and we need to work out the delta (or", "due to IntegrityError. state_delta_for_room (dict[str, (list, dict)]): The current-state delta", "outlier or not. continue outlier_persisted = have_persisted[event.event_id] if not event.internal_metadata.is_outlier()", "def _read_forward_extremities(self): def fetch(txn): txn.execute( \"\"\" select count(*) c from", "events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) #", "rejected. Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events", "max( event.depth, depth_updates.get(event.room_id, event.depth) ) for room_id, depth in iteritems(depth_updates):", "We include the parameter twice since we use the expression", "= ?\", ((sg,) for sg in state_groups_to_delete), ) logger.info(\"[purge] removing", "in the room. # This allows us to later efficiently", "graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete = state_groups_seen - referenced_groups to_dedelta =", "r.redacts as redacts,\" \" rej.event_id as rejects \" \" FROM", "current_forward_id if not have_backfill_events and not have_forward_events: return defer.succeed(AllNewEventsResult([], [],", "fetch) self._current_forward_extremities_amount = c_counter(list(x[0] for x in res)) @defer.inlineCallbacks def", "How does this work with backfilling? if hasattr(event, \"replaces_state\"): vals[\"prev_state\"]", "keep this actually last. txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge] done\") def", "law or agreed to in writing, software # distributed under", "We only update metrics for events that change forward extremities", "to_remove] def _update_metadata_tables_txn( self, txn, events_and_contexts, all_events_and_contexts, backfilled ): \"\"\"Update", "workers see events before the # current_state_delta updates. # sql", "don't have yet so we need to look at the", "state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) # Prefill the event cache self._add_to_cache(txn,", "sqlite driver commits the # transaction on CREATE, so let's", "synapse.util.async_helpers import ObservableDeferred from synapse.util.caches.descriptors import cached, cachedInlineCallbacks from synapse.util.frozenutils", "ev_id, room_id, etype, state_key, ) for (etype, state_key), ev_id in", "return AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn)", "the list back and forth across the # connection. Annoyingly", "is useful when retrying due to IntegrityError. state_delta_for_room (dict[str, (list,", "state group from the database. # Set of events we", "lets just return that. If we happen to already have", "e.event_id FROM events_to_purge AS e\" \" INNER JOIN event_edges AS", "we had already stored as # an outlier in the", "delta_ids) elif current_state is not None: with Measure( self._clock, \"persist_events.calculate_state_delta\"", "sg in new_state_groups} events_map = {ev.event_id: ev for ev, _", "are persisting \"\"\" if not events_and_contexts: # nothing to do", "table. self._store_event_reference_hashes_txn( txn, [event for event, _ in events_and_contexts] )", ") # Don't bother calculating state if they're just #", "\"event_stream_ordering\": stream_order, \"event_id\": event.event_id, \"state_group\": state_group_id, }, ) sql =", "(table,) ) # event_push_actions lacks an index on event_id, and", "next_to_search |= prevs state_groups_seen |= prevs for row in rows:", "None) d.pop(\"redacted_because\", None) return d self._simple_insert_many_txn( txn, table=\"event_json\", values=[ {", "events_and_contexts, backfilled=False, delete_existing=False ): \"\"\"Persist events to db Args: events_and_contexts", "instead. for table in (\"event_push_actions\",): logger.info(\"[purge] removing events from %s\",", "chunks: # We can't easily parallelize these since different chunks", "delta to the existing current state. If both are None", "we use the expression twice should_delete_params += (\"%:\" + self.hs.hostname,", "if len_1: all_single_prev_not_state = all( len(event.prev_event_ids()) == 1 and not", "key, ev_id in iteritems(current_state) if ev_id != existing_state.get(key) } defer.returnValue((to_delete,", "for table in (\"event_push_actions\",): logger.info(\"[purge] removing events from %s\", table)", "ev_id in iteritems(to_insert) ], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, )", "rather than updating if (etype, state_key) not in to_insert ),", "backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, ) if not event.internal_metadata.is_outlier() and", "for e.g. calculating state # groups to purge, etc., so", "that we've # only added or replaced state, never #", "groups being scheduled for deletion). Args: txn state_groups (set[int]): Set", "_ logger.info( \"[purge] found %i state groups to delete\", len(state_groups_to_delete)", "of new_latest_event_ids new_state_groups = set( event_id_to_state_group[evid] for evid in new_latest_event_ids", "existing_state if key not in current_state] to_insert = { key:", "added to the room old_latest_event_ids (iterable[str]): the old forward extremities", "groups that can be deleted\") _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete,", "= ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\"", "shouldn't_delete subsets txn.execute( \"CREATE INDEX events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\" )", "Write events to the database Args: events_and_contexts: list of tuples", "NOT events.outlier AND rejections.event_id IS NULL \"\"\" % ( \",\".join(\"?\"", "# that we can use it to calculate the `prev_event_id`.", "no change in state continue # there should always be", "to count self._current_forward_extremities_amount = c_counter() BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1,", "USING (event_id)\" \" WHERE ? > event_stream_ordering\" \" AND event_stream_ordering", "defer.Deferred: a deferred which will resolve once the events are", "is good enough as if you have silly characters in", "func(self, *args, **kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res = yield", "# were the same when we created the event as", "we can # guess this by looking at the prev_events", "in current_state] to_insert = { key: ev_id for key, ev_id", "(metadata_json, event.event_id)) # Add an entry to the ex_outlier_stream table", "sql, ( ( stream_id, room_id, etype, state_key, None, room_id, etype,", "about to delete all the forward extremeties txn.execute( \"SELECT e.event_id,", "LEFT JOIN events_to_purge AS ep USING (event_id) WHERE state_group IN", "to_2, so_2 = yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) > (to_2, so_2))", "'m.room.message' AND sender LIKE ? AND stream_ordering > ? \"\"\"", "event_id) for event_id, in new_backwards_extrems], ) logger.info(\"[purge] finding redundant state", "so let's do this first. # # furthermore, we might", "event.prev_event_ids() ) result.difference_update(existing_prevs) # We only update metrics for events", "d self._simple_insert_many_txn( txn, table=\"event_json\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id,", "if len(new_forward_events) == limit: upper_bound = new_forward_events[-1][0] else: upper_bound =", "from synapse.util.async_helpers import ObservableDeferred from synapse.util.caches.descriptors import cached, cachedInlineCallbacks from", "room history before a certain point Args: room_id (str): token", "transaction. # # So, let's stick it at the end", "None: state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids", "[], [])) def get_all_new_events_txn(txn): sql = ( \"SELECT e.stream_ordering, e.event_id,", ") # The number of times we are recalculating the", "continue iterating up the state group graphs for state #", "IDs so we can resolve to a single state set.", "context.rejected: depth_updates[event.room_id] = max( event.depth, depth_updates.get(event.room_id, event.depth) ) for room_id,", "@defer.inlineCallbacks def _persist_events( self, events_and_contexts, backfilled=False, delete_existing=False ): \"\"\"Persist events", "values=[ { \"state_group\": sg, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1],", "sg, in txn) referenced_groups |= referenced # We don't continue", "events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled )", "anything. if old_state_groups == new_state_groups: defer.returnValue((None, None)) if len(new_state_groups) ==", "defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter the supplied list of", "or implied. # See the License for the specific language", "(\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql, list(ev_map)) rows = self.cursor_to_dict(txn) for row", "upper_bound = current_backfill_id sql = ( \"SELECT -event_stream_ordering, event_id, state_group\"", "events_and_contexts], ) def _store_event_txn(self, txn, events_and_contexts): \"\"\"Insert new events into", "outliers and which aren't # being rejected. new_events = [", "pull stuff out of the DB later # if necessary.", "_EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps a database", "of the backwards # extremities. However, the events in event_backward_extremities", "\"\" ) # The number of forward extremities for each", "that we don't have the same event twice. events_and_contexts =", "is a fairly handwavey check to see if we could", "for sg in state_groups_to_delete), ) txn.executemany( \"DELETE FROM state_groups WHERE", "r.redacts\" \" WHERE e.event_id IN (%s)\" ) % (\",\".join([\"?\"] *", "table so # that we can use it to calculate", "ctx.state_group in state_groups_map: continue # We're only interested in pulling", "RoomStreamToken, get_domain_from_id from synapse.util import batch_iter from synapse.util.async_helpers import ObservableDeferred", "txn, event): # invalidate the cache for the redacted event", "latest extremities # were the same when we created the", "row in rows) # We don't bother re-handling groups we've", "that # point to it via event_edges table. txn.execute( \"\"\"", "new_latest_event_ids len_1 = ( len(latest_event_ids) == 1 and len(new_latest_event_ids) ==", "AND NOT events.outlier AND rejections.event_id IS NULL \"\"\" % (", "in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering = stream chunks = [ events_and_contexts[x", "= batch while to_recursively_check: sql = \"\"\" SELECT event_id, prev_event_id,", "current state and the second being the delta to the", "-current_backfill_id, limit)) new_backfill_events = txn.fetchall() if len(new_backfill_events) == limit: upper_bound", "old_state_group = next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group, new_state_group), None) if delta_ids", "events which are prev_events of any existing events. existing_prevs =", "to_dedelta.add(sg) return to_delete, to_dedelta @defer.inlineCallbacks def is_event_after(self, event_id1, event_id2): \"\"\"Returns", "table to replicate the # change in outlier status to", "`delete_existing` arg \"\"\" @wraps(func) @defer.inlineCallbacks def f(self, *args, **kwargs): try:", "self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop(): try: queue = self._get_drainining_queue(room_id) for item", "the # forward extremities as the prev_events, so we can", ") # Read the extrems every 60 minutes def read_forward_extremities():", "state group %s\", sg) curr_state = self._get_state_groups_from_groups_txn(txn, [sg]) curr_state =", "EventContext)]): all events that we were going to persist. This", "event_forward_extremities, event_backward_extremities and # event_edges tables. self._handle_mult_prev_events( txn, events=[event for", "ret = yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The current", "into the rejections table self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event) return [ec", "event.room_id, event.internal_metadata.stream_ordering, ) if not event.internal_metadata.is_outlier() and not context.rejected: depth_updates[event.room_id]", "is after event_id2 in the stream \"\"\" to_1, so_1 =", "ep.event_id IS NULL \"\"\" % ( \",\".join(\"?\" for _ in", "with Measure(self._clock, \"persist_events\"): yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue)", "sql = ( \"UPDATE event_json SET internal_metadata = ?\" \"", "that exist. # Counter of number of extremities to count", "# Remove the rejected events from the list now that", "self._update_backward_extremeties(txn, [event]) return [ec for ec in events_and_contexts if ec[0]", "event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event, context),)) except Exception: logger.exception(\"\") raise metadata_json", "yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally handle the case where the", "self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self, last_id, current_id, limit): if", "events that we haven't # seen before. if delete_existing: #", "def _store_redaction(self, txn, event): # invalidate the cache for the", "= \"\"\" SELECT DISTINCT state_group FROM event_to_state_groups LEFT JOIN events_to_purge", "processing one of these events. # What we're interested in", "we need to update the state_groups table with that state.", "We sanity check that we're deleting rather than updating if", "to_prefill = [] rows = [] N = 200 for", "used to find extremities that are ancestors of new events,", "ctx.state_group is not None: event_id_to_state_group[event_id] = ctx.state_group break else: #", "for event_id, in new_backwards_extrems], ) logger.info(\"[purge] finding redundant state groups\")", "as backfilled events\"\"\" have_backfill_events = last_backfill_id != current_backfill_id have_forward_events =", "-upper_bound)) backward_ex_outliers = txn.fetchall() else: new_backfill_events = [] backward_ex_outliers =", "to take out an exclusive lock on room_depth whenever it", "@defer.inlineCallbacks def persist_events(self, events_and_contexts, backfilled=False): \"\"\" Write events to the", "the rejections table self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event) return [ec for", "FROM events_to_purge WHERE should_delete\" \")\" % (table,) ) # event_push_actions", "the function will be given to the deferreds waiting on", "events WHERE type = 'm.room.message' AND stream_ordering > ? \"\"\"", "sql = \"\"\" SELECT stream_id, room_id, type, state_key, event_id FROM", "old_state_groups == new_state_groups: defer.returnValue((None, None)) if len(new_state_groups) == 1 and", "e[0] for e in events_and_contexts[i : i + N]} if", "event_auth # event_backward_extremities # event_edges # event_forward_extremities # event_json #", "None: event_id_to_state_group[event_id] = ctx.state_group break else: # If we couldn't", "we're not about to delete all the forward extremeties txn.execute(", "same `backfilled` setting, # we can just add these new", "us to later efficiently look up the forward extremeties #", "import itertools import logging from collections import Counter as c_counter,", "# event isn't an outlier any more. self._update_backward_extremeties(txn, [event]) return", "the topics table and event_search table. self._store_room_topic_txn(txn, event) elif event.type", "AS e\" \" LEFT JOIN redactions USING (event_id)\" \" LEFT", "\"event_id\": event.event_id, \"room_id\": event.room_id, \"auth_id\": auth_id, } for event, _", "new events to that item. end_item = queue[-1] if end_item.backfilled", "out = out.decode(\"utf8\") return out class _EventPeristenceQueue(object): \"\"\"Queues up events", "with some tables already having # entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn,", "@defer.inlineCallbacks def count_daily_messages(self): \"\"\" Returns an estimate of the number", "): for room_id, new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\":", "list[(EventBase, EventContext)] new list, without events which are already in", "# used in state res v2. # This is only", "event_id, prev_event_id) SELECT ?, ?, ?, ?, ?, ( SELECT", "with Measure( self._clock, \"persist_events.calculate_state_delta\" ): delta = yield self._calculate_state_delta( room_id,", "marking them as outliers and deleting their state groups). \"\"\"", "should_delete\" \")\" % (table,) ) # event_push_actions lacks an index", "= [ event for event, ctx in event_contexts if not", "(\" \" SELECT event_id FROM events_to_purge \" \" WHERE NOT", "can reinsert them. # This gets around any problems with", "events_to_purge AS ep USING (event_id) WHERE state_group IN (%s) AND", "(event_id, redacts) VALUES (?,?)\", (event.event_id, event.redacts), ) @defer.inlineCallbacks def count_daily_messages(self):", "# Ensure that we don't have the same event twice.", "to do # anything. if old_state_groups == new_state_groups: defer.returnValue((None, None))", "# This should only happen for outlier events. if not", "== 1 and len(old_state_groups) == 1: # If we're going", "import StateGroupWorkerStore from synapse.types import RoomStreamToken, get_domain_from_id from synapse.util import", "in txn} to_remove = set() for event, context in events_and_contexts:", "from collections import Counter as c_counter, OrderedDict, deque, namedtuple from", "Returns a tuple of two state maps, the first being", "# only added or replaced state, never # removed keys", "rejections as rej USING (event_id)\" \" LEFT JOIN redactions as", "prev_event_id, internal_metadata, rejections.event_id IS NOT NULL FROM event_edges INNER JOIN", "in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds = [] for room_id,", "for the backward extremeties by finding # events to be", "have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id, limit)) new_forward_events = txn.fetchall() if len(new_forward_events)", "groups are the same then we don't need to do", "in iteritems(to_insert) ], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, ) #", "state etc. Returns: Deferred[int]: the stream ordering of the latest", "_get_event_ordering(self, event_id): res = yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\":", "etype, state_key in itertools.chain(to_delete, to_insert) ), ) self._simple_insert_many_txn( txn, table=\"current_state_events\",", "event, _ in events_and_contexts ], ) self._simple_insert_many_txn( txn, table=\"events\", values=[", "_get_drainining_queue(self, room_id): queue = self._event_persist_queues.setdefault(room_id, deque()) try: while True: yield", "# Update the event_backward_extremities table now that this # event", "backfilled (bool): True if the events were backfilled delete_existing (bool):", "= Counter(\"synapse_storage_events_state_delta\", \"\") # The number of times we are", "room, a tuple (to_delete, to_insert), being a list of type/state", "AS eb INNER JOIN event_edges AS eg ON eg.prev_event_id =", "never # removed keys entirely. state_delta_for_room[room_id] = ([], delta_ids) elif", "event.type == EventTypes.Member ], backfilled=backfilled, ) # Insert event_reference_hashes table.", "state_delta_for_room (dict[str, (list, dict)]): The current-state delta for each room.", "if # we have a delta for that transition. If", "stream ordering of the latest persisted event \"\"\" deferred =", ") @defer.inlineCallbacks def count_daily_messages(self): \"\"\" Returns an estimate of the", "to the room old_latest_event_ids (iterable[str]): the old forward extremities for", "filtered list. events_and_contexts = self._update_outliers_txn( txn, events_and_contexts=events_and_contexts ) # From", "times we are recalculating state when there is only a", "entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn,", "# those users. members_changed = set( state_key for ev_type, state_key", "the License for the specific language governing permissions and #", "to_delete, to_insert = current_state_tuple # First we add entries to", "logger.info(\"[purge] marking remaining events as outliers\") txn.execute( \"UPDATE events SET", "current_forward_id, limit, ): \"\"\"Get all the new events that have", "being added. Used for logging etc events_context (list[(EventBase, EventContext)]): events", "keep shovelling the list back and forth across the #", "then thats your own fault. like_clause = \"%:\" + self.hs.hostname", "INSERT INTO current_state_delta_stream (stream_id, room_id, type, state_key, event_id, prev_event_id) SELECT", "?\" \" WHERE event_id = ?\" ) txn.execute(sql, (metadata_json, event.event_id))", "look at the events that # point to it via", "will not be invoked. \"\"\" if room_id in self._currently_persisting_rooms: return", "bytes): out = out.decode(\"utf8\") return out class _EventPeristenceQueue(object): \"\"\"Queues up", "this server creates a new event (as opposed # to", "\"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\") ) def __init__(self): self._event_persist_queues = {}", "e.room_id = ? AND topological_ordering < ?\" % (should_delete_expr, should_delete_expr),", "and to_insert # is a map (type,key)->event_id giving the state", "so that they can be persisted in bulk with only", "backfilled (bool): Returns: defer.Deferred: a deferred which will resolve once", "ev_ctx_rm, latest_event_ids, new_latest_event_ids, ) current_state, delta_ids = res # If", "yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) == 1: # If there", "referenced # We don't continue iterating up the state group", "extremities, so we'll `continue` above and skip this bit.) assert", "ev_id, \"room_id\": room_id} for room_id, new_extrem in iteritems(new_forward_extremities) for ev_id", "event_search # event_to_state_groups # events # rejections # room_depth #", "connection. Annoyingly the python sqlite driver commits the # transaction", "sql = ( \"SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key,", "\"state_group\": sg, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], \"event_id\": state_id,", "etc events_context (list[(EventBase, EventContext)]): events and contexts which are being", "AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def", "else: upper_bound = current_id sql = ( \"SELECT -event_stream_ordering, e.event_id,", "event.room_id, \"type\": event.type, \"state_key\": event.state_key, } # TODO: How does", "iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn(", "to_delete are the type/state_keys to remove from current_state_events and `to_insert`", "delete\", len(state_groups_to_delete) ) logger.info( \"[purge] de-delta-ing %i remaining state groups\",", "table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if not events_and_contexts: #", "def __init__(self, db_conn, hs): super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue = _EventPeristenceQueue()", "look up the forward extremeties # for a room before", "twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled", "in the create event. # Normally that'd be in the", "# Counter of number of extremities to count self._current_forward_extremities_amount =", "INNER JOIN event_edges AS ed ON e.event_id = ed.prev_event_id\" \"", "# (room_id, event_id) instead. for table in (\"event_push_actions\",): logger.info(\"[purge] removing", "_get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events( self, room_id, events_context,", "\"+Inf\"], ) # Read the extrems every 60 minutes def", "reculating state when we could have resonably # calculated the", "to work out the delta (or use that # given)", "# distributed under the License is distributed on an \"AS", "_get_new_state_after_events( self, room_id, events_context, old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate the current", "id = ?\", ((sg,) for sg in state_groups_to_delete), ) logger.info(\"[purge]", "room_id (str): room to which the events are being added.", "\"\"\" SELECT DISTINCT state_group FROM events_to_purge INNER JOIN event_to_state_groups USING", "one room at a time. Returns: tuple[list, dict] (to_delete, to_insert):", "an outlier in the database. We now have some state", "be moved in here) class EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore,", "ev_id for key, ev_id in iteritems(current_state) if ev_id != existing_state.get(key)", "Insert into the redactions table. self._store_redaction(txn, event) elif event.type ==", "state groups. First, let's # check if the event is", "sender LIKE ? AND stream_ordering > ? \"\"\" txn.execute(sql, (like_clause,", "the caches for all # those users. members_changed = set(", "prev_events, so we can # guess this by looking at", "new_forward_extremeties[room_id] = new_latest_event_ids len_1 = ( len(latest_event_ids) == 1 and", "f \" \"ON e.event_id = f.event_id \" \"AND e.room_id =", "(due to not # having any backwards extremeties) raise SynapseError(", "to another, lets check if # we have a delta", "into the events table, the events_json table, and the rejections", "depth_updates = {} for event, context in events_and_contexts: # Remove", "and recurses up the prev-event graph until it finds no", "def count_daily_messages(self): \"\"\" Returns an estimate of the number of", "the current state etc. Returns: Deferred[int]: the stream ordering of", "and we need to work out the delta (or use", "which might update the current state etc. Returns: Deferred[int]: the", "txn, event.room_id, event.redacts ) # Remove from relations table. self._handle_redaction(txn,", "queue: # if the last item in the queue has", "= txn.fetchall() logger.info(\"[purge] replacing backward extremities: %r\", new_backwards_extrems) txn.execute( \"DELETE", "for room_id, new_extrem in iteritems(new_forward_extremities) for ev_id in new_extrem ],", "stream_id, room_id, etype, state_key, None, room_id, etype, state_key, ) for", "backfilled events\"\"\" have_backfill_events = last_backfill_id != current_backfill_id have_forward_events = last_forward_id", "different chunks # might contain the same event. :( #", "# want to set the event_persisted_position to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering", "namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps a database function so", "limit): if last_id == current_id: return defer.succeed([]) def get_all_new_forward_event_rows(txn): sql", "event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\": event.depth, \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\":", "when purging history to figure out which state groups can", "token.topological) # Note that we insert events that are outliers", "# For paranoia reasons, we go and delete all the", "\"WHERE event_id IN (SELECT event_id from events_to_purge)\" ) for event_id,", "the any existing cache entries for the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id)", "of type _EventPersistQueueItem. The per_item_callback will continuously be called with", "current state, # so lets just return that. If we", "ev_map: break sql = ( \"SELECT \" \" e.event_id as", "room_id, evs_ctxs, backfilled=backfilled ) deferreds.append(d) for room_id in partitioned: self._maybe_start_persisting(room_id)", "under the License is distributed on an \"AS IS\" BASIS,", "one day since the last call to this function, it", "a time. Returns: tuple[list, dict] (to_delete, to_insert): where to_delete are", "event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete all remote non-state events for", "queue.popleft() except IndexError: # Queue has been drained. pass _EventCacheEntry", "room before a given stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[ {", "not events_and_contexts: return if backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts) )", "take out an exclusive lock on room_depth whenever it #", "in queue: try: ret = yield per_item_callback(item) except Exception: with", "type/state keys to be removed from the current state, and", "the entire event # anyway). self._simple_insert_many_txn( txn, table=\"event_auth\", values=[ {", "%i referenced state groups\", len(referenced_state_groups) ) logger.info(\"[purge] finding state groups", "just # return that. new_state_group = next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups))", "The current-state delta for each room. For each room, a", "logger.info(\"Calculating state delta for room %s\", room_id) with Measure( self._clock,", "room_id, latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) ) @defer.inlineCallbacks def", "Returns: tuple[list, dict] (to_delete, to_insert): where to_delete are the type/state_keys", "be in events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group = {} for", "= max(row[1] for row in rows) if max_depth < token.topological:", "and not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) ) def prefill(): for", "\"synapse_storage_events_forward_extremities_persisted\", \"Number of forward extremities for each new event\", buckets=(1,", "commit the txn in sqlite, # so make sure to", "(ev.event_id,) ) continue if ctx.state_group in state_groups_map: continue # We're", "\" SELECT event_id FROM events_to_purge \" \" WHERE NOT should_delete\"", "one of these events. # What we're interested in is", "to update the state_groups table with that state. # insert", "events_and_contexts for auth_id in event.auth_event_ids() if event.is_state() ], ) #", "old_state_groups = set( event_id_to_state_group[evid] for evid in old_latest_event_ids ) #", "members_changed = set( state_key for ev_type, state_key in itertools.chain(to_delete, to_insert)", "event_search table. self._store_room_message_txn(txn, event) elif event.type == EventTypes.Redaction: # Insert", "events before cutoff, of which %i can be deleted\", len(event_rows),", "= self._get_state_groups_from_groups_txn(txn, [sg]) curr_state = curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\":", "added or replaced state, never # removed keys entirely. state_delta_for_room[room_id]", "whenever anything is added to the queue. If another callback", "retried on IntegrityError, with `delete_existing=True` passed in. Args: func: function", "that we insert events that are outliers and aren't going", "from a previous (failed) # purge attempt, so let's drop", "chain of single ancestor non-state events. if all_single_prev_not_state: continue state_delta_counter.inc()", "? ORDER BY stream_id ASC LIMIT ? \"\"\" txn.execute(sql, (from_token,", "caches # Figure out the changes of membership to invalidate", "forward extremities for each new event. Stale extremities # are", "\"topological_ordering is greater than forward extremeties\" ) logger.info(\"[purge] looking for", "room_id, new_extrem in iteritems(new_forward_extremities) for event_id in new_extrem ], )", "when we created the event as they are # now.", "rejected. Returns those soft failed/rejected events and their prev events", "txn.execute(sql, (False, event.event_id)) # Update the event_backward_extremities table now that", "from event_to_state_groups\") txn.execute( \"DELETE FROM event_to_state_groups \" \"WHERE event_id IN", "store them (and # it doesn't take much storage compared", "table=\"event_json\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict()", "return value of the function will be given to the", "_count) defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The current minimum token that backfilled", "currently handling the queue then it will not be invoked.", "if current_state_ids is not None: state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group:", "the License. # You may obtain a copy of the", "JOIN event_forward_extremities as f \" \"ON e.event_id = f.event_id \"", "current state is only returned if we've already calculated it.", "event_to_state_groups LEFT JOIN events_to_purge AS ep USING (event_id) WHERE state_group", "yield self._get_event_ordering(event_id1) to_2, so_2 = yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) >", "in new_extrem ], ) @classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that", "\"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self, last_id, current_id, limit): if last_id", "up at once, to stop the # SQL query getting", "return that. If we happen to already have # the", "backfilled (bool): True if the events were backfilled \"\"\" #", "> ? \"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count, = txn.fetchone() return", "options. NB: due to the normal usage pattern of this", "new_latest_event_ids == latest_event_ids: # No change in extremities, so no", "the # connection. Annoyingly the python sqlite driver commits the", "event, context in events_and_contexts: # Remove the any existing cache", "(event_id)\" \" LEFT JOIN state_events USING (event_id)\" \" WHERE ?", "= OrderedDict() for event, context in events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id)", "event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering,", "driver commits the # transaction on CREATE, so let's do", "For paranoia reasons, we go and delete all the existing", "because later we'll be looking for # the should_delete /", "None then there has been a change, # and we", "event_stream_ordering DESC\" ) txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers = txn.fetchall() else:", "We want to store event_auth mappings for rejected events, as", "\"DELETE FROM event_to_state_groups \" \"WHERE event_id IN (SELECT event_id from", "the new state deltas for a room. Assumes that we", "nothing will happen to them. txn.execute( \"INSERT INTO events_to_purge\" \"", "extremities for each new event. Stale extremities # are those", "has been no change. If there has been a change", "FROM events_to_purge WHERE should_delete\" \")\" % (table,), (room_id,), ) #", "we are persisting Returns: list[(EventBase, EventContext)] new list, without the", "previous (failed) # purge attempt, so let's drop the table", "\"json\": encode_json(event_dict(event)), \"format_version\": event.format_version, } for event, _ in events_and_contexts", "current state state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\") # The number of", "for events to delete\") should_delete_expr = \"state_key IS NULL\" should_delete_params", "# Set of state groups to handle next. next_to_search =", "handling the queue then it will not be invoked. \"\"\"", "token, delete_local_events): \"\"\"Deletes room history before a certain point Args:", "before the # current_state_delta updates. # sql = \"\"\" INSERT", "CREATE, so let's do this first. # # furthermore, we", "is simply used to prefill the get_current_state_ids # cache current_state_for_room", "self.get_current_state_ids.prefill((room_id,), new_state) for room_id, latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids)", "Histogram from twisted.internet import defer import synapse.metrics from synapse.api.constants import", "accepts a `delete_existing` arg \"\"\" @wraps(func) @defer.inlineCallbacks def f(self, *args,", "[ event for event, _ in events_and_contexts if event.type ==", "EventTypes.Name: # Insert into the room_names and event_search tables. self._store_room_name_txn(txn,", "ev_ctx_rm ) # Don't bother calculating state if they're just", "FROM current_state_events WHERE room_id = ? AND type = ?", "new_event_updates = txn.fetchall() if len(new_event_updates) == limit: upper_bound = new_event_updates[-1][0]", "need to look at the events that # point to", "1 and len(new_latest_event_ids) == 1 ) if len_1: all_single_prev_not_state =", "c_counter, OrderedDict, deque, namedtuple from functools import wraps from six", "events from %s\", table) txn.execute( \"DELETE FROM %s WHERE event_id", "cache current_state_for_room = {} # map room_id->(to_delete, to_insert) where to_delete", "state group can have at most one prev group graph[row[\"state_group\"]]", "sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key,", "ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers =", "txn, events_and_contexts, backfilled): \"\"\"Update min_depth for each room Args: txn", "redacts\" \" FROM events AS e\" \" LEFT JOIN redactions", "ret = yield per_item_callback(item) except Exception: with PreserveLoggingContext(): item.deferred.errback() else:", "# for a room before a given stream_ordering self._simple_insert_many_txn( txn,", "referenced by events referenced_groups = set() # Set of state", "event_push_actions # event_reference_hashes # event_search # event_to_state_groups # events #", "return new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10) def", "sql = ( \"SELECT event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\"", "\"events\", \"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\", ): logger.info(\"[purge]", "Now remove all events which are prev_events of any of", "\"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \"", "= graph.get(sg) if prev_sg and prev_sg in to_delete: to_dedelta.add(sg) return", "the expression twice should_delete_params += (\"%:\" + self.hs.hostname, \"%:\" +", "synapse.metrics.background_process_metrics import run_as_background_process from synapse.state import StateResolutionStore from synapse.storage.background_updates import", "limit): def get_all_updated_current_state_deltas_txn(txn): sql = \"\"\" SELECT stream_id, room_id, type,", "state \" \"group\" % (ev.event_id,) ) continue if ctx.state_group in", "forward_ex_outliers = txn.fetchall() else: new_forward_events = [] forward_ex_outliers = []", "in rows: event = ev_map[row[\"event_id\"]] if not row[\"rejects\"] and not", "json from prometheus_client import Counter, Histogram from twisted.internet import defer", "in events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group = {} for event_id", "context in chunk: if context.app_service: origin_type = \"local\" origin_entity =", "delete them. txn.execute( \"\"\" SELECT DISTINCT state_group FROM events_to_purge INNER", "self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else: stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with", "buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50, 100,", "for logging etc events_context (list[(EventBase, EventContext)]): events and contexts which", "map (type,key)->event_id giving the state delta in each # room", "going from one state group to another, lets check if", "Annoyingly the python sqlite driver commits the # transaction on", "room. \"\"\" _EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\") )", "New Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C.", "\" WHERE event_id IN (\" \" SELECT event_id FROM events_to_purge", "the prev_events, so we can # guess this by looking", "extremeties in the room. # This allows us to later", "event) # Insert into the room_memberships table. self._store_room_members_txn( txn, [", "if not ev_map: break sql = ( \"SELECT \" \"", "table) txn.execute( \"DELETE FROM %s WHERE event_id IN (\" \"", "event.internal_metadata.stream_ordering, ) if not event.internal_metadata.is_outlier() and not context.rejected: depth_updates[event.room_id] =", "\"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\",", "missing events from DB event_to_groups = yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) #", "new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self,", "= events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room,", "from six import iteritems, text_type from six.moves import range from", "txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if not events_and_contexts: # nothing to", "stream_id): for room_id, current_state_tuple in iteritems(state_delta_by_room): to_delete, to_insert = current_state_tuple", "fetch(txn): txn.execute( \"\"\" select count(*) c from event_forward_extremities group by", "100, 200, 500, \"+Inf\"), ) # The number of stale", "to remove from current state, and to_insert # is a", "( ( stream_id, room_id, etype, state_key, None, room_id, etype, state_key,", "there has been a change, # and we need to", "significantly less or more than one day since the last", "%r\", new_backwards_extrems) txn.execute( \"DELETE FROM event_backward_extremities WHERE room_id = ?\",", "result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter the supplied", "txn.execute(sql, (metadata_json, event.event_id)) # Add an entry to the ex_outlier_stream", "its easier for now just to store them (and #", "chunks # might contain the same event. :( # NB:", "[] for event_id, prev_event_id, metadata, rejected in txn: if prev_event_id", "encode_json(json_object): \"\"\" Encode a Python object as JSON and return", "# Insert into the event_search table. self._store_history_visibility_txn(txn, event) elif event.type", "and check if they are referenced by other events #", "one, else the earliest one. Args: events_and_contexts (list[(EventBase, EventContext)]): Returns:", "Counter as c_counter, OrderedDict, deque, namedtuple from functools import wraps", "new_backfill_events = [] backward_ex_outliers = [] return AllNewEventsResult( new_forward_events, new_backfill_events,", "number of forward extremities that exist. # Counter of number", "? < stream_ordering AND stream_ordering <= ?\" \" ORDER BY", "database, but its also possible that we're # currently trying", "what the delta would have been when # processing one", "= ( \"SELECT event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \"", "= {} # map room_id->(to_delete, to_insert) where to_delete is a", "True if event_id1 is after event_id2 in the stream \"\"\"", "so we can reinsert them. # This gets around any", "(bool): Returns: defer.Deferred: a deferred which will resolve once the", "set of state groups that need to be de-delta'ed \"\"\"", "ctx in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds = [] for", "same event. :( # NB: Assumes that we are only", "defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok, we need to defer to the", "we need to fetch groups for. (We know none of", "we're interested in is if the latest extremities # were", "received events which were rejected Args: txn (twisted.enterprise.adbapi.Connection): db connection", "will happen to them. txn.execute( \"INSERT INTO events_to_purge\" \" SELECT", "state if they're just # a long chain of single", "e.type,\" \" state_key, redacts, relates_to_id\" \" FROM events AS e\"", "True, we will delete local events as well as remote", "count_daily_sent_messages(self): def _count_messages(txn): # This is good enough as if", "in events_and_contexts] ) for event, _ in events_and_contexts: if event.type", "the event_persisted_position to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for event, context", "tuple[list, dict] (to_delete, to_insert): where to_delete are the type/state_keys to", "if len(next_to_search) < 100: current_search = next_to_search next_to_search = set()", "Now pull out the state groups for any missing events", "\"INSERT INTO events_to_purge\" \" SELECT event_id, %s\" \" FROM events", "is not None: state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)]", "prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state delta for room %s\", room_id)", "next_to_search = set() else: current_search = set(itertools.islice(next_to_search, 100)) next_to_search -=", "if end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(),", "# Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) # We want to", "is only one state group, then we know what the", "txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg} ) self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg}", "in rows) # We don't bother re-handling groups we've already", "specific language governing permissions and # limitations under the License.", ") self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id))", "as that's a lot faster. # create an index on", "state groups that are referenced by events that are to", "are recalculating the current state state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\") #", "if room_id in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop(): try:", "usage pattern of this method, it does *not* follow the", "the queue has the same `backfilled` setting, # we can", "when we calculated the state for an event we were", "from the existing to new current state, # so lets", "# connection. Annoyingly the python sqlite driver commits the #", "state_groups WHERE id = ?\", ((sg,) for sg in state_groups_to_delete),", "-= current_search # Check if state groups are referenced sql", "from canonicaljson import json from prometheus_client import Counter, Histogram from", "forward extremity. # (except during the initial persistence of the", "ctx.delta_ids # We need to map the event_ids to their", "set of event_ids to return. This includes all soft-failed events", "# extremities are going to be in events_context). missing_event_ids =", "# if necessary. current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids is not", "def get_all_new_backfill_event_rows(txn): sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\"", "batch_iter from synapse.util.async_helpers import ObservableDeferred from synapse.util.caches.descriptors import cached, cachedInlineCallbacks", "\"sender\": event.sender, \"contains_url\": ( \"url\" in event.content and isinstance(event.content[\"url\"], text_type)", "# new stream_ordering to new forward extremeties in the room.", "self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) # Prefill the event cache self._add_to_cache(txn, events_and_contexts)", "for the # redacted event. self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts )", "groups we're looking up at once, to stop the #", "the events table, the events_json table, and the rejections table.", "forward extremities for each new event\", buckets=(1, 2, 3, 5,", "have_persisted = {event_id: outlier for event_id, outlier in txn} to_remove", "already persisted, etc, that wouldn't appear in events_and_context. backfilled (bool):", "token that backfilled events have reached\"\"\" return -self._backfill_id_gen.get_current_token() def get_current_events_token(self):", "event_id_to_state_group[evid] for evid in new_latest_event_ids ) # If they old", "the synapse logcontext rules, and leaves the logcontext in place", "been when # processing one of these events. # What", "self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id, current_id, limit): if last_id == current_id:", "stream_id ASC LIMIT ? \"\"\" txn.execute(sql, (from_token, to_token, limit)) return", "ev_type == EventTypes.Member ) for member in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate,", ") # Update backward extremeties txn.executemany( \"INSERT INTO event_backward_extremities (room_id,", "item in the queue, of type _EventPersistQueueItem. The per_item_callback will", ") state_delta_for_room[room_id] = delta # If we have the current_state", "e in events_and_contexts[i : i + N]} if not ev_map:", "yield queue.popleft() except IndexError: # Queue has been drained. pass", "DISTINCT state_group FROM event_to_state_groups LEFT JOIN events_to_purge AS ep USING", "not event.internal_metadata.is_outlier() and outlier_persisted: # We received a copy of", "deferred which will resolve once the events are persisted. Runs", "any existing cache entries for the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if", "event_backward_extremities WHERE room_id = ?\", (room_id,) ) # Update backward", "the state from that. events_by_room = {} for event, context", "preserve_events\") res = yield self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self),", "for event, context in events_and_contexts: # Remove the any existing", "point to it via event_edges table. txn.execute( \"\"\" SELECT COALESCE(MIN(depth),", "= txn.fetchall() else: new_forward_events = [] forward_ex_outliers = [] sql", "Encode a Python object as JSON and return it in", "all those that have been soft-failed or rejected. Returns those", "[ec for ec in events_and_contexts if ec[0] not in to_remove]", "+ self.hs.hostname sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM events", "have_forward_events: return defer.succeed(AllNewEventsResult([], [], [], [], [])) def get_all_new_events_txn(txn): sql", "their prev events, # otherwise we end up with dangling", "None. \"\"\" def _count_messages(txn): sql = \"\"\" SELECT COALESCE(COUNT(*), 0)", "Deferred: resolves to (int, int): the stream ordering of ``event``,", "15, 20, 50, 100, 200, 500, \"+Inf\"), ) # The", "fault. like_clause = \"%:\" + self.hs.hostname sql = \"\"\" SELECT", "\"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\", ): logger.info(\"[purge] removing events from", "and event_json tables Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase,", "self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled ) # _update_outliers_txn filters out any", "connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting backfilled (bool):", "forward extremities for a room given events to persist. Assumes", "we will build a temporary table listing the events so", "(list[(EventBase, EventContext)]): events we are persisting backfilled (bool): True if", "all_events_and_contexts = events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn,", "context), stream in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering = stream chunks =", "elif current_state is not None: with Measure( self._clock, \"persist_events.calculate_state_delta\" ):", "pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps a", "We bound size of groups we're looking up at once,", "a fairly handwavey check to see if we could #", "JOIN ex_outlier_stream USING (event_id)\" \" LEFT JOIN redactions USING (event_id)\"", "if new_latest_event_ids == latest_event_ids: # No change in extremities, so", "set(latest_event_ids) if new_latest_event_ids == latest_event_ids: # No change in extremities,", "events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert some number of", "events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if not events_and_contexts: # nothing to do", "room. Assumes that we are only persisting events for one", "2014-2016 OpenMarket Ltd # Copyright 2018-2019 New Vector Ltd #", "], ) self._simple_insert_many_txn( txn, table=\"events\", values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\":", "?\", (min_depth, room_id), ) # finally, drop the temp table.", "events SET outlier = ?\" \" WHERE event_id IN (\"", "20, 50, 100, 200, 500, \"+Inf\"], ) # Read the", "yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True, ) if", "synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for event, context in chunk: if context.app_service:", "in chunk: events_by_room.setdefault(event.room_id, []).append( (event, context) ) for room_id, ev_ctx_rm", "not backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"): # Work out the new", "(table,), [(ev.event_id,) for ev, _ in events_and_contexts], ) for table", "Normally that'd be in the database, but its also possible", "= [] forward_ex_outliers = [] sql = ( \"SELECT -e.stream_ordering,", "AND type = ? AND state_key = ?\", ( (room_id,", "tuples of (event, context) backfilled (bool): Whether the results are", "synapse.metrics from synapse.api.constants import EventTypes from synapse.api.errors import SynapseError from", "to handle the queue for a room if not already", "has been drained. pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def", "# If the event is rejected then we don't care", "turn the state groups that reference to-be-deleted state # groups", "context.rejected: # Insert the event_id into the rejections table self._store_rejections_txn(txn,", "exist. # Counter of number of extremities to count self._current_forward_extremities_amount", "handle the queue for a room if not already being", "not in have_persisted: continue to_remove.add(event) if context.rejected: # If the", "a room Args: room_id (str): room to which the events", "raise Exception( \"Context for new event %s has no state", "JOIN event_json USING (event_id) WHERE event_id IN (%s) AND NOT", "nothing to do here return def event_dict(event): d = event.get_dict()", "self._currently_persisting_rooms = set() def add_to_queue(self, room_id, events_and_contexts, backfilled): \"\"\"Add events", "group_to_state = yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) == 1: #", "we wouldn't be able to send any events (due to", "== EventTypes.Redaction: # Insert into the redactions table. self._store_redaction(txn, event)", "JOIN event_to_state_groups USING (event_id) \"\"\" ) referenced_state_groups = set(sg for", "text_type) ), } for event, _ in events_and_contexts ], )", "state state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\") # The number of times", "the last day. If it has been significantly less or", "outliers and aren't going to be # deleted, as nothing", "should_delete FROM events_to_purge\") event_rows = txn.fetchall() logger.info( \"[purge] found %i", "retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True, ) if not res: raise", "\"depth\": event.depth, \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"processed\": True,", "delta for each room. For each room, a tuple (to_delete,", "event.event_id not in have_persisted: continue to_remove.add(event) if context.rejected: # If", "easier for now just to store them (and # it", ") txn.execute(sql, to_recursively_check) to_recursively_check = [] for event_id, prev_event_id, metadata,", "if event.type == EventTypes.Redaction and event.redacts is not None: #", "they're just # a long chain of single ancestor non-state", "\"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\", ): logger.info(\"[purge] removing", "@classmethod def _delete_existing_rows_txn(cls, txn, events_and_contexts): if not events_and_contexts: # nothing", "\"stream_ordering\": max_stream_order, } for room_id, new_extrem in iteritems(new_forward_extremities) for event_id", "current forward extremities. for ev, _ in ev_ctx_rm: prev_event_ids =", "connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting \"\"\" if", "enough as if you have silly characters in your own", "?)\", [(room_id, event_id) for event_id, in new_backwards_extrems], ) logger.info(\"[purge] finding", "the current state, and a state set to be added", "# so we need to update the state_groups table with", "for chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk", "let's # check if the event is one we're persisting,", "each room new_forward_extremeties = {} # map room_id->(type,state_key)->event_id tracking the", "Now we actually update the current_state_events table txn.executemany( \"DELETE FROM", "we are persisting \"\"\" if not events_and_contexts: # nothing to", "from room_id, # new stream_ordering to new forward extremeties in", "|= prevs for row in rows: # Note: Each state", "self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop off in the background run_as_background_process(\"persist_events\", handle_queue_loop)", "This turns outliers into ex-outliers (unless the new event was", "First, let's # check if the event is one we're", "return end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled,", "events which were rejected Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts", "ON eg.prev_event_id = eb.event_id INNER JOIN events AS e ON", "self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally handle the case where the new", "for _ in to_recursively_check), ) txn.execute(sql, to_recursively_check) to_recursively_check = []", "current_state_events table txn.executemany( \"DELETE FROM current_state_events\" \" WHERE room_id =", "with only one concurrent transaction per room. \"\"\" _EventPersistQueueItem =", "synapse logcontext rules, and leaves the logcontext in place whether", "yield self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids ) latest_event_ids = set(latest_event_ids) if", "room_id, token, delete_local_events, ) def _purge_history_txn(self, txn, room_id, token_str, delete_local_events):", "persisting backfilled (bool): True if the events were backfilled \"\"\"", "set(sg for sg, in txn) logger.info( \"[purge] found %i referenced", "The stream_id for the update is chosen to be the", "e[1]), ) logger.info(\"[purge] Finding new backward extremities\") # We calculate", "event_forward_extremities # event_json # event_push_actions # event_reference_hashes # event_search #", "(str): token (str): A topological token to delete events before", "each room. For each room, a list of the event", "\"\"\"The current minimum token that backfilled events have reached\"\"\" return", "txn) logger.info( \"[purge] found %i referenced state groups\", len(referenced_state_groups) )", "self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) > (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id):", "Returns those soft failed/rejected events and their prev events (whether", "have resonably # calculated the delta when we calculated the", "we know that we've # only added or replaced state,", "backfilled=backfilled ) deferreds.append(d) for room_id in partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable(", "# From this point onwards the events are only events", ") defer.returnValue((res.state, None)) @defer.inlineCallbacks def _calculate_state_delta(self, room_id, current_state): \"\"\"Calculate the", "%s\", sg) curr_state = self._get_state_groups_from_groups_txn(txn, [sg]) curr_state = curr_state[sg] self._simple_delete_txn(", "replacing backward extremities: %r\", new_backwards_extrems) txn.execute( \"DELETE FROM event_backward_extremities WHERE", "events AS e\" \" LEFT JOIN redactions USING (event_id)\" \"", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "\")\", (True,), ) # synapse tries to take out an", "_read_forward_extremities(self): def fetch(txn): txn.execute( \"\"\" select count(*) c from event_forward_extremities", "rejects \" \" FROM events as e\" \" LEFT JOIN", "current_id sql = ( \"SELECT event_stream_ordering, e.event_id, e.room_id, e.type,\" \"", "= ?\" ) txn.execute(sql, (metadata_json, event.event_id)) # Add an entry", "from the database. This is useful when retrying due to", "in iteritems(new_forward_extremities) for event_id in new_extrem ], ) @classmethod def", "synapse.api.constants import EventTypes from synapse.api.errors import SynapseError from synapse.events import", "fairly handwavey check to see if we could # have", "and _handle_mult_prev_events (though arguably those could both be moved in", "for item in queue: try: ret = yield per_item_callback(item) except", "batch), ) txn.execute(sql, batch) results.extend(r[0] for r in txn if", "def add_to_queue(self, room_id, events_and_contexts, backfilled): \"\"\"Add events to the queue,", "room_id->(type,state_key)->event_id tracking the full # state in each room after", "in events_and_contexts], ) for table in (\"event_push_actions\",): txn.executemany( \"DELETE FROM", "that change forward extremities # (e.g. we ignore backfill/outliers/etc) if", "groups are referenced sql = \"\"\" SELECT DISTINCT state_group FROM", "rejections.event_id IS NOT NULL FROM event_edges INNER JOIN events USING", "_EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\") ) def __init__(self):", "in txn) referenced_groups |= referenced # We don't continue iterating", "(?, ?)\", [(room_id, event_id) for event_id, in new_backwards_extrems], ) logger.info(\"[purge]", "row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) ) def prefill(): for cache_entry in", "add all the new events to the list result.update(event.event_id for", "above and skip this bit.) assert new_latest_event_ids, \"No forward extremities", "to the deferreds as well. This function should therefore be", "WHERE prev_event_id IN (%s) AND NOT events.outlier AND rejections.event_id IS", "txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) # Ensure that we don't have", "# Set of events that we have found to be", "in the list of new events we're adding. for ev,", "events_by_room.setdefault(event.room_id, []).append( (event, context) ) for room_id, ev_ctx_rm in iteritems(events_by_room):", "as well as remote ones (instead of just marking them", "and not ctx.rejected and not event.internal_metadata.is_soft_failed() ] latest_event_ids = set(latest_event_ids)", "+ self.hs.hostname, \"%:\" + self.hs.hostname) should_delete_params += (room_id, token.topological) #", "in iteritems(state_delta_by_room): to_delete, to_insert = current_state_tuple # First we add", "\"\"\" # Graph of state group -> previous group graph", "and # event_edges tables. self._handle_mult_prev_events( txn, events=[event for event, _", "delete_existing=True, **kwargs) defer.returnValue(res) return f # inherits from EventFederationStore so", "set(sg for sg, in txn) referenced_groups |= referenced # We", "extremities for the room. Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]: Returns", "of ``event``, and the stream ordering of the latest persisted", "deleted and which need to be de-delta'ed (due to one", "deque()) if queue: # if the last item in the", "sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM events WHERE type", "(self.stream_ordering_day_ago,)) count, = txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_active_rooms\",", "for # the should_delete / shouldn't_delete subsets txn.execute( \"CREATE INDEX", "drained. pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps", "of type/state keys to remove from current state, and to_insert", "= ( \"SELECT event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts,", "import Measure logger = logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter", "groups\") # Get all state groups that are referenced by", "import EventsWorkerStore from synapse.storage.state import StateGroupWorkerStore from synapse.types import RoomStreamToken,", "state # groups that are referenced. current_search -= referenced rows", "We can't easily parallelize these since different chunks # might", "= ( \"SELECT \" \" e.event_id as event_id, \" \"", "(bool): True to purge existing table rows for the events", "the update is chosen to be the minimum of the", "in the event_push_actions table for the # redacted event. self._remove_push_actions_for_event_id_txn(", "entries # for these events so we can reinsert them.", "bulk with only one concurrent transaction per room. \"\"\" _EventPersistQueueItem", "are persisted. Runs its callbacks *without* a logcontext. \"\"\" queue", "7, 10, 15, 20, 50, 100, 200, 500, \"+Inf\"), )", "ORDER BY stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql, (-last_id,", "Update backward extremeties txn.executemany( \"INSERT INTO event_backward_extremities (room_id, event_id)\" \"", "first. txn.execute(\"DROP TABLE IF EXISTS events_to_purge\") txn.execute( \"CREATE TEMPORARY TABLE", "? < stream_id AND stream_id <= ? ORDER BY stream_id", "stream_id for the update is chosen to be the minimum", "txn, table=\"event_auth\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"auth_id\": auth_id,", "key[0], \"state_key\": key[1], \"event_id\": state_id, } for key, state_id in", "the events_json table, and the rejections table. Things reading from", "backfilled=backfilled, ) # Insert event_reference_hashes table. self._store_event_reference_hashes_txn( txn, [event for", "sure that the database transactions # have a logcontext to", "can call _update_backward_extremities # and _handle_mult_prev_events (though arguably those could", "\" LEFT JOIN redactions as r ON e.event_id = r.redacts\"", "function so that it gets retried on IntegrityError, with `delete_existing=True`", "\" VALUES (?, ?)\", [(room_id, event_id) for event_id, in new_backwards_extrems],", "remove from current_state_events and `to_insert` are the updates to current_state_events.", "stream_ordering >= ?\" \" ORDER BY stream_ordering DESC\" \" LIMIT", "'rejections' table for received events which were rejected Args: txn", "We'll pull stuff out of the DB later # if", "ret = yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self): def", "if delete_existing: # For paranoia reasons, we go and delete", "import EventFederationStore from synapse.storage.events_worker import EventsWorkerStore from synapse.storage.state import StateGroupWorkerStore", "of the DB later # if necessary. current_state_ids = ctx.get_cached_current_state_ids()", "since different chunks # might contain the same event. :(", "import logging from collections import Counter as c_counter, OrderedDict, deque,", "= { key: ev_id for key, ev_id in iteritems(current_state) if", "event_contexts if not event.internal_metadata.is_outlier() and not ctx.rejected and not event.internal_metadata.is_soft_failed()", "key[1], \"event_id\": state_id, } for key, state_id in iteritems(curr_state) ],", "to keep this actually last. txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge] done\")", "software # distributed under the License is distributed on an", "?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_id, -upper_bound))", ") rows = txn.fetchall() max_depth = max(row[1] for row in", "if prev_sg and prev_sg in to_delete: to_dedelta.add(sg) return to_delete, to_dedelta", "from synapse.util.caches.descriptors import cached, cachedInlineCallbacks from synapse.util.frozenutils import frozendict_json_encoder from", "state_key, redacts, relates_to_id\" \" FROM events AS e\" \" INNER", "want to set the event_persisted_position to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering )", "else the earliest one. Args: events_and_contexts (list[(EventBase, EventContext)]): Returns: list[(EventBase,", "(as opposed # to receiving it over federation) it will", "the event_ids to their state groups. First, let's # check", "have reached\"\"\" return -self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The current maximum token", "\"\") event_counter = Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\", \"origin_entity\"], )", "if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids # We need to", "frozendict_json_encoder from synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils import log_function", ") @classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that we don't have", "single forward extremity state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\", \"\" ) #", "sql = \"UPDATE events SET outlier = ?\" \" WHERE", "have added, then we invlidate the caches for all #", "[(room_id, event_id) for event_id, in new_backwards_extrems], ) logger.info(\"[purge] finding redundant", "for event_id in new_latest_event_ids: # First search in the list", "> stream_ordering AND stream_ordering >= ?\" \" ORDER BY stream_ordering", "%i events before cutoff, of which %i can be deleted\",", "defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The current minimum token that backfilled events", "to_dedelta @defer.inlineCallbacks def is_event_after(self, event_id1, event_id2): \"\"\"Returns True if event_id1", "%s\" % (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self, from_token,", "# entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert into event_to_state_groups.", "so we need to update the state_groups table with that", "logger.info(\"[purge] finding redundant state groups\") # Get all state groups", "being handled. The given callback will be invoked with for", "# state in each room after adding these events. #", "\" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn)", "there is one, else the earliest one. Args: events_and_contexts (list[(EventBase,", "whenever it # persists events (because upsert), and once we", "event.type, \"state_key\": event.state_key, } # TODO: How does this work", "an index. txn.execute(\"CREATE INDEX events_to_purge_id\" \" ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id,", "tables Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events", "class _EventPeristenceQueue(object): \"\"\"Queues up events so that they can be", "to be purged that are pointed to by events we're", "The set of event_ids to return. This includes all soft-failed", "self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, ) # Invalidate the various caches #", "are reculating state when we could have resonably # calculated", "database. # Set of events we need to fetch groups", "Figure out the changes of membership to invalidate the #", "self, txn, events_and_contexts, all_events_and_contexts, backfilled ): \"\"\"Update all the miscellaneous", "COALESCE(COUNT(DISTINCT room_id), 0) FROM events WHERE type = 'm.room.message' AND", "table listing the events so that we don't # have", "set( event_id_to_state_group[evid] for evid in new_latest_event_ids ) # If they", "backward_ex_outliers = [] return AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers, )", "AS eg ON eg.prev_event_id = eb.event_id INNER JOIN events AS", "NULL FROM event_edges INNER JOIN events USING (event_id) LEFT JOIN", "\" \" FROM events as e\" \" LEFT JOIN rejections", "(etype, state_key), ev_id in iteritems(to_insert) ), ) # Now we", "logger.info(\"Deleting existing\") for table in ( \"events\", \"event_auth\", \"event_json\", \"event_edges\",", "events_to_purge\") txn.execute( \"CREATE TEMPORARY TABLE events_to_purge (\" \" event_id TEXT", "ev_id, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], } for key,", "*args, **kwargs): try: res = yield func(self, *args, **kwargs) except", "IN (%s) AND NOT events.outlier AND rejections.event_id IS NULL \"\"\"", "state_key, ev_id, room_id, etype, state_key, ) for (etype, state_key), ev_id", "room_id): queue = self._event_persist_queues.setdefault(room_id, deque()) try: while True: yield queue.popleft()", "to current_state_events. \"\"\" existing_state = yield self.get_current_state_ids(room_id) to_delete = [key", "# event_forward_extremities # event_json # event_push_actions # event_reference_hashes # event_search", "should be pruned: # event_auth # event_backward_extremities # event_edges #", "# Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed", "if ec[0] not in to_remove] def _update_metadata_tables_txn( self, txn, events_and_contexts,", "if isinstance(out, bytes): out = out.decode(\"utf8\") return out class _EventPeristenceQueue(object):", "in events_context: if event_id == ev.event_id and ctx.state_group is not", "# rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def _update_current_state_txn(self,", "txn.execute( \"DELETE FROM %s WHERE event_id IN (\" \" SELECT", "txn, table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id, \"room_id\": room_id} for room_id, new_extrem", "upper_bound = current_id sql = ( \"SELECT -event_stream_ordering, e.event_id, e.room_id,", "continue # We're only interested in pulling out state that", "to_recursively_check: sql = \"\"\" SELECT event_id, prev_event_id, internal_metadata, rejections.event_id IS", "def get_current_events_token(self): \"\"\"The current maximum token that events have reached\"\"\"", "self).__init__(db_conn, hs) self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler() # Collect", "that they can be persisted in bulk with only one", "the stream \"\"\" to_1, so_1 = yield self._get_event_ordering(event_id1) to_2, so_2", "# groups that are referenced. current_search -= referenced rows =", "into the room_memberships table. self._store_room_members_txn( txn, [ event for event,", "from prometheus_client import Counter, Histogram from twisted.internet import defer import", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "import Counter, Histogram from twisted.internet import defer import synapse.metrics from", "# calculated the delta when we calculated the state for", "events that # point to it via event_edges table. txn.execute(", "len_1: all_single_prev_not_state = all( len(event.prev_event_ids()) == 1 and not event.is_state()", ") have_persisted = {event_id: outlier for event_id, outlier in txn}", "transition. If we do then we can just # return", "depth_updates[event.room_id] = max( event.depth, depth_updates.get(event.room_id, event.depth) ) for room_id, depth", "last day. If it has been significantly less or more", "need to do # anything. if old_state_groups == new_state_groups: defer.returnValue((None,", "should_delete because later we'll be looking for # the should_delete", "SELECT event_id FROM events_to_purge WHERE should_delete\" \")\" % (table,), (room_id,),", "ObservableDeferred from synapse.util.caches.descriptors import cached, cachedInlineCallbacks from synapse.util.frozenutils import frozendict_json_encoder", "<= ?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_id,", "_EventPeristenceQueue(object): \"\"\"Queues up events so that they can be persisted", "we'll need to pull # the state from the database", "any existing events. existing_prevs = yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally", ") min_depth, = txn.fetchone() logger.info(\"[purge] updating room_depth to %d\", min_depth)", "existing_state.get(key) } defer.returnValue((to_delete, to_insert)) @log_function def _persist_events_txn( self, txn, events_and_contexts,", "before delete_local_events (bool): if True, we will delete local events", "room_id): @defer.inlineCallbacks def persisting_queue(item): with Measure(self._clock, \"persist_events\"): yield self._persist_events( item.events_and_contexts,", "state_delta_by_room, stream_id): for room_id, current_state_tuple in iteritems(state_delta_by_room): to_delete, to_insert =", "state_group IN (%s) AND ep.event_id IS NULL \"\"\" % (", "by first insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] = (event, context) else:", "so that we don't block event # persistence. # #", "room state_delta_for_room = {} if not backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"):", "of room events into the necessary database tables. Rejected events", "run as a background process to make sure that the", "We find out which membership events we may have deleted", "in to_remove] @classmethod def _delete_existing_rows_txn(cls, txn, events_and_contexts): if not events_and_contexts:", ") % (\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql, list(ev_map)) rows = self.cursor_to_dict(txn)", "indices *after* insertion as that's a lot faster. # create", "return txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult = namedtuple(", "FROM events AS e\" \" INNER JOIN ex_outlier_stream USING (event_id)\"", "the # current_state_delta updates. # sql = \"\"\" INSERT INTO", "IN (%s) AND NOT events.outlier \"\"\" % ( \",\".join(\"?\" for", "event.depth) ) for room_id, depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth)", "for event, context in events_and_contexts: if context.rejected: # Insert the", "for sg, in txn) logger.info( \"[purge] found %i referenced state", "# the state from the database missing_event_ids.add(event_id) if missing_event_ids: #", "all soft-failed events # and their prev events. existing_prevs =", "(True,), ) # synapse tries to take out an exclusive", "event, context in chunk: events_by_room.setdefault(event.room_id, []).append( (event, context) ) for", "upper_bound = new_event_updates[-1][0] else: upper_bound = current_id sql = (", "ev_id != existing_state.get(key) } defer.returnValue((to_delete, to_insert)) @log_function def _persist_events_txn( self,", "(to_delete, to_insert): where to_delete are the type/state_keys to remove from", "for a room if not already being handled. The given", "} for key, ev_id in iteritems(to_insert) ], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed,", "each room Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]):", "event.type == EventTypes.Redaction and event.redacts is not None: # Remove", "callback will be invoked with for each item in the", "event, _ in events_and_contexts ], ) def _store_rejected_events_txn(self, txn, events_and_contexts):", "# start with the existing forward extremities result = set(latest_event_ids)", "ctx.state_group)] = ctx.delta_ids # We need to map the event_ids", "extremities for a room given events to persist. Assumes that", "so we don't # want to set the event_persisted_position to", "yield self.get_current_state_ids(room_id) to_delete = [key for key in existing_state if", "FROM events_to_purge\") event_rows = txn.fetchall() logger.info( \"[purge] found %i events", "events_and_contexts): if not events_and_contexts: # nothing to do here return", "= [] return AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers, ) return", "? ) \"\"\" txn.executemany( sql, ( ( stream_id, room_id, etype,", "the server either as new events or as backfilled events\"\"\"", "referenced by other events # or state groups, and if", "len(next_to_search) < 100: current_search = next_to_search next_to_search = set() else:", "of state groups that can be deleted and the set", "len(remaining_state_groups), ) # Now we turn the state groups that", "delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if not backfilled: # backfilled", "If we have the current_state then lets prefill # the", "1000) @defer.inlineCallbacks def _read_forward_extremities(self): def fetch(txn): txn.execute( \"\"\" select count(*)", "ASC\" \" LIMIT ?\" ) if have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id,", "list. events_and_contexts = self._update_outliers_txn( txn, events_and_contexts=events_and_contexts ) # From this", "the events were backfilled delete_existing (bool): True to purge existing", "maps, the first being the full new current state and", "caches for all # those users. members_changed = set( state_key", "in existing_state if key not in current_state] to_insert = {", "updating the current_state_events table so # that we can use", "?\", ((sg,) for sg in state_groups_to_delete), ) txn.executemany( \"DELETE FROM", "for table in (\"event_push_actions\",): txn.executemany( \"DELETE FROM %s WHERE room_id", "at a time. \"\"\" # we're only interested in new", "the cache for the redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT", "e\" \" LEFT JOIN rejections as rej USING (event_id)\" \"", "one of its prev groups being scheduled for deletion). Args:", "\" event_id TEXT NOT NULL,\" \" should_delete BOOLEAN NOT NULL\"", "\"\"\" all_events_and_contexts = events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering", "the full new current state and the second being the", "# if the last item in the queue has the", "AS ep USING (event_id) WHERE state_group IN (%s) AND ep.event_id", "the event_search table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event) # Insert into", "as the prev_events, so we can # guess this by", "event.internal_metadata.stream_ordering = stream chunks = [ events_and_contexts[x : x +", "is not None: current_state_for_room[room_id] = current_state yield self.runInteraction( \"persist_events\", self._persist_events_txn,", "extremities that exist. # Counter of number of extremities to", "a logcontext to report to return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities )", "need to check whether the event was rejected. Args: txn", "out which membership events we may have deleted # and", "persisting_queue(item): with Measure(self._clock, \"persist_events\"): yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id,", "state_groups_state # we will build a temporary table listing the", "try: res = yield func(self, *args, **kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError,", "= set( state_key for ev_type, state_key in itertools.chain(to_delete, to_insert) if", "state groups\") txn.executemany( \"DELETE FROM state_groups_state WHERE state_group = ?\",", "correct ordering we pop, as OrderedDict is # ordered by", "new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10) def get_all_new_events(", "# finally, drop the temp table. this will commit the", "they old and new groups are the same then we", "de-delta'ed (due to one of its prev groups being scheduled", "current_forward_id, limit)) new_forward_events = txn.fetchall() if len(new_forward_events) == limit: upper_bound", "!= current_forward_id if not have_backfill_events and not have_forward_events: return defer.succeed(AllNewEventsResult([],", "?\", (room_id,), ) rows = txn.fetchall() max_depth = max(row[1] for", "and len(new_latest_event_ids) == 1 ) if len_1: all_single_prev_not_state = all(", "_update_room_depths_txn(self, txn, events_and_contexts, backfilled): \"\"\"Update min_depth for each room Args:", "_update_metadata_tables_txn( self, txn, events_and_contexts, all_events_and_contexts, backfilled ): \"\"\"Update all the", "that have been soft-failed or rejected. Returns those soft failed/rejected", "FROM events_to_purge \" \" WHERE NOT should_delete\" \")\", (True,), )", "the event and event_json tables Args: txn (twisted.enterprise.adbapi.Connection): db connection", "\"ON e.event_id = f.event_id \" \"AND e.room_id = f.room_id \"", "IS NULL \"\"\" % ( \",\".join(\"?\" for _ in batch),", "in state_groups_to_delete), ) txn.executemany( \"DELETE FROM state_groups WHERE id =", "encode_json(event_dict(event)), \"format_version\": event.format_version, } for event, _ in events_and_contexts ],", "== EventTypes.RoomHistoryVisibility: # Insert into the event_search table. self._store_history_visibility_txn(txn, event)", "IN (%s) AND ep.event_id IS NULL \"\"\" % ( \",\".join(\"?\"", "sum(1 for e in event_rows if e[1]), ) logger.info(\"[purge] Finding", "def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter the supplied list of event_ids to", "len(new_state_groups) == 1 and len(old_state_groups) == 1: # If we're", "batch_iter(event_ids, 100): yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk ) defer.returnValue(results) @defer.inlineCallbacks", "see if we could # have guessed what the delta", "list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn, events_and_contexts, backfilled): \"\"\"Update min_depth for each", "state_groups_to_delete), ) txn.executemany( \"DELETE FROM state_groups WHERE id = ?\",", "ones we don't have yet so we need to look", "could both be moved in here) class EventsStore( StateGroupWorkerStore, EventFederationStore,", "\"state_group\"), ) prevs = set(row[\"state_group\"] for row in rows) #", ") logger.info(\"[purge] removing redundant state groups\") txn.executemany( \"DELETE FROM state_groups_state", "= state_groups_seen - referenced_groups to_dedelta = set() for sg in", "We then go and check if they are referenced by", "Copyright 2019 The Matrix.org Foundation C.I.C. # # Licensed under", "compared to storing the entire event # anyway). self._simple_insert_many_txn( txn,", "is added to the queue. If another callback is currently", "inserted into the events table, the events_json table, and the", "which were rejected Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase,", "if they're just # a long chain of single ancestor", "of the send_join # results, in which case there will", "7, 10, 15, 20, 50, 100, 200, 500, \"+Inf\"], )", "txn.execute(sql, list(ev_map)) rows = self.cursor_to_dict(txn) for row in rows: event", "number of messages sent in the last day. If it", "self._handle_mult_prev_events( txn, events=[event for event, _ in events_and_contexts] ) for", "state continue # there should always be at least one", "== EventTypes.Message: # Insert into the event_search table. self._store_room_message_txn(txn, event)", "the filtered list. events_and_contexts = self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts ) #", "soft_failed or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk in batch_iter(event_ids, 100):", "self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id = yield self._stream_id_gen.get_current_token()", "room after adding these events. # This is simply used", "zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering = stream chunks = [ events_and_contexts[x :", "state_key, ) for etype, state_key in to_delete # We sanity", "the queue for a room if not already being handled.", "groups of new_latest_event_ids new_state_groups = set( event_id_to_state_group[evid] for evid in", "JOIN event_edges AS ed ON e.event_id = ed.prev_event_id\" \" LEFT", "extremities # were the same when we created the event", "state_group = ?\", ((sg,) for sg in state_groups_to_delete), ) txn.executemany(", "from synapse.metrics import BucketCollector from synapse.metrics.background_process_metrics import run_as_background_process from synapse.state", "backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def _persist_events( self, events_and_contexts,", "# Set of state groups we've already seen state_groups_seen =", "IN (%s)\" ) % (\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql, list(ev_map)) rows", "SET min_depth = ? WHERE room_id = ?\", (min_depth, room_id),", "\"replaces_state\"): vals[\"prev_state\"] = event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) # Prefill", "state_groups_seen next_to_search |= prevs state_groups_seen |= prevs for row in", "delete_local_events): \"\"\"Deletes room history before a certain point Args: room_id", "be added to the current state. new_forward_extremeties (dict[str, list[str]]): The", "soft-failed or rejected. Returns those soft failed/rejected events and their", "a # single forward extremity state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\", \"\"", "be in the database, but its also possible that we're", "in events_context: if ev.type == EventTypes.Create and ev.state_key == \"\":", "that we don't block event # persistence. # # We", "\"1\") break if not room_version: room_version = yield self.get_room_version(room_id) logger.debug(\"calling", "was rejected. Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]):", "by room_id \"\"\" ) return txn.fetchall() res = yield self.runInteraction(\"read_forward_extremities\",", "events. existing_prevs = yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally handle the", "events for one room at a time. Returns: tuple[list, dict]", "the database transactions # have a logcontext to report to", "groups that can be deleted and the set of state", "tables. self._handle_mult_prev_events( txn, events=[event for event, _ in events_and_contexts] )", "prev_event_context[0].internal_metadata.is_outlier(): # To ensure correct ordering we pop, as OrderedDict", "point onwards the events are only ones that weren't #", "added, then we invlidate the caches for all # those", "chunk in chunks: # We can't easily parallelize these since", "Finally handle the case where the new events have soft-failed", "its callbacks *without* a logcontext. \"\"\" queue = self._event_persist_queues.setdefault(room_id, deque())", "event, _ in events_and_contexts] ) state_events_and_contexts = [ ec for", "The number of stale forward extremities for each new event.", "= encode_json(event.internal_metadata.get_dict()) sql = ( \"UPDATE event_json SET internal_metadata =", "the second being the delta to the existing current state.", "return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60 * 60 *", "return that, # but it doesn't matter if we don't.", "a Unicode string. \"\"\" out = frozendict_json_encoder.encode(json_object) if isinstance(out, bytes):", "synapse.storage.event_federation import EventFederationStore from synapse.storage.events_worker import EventsWorkerStore from synapse.storage.state import", "event_contexts, latest_event_ids): \"\"\"Calculates the new forward extremities for a room", "list result.update(event.event_id for event in new_events) # Now remove all", "\"\"\" txn.execute(sql, (from_token, to_token, limit)) return txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\",", "Assumes that we are only persisting events for one room", "non delta versions. for sg in remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining", "we need to defer to the state handler to resolve", "if context.rejected: # If the event is rejected then we", "d = event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\", None) return d self._simple_insert_many_txn(", "Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of forward extremities for each new event\",", "not we delete them. txn.execute( \"\"\" SELECT DISTINCT state_group FROM", "redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT INTO redactions (event_id, redacts)", "we are only persisting events for one room # at", "self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def _store_redaction(self, txn, event): # invalidate the", "removing events from %s\", table) txn.execute( \"DELETE FROM %s WHERE", "go and delete all the existing entries # for these", "if all_single_prev_not_state: continue state_delta_counter.inc() if len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc() #", "From this point onwards the events are only events that", "to handle next. next_to_search = set(state_groups) while next_to_search: # We", "Unicode string. \"\"\" out = frozendict_json_encoder.encode(json_object) if isinstance(out, bytes): out", "= {} if not backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"): # Work", "don't need to do # anything. if old_state_groups == new_state_groups:", "self._persist_events( item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def _persist_events(", "\"\"\" SELECT event_id, prev_event_id, internal_metadata, rejections.event_id IS NOT NULL FROM", "to their state groups. First, let's # check if the", "set() for sg in referenced_groups: prev_sg = graph.get(sg) if prev_sg", "context.app_service: origin_type = \"local\" origin_entity = context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type", "failed events. Args: event_ids (Iterable[str]): Events to find prev events", "sql = \"\"\" SELECT DISTINCT state_group FROM event_to_state_groups LEFT JOIN", "only return the delta if its already been calculated. Conversely", "logger.info( \"[purge] found %i state groups to delete\", len(state_groups_to_delete) )", "i in range(0, len(events_and_contexts), N): ev_map = {e[0].event_id: e[0] for", "\"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\", \"state_events\", \"rejections\", \"redactions\", \"room_memberships\",", "event.event_id)) # Update the event_backward_extremities table now that this #", "going to be # deleted, as nothing will happen to", "the set of state groups that need to be de-delta'ed", "(%s) AND ep.event_id IS NULL \"\"\" % ( \",\".join(\"?\" for", "values={ \"event_stream_ordering\": stream_order, \"event_id\": event.event_id, \"state_group\": state_group_id, }, ) sql", "table=\"event_auth\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"auth_id\": auth_id, }", "== EventTypes.Create and ev.state_key == \"\": room_version = ev.content.get(\"room_version\", \"1\")", "new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for room_id, latest_event_ids in iteritems(new_forward_extremeties):", "_ in events_and_contexts ], ) self._simple_insert_many_txn( txn, table=\"events\", values=[ {", "retcols=(\"prev_state_group\", \"state_group\"), ) prevs = set(row[\"state_group\"] for row in rows)", "events. This is used to find extremities that are ancestors", "server either as new events or as backfilled events\"\"\" have_backfill_events", "= ? ) \"\"\" txn.executemany( sql, ( ( stream_id, room_id,", "initial persistence of the send_join # results, in which case", "in events_and_contexts: if context.rejected: # Insert the event_id into the", "We need to get the room version, which is in", "(list[(EventBase, EventContext)]): events to persist backfilled (bool): True if the", "in the queue, of type _EventPersistQueueItem. The per_item_callback will continuously", "iteritems(new_forward_extremities) for event_id in new_extrem ], ) @classmethod def _filter_events_and_contexts_for_duplicates(cls,", "return [ec for ec in events_and_contexts if ec[0] not in", "to get the room version, which is in the create", "to the queue. If another callback is currently handling the", "except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res = yield func(self, *args, delete_existing=True,", "self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled ) deferreds.append(d) for room_id in partitioned:", "3, 5, 7, 10, 15, 20, 50, 100, 200, 500,", "do here return for event, context in events_and_contexts: if event.type", "= set() # Set of state groups we've already seen", "event) elif event.type == EventTypes.Message: # Insert into the event_search", "txn.execute(sql, (-last_id, -current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates) ==", "the filtered list. events_and_contexts = self._update_outliers_txn( txn, events_and_contexts=events_and_contexts ) #", "\"\"\" out = frozendict_json_encoder.encode(json_object) if isinstance(out, bytes): out = out.decode(\"utf8\")", "= Counter( \"synapse_storage_events_state_delta_single_event\", \"\" ) # The number of times", "being added to the room old_latest_event_ids (iterable[str]): the old forward", "= yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if len(new_state_groups) == 1: # If", "def _purge_history_txn(self, txn, room_id, token_str, delete_local_events): token = RoomStreamToken.parse(token_str) #", "for e_id in event.prev_event_ids() ) # Remove any events which", "from preserve_events\") res = yield self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map,", "metrics for events that change forward extremities # (e.g. we", "?\" txn.execute(sql, (False, event.event_id)) # Update the event_backward_extremities table now", "during the initial persistence of the send_join # results, in", "in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop(): try: queue =", "self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def _update_forward_extremities_txn( self, txn, new_forward_extremities, max_stream_order ):", "is only returned if we've already calculated it. \"\"\" #", "done\") def _find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used when purging history to", "return d self._simple_insert_many_txn( txn, table=\"event_json\", values=[ { \"event_id\": event.event_id, \"room_id\":", "Things reading from those table will need to check whether", "call to this function, it will return None. \"\"\" def", "we actually update the current_state_events table txn.executemany( \"DELETE FROM current_state_events\"", "the last item in the queue has the same `backfilled`", "event_stream_ordering\" \" AND event_stream_ordering >= ?\" \" ORDER BY event_stream_ordering", "event_id into the rejections table self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event) return", "logging etc events_context (list[(EventBase, EventContext)]): events and contexts which are", "db Args: events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): delete_existing (bool): Returns:", "(self.stream_ordering_day_ago,)) count, = txn.fetchone() return count ret = yield self.runInteraction(\"count_messages\",", "(-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows )", "old_latest_event_ids old_state_groups = set( event_id_to_state_group[evid] for evid in old_latest_event_ids )", "\" WHERE event_id = ?\" txn.execute(sql, (False, event.event_id)) # Update", "set(old_latest_event_ids) event_id_to_state_group = {} for event_id in new_latest_event_ids: # First", "if result != latest_event_ids: forward_extremities_counter.observe(len(result)) stale = latest_event_ids & result", "to determine if they're \"new\" events which might update the", "extremities. existing_prevs = yield self._get_prevs_before_rejected( e_id for event in new_events", "each room, a tuple (to_delete, to_insert), being a list of", "latest persisted event \"\"\" deferred = self._event_persist_queue.add_to_queue( event.room_id, [(event, context)],", "been soft-failed or rejected. Returns those soft failed/rejected events and", "= ?\" % (table,), [(ev.room_id, ev.event_id) for ev, _ in", "been a change, # and we need to work out", "# event's auth chain, but its easier for now just", "a lot faster. # create an index on should_delete because", "delta for that transition. If we do then we can", "event_id_to_state_group[event_id] = ctx.state_group break else: # If we couldn't find", "\"SELECT event_id, outlier FROM events WHERE event_id in (%s)\" %", ") continue if ctx.state_group in state_groups_map: continue # We're only", "NULL\" ) new_backwards_extrems = txn.fetchall() logger.info(\"[purge] replacing backward extremities: %r\",", "EventContext)]): backfilled (bool): delete_existing (bool): Returns: Deferred: resolves when the", "?\" \" ORDER BY stream_ordering DESC\" \" LIMIT ?\" )", "state groups, and if not we delete them. txn.execute( \"\"\"", "the rejected events from the list now that we've added", "of any of the new events result.difference_update( e_id for event", "If we're going from one state group to another, lets", "status to our workers. stream_order = event.internal_metadata.stream_ordering state_group_id = context.state_group", "is chosen to be the minimum of the stream_ids #", "def _update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update any outliers with new event", "events_and_contexts: if event.type == EventTypes.Redaction and event.redacts is not None:", "# Update backward extremeties txn.executemany( \"INSERT INTO event_backward_extremities (room_id, event_id)\"", "current_state_events. \"\"\" existing_state = yield self.get_current_state_ids(room_id) to_delete = [key for", "persist_event_counter.inc(len(chunk)) if not backfilled: # backfilled events have negative stream", "orderings, so we don't # want to set the event_persisted_position", "USING (event_id)\" \" LEFT JOIN redactions USING (event_id)\" \" LEFT", "event. forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of forward extremities for", ") if not events_and_contexts: # nothing to do here return", "the events from the database # otherwise we wouldn't be", ") @cached(num_args=5, max_entries=10) def get_all_new_events( self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id,", "or more than one day since the last call to", "outlier OR (%s)) AND e.room_id = ? AND topological_ordering <", "try: while True: yield queue.popleft() except IndexError: # Queue has", "groups, and if not we delete them. txn.execute( \"\"\" SELECT", "# purge attempt, so let's drop the table first. txn.execute(\"DROP", "0) FROM events WHERE type = 'm.room.message' AND stream_ordering >", "for ev_id in new_extrem ], ) # We now insert", "outlier in txn} to_remove = set() for event, context in", "= yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def persist_event(self, event, context,", "event twice. Pick the earliest non-outlier if there is one,", "state. new_forward_extremeties (dict[str, list[str]]): The new forward extremities for each", "list of tuples of (event, context) backfilled (bool): Whether the", "yet so we need to look at the events that", "prev_sg and prev_sg in to_delete: to_dedelta.add(sg) return to_delete, to_dedelta @defer.inlineCallbacks", "new_latest_event_ids ): \"\"\"Calculate the current state dict after adding some", "def _count_messages(txn): # This is good enough as if you", "state_key = ? ) \"\"\" txn.executemany( sql, ( ( stream_id,", "Copyright 2014-2016 OpenMarket Ltd # Copyright 2018-2019 New Vector Ltd", "then there has been a change, # and we need", "room_id, etype, state_key, ) for (etype, state_key), ev_id in iteritems(to_insert)", "queue has the same `backfilled` setting, # we can just", "less or more than one day since the last call", "backfilling? if hasattr(event, \"replaces_state\"): vals[\"prev_state\"] = event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\",", "to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def _store_redaction(self, txn, event): # invalidate", "table=\"state_groups_state\", values=[ { \"state_group\": sg, \"room_id\": room_id, \"type\": key[0], \"state_key\":", "ep USING (event_id) WHERE state_group IN (%s) AND ep.event_id IS", "event_rows = txn.fetchall() logger.info( \"[purge] found %i events before cutoff,", "old_latest_event_ids (iterable[str]): the old forward extremities for the room. new_latest_event_ids", "yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk ) defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self,", "We received a copy of an event that we had", "an index on should_delete because later we'll be looking for", "state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\", \"\" ) # The number of", "def get_all_updated_current_state_deltas_txn(txn): sql = \"\"\" SELECT stream_id, room_id, type, state_key,", "arguably those could both be moved in here) class EventsStore(", "it over federation) it will use the # forward extremities", "= \"\"\" SELECT event_id, prev_event_id, internal_metadata, rejections.event_id IS NOT NULL", "for one room at a time. Returns: tuple[list, dict] (to_delete,", "= self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled ) deferreds.append(d) for room_id in", "into stream_ordering_to_exterm a mapping from room_id, # new stream_ordering to", "that are referenced. current_search -= referenced rows = self._simple_select_many_txn( txn,", "event_id): res = yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id},", "# We don't continue iterating up the state group graphs", "this # event isn't an outlier any more. self._update_backward_extremeties(txn, [event])", "\" LEFT JOIN events_to_purge AS ep2 ON ed.event_id = ep2.event_id\"", "delta # If we have the current_state then lets prefill", "with the given persist_event options. NB: due to the normal", "if ev_type == EventTypes.Member ) for member in members_changed: txn.call_after(", "{event_id: outlier for event_id, outlier in txn} to_remove = set()", "400, \"topological_ordering is greater than forward extremeties\" ) logger.info(\"[purge] looking", "result.difference_update(existing_prevs) # Finally handle the case where the new events", "missing_event_ids = set(old_latest_event_ids) event_id_to_state_group = {} for event_id in new_latest_event_ids:", "not room_version: room_version = yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from preserve_events\")", "\"CREATE TEMPORARY TABLE events_to_purge (\" \" event_id TEXT NOT NULL,\"", "self._current_forward_extremities_amount = c_counter() BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1, 2, 3,", "None)) @defer.inlineCallbacks def _calculate_state_delta(self, room_id, current_state): \"\"\"Calculate the new state", "to send any events (due to not # having any", "those soft failed/rejected events and their prev events (whether soft-failed/rejected", "found %i events before cutoff, of which %i can be", "is one we're persisting, in which case we can #", "already have # the current state in memory then lets", "shovelling the list back and forth across the # connection.", "int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\": event.sender, \"contains_url\": ( \"url\" in event.content", "queue becomnes empty. The return value of the function will", "# The number of times we are reculating state when", "sg} ) self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn( txn,", "in event.content and isinstance(event.content[\"url\"], text_type) ), } for event, _", "need to remove them and their prev events, # otherwise", "we can use it to calculate the `prev_event_id`. (This #", "\"[purge] de-delta-ing %i remaining state groups\", len(remaining_state_groups), ) # Now", "current_state yield self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties,", "new_forward_extremeties (dict[str, list[str]]): The new forward extremities for each room.", "and returns the filtered list. events_and_contexts = self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts", "into the room_names and event_search tables. self._store_room_name_txn(txn, event) elif event.type", "Deferred[set[str]] \"\"\" # The set of event_ids to return. This", "a new event (as opposed # to receiving it over", "Counter, Histogram from twisted.internet import defer import synapse.metrics from synapse.api.constants", "rows) # We don't bother re-handling groups we've already seen", "in each room after adding these events. # This is", "for event, _ in events_and_contexts ], ) def _store_rejected_events_txn(self, txn,", ") txn.execute(sql, list(current_search)) referenced = set(sg for sg, in txn)", "\"event_id\": event.event_id, \"room_id\": event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)),", "\"state_key\": event.state_key, } # TODO: How does this work with", "Otherwise we need to pull the state group from the", "? > stream_ordering AND stream_ordering >= ?\" \" ORDER BY", "state_groups_seen - referenced_groups to_dedelta = set() for sg in referenced_groups:", ") logger.info( \"[purge] de-delta-ing %i remaining state groups\", len(remaining_state_groups), )", "the batch of the events that we are persisting; that", "\"deferred\") ) def __init__(self): self._event_persist_queues = {} self._currently_persisting_rooms = set()", "( \"events\", \"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\", ):", "txn.execute( \"CREATE INDEX events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\" ) # We", "were the same when we created the event as they", "are being added. Used for logging etc events_context (list[(EventBase, EventContext)]):", "certain point Args: room_id (str): token (str): A topological token", "build a temporary table listing the events so that we", "Ensure that we don't have the same event twice. events_and_contexts", "only added or replaced state, never # removed keys entirely.", "prev events. existing_prevs = set() def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check =", "= yield per_item_callback(item) except Exception: with PreserveLoggingContext(): item.deferred.errback() else: with", "outlier_persisted = have_persisted[event.event_id] if not event.internal_metadata.is_outlier() and outlier_persisted: # We", "persisting all_events_and_contexts (list[(EventBase, EventContext)]): all events that we were going", "to filter Returns: Deferred[List[str]]: filtered event ids \"\"\" results =", "just to store them (and # it doesn't take much", "= stream chunks = [ events_and_contexts[x : x + 100]", "type/state_keys to remove from current_state_events and `to_insert` are the updates", "which were # rejected, and returns the filtered list. events_and_contexts", "that has already # been cached in the context. We'll", "else: upper_bound = current_forward_id sql = ( \"SELECT event_stream_ordering, event_id,", "# unnecessarily). # # The stream_id for the update is", "them as outliers and deleting their state groups). \"\"\" return", "-self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The current maximum token that events have", "def get_all_updated_current_state_deltas(self, from_token, to_token, limit): def get_all_updated_current_state_deltas_txn(txn): sql = \"\"\"", "stream orderings, so we don't # want to set the", "of the stream_ids # for the batch of the events", "remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining state group %s\", sg) curr_state =", "= yield self._get_prevs_before_rejected( e_id for event in new_events for e_id", "LIKE ? AND stream_ordering > ? \"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago))", "if e[1]), ) logger.info(\"[purge] Finding new backward extremities\") # We", "deferreds waiting on the item, exceptions will be passed to", "a Deferred and accepts a `delete_existing` arg \"\"\" @wraps(func) @defer.inlineCallbacks", "= \"%:\" + self.hs.hostname sql = \"\"\" SELECT COALESCE(COUNT(*), 0)", "for table in ( \"events\", \"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\",", "rest of our transaction. # # So, let's stick it", "# noqa: F401 from synapse.events.snapshot import EventContext # noqa: F401", "were rejected Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]):", "into ex-outliers (unless the new event was rejected). Args: txn", "x in range(0, len(events_and_contexts), 100) ] for chunk in chunks:", "not # end up in a situation where workers see", "figure out which state groups can be deleted and which", "in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth) def _update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update", ") defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed ancestors to", "various caches # Figure out the changes of membership to", ") def _store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add rows to the 'rejections'", "be deleted. Returns: tuple[set[int], set[int]]: The set of state groups", "seen before. if delete_existing: # For paranoia reasons, we go", "calculated the state for an event we were # persisting.", "NULL \"\"\" % ( \",\".join(\"?\" for _ in current_search), )", "(room_id, event_id)\" \" VALUES (?, ?)\", [(room_id, event_id) for event_id,", "200, 500, \"+Inf\"], ) # Read the extrems every 60", "= self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled ) #", "defer.returnValue((new_state, delta_ids)) # Now that we have calculated new_state_groups we", "# map room_id->(to_delete, to_insert) where to_delete is a list #", "removed keys entirely. state_delta_for_room[room_id] = ([], delta_ids) elif current_state is", "yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def", "%d\", min_depth) txn.execute( \"UPDATE room_depth SET min_depth = ? WHERE", "that need to be de-delta'ed \"\"\" # Graph of state", "state in memory then lets also return that, # but", ") # Remove any events which are prev_events of any", "e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \" FROM events", "not None: # We have a delta from the existing", "table=\"current_state_events\", values=[ { \"event_id\": ev_id, \"room_id\": room_id, \"type\": key[0], \"state_key\":", "connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting Returns: list[(EventBase,", "prevs -= state_groups_seen next_to_search |= prevs state_groups_seen |= prevs for", "or agreed to in writing, software # distributed under the", "EventFederationStore from synapse.storage.events_worker import EventsWorkerStore from synapse.storage.state import StateGroupWorkerStore from", "no more soft-failed/rejected events. This is used to find extremities", "if we do know the delta then the new current", "pulling out state that has already # been cached in", "txn.execute( \"UPDATE events SET outlier = ?\" \" WHERE event_id", "\" WHERE ? > event_stream_ordering\" \" AND event_stream_ordering >= ?\"", "origin_entity = context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type = \"local\" origin_entity =", "those that were in the previous set of extremities as", "event (as opposed # to receiving it over federation) it", "prev events, # otherwise we end up with dangling extremities.", "we're # currently trying to persist it. room_version = None", "# persisting. state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" ) # The", "so lets just return that. If we happen to already", "state_values = [] for event, context in state_events_and_contexts: vals =", "e.event_id as event_id, \" \" r.redacts as redacts,\" \" rej.event_id", "are only persisting events for one room at a time.", "contexts which are being added to the room old_latest_event_ids (iterable[str]):", "under the License. import itertools import logging from collections import", "for each room Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase,", "whether the event was rejected. Args: txn (twisted.enterprise.adbapi.Connection): db connection", "self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None)) @defer.inlineCallbacks", "if have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit)) new_backfill_events = txn.fetchall() if", "and if not we delete them. txn.execute( \"\"\" SELECT DISTINCT", "\"\"\" depth_updates = {} for event, context in events_and_contexts: #", "set() for event, context in events_and_contexts: if event.event_id not in", "looking at the prev_events and checking # if they match", "all_events_and_contexts (list[(EventBase, EventContext)]): all events that we were going to", "mappings for rejected events, as they're # used in state", "_find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used when purging history to figure out", "a background process to make sure that the database transactions", "self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order, \"event_id\": event.event_id, \"state_group\": state_group_id,", "def _retry_on_integrity_error(func): \"\"\"Wraps a database function so that it gets", "those users. members_changed = set( state_key for ev_type, state_key in", "# Note: Each state group can have at most one", "new events we're adding. for ev, ctx in events_context: if", "Args: events_and_contexts: list of tuples of (event, context) backfilled (bool):", "the database. This is useful when retrying due to IntegrityError.", "_get_prevs_before_rejected_txn(txn, batch): to_recursively_check = batch while to_recursively_check: sql = \"\"\"", "# Figure out the changes of membership to invalidate the", "forward_extremities_counter.observe(len(result)) stale = latest_event_ids & result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def", "event_ids to get those which are prev_events of existing (non-outlier/rejected)", "if queue: # if the last item in the queue", "keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[ {\"event_id\":", "to ((type, key) -> event_id) state map state_groups_map = {}", "there will be no existing # extremities, so we'll `continue`", "1: state_delta_single_event_counter.inc() # This is a fairly handwavey check to", "< stream_id AND stream_id <= ? ORDER BY stream_id ASC", "callbacks *without* a logcontext. \"\"\" queue = self._event_persist_queues.setdefault(room_id, deque()) if", "current state dict after adding some new events to a", "temp table. this will commit the txn in sqlite, #", "IS NULL\" should_delete_params = () if not delete_local_events: should_delete_expr +=", "these events so we can reinsert them. # This gets", "from event_forward_extremities group by room_id \"\"\" ) return txn.fetchall() res", "-*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018-2019 New", "both are None then there has been no change. If", "# State groups of new_latest_event_ids new_state_groups = set( event_id_to_state_group[evid] for", "to be added to the current state. new_forward_extremeties (dict[str, list[str]]):", "room_id) with Measure( self._clock, \"persist_events.get_new_state_after_events\" ): res = yield self._get_new_state_after_events(", "_ in batch), ) txn.execute(sql, batch) results.extend(r[0] for r in", "match the current forward extremities. for ev, _ in ev_ctx_rm:", "AND event_id NOT LIKE ?\" # We include the parameter", "on # (room_id, event_id) instead. for table in (\"event_push_actions\",): logger.info(\"[purge]", "long chain of single ancestor non-state events. if all_single_prev_not_state: continue", "events, but are separated by soft failed events. Args: event_ids", "skip this bit.) assert new_latest_event_ids, \"No forward extremities left!\" new_forward_extremeties[room_id]", "LEFT JOIN event_relations USING (event_id)\" \" WHERE ? > stream_ordering", "If we do then we can just # return that.", "the number of forward extremities that exist. # Counter of", "defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def persist_event(self, event, context, backfilled=False): \"\"\" Args:", "current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids # We need", "state # groups to purge, etc., so lets make an", "\"\"\" Args: event (EventBase): context (EventContext): backfilled (bool): Returns: Deferred:", "in new_events for e_id in event.prev_event_ids() ) # Remove any", "events_and_contexts if ec[0] not in to_remove] @classmethod def _delete_existing_rows_txn(cls, txn,", "do then we can just # return that. new_state_group =", "# redacted event. self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts ) # Remove", "try: self._store_event_state_mappings_txn(txn, ((event, context),)) except Exception: logger.exception(\"\") raise metadata_json =", "range from canonicaljson import json from prometheus_client import Counter, Histogram", "current_state): \"\"\"Calculate the new state deltas for a room. Assumes", "of state groups to handle next. next_to_search = set(state_groups) while", "len(event.prev_event_ids()) == 1 and not event.is_state() for event, ctx in", "to_insert ), ) txn.executemany( sql, ( ( stream_id, room_id, etype,", "server creates a new event (as opposed # to receiving", "events # rejections # room_depth # state_groups # state_groups_state #", "= () if not delete_local_events: should_delete_expr += \" AND event_id", "e.event_id = f.event_id \" \"AND e.room_id = f.room_id \" \"WHERE", "(%s) AND NOT events.outlier \"\"\" % ( \",\".join(\"?\" for _", "persisting. state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" ) # The number", "and the stream ordering of the latest persisted event \"\"\"", "txn.call_after(self._invalidate_get_event_cache, event.event_id) if not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, )", "make sure that the database transactions # have a logcontext", "event.event_id, \"room_id\": event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)), \"format_version\":", "# is a map (type,key)->event_id giving the state delta in", "event, _ in events_and_contexts for auth_id in event.auth_event_ids() if event.is_state()", "backfilled (bool): True if the events were backfilled \"\"\" depth_updates", "limit): if last_id == current_id: return defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql", "{ \"event_id\": ev_id, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], }", "events to the list result.update(event.event_id for event in new_events) #", "def get_all_new_events_txn(txn): sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\"", "be passed to the deferreds as well. This function should", "dict state_group_deltas = {} for ev, ctx in events_context: if", "of (event, context) backfilled (bool): Whether the results are retrieved", "a logcontext. \"\"\" queue = self._event_persist_queues.setdefault(room_id, deque()) if queue: #", "relations table. self._handle_redaction(txn, event.redacts) # Update the event_forward_extremities, event_backward_extremities and", "when # processing one of these events. # What we're", "members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def _update_forward_extremities_txn(", "event as they are # now. When this server creates", "} for room_id, new_extrem in iteritems(new_forward_extremities) for event_id in new_extrem", "set of state groups that can be deleted and the", "table and event_search table. self._store_room_topic_txn(txn, event) elif event.type == EventTypes.Message:", "from the extremities. Given a set of events, find all", "already seen prevs -= state_groups_seen next_to_search |= prevs state_groups_seen |=", "will be invoked with for each item in the queue,", "\"\"\" SELECT prev_event_id, internal_metadata FROM event_edges INNER JOIN events USING", "chunk ) defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed ancestors", "@defer.inlineCallbacks def count_daily_active_rooms(self): def _count(txn): sql = \"\"\" SELECT COALESCE(COUNT(DISTINCT", "as nothing will happen to them. txn.execute( \"INSERT INTO events_to_purge\"", "`delete_existing=True` passed in. Args: func: function that returns a Deferred", "existing\") for table in ( \"events\", \"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\",", "\"\"\" new_events_and_contexts = OrderedDict() for event, context in events_and_contexts: prev_event_context", "for event, context in chunk: if context.app_service: origin_type = \"local\"", "event_id)\" \" VALUES (?, ?)\", [(room_id, event_id) for event_id, in", ") self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[ { \"event_id\": ev_id, \"room_id\": room_id,", "in outlier status to our workers. stream_order = event.internal_metadata.stream_ordering state_group_id", "res)) @defer.inlineCallbacks def persist_events(self, events_and_contexts, backfilled=False): \"\"\" Write events to", "@defer.inlineCallbacks def count_daily_sent_messages(self): def _count_messages(txn): # This is good enough", "the new events to the list result.update(event.event_id for event in", "\"processed\": True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\": event.sender,", "event_push_actions lacks an index on event_id, and has one on", "find out which membership events we may have deleted #", "language governing permissions and # limitations under the License. import", "room_id->(to_delete, to_insert) where to_delete is a list # of type/state", "= frozendict_json_encoder.encode(json_object) if isinstance(out, bytes): out = out.decode(\"utf8\") return out", "Insert all the push actions into the event_push_actions table. self._set_push_actions_for_event_and_users_txn(", "in iteritems(new_forward_extremities) for ev_id in new_extrem ], ) # We", "FROM events AS e\" \" LEFT JOIN redactions USING (event_id)\"", "( \"events\", \"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\",", "in to_remove] def _update_metadata_tables_txn( self, txn, events_and_contexts, all_events_and_contexts, backfilled ):", "50, 100, 200, 500, \"+Inf\"], ) # Read the extrems", "We do joins against events_to_purge for e.g. calculating state #", "def _update_current_state_txn(self, txn, state_delta_by_room, stream_id): for room_id, current_state_tuple in iteritems(state_delta_by_room):", "extremities as the prev_events, so we can # guess this", "(EventContext): backfilled (bool): Returns: Deferred: resolves to (int, int): the", "events result.difference_update( e_id for event in new_events for e_id in", "= state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) # Now that we have calculated", "ON ed.event_id = ep2.event_id\" \" WHERE ep2.event_id IS NULL\" )", "key[0], \"state_key\": key[1], } for key, ev_id in iteritems(to_insert) ],", "be able to send any events (due to not #", "upper_bound = new_backfill_events[-1][0] else: upper_bound = current_backfill_id sql = (", ":( # NB: Assumes that we are only persisting events", "Exception: logger.exception(\"\") raise metadata_json = encode_json(event.internal_metadata.get_dict()) sql = ( \"UPDATE", "5, 7, 10, 15, 20, 50, 100, 200, 500, \"+Inf\"],", "arg \"\"\" @wraps(func) @defer.inlineCallbacks def f(self, *args, **kwargs): try: res", "return new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self, last_id,", "_update_backward_extremities # and _handle_mult_prev_events (though arguably those could both be", "out which state groups can be deleted and which need", "table=\"state_group_edges\", keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[ { \"state_group\":", "event_id = ?\" % (table,), [(ev.room_id, ev.event_id) for ev, _", "\" WHERE room_id = ? AND type = ? AND", "passed in. Args: func: function that returns a Deferred and", "event_id, %s\" \" FROM events AS e LEFT JOIN state_events", "next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group, new_state_group), None) if", "e.room_id, e.type,\" \" state_key, redacts\" \" FROM events AS e\"", "the event is rejected then we don't care if the", "insert events that are outliers and aren't going to be", "their prev events (whether soft-failed/rejected or not), and recurses up", "for room_id, latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) ) @defer.inlineCallbacks", "== latest_event_ids: # No change in extremities, so no change", "and checking # if they match the current forward extremities.", "= set(state_groups) while next_to_search: # We bound size of groups", "not events_and_contexts: # nothing to do here return for event,", "internal_metadata FROM event_edges INNER JOIN events USING (event_id) LEFT JOIN", ") for event, context in chunk: if context.app_service: origin_type =", "state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids #", "\" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers", "event.sender, \"contains_url\": ( \"url\" in event.content and isinstance(event.content[\"url\"], text_type) ),", "def _count_messages(txn): sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM events", "prevs state_groups_seen |= prevs for row in rows: # Note:", "\"DELETE FROM %s WHERE event_id IN (\" \" SELECT event_id", "\"\"\" queue = self._event_persist_queues.setdefault(room_id, deque()) if queue: # if the", "events from the list now that we've added them #", "delta when we calculated the state for an event we", "replaced state, never # removed keys entirely. state_delta_for_room[room_id] = ([],", "return logger.info(\"Deleting existing\") for table in ( \"events\", \"event_auth\", \"event_json\",", "off in the background run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self, room_id): queue", "INTO current_state_delta_stream (stream_id, room_id, type, state_key, event_id, prev_event_id) SELECT ?,", "# Add an entry to the ex_outlier_stream table to replicate", "\"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk ) defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids): \"\"\"Get", "= set() def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check = batch while to_recursively_check:", "event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if not events_and_contexts:", "return for event, context in events_and_contexts: if event.type == EventTypes.Redaction", "forward extremities. for ev, _ in ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids())", "\"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count, = txn.fetchone() return count ret =", "report to return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60 *", "d = self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled ) deferreds.append(d) for room_id", "txn if not json.loads(r[1]).get(\"soft_failed\")) for chunk in batch_iter(event_ids, 100): yield", "= event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) # Prefill the event", "called whenever anything is added to the queue. If another", "(\"events_and_contexts\", \"backfilled\", \"deferred\") ) def __init__(self): self._event_persist_queues = {} self._currently_persisting_rooms", "the latest persisted event \"\"\" partitioned = {} for event,", "eb INNER JOIN event_edges AS eg ON eg.prev_event_id = eb.event_id", "new events to a room Args: room_id (str): room to", "the events are only ones that weren't # rejected. self._update_metadata_tables_txn(", "events which might update the current state etc. Returns: Deferred[int]:", "ev, _ in events_and_contexts], ) for table in (\"event_push_actions\",): txn.executemany(", ") AllNewEventsResult = namedtuple( \"AllNewEventsResult\", [ \"new_forward_events\", \"new_backfill_events\", \"forward_ex_outliers\", \"backward_ex_outliers\",", "state groups referenced by events that are going to be", "JOIN state_events USING (event_id)\" \" LEFT JOIN event_relations USING (event_id)\"", "this by calculating the minimum depth of the backwards #", "Unless required by applicable law or agreed to in writing,", "if ctx.state_group is None: # This should only happen for", "txn.execute( \"DELETE FROM event_backward_extremities WHERE room_id = ?\", (room_id,) )", "Deferred[int]: the stream ordering of the latest persisted event \"\"\"", "\" WHERE NOT should_delete\" \")\", (True,), ) # synapse tries", "synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils import log_function from synapse.util.metrics", "event.type == EventTypes.GuestAccess: # Insert into the event_search table. self._store_guest_access_txn(txn,", "txn.executemany( \"DELETE FROM state_groups_state WHERE state_group = ?\", ((sg,) for", "(to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id): res = yield self._simple_select_one(", "txn.execute(\"SELECT event_id, should_delete FROM events_to_purge\") event_rows = txn.fetchall() logger.info( \"[purge]", "**kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res = yield func(self, *args,", "forth across the # connection. Annoyingly the python sqlite driver", "each new event. forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of forward", "ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers =", "have a delta from the existing to new current state,", "self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000) @defer.inlineCallbacks def", "for event_id, _ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete all", "has already # been cached in the context. We'll pull", "to the current_state_delta_stream. We # do this before updating the", "( stream_id, room_id, etype, state_key, None, room_id, etype, state_key, )", "to_insert = current_state_tuple # First we add entries to the", "Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]: Returns a tuple of two", "\"remote\" origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc() for room_id, new_state", "events USING (event_id) LEFT JOIN rejections USING (event_id) LEFT JOIN", "count ret = yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self):", "(bool): if True, we will delete local events as well", "so_1) > (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id): res =", "already have the table from a previous (failed) # purge", "and a state set to be added to the current", "events so we can reinsert them. # This gets around", "\"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000) @defer.inlineCallbacks", "events_and_contexts=events_and_contexts, backfilled=backfilled ) # _update_outliers_txn filters out any events which", "to be in events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group = {}", "unchanged forward extremities for each new event\", buckets=(0, 1, 2,", "event.type, \"processed\": True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\":", "that are pointed to by events we're not going to", "that are ancestors of new events, but are separated by", "list of type/state keys to be removed from the current", "the database. # Set of events we need to fetch", ") # The number of forward extremities for each new", "if key not in current_state] to_insert = { key: ev_id", "in events_and_contexts: if event.type == EventTypes.Redaction and event.redacts is not", "?\", (room_id,) ) # Update backward extremeties txn.executemany( \"INSERT INTO", "take much storage compared to storing the entire event #", "redacts,\" \" rej.event_id as rejects \" \" FROM events as", "FROM ex_outlier_stream\" \" WHERE ? > event_stream_ordering\" \" AND event_stream_ordering", "WHERE eb.room_id = ? \"\"\", (room_id,), ) min_depth, = txn.fetchone()", "> ? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count, = txn.fetchone() return count", "room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None)) @defer.inlineCallbacks def", "\"\"\" % ( \",\".join(\"?\" for _ in batch), ) txn.execute(sql,", "def handle_queue_loop(): try: queue = self._get_drainining_queue(room_id) for item in queue:", "trying to persist it. room_version = None for ev, _", "= {} # Set of events that we have found", "before updating the current_state_events table so # that we can", "? AND type = ? AND state_key = ?\", (", "logging from collections import Counter as c_counter, OrderedDict, deque, namedtuple", "= ? AND type = ? AND state_key = ?\",", "{ \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\": event.depth, \"event_id\": event.event_id, \"room_id\":", "to delete\") should_delete_expr = \"state_key IS NULL\" should_delete_params = ()", "the room. new_latest_event_ids (iterable[str]): the new forward extremities for the", "event is one we're persisting, in which case we can", "events have soft-failed prev # events. If they do we", "which are being added to the room old_latest_event_ids (iterable[str]): the", "added to the queue. If another callback is currently handling", "if the events were backfilled \"\"\" # Insert all the", "etype, state_key, ev_id, room_id, etype, state_key, ) for (etype, state_key),", "current_state_delta_stream (stream_id, room_id, type, state_key, event_id, prev_event_id) SELECT ?, ?,", "Stale extremities # are those that were in the previous", "room new_forward_extremeties = {} # map room_id->(type,state_key)->event_id tracking the full", "if not have_backfill_events and not have_forward_events: return defer.succeed(AllNewEventsResult([], [], [],", "room_id = ?\", (min_depth, room_id), ) # finally, drop the", "include the parameter twice since we use the expression twice", "{ \"event_id\": event.event_id, \"room_id\": event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict() ), \"json\":", "{} # map room_id->(to_delete, to_insert) where to_delete is a list", "[] return AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers, backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\",", "[]).append((event, ctx)) deferreds = [] for room_id, evs_ctxs in iteritems(partitioned):", "we're looking up at once, to stop the # SQL", "ex_outlier_stream table to replicate the # change in outlier status", "for chunk in chunks: # We can't easily parallelize these", "= set() def add_to_queue(self, room_id, events_and_contexts, backfilled): \"\"\"Add events to", "BackgroundUpdateStore from synapse.storage.event_federation import EventFederationStore from synapse.storage.events_worker import EventsWorkerStore from", "import cached, cachedInlineCallbacks from synapse.util.frozenutils import frozendict_json_encoder from synapse.util.logcontext import", "ev_ctx_rm, latest_event_ids ) latest_event_ids = set(latest_event_ids) if new_latest_event_ids == latest_event_ids:", "if delta_ids is not None: # If there is a", "= self._event_persist_queues.pop(room_id, None) if queue: self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id) #", "event_id, outlier in txn} to_remove = set() for event, context", "You may obtain a copy of the License at #", "Insert into the topics table and event_search table. self._store_room_topic_txn(txn, event)", "for row in rows: event = ev_map[row[\"event_id\"]] if not row[\"rejects\"]", "# nothing to do here return for event, context in", "(int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self, from_token, to_token, limit): def get_all_updated_current_state_deltas_txn(txn):", "synapse.storage.background_updates import BackgroundUpdateStore from synapse.storage.event_federation import EventFederationStore from synapse.storage.events_worker import", "invalidate the # `get_rooms_for_user` cache. # We find out which", "\"\"\" # Insert all the push actions into the event_push_actions", "Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged forward extremities for each new", "existing_prevs.add(prev_event_id) for chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn,", "new event\", buckets=(0, 1, 2, 3, 5, 7, 10, 15,", "Given a set of events, find all those that have", "to_recursively_check) to_recursively_check = [] for event_id, prev_event_id, metadata, rejected in", "a previous (failed) # purge attempt, so let's drop the", "room_id, ev_ctx_rm, latest_event_ids ) latest_event_ids = set(latest_event_ids) if new_latest_event_ids ==", "Counter(\"synapse_storage_events_state_delta\", \"\") # The number of times we are recalculating", "We don't continue iterating up the state group graphs for", "be referenced by events referenced_groups = set() # Set of", "where to_delete is a list # of type/state keys to", "@defer.inlineCallbacks def _calculate_state_delta(self, room_id, current_state): \"\"\"Calculate the new state deltas", "results = [] def _get_events_which_are_prevs_txn(txn, batch): sql = \"\"\" SELECT", "the entries in the event_push_actions table for the # redacted", "new events or as backfilled events\"\"\" have_backfill_events = last_backfill_id !=", "origin_entity).inc() for room_id, new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for room_id,", "if not event.internal_metadata.is_outlier() and outlier_persisted: # We received a copy", "any backwards extremeties) raise SynapseError( 400, \"topological_ordering is greater than", "current_state_events table so # that we can use it to", "extremities that are ancestors of new events, but are separated", "ids which are the forward extremities. \"\"\" all_events_and_contexts = events_and_contexts", "def _delete_existing_rows_txn(cls, txn, events_and_contexts): if not events_and_contexts: # nothing to", "= txn.fetchall() else: new_backfill_events = [] backward_ex_outliers = [] return", "also possible that we're # currently trying to persist it.", "to see if we could # have guessed what the", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= delta # If we have the current_state then lets", "that we can call _update_backward_extremities # and _handle_mult_prev_events (though arguably", "make_deferred_yieldable from synapse.util.logutils import log_function from synapse.util.metrics import Measure logger", "sql = ( \"SELECT \" \" e.event_id as event_id, \"", "event.format_version, } for event, _ in events_and_contexts ], ) self._simple_insert_many_txn(", "[] rows = [] N = 200 for i in", "e.event_id = r.redacts\" \" WHERE e.event_id IN (%s)\" ) %", "room_id, \"type\": key[0], \"state_key\": key[1], } for key, ev_id in", ") # The number of stale forward extremities for each", "the events are persisted. Runs its callbacks *without* a logcontext.", "NULL \"\"\" % ( \",\".join(\"?\" for _ in batch), )", "in itertools.chain(to_delete, to_insert) if ev_type == EventTypes.Member ) for member", "list back and forth across the # connection. Annoyingly the", "that # so we need to update the state_groups table", ") new_latest_event_ids = yield self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids ) latest_event_ids", "one forward extremity. # (except during the initial persistence of", "\"\"\" # we're only interested in new events which aren't", "self._clock, \"persist_events.get_new_state_after_events\" ): res = yield self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids,", "existing table rows for the events from the database. This", "0) FROM event_backward_extremities AS eb INNER JOIN event_edges AS eg", "necessary database tables. Rejected events are only inserted into the", "def purge_history(self, room_id, token, delete_local_events): \"\"\"Deletes room history before a", "and which aren't # being rejected. new_events = [ event", "iteritems(partitioned): d = self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled ) deferreds.append(d) for", "with it. if current_state is not None: current_state_for_room[room_id] = current_state", "in events_and_contexts ], ) def _store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add rows", "except Exception: with PreserveLoggingContext(): item.deferred.errback() else: with PreserveLoggingContext(): item.deferred.callback(ret) finally:", "IN (\" \" SELECT event_id FROM events_to_purge \" \" WHERE", "_count_messages(txn): sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM events WHERE", "@defer.inlineCallbacks def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids): \"\"\"Calculates the new forward", "silly characters in your own # hostname then thats your", "USING (event_id) LEFT JOIN event_json USING (event_id) WHERE prev_event_id IN", "e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \" FROM", "state groups that can be deleted and the set of", "given stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[ { \"room_id\": room_id, \"event_id\":", "change in extremities, so no change in state continue #", "(min_depth, room_id), ) # finally, drop the temp table. this", "event_id, in new_backwards_extrems], ) logger.info(\"[purge] finding redundant state groups\") #", "events. Args: event_ids (Iterable[str]): Events to find prev events for.", "stream_ordering > ? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count, = txn.fetchone() return", "in iteritems(to_insert) ), ) # Now we actually update the", "results, in which case there will be no existing #", "\" r.redacts as redacts,\" \" rej.event_id as rejects \" \"", "\"WHERE f.room_id = ?\", (room_id,), ) rows = txn.fetchall() max_depth", "state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) # Now that we have calculated new_state_groups", "for e in event_rows if e[1]), ) logger.info(\"[purge] Finding new", "query getting too big if len(next_to_search) < 100: current_search =", "events WHERE event_id in (%s)\" % (\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id", "self._store_room_message_txn(txn, event) elif event.type == EventTypes.Redaction: # Insert into the", "# hostname then thats your own fault. like_clause = \"%:\"", "to one of its prev groups being scheduled for deletion).", "either as new events or as backfilled events\"\"\" have_backfill_events =", "from_token, to_token, limit): def get_all_updated_current_state_deltas_txn(txn): sql = \"\"\" SELECT stream_id,", "Work out the new \"current state\" for each room. #", "# We need to map the event_ids to their state", "event, ctx in ev_ctx_rm ) # Don't bother calculating state", "ctx.get_cached_current_state_ids() if current_state_ids is not None: state_groups_map[ctx.state_group] = current_state_ids if", "DB event_to_groups = yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups of", "ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids # We need to map", "as rejects \" \" FROM events as e\" \" LEFT", "prev_event_id) SELECT ?, ?, ?, ?, ?, ( SELECT event_id", "forward extremities for each new event\", buckets=(0, 1, 2, 3,", "# What we're interested in is if the latest extremities", "= ( \"SELECT -event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \"", "for each room. # We do this by working out", "limit: upper_bound = new_event_updates[-1][0] else: upper_bound = current_id sql =", "( \",\".join(\"?\" for _ in batch), ) txn.execute(sql, batch) results.extend(r[0]", "which case we can # pull the state group from", "= set(latest_event_ids) # add all the new events to the", "forward extremities for each new event. forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\",", "\")\" % (table,) ) # event_push_actions lacks an index on", "self._get_event_ordering(event_id1) to_2, so_2 = yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) > (to_2,", "forward_ex_outliers = [] sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id,", "WHERE ep2.event_id IS NULL\" ) new_backwards_extrems = txn.fetchall() logger.info(\"[purge] replacing", "limit: upper_bound = new_backfill_events[-1][0] else: upper_bound = current_backfill_id sql =", "which have already been # persisted, and returns the filtered", "the new current state is only returned if we've already", "events or as backfilled events\"\"\" have_backfill_events = last_backfill_id != current_backfill_id", "as c_counter, OrderedDict, deque, namedtuple from functools import wraps from", ") logger.info(\"[purge] removing events from event_to_state_groups\") txn.execute( \"DELETE FROM event_to_state_groups", "groups of old_latest_event_ids old_state_groups = set( event_id_to_state_group[evid] for evid in", "AND rejections.event_id IS NULL \"\"\" % ( \",\".join(\"?\" for _", "to delete events before delete_local_events (bool): if True, we will", "(Iterable[str]): Events to find prev events for. Note that these", "_update_forward_extremities_txn( self, txn, new_forward_extremities, max_stream_order ): for room_id, new_extrem in", "\"_calculate_state_and_extrem\"): # Work out the new \"current state\" for each", "VALUES (?, ?)\", [(room_id, event_id) for event_id, in new_backwards_extrems], )", "\"type\": key[0], \"state_key\": key[1], \"event_id\": state_id, } for key, state_id", "# Now that we have calculated new_state_groups we need to", "Set of events we need to fetch groups for. (We", "member in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn, room_id, members_changed)", "time. # map room_id->list[event_ids] giving the new forward # extremities", "state # groups to non delta versions. for sg in", "else: new_events_and_contexts[event.event_id] = (event, context) return list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn,", "ordering of the latest persisted event \"\"\" deferred = self._event_persist_queue.add_to_queue(", "# transaction on CREATE, so let's do this first. #", "event_backward_extremities and # event_edges tables. self._handle_mult_prev_events( txn, events=[event for event,", "event_persisted_position to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for event, context in", "distributed under the License is distributed on an \"AS IS\"", "txn, events_and_contexts, all_events_and_contexts, backfilled ): \"\"\"Update all the miscellaneous tables", "prev_event_ids = set(ev.prev_event_ids()) if latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating", "event_relations USING (event_id)\" \" WHERE ? < stream_ordering AND stream_ordering", "The number of times we are reculating state when we", "for event in new_events for e_id in event.prev_event_ids() ) result.difference_update(existing_prevs)", "# We have a delta from the existing to new", "JOIN event_relations USING (event_id)\" \" WHERE ? > event_stream_ordering\" \"", "backfilled): \"\"\"Add events to the queue, with the given persist_event", "in the database, but its also possible that we're #", "None) if delta_ids is not None: # We have a", "True to purge existing table rows for the events from", "event in new_events for e_id in event.prev_event_ids() ) result.difference_update(existing_prevs) #", "table for the # redacted event. self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts", "been significantly less or more than one day since the", "of single ancestor non-state events. if all_single_prev_not_state: continue state_delta_counter.inc() if", "given callback will be invoked with for each item in", "USING (event_id)\" \" WHERE (NOT outlier OR (%s)) AND e.room_id", "raise SynapseError( 400, \"topological_ordering is greater than forward extremeties\" )", "a map (type,key)->event_id giving the state delta in each #", "been calculated. Conversely if we do know the delta then", "for evid in old_latest_event_ids ) # State groups of new_latest_event_ids", "(last_id, current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates) == limit:", "this actually last. txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self,", "of the function will be given to the deferreds waiting", "and event.redacts is not None: # Remove the entries in", "\" ORDER BY stream_ordering ASC\" \" LIMIT ?\" ) if", "?\" ) txn.execute(sql, (metadata_json, event.event_id)) # Add an entry to", "that can be deleted\") _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups", "lot faster. # create an index on should_delete because later", "to (int, int): the stream ordering of ``event``, and the", "delta if its already been calculated. Conversely if we do", "with PreserveLoggingContext(): item.deferred.errback() else: with PreserveLoggingContext(): item.deferred.callback(ret) finally: queue =", "or as backfilled events\"\"\" have_backfill_events = last_backfill_id != current_backfill_id have_forward_events", "event.internal_metadata.is_outlier() and not ctx.rejected and not event.internal_metadata.is_soft_failed() ] latest_event_ids =", "# map from state_group to ((type, key) -> event_id) state", "synapse.metrics import BucketCollector from synapse.metrics.background_process_metrics import run_as_background_process from synapse.state import", "and the rejections table. Things reading from those table will", "we haven't # seen before. if delete_existing: # For paranoia", "# event_reference_hashes # event_search # event_to_state_groups # events # rejections", "event_edges # event_forward_extremities # event_json # event_push_actions # event_reference_hashes #", "are not None then there has been a change, #", "min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn(", "= (event, context) else: new_events_and_contexts[event.event_id] = (event, context) return list(new_events_and_contexts.values())", "state_groups_to_delete, remaining_state_groups = _ logger.info( \"[purge] found %i state groups", "f # inherits from EventFederationStore so that we can call", "once we run this update, we # will block that", "groups referenced by events that are going to be deleted.", "state that has already # been cached in the context.", "already calculated it. \"\"\" # map from state_group to ((type,", "() if not delete_local_events: should_delete_expr += \" AND event_id NOT", "events to a room Args: room_id (str): room to which", "type = 'm.room.message' AND sender LIKE ? AND stream_ordering >", "get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc() for room_id, new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,),", "= txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret)", "the existing entries # for these events so we can", "not), and recurses up the prev-event graph until it finds", "* len(ev_map)),) txn.execute(sql, list(ev_map)) rows = self.cursor_to_dict(txn) for row in", "chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk )", "count, = txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_sent_messages\", _count_messages)", "for key, ev_id in iteritems(to_insert) ], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id,", "= hs.get_state_resolution_handler() # Collect metrics on the number of forward", "First ensure that we're not about to delete all the", "has the same `backfilled` setting, # we can just add", "current state in memory then lets also return that, #", "the events_json table. to_remove = set() for event, context in", "deleted. We then go and check if they are referenced", "\"event_id\": event_id, \"stream_ordering\": max_stream_order, } for room_id, new_extrem in iteritems(new_forward_extremities)", "txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT INTO redactions (event_id, redacts) VALUES (?,?)\",", "the case where the new events have soft-failed prev #", "TABLE events_to_purge (\" \" event_id TEXT NOT NULL,\" \" should_delete", "stream_ordering ASC\" \" LIMIT ?\" ) if have_forward_events: txn.execute(sql, (last_forward_id,", "missing_event_ids.add(event_id) if missing_event_ids: # Now pull out the state groups", "# event_auth # event_backward_extremities # event_edges # event_forward_extremities # event_json", "INTO redactions (event_id, redacts) VALUES (?,?)\", (event.event_id, event.redacts), ) @defer.inlineCallbacks", "\",\".join(\"?\" for _ in batch), ) txn.execute(sql, batch) results.extend(r[0] for", "self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg} ) self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\":", "current_state is not None: with Measure( self._clock, \"persist_events.calculate_state_delta\" ): delta", "# Copyright 2014-2016 OpenMarket Ltd # Copyright 2018-2019 New Vector", "txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used", "in iteritems(curr_state) ], ) logger.info(\"[purge] removing redundant state groups\") txn.executemany(", "(due to one of its prev groups being scheduled for", "return that. new_state_group = next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids =", "stream_id AND stream_id <= ? ORDER BY stream_id ASC LIMIT", "set(latest_event_ids) # start with the existing forward extremities result =", "this update, we # will block that for the rest", "events_and_contexts (list[(EventBase, EventContext)]): events we are persisting \"\"\" if not", "event and event_json tables Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts", "twice. Pick the earliest non-outlier if there is one, else", "may obtain a copy of the License at # #", "{} # Map from (prev state group, new state group)", "event_stream_ordering <= ?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql,", "in events_and_contexts if ec[0] not in to_remove] @classmethod def _delete_existing_rows_txn(cls,", "current_state ) state_delta_for_room[room_id] = delta # If we have the", "stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql, (-last_id, -current_id, limit))", "\" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers", "new items, unless the queue becomnes empty. The return value", "txn, events_and_contexts=events_and_contexts ) # From this point onwards the events", "def _update_room_depths_txn(self, txn, events_and_contexts, backfilled): \"\"\"Update min_depth for each room", "remove them and their prev events, # otherwise we end", "txn.execute(sql, batch) results.extend(r[0] for r in txn if not json.loads(r[1]).get(\"soft_failed\"))", "the current forward extremities. for ev, _ in ev_ctx_rm: prev_event_ids", "else: # If we couldn't find it, then we'll need", "synapse.util import batch_iter from synapse.util.async_helpers import ObservableDeferred from synapse.util.caches.descriptors import", "events_context (list[(EventBase, EventContext)]): events and contexts which are being added", "care if the event # was an outlier or not.", "Set of state groups we've already seen state_groups_seen = set(state_groups)", "new_event_updates[-1][0] else: upper_bound = current_id sql = ( \"SELECT event_stream_ordering,", "Map from (prev state group, new state group) -> delta", "are ancestors of new events, but are separated by soft", "referenced sql = \"\"\" SELECT DISTINCT state_group FROM event_to_state_groups LEFT", "any events which were # rejected, and returns the filtered", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "the database. We now have some state at that #", "sql = \"\"\" SELECT prev_event_id, internal_metadata FROM event_edges INNER JOIN", "groups\") txn.executemany( \"DELETE FROM state_groups_state WHERE state_group = ?\", ((sg,)", "state dict after adding some new events to a room", "find prev events for. Note that these must have already", "invlidate the caches for all # those users. members_changed =", "# insert into event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event, context),)) except Exception:", "there should always be at least one forward extremity. #", "room_id = ? AND event_id IN (\" \" SELECT event_id", "context in chunk: events_by_room.setdefault(event.room_id, []).append( (event, context) ) for room_id,", "def is_event_after(self, event_id1, event_id2): \"\"\"Returns True if event_id1 is after", "the initial persistence of the send_join # results, in which", "set[int]]: The set of state groups that can be deleted", "def __init__(self): self._event_persist_queues = {} self._currently_persisting_rooms = set() def add_to_queue(self,", "\"\"\" # The set of event_ids to return. This includes", "to check whether the event was rejected. Args: txn (twisted.enterprise.adbapi.Connection):", "event.redacts), ) @defer.inlineCallbacks def count_daily_messages(self): \"\"\" Returns an estimate of", "extremeties txn.execute( \"SELECT e.event_id, e.depth FROM events as e \"", "get_all_updated_current_state_deltas(self, from_token, to_token, limit): def get_all_updated_current_state_deltas_txn(txn): sql = \"\"\" SELECT", "event_reference_hashes # event_search # event_to_state_groups # events # rejections #", "events_and_contexts): \"\"\"Update any outliers with new event info. This turns", "ep2 ON ed.event_id = ep2.event_id\" \" WHERE ep2.event_id IS NULL\"", "a delta for that transition. If we do then we", "def f(self, *args, **kwargs): try: res = yield func(self, *args,", "been # persisted, and returns the filtered list. events_and_contexts =", "if the rejected event appears in an accepted # event's", ") txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn) return new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\",", "as redacts,\" \" rej.event_id as rejects \" \" FROM events", "\"url\" in event.content and isinstance(event.content[\"url\"], text_type) ), } for event,", "def _persist_events( self, events_and_contexts, backfilled=False, delete_existing=False ): \"\"\"Persist events to", "in txn: if prev_event_id in existing_prevs: continue soft_failed = json.loads(metadata).get(\"soft_failed\")", "def _persist_events_txn( self, txn, events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ):", "%i state groups to delete\", len(state_groups_to_delete) ) logger.info( \"[purge] de-delta-ing", "= self._get_drainining_queue(room_id) for item in queue: try: ret = yield", "_ in events_context: if ev.type == EventTypes.Create and ev.state_key ==", "doesn't matter if we don't. new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids))", "when we could have resonably # calculated the delta when", "= ? AND state_key = ? ) \"\"\" txn.executemany( sql,", "be persisted in bulk with only one concurrent transaction per", "for one room # at a time. # map room_id->list[event_ids]", "state delta for room %s\", room_id) with Measure( self._clock, \"persist_events.get_new_state_after_events\"", "room_id, current_state): \"\"\"Calculate the new state deltas for a room.", "Remove the any existing cache entries for the event_ids txn.call_after(self._invalidate_get_event_cache,", "USING (event_id) WHERE event_id IN (%s) AND NOT events.outlier \"\"\"", "events_and_contexts: return if backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else:", "index on should_delete because later we'll be looking for #", "one room at a time. \"\"\" # we're only interested", "to the 'rejections' table for received events which were rejected", "txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers = txn.fetchall() else: new_backfill_events = []", "the miscellaneous tables for new events Args: txn (twisted.enterprise.adbapi.Connection): db", "= _EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler() # Collect metrics on the", "= {} # Map from (prev state group, new state", "Check if state groups are referenced sql = \"\"\" SELECT", "set the event_persisted_position to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for event,", "end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts,", "evid in old_latest_event_ids ) # State groups of new_latest_event_ids new_state_groups", "state groups to delete\", len(state_groups_to_delete) ) logger.info( \"[purge] de-delta-ing %i", "exceptions will be passed to the deferreds as well. This", "were going to persist. This includes events we've already persisted,", "onwards the events are only events that we haven't #", "State groups of new_latest_event_ids new_state_groups = set( event_id_to_state_group[evid] for evid", "(room_id,) ) # Update backward extremeties txn.executemany( \"INSERT INTO event_backward_extremities", "room_id, token_str, delete_local_events): token = RoomStreamToken.parse(token_str) # Tables that should", "If it has been significantly less or more than one", "== 1 and not event.is_state() for event, ctx in ev_ctx_rm", "License. import itertools import logging from collections import Counter as", "backfilled=backfilled, deferred=deferred, ) ) return deferred.observe() def handle_queue(self, room_id, per_item_callback):", "to purge, etc., so lets make an index. txn.execute(\"CREATE INDEX", "{ \"room_id\": room_id, \"event_id\": event_id, \"stream_ordering\": max_stream_order, } for room_id,", "and `to_insert` are the updates to current_state_events. \"\"\" existing_state =", "latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) ) @defer.inlineCallbacks def _calculate_new_extremities(self,", "yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks def persisting_queue(item):", "(%s) AND NOT events.outlier AND rejections.event_id IS NULL \"\"\" %", "iteritems, text_type from six.moves import range from canonicaljson import json", "events_to_purge\" \" SELECT event_id, %s\" \" FROM events AS e", "(except during the initial persistence of the send_join # results,", "new event. forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of forward extremities", "\")\" ) # First ensure that we're not about to", "__init__(self): self._event_persist_queues = {} self._currently_persisting_rooms = set() def add_to_queue(self, room_id,", "where workers see events before the # current_state_delta updates. #", "aren't # being rejected. new_events = [ event for event,", "not be invoked. \"\"\" if room_id in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id)", "events_and_contexts = self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts ) # From this point", "WHERE event_id IN (\" \" SELECT event_id FROM events_to_purge WHERE", "so that we can call _update_backward_extremities # and _handle_mult_prev_events (though", "event.redacts) txn.execute( \"INSERT INTO redactions (event_id, redacts) VALUES (?,?)\", (event.event_id,", "res = yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True,", "state_events_and_contexts = [ ec for ec in events_and_contexts if ec[0].is_state()", "is not None: # Remove the entries in the event_push_actions", "if len(new_state_groups) == 1: # If there is only one", "WHERE event_id in (%s)\" % (\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id for", "event_backward_extremities AS eb INNER JOIN event_edges AS eg ON eg.prev_event_id", "reasons, we go and delete all the existing entries #", "to not # having any backwards extremeties) raise SynapseError( 400,", "+= (room_id, token.topological) # Note that we insert events that", "Returns: Deferred[int]: the stream ordering of the latest persisted event", ") # Invalidate the various caches # Figure out the", "set of extremities as well as the new. stale_forward_extremities_counter =", "yield func(self, *args, **kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res =", "table. \"\"\" txn.execute( \"SELECT event_id, outlier FROM events WHERE event_id", "state_key in itertools.chain(to_delete, to_insert) ), ) self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[", "as outliers logger.info(\"[purge] marking remaining events as outliers\") txn.execute( \"UPDATE", "yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self): def _count_messages(txn): #", "the current_state_delta_stream. We # do this before updating the current_state_events", "chunk[-1][0].internal_metadata.stream_ordering ) for event, context in chunk: if context.app_service: origin_type", "# Update the event_forward_extremities, event_backward_extremities and # event_edges tables. self._handle_mult_prev_events(", "JOIN event_relations USING (event_id)\" \" WHERE ? > stream_ordering AND", "\"Context for new event %s has no state \" \"group\"", "defer to the state handler to resolve our state sets.", "\"local\" origin_entity = context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type = \"local\" origin_entity", "check if # we have a delta for that transition.", "self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if not", "entries for the backward extremeties by finding # events to", "yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events(", "keyvalues={\"event_id\": event_id}, allow_none=True, ) if not res: raise SynapseError(404, \"Could", "First search in the list of new events we're adding.", "new_state_groups we need to get # their state IDs so", "not ev_map: break sql = ( \"SELECT \" \" e.event_id", "else: origin_type = \"remote\" origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc()", "# invalidate the cache for the redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts)", "which need to be de-delta'ed (due to one of its", "len(latest_event_ids) == 1 and len(new_latest_event_ids) == 1 ) if len_1:", "events_to_purge AS e\" \" INNER JOIN event_edges AS ed ON", "not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): # To ensure correct ordering we", "might contain the same event. :( # NB: Assumes that", "\"\"\"Update min_depth for each room Args: txn (twisted.enterprise.adbapi.Connection): db connection", "# if they match the current forward extremities. for ev,", "FROM current_state_events\" \" WHERE room_id = ? AND type =", "current minimum token that backfilled events have reached\"\"\" return -self._backfill_id_gen.get_current_token()", "can be deleted\") _ = self._find_unreferenced_groups_during_purge(txn, referenced_state_groups) state_groups_to_delete, remaining_state_groups =", "utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # Copyright 2018-2019", "= {} for event, context in events_and_contexts: # Remove the", "events_context, old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate the current state dict after", "event_id FROM events_to_purge WHERE should_delete\" \")\" % (table,), (room_id,), )", "events AS e ON e.event_id = eg.event_id WHERE eb.room_id =", "not already being handled. The given callback will be invoked", "d.pop(\"redacted_because\", None) return d self._simple_insert_many_txn( txn, table=\"event_json\", values=[ { \"event_id\":", "token to delete events before delete_local_events (bool): if True, we", "state_events USING (event_id)\" \" WHERE ? > stream_ordering AND stream_ordering", "def get_all_new_forward_event_rows(txn): sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\"", "%s\", room_id) with Measure( self._clock, \"persist_events.get_new_state_after_events\" ): res = yield", "), } for event, _ in events_and_contexts ], ) def", "buckets=[1, 2, 3, 5, 7, 10, 15, 20, 50, 100,", "we can just # return that. new_state_group = next(iter(new_state_groups)) old_state_group", "|= referenced # We don't continue iterating up the state", "[ ec for ec in events_and_contexts if ec[0].is_state() ] state_values", "count_daily_active_rooms(self): def _count(txn): sql = \"\"\" SELECT COALESCE(COUNT(DISTINCT room_id), 0)", "logcontext rules, and leaves the logcontext in place whether or", "WHERE ? < event_stream_ordering\" \" AND event_stream_ordering <= ?\" \"", "(event_id)\" \" LEFT JOIN event_relations USING (event_id)\" \" WHERE ?", "events, find all those that have been soft-failed or rejected.", "with dangling extremities. existing_prevs = yield self._get_prevs_before_rejected( e_id for event", "over federation) it will use the # forward extremities as", "events_and_contexts] ) state_events_and_contexts = [ ec for ec in events_and_contexts", "_ in events_and_contexts if event.type == EventTypes.Member ], backfilled=backfilled, )", "for now just to store them (and # it doesn't", "# removed keys entirely. state_delta_for_room[room_id] = ([], delta_ids) elif current_state", "if soft_failed or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk in batch_iter(event_ids,", "self._store_room_name_txn(txn, event) elif event.type == EventTypes.Topic: # Insert into the", "were in the previous set of extremities as well as", "from synapse.api.constants import EventTypes from synapse.api.errors import SynapseError from synapse.events", "for that transition. If we do then we can just", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "context in events_and_contexts: # Remove the any existing cache entries", "evs_ctxs, backfilled=backfilled ) deferreds.append(d) for room_id in partitioned: self._maybe_start_persisting(room_id) yield", "stream_ordering_manager as stream_orderings: for (event, context), stream in zip(events_and_contexts, stream_orderings):", "= set(ev.prev_event_ids()) if latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state", "break logger.info(\"Calculating state delta for room %s\", room_id) with Measure(", "if event.event_id not in have_persisted: continue to_remove.add(event) if context.rejected: #", "\"\"\"Queues up events so that they can be persisted in", "not about to delete all the forward extremeties txn.execute( \"SELECT", "100): yield self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk ) defer.returnValue(results) @defer.inlineCallbacks def", "AND stream_id <= ? ORDER BY stream_id ASC LIMIT ?", "then we don't need to do # anything. if old_state_groups", "state groups\", len(referenced_state_groups) ) logger.info(\"[purge] finding state groups that can", "table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order, \"event_id\": event.event_id, \"state_group\": state_group_id, }, )", "existing # extremities, so we'll `continue` above and skip this", "to_remove = set() for event, context in events_and_contexts: if context.rejected:", "(e.g. we ignore backfill/outliers/etc) if result != latest_event_ids: forward_extremities_counter.observe(len(result)) stale", "# we will build a temporary table listing the events", "new events into the event and event_json tables Args: txn", "INDEX events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\" ) # We do joins", "to the existing current state. If both are None then", "count, = txn.fetchone() return count ret = yield self.runInteraction(\"count_messages\", _count_messages)", "def handle_queue(self, room_id, per_item_callback): \"\"\"Attempts to handle the queue for", "curr_state = curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg} ) self._simple_delete_txn(", "\"current state\" for each room. # We do this by", "Remove the entries in the event_push_actions table for the #", "EventContext)]): events and contexts which are being added to the", "given persist_event options. NB: due to the normal usage pattern", "event in new_events) # Now remove all events which are", "\"INNER JOIN event_forward_extremities as f \" \"ON e.event_id = f.event_id", "for these events so we can reinsert them. # This", "@log_function def _persist_events_txn( self, txn, events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={},", "Returns: Deferred: resolves to (int, int): the stream ordering of", "(event, context) backfilled (bool): Whether the results are retrieved from", "to_insert) if ev_type == EventTypes.Member ) for member in members_changed:", "outlier status to our workers. stream_order = event.internal_metadata.stream_ordering state_group_id =", "events before the # current_state_delta updates. # sql = \"\"\"", "persisted event \"\"\" deferred = self._event_persist_queue.add_to_queue( event.room_id, [(event, context)], backfilled=backfilled", "\" ON events_to_purge(should_delete)\" ) # We do joins against events_to_purge", "the existing to new current state, # so lets just", "to get # their state IDs so we can resolve", "events are being added. Used for logging etc events_context (list[(EventBase,", "Add an entry to the ex_outlier_stream table to replicate the", "we are persisting Returns: list[(EventBase, EventContext)] new list, without events", "from the database missing_event_ids.add(event_id) if missing_event_ids: # Now pull out", "if not events_and_contexts: # nothing to do here return for", "are # now. When this server creates a new event", "current state, and to_insert # is a map (type,key)->event_id giving", "a temporary table listing the events so that we don't", "stream_orderings: for (event, context), stream in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering =", "current state. new_forward_extremeties (dict[str, list[str]]): The new forward extremities for", "= set() for event, context in events_and_contexts: if context.rejected: #", "= set(sg for sg, in txn) logger.info( \"[purge] found %i", "for each new event\", buckets=(1, 2, 3, 5, 7, 10,", "(\"%:\" + self.hs.hostname, \"%:\" + self.hs.hostname) should_delete_params += (room_id, token.topological)", "that have arrived at the server either as new events", "for each item in the queue, of type _EventPersistQueueItem. The", "Events to find prev events for. Note that these must", "we don't block event # persistence. # # We do", "ordering we pop, as OrderedDict is # ordered by first", "in events_and_contexts], ) have_persisted = {event_id: outlier for event_id, outlier", "new_latest_event_ids ) # If they old and new groups are", "before. if delete_existing: # For paranoia reasons, we go and", "txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), ) prevs =", "referenced_groups to_dedelta = set() for sg in referenced_groups: prev_sg =", "# Now we turn the state groups that reference to-be-deleted", "return to_delete, to_dedelta @defer.inlineCallbacks def is_event_after(self, event_id1, event_id2): \"\"\"Returns True", "# Remove the any existing cache entries for the event_ids", "WHERE ? > event_stream_ordering\" \" AND event_stream_ordering >= ?\" \"", "gets retried on IntegrityError, with `delete_existing=True` passed in. Args: func:", "for (etype, state_key), ev_id in iteritems(to_insert) ), ) # Now", "the event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, ) if not", "list \"\"\" new_events_and_contexts = OrderedDict() for event, context in events_and_contexts:", "): \"\"\"Calculate the current state dict after adding some new", "room_depth to %d\", min_depth) txn.execute( \"UPDATE room_depth SET min_depth =", "to pull the state group from the database. # Set", "on room_depth whenever it # persists events (because upsert), and", "events as outliers\") txn.execute( \"UPDATE events SET outlier = ?\"", "\"DELETE FROM %s WHERE room_id = ? AND event_id =", "delete_existing: # For paranoia reasons, we go and delete all", "res = yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount = c_counter(list(x[0] for x", "outlier for event_id, outlier in txn} to_remove = set() for", "int): the stream ordering of ``event``, and the stream ordering", "60 * 60 * 1000) @defer.inlineCallbacks def _read_forward_extremities(self): def fetch(txn):", "context in events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id) if prev_event_context: if not", "= [] def _get_events_which_are_prevs_txn(txn, batch): sql = \"\"\" SELECT prev_event_id,", "= events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn,", "? AND event_id IN (\" \" SELECT event_id FROM events_to_purge", "logcontext in place whether or not the returned deferred is", "new_latest_event_ids, \"No forward extremities left!\" new_forward_extremeties[room_id] = new_latest_event_ids len_1 =", ") # Ensure that we don't have the same event", "\" rej.event_id as rejects \" \" FROM events as e\"", "fetch groups for. (We know none of the old #", "yield self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids = yield self._calculate_new_extremities( room_id, ev_ctx_rm,", "events_and_contexts ], ) def _store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add rows to", "in event_rows if e[1]), ) logger.info(\"[purge] Finding new backward extremities\")", "we need to work out the delta (or use that", "the returned deferred is ready. Args: room_id (str): events_and_contexts (list[(EventBase,", "much storage compared to storing the entire event # anyway).", "keys to be removed from the current state, and a", "event.room_id, \"internal_metadata\": encode_json( event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)), \"format_version\": event.format_version, }", "that we're not about to delete all the forward extremeties", "# persistence. # # We do this by calculating the", "rejected. new_events = [ event for event, ctx in event_contexts", "count(*) c from event_forward_extremities group by room_id \"\"\" ) return", "event.internal_metadata.is_outlier() and outlier_persisted: # We received a copy of an", "\"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"state_key\": event.state_key, } #", "we're only interested in new events which aren't outliers and", "= None for ev, _ in events_context: if ev.type ==", "# Don't bother calculating state if they're just # a", ">= ?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_backfill_id,", "new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] = (event, context) else: new_events_and_contexts[event.event_id] = (event,", "to figure out which state groups can be deleted and", "at once, to stop the # SQL query getting too", "table. self._store_redaction(txn, event) elif event.type == EventTypes.RoomHistoryVisibility: # Insert into", "backfill or not. Used to determine if they're \"new\" events", "EventTypes.Redaction and event.redacts is not None: # Remove the entries", "# state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok, we need to", "\"DELETE FROM current_state_events\" \" WHERE room_id = ? AND type", "events_to_purge WHERE should_delete\" \")\" % (table,) ) # event_push_actions lacks", "ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn) return", "state_groups_seen = set(state_groups) # Set of state groups to handle", "%s\", table) txn.execute( \"DELETE FROM %s WHERE event_id IN (\"", "to be de-delta'ed \"\"\" # Graph of state group ->", "listing the events so that we don't # have to", "import batch_iter from synapse.util.async_helpers import ObservableDeferred from synapse.util.caches.descriptors import cached,", "events_and_contexts): \"\"\"Insert new events into the event and event_json tables", "FROM state_groups_state WHERE state_group = ?\", ((sg,) for sg in", "): \"\"\"Update all the miscellaneous tables for new events Args:", "ON e.event_id = ed.prev_event_id\" \" LEFT JOIN events_to_purge AS ep2", "ANY KIND, either express or implied. # See the License", "going to be in events_context). missing_event_ids = set(old_latest_event_ids) event_id_to_state_group =", "from EventFederationStore so that we can call _update_backward_extremities # and", "# given) if delta_ids is not None: # If there", "by looking at the prev_events and checking # if they", "at the end so that we don't block event #", "events_and_contexts = self._update_outliers_txn( txn, events_and_contexts=events_and_contexts ) # From this point", "so make sure to keep this actually last. txn.execute(\"DROP TABLE", "iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for room_id, latest_event_ids in iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,),", "count self._current_forward_extremities_amount = c_counter() BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1, 2,", "\"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount, buckets=[1, 2, 3, 5, 7, 10, 15,", "FROM events as e\" \" LEFT JOIN rejections as rej", "# See the License for the specific language governing permissions", "Get all state groups that are referenced by events that", "should only happen for outlier events. if not ev.internal_metadata.is_outlier(): raise", "events we're not going to # purge. txn.execute( \"SELECT DISTINCT", "_purge_history_txn(self, txn, room_id, token_str, delete_local_events): token = RoomStreamToken.parse(token_str) # Tables", "for etype, state_key in to_delete # We sanity check that", "users. members_changed = set( state_key for ev_type, state_key in itertools.chain(to_delete,", "# _update_outliers_txn filters out any events which have already been", "events for table in ( \"events\", \"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\",", "_store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add rows to the 'rejections' table for", "type = 'm.room.message' AND stream_ordering > ? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,))", "== new_state_groups: defer.returnValue((None, None)) if len(new_state_groups) == 1 and len(old_state_groups)", "extremities result = set(latest_event_ids) # add all the new events", "to-be-deleted state # groups to non delta versions. for sg", "referenced_groups: prev_sg = graph.get(sg) if prev_sg and prev_sg in to_delete:", "(This # allows us to not have to pull out", "= {} for event, ctx in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx))", "# We need to ensure we don't delete all the", "Ltd # Copyright 2018-2019 New Vector Ltd # Copyright 2019", "\"room_id\": event.room_id, \"type\": event.type, \"processed\": True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts),", "\"\"\" Write events to the database Args: events_and_contexts: list of", "existing_prevs = set() def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check = batch while", "events_and_contexts=events_and_contexts) # Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) # We want", "table in (\"event_push_actions\",): txn.executemany( \"DELETE FROM %s WHERE room_id =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "we do know the delta then the new current state", "without the rejected events. \"\"\" # Remove the rejected events", "new events have soft-failed prev # events. If they do", "BY stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql, (last_id, current_id,", "a mapping from room_id, # new stream_ordering to new forward", "Args: event_ids (Iterable[str]): event ids to filter Returns: Deferred[List[str]]: filtered", "database. This is useful when retrying due to IntegrityError. state_delta_for_room", "@defer.inlineCallbacks def _read_forward_extremities(self): def fetch(txn): txn.execute( \"\"\" select count(*) c", "max_stream_order ): for room_id, new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\",", "new_backfill_events, forward_ex_outliers, backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self, room_id,", "USING (event_id) \"\"\" ) referenced_state_groups = set(sg for sg, in", "DESC\" ) txn.execute(sql, (last_forward_id, upper_bound)) forward_ex_outliers = txn.fetchall() else: new_forward_events", "time. Returns: tuple[list, dict] (to_delete, to_insert): where to_delete are the", "events in event_backward_extremities # are ones we don't have yet", "table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True, ) if not res:", "Deferred and accepts a `delete_existing` arg \"\"\" @wraps(func) @defer.inlineCallbacks def", "(event_id)\" \" WHERE ? > event_stream_ordering\" \" AND event_stream_ordering >=", ") # First ensure that we're not about to delete", "= \"local\" origin_entity = context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type = \"local\"", "LEFT JOIN state_events USING (event_id)\" \" WHERE ? > stream_ordering", "stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged forward extremities for", "\"\"\" if not events_and_contexts: # nothing to do here return", "not None: current_state_for_room[room_id] = current_state yield self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk,", "them. txn.execute( \"\"\" SELECT DISTINCT state_group FROM events_to_purge INNER JOIN", "the stream ordering of ``event``, and the stream ordering of", "func(self, *args, delete_existing=True, **kwargs) defer.returnValue(res) return f # inherits from", "NULL\" \")\" ) # First ensure that we're not about", "by events we're not going to # purge. txn.execute( \"SELECT", "txn, table=\"current_state_events\", values=[ { \"event_id\": ev_id, \"room_id\": room_id, \"type\": key[0],", "# Normally that'd be in the database, but its also", "last item in the queue has the same `backfilled` setting,", "case there will be no existing # extremities, so we'll", "maximum token that events have reached\"\"\" return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self,", "not None: # Remove the entries in the event_push_actions table", "that state. # insert into event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event, context),))", "def _update_forward_extremities_txn( self, txn, new_forward_extremities, max_stream_order ): for room_id, new_extrem", "= ctx.state_group break else: # If we couldn't find it,", "the events were backfilled \"\"\" # Insert all the push", "we don't need to do # anything. if old_state_groups ==", "state and own events as outliers logger.info(\"[purge] marking remaining events", "events that we have found to be referenced by events", "stale = latest_event_ids & result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self,", "- referenced_groups to_dedelta = set() for sg in referenced_groups: prev_sg", "existing cache entries for the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if not", "given to the deferreds waiting on the item, exceptions will", "for state # groups that are referenced. current_search -= referenced", "USING (event_id)\" \" LEFT JOIN redactions as r ON e.event_id", "= [ ec for ec in events_and_contexts if ec[0].is_state() ]", "= namedtuple( \"AllNewEventsResult\", [ \"new_forward_events\", \"new_backfill_events\", \"forward_ex_outliers\", \"backward_ex_outliers\", ], )", "can # pull the state group from its context. #", "aren't going to be # deleted, as nothing will happen", "we may have deleted # and which we have added,", "scheduled for deletion). Args: txn state_groups (set[int]): Set of state", "table=\"stream_ordering_to_exterm\", values=[ { \"room_id\": room_id, \"event_id\": event_id, \"stream_ordering\": max_stream_order, }", "as the new. stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged", "(False, event.event_id)) # Update the event_backward_extremities table now that this", "of events that we have found to be referenced by", "namedtuple from functools import wraps from six import iteritems, text_type", "(event.event_id, event.redacts), ) @defer.inlineCallbacks def count_daily_messages(self): \"\"\" Returns an estimate", "table from a previous (failed) # purge attempt, so let's", "have a logcontext to report to return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities", "= [] for event, context in state_events_and_contexts: vals = {", "SET internal_metadata = ?\" \" WHERE event_id = ?\" )", "self._simple_insert_many_txn( txn, table=\"events\", values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\":", "60 * 1000) @defer.inlineCallbacks def _read_forward_extremities(self): def fetch(txn): txn.execute( \"\"\"", "state_key), ev_id in iteritems(to_insert) ), ) # Now we actually", "backfilled (bool): Returns: Deferred: resolves to (int, int): the stream", "add these new events to that item. end_item = queue[-1]", "then the new current state is only returned if we've", "self._get_drainining_queue(room_id) for item in queue: try: ret = yield per_item_callback(item)", "the existing state # unnecessarily). # # The stream_id for", "becomnes empty. The return value of the function will be", "- set(state_groups_map) if missing_state: group_to_state = yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state) if", "= ( len(latest_event_ids) == 1 and len(new_latest_event_ids) == 1 )", "# check if the event is one we're persisting, in", "once, to stop the # SQL query getting too big", "values=[ { \"room_id\": room_id, \"event_id\": event_id, \"stream_ordering\": max_stream_order, } for", "while next_to_search: # We bound size of groups we're looking", "(We know none of the old # extremities are going", "(list[(EventBase, EventContext)]): events we are persisting \"\"\" if not events_and_contexts:", "None) return d self._simple_insert_many_txn( txn, table=\"event_json\", values=[ { \"event_id\": event.event_id,", "a change, # and we need to work out the", "the given persist_event options. NB: due to the normal usage", "to pull out the existing state # unnecessarily). # #", "current_state_events and `to_insert` are the updates to current_state_events. \"\"\" existing_state", "were backfilled delete_existing (bool): True to purge existing table rows", "redactions USING (event_id)\" \" LEFT JOIN state_events USING (event_id)\" \"", "the new events have soft-failed prev # events. If they", "%s\", table) txn.execute( \"DELETE FROM %s WHERE room_id = ?", "to calculate the `prev_event_id`. (This # allows us to not", "and skip this bit.) assert new_latest_event_ids, \"No forward extremities left!\"", "table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[", "item in the queue has the same `backfilled` setting, #", "room_id in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop(): try: queue", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"auth_id\": auth_id, } for", "If either are not None then there has been a", "batch): sql = \"\"\" SELECT prev_event_id, internal_metadata FROM event_edges INNER", "are only ones that weren't # rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts,", "event) elif event.type == EventTypes.Redaction: # Insert into the redactions", "event, context in events_and_contexts: if context.rejected: # Insert the event_id", "state_groups = {sg: state_groups_map[sg] for sg in new_state_groups} events_map =", "= [] backward_ex_outliers = [] return AllNewEventsResult( new_forward_events, new_backfill_events, forward_ex_outliers,", "1, 2, 3, 5, 7, 10, 15, 20, 50, 100,", "self.cursor_to_dict(txn) for row in rows: event = ev_map[row[\"event_id\"]] if not", "rows to the 'rejections' table for received events which were", "from synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils import log_function from", "LIMIT ? \"\"\" txn.execute(sql, (from_token, to_token, limit)) return txn.fetchall() return", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "stream_id <= ? ORDER BY stream_id ASC LIMIT ? \"\"\"", "context) else: new_events_and_contexts[event.event_id] = (event, context) return list(new_events_and_contexts.values()) def _update_room_depths_txn(self,", "Remove from relations table. self._handle_redaction(txn, event.redacts) # Update the event_forward_extremities,", "= ( \"UPDATE event_json SET internal_metadata = ?\" \" WHERE", "will delete local events as well as remote ones (instead", "events to persist. Assumes that we are only persisting events", "? WHERE room_id = ?\", (min_depth, room_id), ) # finally,", "= self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), )", "lets also return that, # but it doesn't matter if", "pull out the existing state # unnecessarily). # # The", "event_id in new_extrem ], ) @classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure", "= last_forward_id != current_forward_id if not have_backfill_events and not have_forward_events:", "to_remove = set() for event, context in events_and_contexts: if event.event_id", "forward extremeties txn.execute( \"SELECT e.event_id, e.depth FROM events as e", "item in queue: try: ret = yield per_item_callback(item) except Exception:", "self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk))", "all the forward extremeties txn.execute( \"SELECT e.event_id, e.depth FROM events", "= yield self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids, ) current_state, delta_ids", "\"No forward extremities left!\" new_forward_extremeties[room_id] = new_latest_event_ids len_1 = (", "\"DELETE FROM event_backward_extremities WHERE room_id = ?\", (room_id,) ) #", "event_id from events_to_purge)\" ) for event_id, _ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "in each # room state_delta_for_room = {} if not backfilled:", "ev_id in iteritems(to_insert) ), ) # Now we actually update", "extremities # (e.g. we ignore backfill/outliers/etc) if result != latest_event_ids:", "the existing forward extremities result = set(latest_event_ids) # add all", "table in ( \"events\", \"event_json\", \"event_auth\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\",", "retrying.\") res = yield func(self, *args, delete_existing=True, **kwargs) defer.returnValue(res) return", "end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True)", "we're going from one state group to another, lets check", "INNER JOIN event_to_state_groups USING (event_id) \"\"\" ) referenced_state_groups = set(sg", "etc., so lets make an index. txn.execute(\"CREATE INDEX events_to_purge_id\" \"", "for event, _ in events_and_contexts: if event.type == EventTypes.Name: #", "store event_auth mappings for rejected events, as they're # used", "persist. Assumes that we are only persisting events for one", "\"CREATE INDEX events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\" ) # We do", "after event_id2 in the stream \"\"\" to_1, so_1 = yield", "search in the list of new events we're adding. for", "\"+Inf\"), ) def encode_json(json_object): \"\"\" Encode a Python object as", "been drained. pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def _retry_on_integrity_error(func):", "miscellaneous tables for new events Args: txn (twisted.enterprise.adbapi.Connection): db connection", "(room_id, token.topological) # Note that we insert events that are", "max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def persist_event(self, event,", "type = ? AND state_key = ? ) \"\"\" txn.executemany(", "= yield self._get_event_ordering(event_id1) to_2, so_2 = yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1)", "== 1 ) if len_1: all_single_prev_not_state = all( len(event.prev_event_ids()) ==", "existing_prevs: continue soft_failed = json.loads(metadata).get(\"soft_failed\") if soft_failed or rejected: to_recursively_check.append(prev_event_id)", "if its already been calculated. Conversely if we do know", "import frozendict_json_encoder from synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils import", "room_id, per_item_callback): \"\"\"Attempts to handle the queue for a room", "which %i can be deleted\", len(event_rows), sum(1 for e in", "existing_prevs = yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) # Finally handle the case", "the DB later # if necessary. current_state_ids = ctx.get_cached_current_state_ids() if", "new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self, last_id, current_id,", "# you may not use this file except in compliance", "latest_event_ids = set(latest_event_ids) if new_latest_event_ids == latest_event_ids: # No change", "current_id, limit): if last_id == current_id: return defer.succeed([]) def get_all_new_forward_event_rows(txn):", "be pruned: # event_auth # event_backward_extremities # event_edges # event_forward_extremities", "\"SELECT DISTINCT e.event_id FROM events_to_purge AS e\" \" INNER JOIN", "from synapse.util.frozenutils import frozendict_json_encoder from synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable from", "well as remote ones (instead of just marking them as", "result = set(latest_event_ids) # add all the new events to", "do here return def event_dict(event): d = event.get_dict() d.pop(\"redacted\", None)", "actually update the current_state_events table txn.executemany( \"DELETE FROM current_state_events\" \"", "mapping from room_id, # new stream_ordering to new forward extremeties", "if len(new_event_updates) == limit: upper_bound = new_event_updates[-1][0] else: upper_bound =", "to_insert) ), ) self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[ { \"event_id\": ev_id,", "self._handle_event_relations(txn, event) # Insert into the room_memberships table. self._store_room_members_txn( txn,", ") return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self, room_id, token, delete_local_events): \"\"\"Deletes", "are prev_events of any of the new events result.difference_update( e_id", "redactions as r ON e.event_id = r.redacts\" \" WHERE e.event_id", "events_and_contexts: # nothing to do here return logger.info(\"Deleting existing\") for", "row in rows) if max_depth < token.topological: # We need", "current_search = set(itertools.islice(next_to_search, 100)) next_to_search -= current_search # Check if", "import iteritems, text_type from six.moves import range from canonicaljson import", "would have been when # processing one of these events.", "txn.fetchall() else: new_forward_events = [] forward_ex_outliers = [] sql =", "?\" ) if have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit)) new_backfill_events =", "have found to be referenced by events referenced_groups = set()", "event, ctx in event_contexts if not event.internal_metadata.is_outlier() and not ctx.rejected", "finding state groups that can be deleted\") _ = self._find_unreferenced_groups_during_purge(txn,", "\"\"\"Deletes room history before a certain point Args: room_id (str):", "happen to them. txn.execute( \"INSERT INTO events_to_purge\" \" SELECT event_id,", "to invalidate the # `get_rooms_for_user` cache. # We find out", "events as e\" \" LEFT JOIN rejections as rej USING", "delete_local_events): token = RoomStreamToken.parse(token_str) # Tables that should be pruned:", "the event_search table. self._store_history_visibility_txn(txn, event) elif event.type == EventTypes.GuestAccess: #", "find event %s\" % (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def", "# seen before. if delete_existing: # For paranoia reasons, we", "metrics on the number of forward extremities that exist. #", "self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with stream_ordering_manager as stream_orderings: for (event, context),", "do # anything. if old_state_groups == new_state_groups: defer.returnValue((None, None)) if", "the end so that we don't block event # persistence.", "return the delta if its already been calculated. Conversely if", "nothing to do here return for event, context in events_and_contexts:", "sg in state_groups_to_delete), ) logger.info(\"[purge] removing events from event_to_state_groups\") txn.execute(", "synapse.util.frozenutils import frozendict_json_encoder from synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils", "backwards extremeties) raise SynapseError( 400, \"topological_ordering is greater than forward", "events_and_contexts (list[(EventBase, EventContext)]): events to persist backfilled (bool): True if", "_get_events_which_are_prevs_txn, chunk ) defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed", "This function should therefore be called whenever anything is added", ") # We now insert into stream_ordering_to_exterm a mapping from", "Deferred[List[str]]: filtered event ids \"\"\" results = [] def _get_events_which_are_prevs_txn(txn,", "iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth) def _update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update any", "StateGroupWorkerStore from synapse.types import RoomStreamToken, get_domain_from_id from synapse.util import batch_iter", "their state groups. First, let's # check if the event", "txn.execute( \"\"\" SELECT DISTINCT state_group FROM events_to_purge INNER JOIN event_to_state_groups", "= _ logger.info( \"[purge] found %i state groups to delete\",", "State groups of old_latest_event_ids old_state_groups = set( event_id_to_state_group[evid] for evid", "1: # If there is only one state group, then", "it. \"\"\" # map from state_group to ((type, key) ->", "events that have arrived at the server either as new", "room. Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]: Returns a tuple of", "ed ON e.event_id = ed.prev_event_id\" \" LEFT JOIN events_to_purge AS", "(event_id) \"\"\" ) referenced_state_groups = set(sg for sg, in txn)", "the events that we are persisting; that means we do", "txn.execute( \"DELETE FROM %s WHERE room_id = ? AND event_id", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "event_search table. self._store_room_topic_txn(txn, event) elif event.type == EventTypes.Message: # Insert", "WHERE event_id = ?\" ) txn.execute(sql, (metadata_json, event.event_id)) # Add", ") if not event.internal_metadata.is_outlier() and not context.rejected: depth_updates[event.room_id] = max(", "\"\"\", (room_id,), ) min_depth, = txn.fetchone() logger.info(\"[purge] updating room_depth to", "in (%s)\" % (\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id for event, _", "def _get_drainining_queue(self, room_id): queue = self._event_persist_queues.setdefault(room_id, deque()) try: while True:", "receiving it over federation) it will use the # forward", "logger.info( \"[purge] found %i referenced state groups\", len(referenced_state_groups) ) logger.info(\"[purge]", "of the latest persisted event \"\"\" partitioned = {} for", "group) -> delta state dict state_group_deltas = {} for ev,", "for event, context in chunk: events_by_room.setdefault(event.room_id, []).append( (event, context) )", "event, context in events_and_contexts: if event.type == EventTypes.Redaction and event.redacts", "# Finally handle the case where the new events have", "new current state is only returned if we've already calculated", "\" LIMIT ?\" ) txn.execute(sql, (-last_id, -current_id, limit)) new_event_updates =", "min_depth = ? WHERE room_id = ?\", (min_depth, room_id), )", "second being the delta to the existing current state. If", "self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[ { \"room_id\": room_id, \"event_id\": event_id, \"stream_ordering\":", "[ event for event, ctx in event_contexts if not event.internal_metadata.is_outlier()", "new_backwards_extrems], ) logger.info(\"[purge] finding redundant state groups\") # Get all", "queue: self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop off in", "etype, state_key, None, room_id, etype, state_key, ) for etype, state_key", "map room_id->(to_delete, to_insert) where to_delete is a list # of", "know that we've # only added or replaced state, never", "set() def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check = batch while to_recursively_check: sql", "\"\"\" if not events_and_contexts: return if backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult(", "We don't bother re-handling groups we've already seen prevs -=", "_count(txn): sql = \"\"\" SELECT COALESCE(COUNT(DISTINCT room_id), 0) FROM events", "in sqlite, # so make sure to keep this actually", "to be removed from the current state, and a state", "update, we # will block that for the rest of", "actually last. txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self, txn,", "15, 20, 50, 100, 200, 500, \"+Inf\"], ) # Read", "# We want to store event_auth mappings for rejected events,", "do this by calculating the minimum depth of the backwards", "Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" ) # The number of forward extremities", "self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) # We", "TODO: How does this work with backfilling? if hasattr(event, \"replaces_state\"):", "isinstance(out, bytes): out = out.decode(\"utf8\") return out class _EventPeristenceQueue(object): \"\"\"Queues", "FROM event_edges INNER JOIN events USING (event_id) LEFT JOIN rejections", "they're # used in state res v2. # This is", "estimate of the number of messages sent in the last", "JOIN events AS e ON e.event_id = eg.event_id WHERE eb.room_id", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "synapse.util.metrics import Measure logger = logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\")", ") def encode_json(json_object): \"\"\" Encode a Python object as JSON", "new_events_and_contexts[event.event_id] = (event, context) return list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn, events_and_contexts,", "We need to ensure we don't delete all the events", "(event_id) WHERE prev_event_id IN (%s) AND NOT events.outlier AND rejections.event_id", "finding # events to be purged that are pointed to", "so that it gets retried on IntegrityError, with `delete_existing=True` passed", "= {ev.event_id: ev for ev, _ in events_context} # We", "Apache License, Version 2.0 (the \"License\"); # you may not", "room_id, depth) def _update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update any outliers with", "room. new_latest_event_ids (iterable[str]): the new forward extremities for the room.", "vals[\"prev_state\"] = event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) # Prefill the", "deleting rather than updating if (etype, state_key) not in to_insert", "change in state continue # there should always be at", "event.room_id, \"auth_id\": auth_id, } for event, _ in events_and_contexts for", "logger.info(\"[purge] removing redundant state groups\") txn.executemany( \"DELETE FROM state_groups_state WHERE", "= set() for sg in referenced_groups: prev_sg = graph.get(sg) if", "events to persist backfilled (bool): True if the events were", "all_events_and_contexts=all_events_and_contexts, ) if not events_and_contexts: # nothing to do here", "SELECT event_id FROM events_to_purge WHERE should_delete\" \")\" % (table,) )", "if context.app_service: origin_type = \"local\" origin_entity = context.app_service.id elif self.hs.is_mine_id(event.sender):", "= ctx.delta_ids # We need to map the event_ids to", "# # furthermore, we might already have the table from", "SQL query getting too big if len(next_to_search) < 100: current_search", "the rejections table. Things reading from those table will need", "event, context, backfilled=False): \"\"\" Args: event (EventBase): context (EventContext): backfilled", "into the event_search table. self._store_room_message_txn(txn, event) elif event.type == EventTypes.Redaction:", "events that are going to be deleted. Returns: tuple[set[int], set[int]]:", "None: # If there is a delta we know that", "event_json # event_push_actions # event_reference_hashes # event_search # event_to_state_groups #", "minutes def read_forward_extremities(): # run as a background process to", "= yield func(self, *args, **kwargs) except self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res", ") referenced_state_groups = set(sg for sg, in txn) logger.info( \"[purge]", "we were # persisting. state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" )", "stream_ordering AND stream_ordering <= ?\" \" ORDER BY stream_ordering ASC\"", "new_state_groups} events_map = {ev.event_id: ev for ev, _ in events_context}", "% (table,) ) # event_push_actions lacks an index on event_id,", "type/state keys to remove from current state, and to_insert #", "( ( stream_id, room_id, etype, state_key, ev_id, room_id, etype, state_key,", "\"SELECT event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE ?", "event_id in (%s)\" % (\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id for event,", "== 1: # If there is only one state group,", "(event_id,)) # Delete all remote non-state events for table in", "= eg.event_id WHERE eb.room_id = ? \"\"\", (room_id,), ) min_depth,", "e.g. calculating state # groups to purge, etc., so lets", "on IntegrityError, with `delete_existing=True` passed in. Args: func: function that", "\"local_invites\", \"room_names\", \"state_events\", \"rejections\", \"redactions\", \"room_memberships\", \"topics\", ): txn.executemany( \"DELETE", "to_insert # is a map (type,key)->event_id giving the state delta", "no existing # extremities, so we'll `continue` above and skip", "or not. continue outlier_persisted = have_persisted[event.event_id] if not event.internal_metadata.is_outlier() and", "event_ids): \"\"\"Filter the supplied list of event_ids to get those", "_ in events_and_contexts: if event.type == EventTypes.Name: # Insert into", "in ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids()) if latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc()", "current # state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok, we need", "new_forward_extremeties={}, ): \"\"\"Insert some number of room events into the", "events_and_contexts (list[(EventBase, EventContext)]): events we are persisting backfilled (bool): True", "e.event_id IN (%s)\" ) % (\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql, list(ev_map))", "to report to return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60", ") with stream_ordering_manager as stream_orderings: for (event, context), stream in", "yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from preserve_events\") res = yield self._state_resolution_handler.resolve_state_groups(", "current_state_events\" \" WHERE room_id = ? AND type = ?", "the new forward extremities for a room given events to", "group -> previous group graph = {} # Set of", "here return logger.info(\"Deleting existing\") for table in ( \"events\", \"event_auth\",", "current_state_delta_stream WHERE ? < stream_id AND stream_id <= ? ORDER", "{ \"event_id\": event.event_id, \"room_id\": event.room_id, \"auth_id\": auth_id, } for event,", "defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self): def _count(txn): sql = \"\"\" SELECT", "# TODO: How does this work with backfilling? if hasattr(event,", "there is only a # single forward extremity state_delta_single_event_counter =", "key, state_id in iteritems(curr_state) ], ) logger.info(\"[purge] removing redundant state", "( \"UPDATE event_json SET internal_metadata = ?\" \" WHERE event_id", "_store_event_txn(self, txn, events_and_contexts): \"\"\"Insert new events into the event and", "\")\" % (table,), (room_id,), ) # Mark all state and", "= txn.fetchall() if len(new_backfill_events) == limit: upper_bound = new_backfill_events[-1][0] else:", "finally: queue = self._event_persist_queues.pop(room_id, None) if queue: self._event_persist_queues[room_id] = queue", "find it, then we'll need to pull # the state", "deletion). Args: txn state_groups (set[int]): Set of state groups referenced", "txn.execute( \"SELECT e.event_id, e.depth FROM events as e \" \"INNER", "def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that we don't have the same", "event_search tables. self._store_room_name_txn(txn, event) elif event.type == EventTypes.Topic: # Insert", "in. Args: func: function that returns a Deferred and accepts", "having any backwards extremeties) raise SynapseError( 400, \"topological_ordering is greater", "so we can # guess this by looking at the", "If the event is rejected then we don't care if", "number of times we are recalculating state when there is", "max_persisted_id)) def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks def persisting_queue(item): with Measure(self._clock, \"persist_events\"):", ") return txn.fetchall() res = yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount =", "own fault. like_clause = \"%:\" + self.hs.hostname sql = \"\"\"", "\" LEFT JOIN state_events USING (event_id)\" \" WHERE ? >", "state groups for any missing events from DB event_to_groups =", "_calculate_state_delta(self, room_id, current_state): \"\"\"Calculate the new state deltas for a", "ev_type, state_key in itertools.chain(to_delete, to_insert) if ev_type == EventTypes.Member )", "was an outlier or not. continue outlier_persisted = have_persisted[event.event_id] if", "only ones that weren't # rejected. self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts,", "they do we need to remove them and their prev", "% (table,), (room_id,), ) # Mark all state and own", "backward extremeties txn.executemany( \"INSERT INTO event_backward_extremities (room_id, event_id)\" \" VALUES", "for the batch of the events that we are persisting;", "txn.execute( \"INSERT INTO redactions (event_id, redacts) VALUES (?,?)\", (event.event_id, event.redacts),", "those table will need to check whether the event was", "prev_events and checking # if they match the current forward", "= \"\"\" SELECT prev_event_id, internal_metadata FROM event_edges INNER JOIN events", "(last_forward_id, current_forward_id, limit)) new_forward_events = txn.fetchall() if len(new_forward_events) == limit:", "are outliers and aren't going to be # deleted, as", "for ev, ctx in events_context: if event_id == ev.event_id and", "room_id, etype, state_key, None, room_id, etype, state_key, ) for etype,", "as outliers and deleting their state groups). \"\"\" return self.runInteraction(", "IN (SELECT event_id from events_to_purge)\" ) for event_id, _ in", "to be # deleted, as nothing will happen to them.", "to the normal usage pattern of this method, it does", "to store them (and # it doesn't take much storage", "self._event_persist_queues.pop(room_id, None) if queue: self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id) # set", "event %s\" % (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self,", "-current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates) == limit: upper_bound", "graph.get(sg) if prev_sg and prev_sg in to_delete: to_dedelta.add(sg) return to_delete,", "ev_id in iteritems(current_state) if ev_id != existing_state.get(key) } defer.returnValue((to_delete, to_insert))", "AND event_stream_ordering <= ?\" \" ORDER BY event_stream_ordering DESC\" )", "later we'll be looking for # the should_delete / shouldn't_delete", "groups to handle next. next_to_search = set(state_groups) while next_to_search: #", "if necessary. current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids is not None:", "result.difference_update( e_id for event in new_events for e_id in event.prev_event_ids()", "in compliance with the License. # You may obtain a", "queue[-1] if end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred =", "in events_and_contexts: if event.event_id not in have_persisted: continue to_remove.add(event) if", "# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd", "do here return logger.info(\"Deleting existing\") for table in ( \"events\",", "should_delete_expr), should_delete_params, ) # We create the indices *after* insertion", "if not ev.internal_metadata.is_outlier(): raise Exception( \"Context for new event %s", "state set. missing_state = new_state_groups - set(state_groups_map) if missing_state: group_to_state", "synapse.storage.events_worker import EventsWorkerStore from synapse.storage.state import StateGroupWorkerStore from synapse.types import", "called with new items, unless the queue becomnes empty. The", "faster. # create an index on should_delete because later we'll", "into the necessary database tables. Rejected events are only inserted", "= ?\", ( (room_id, etype, state_key) for etype, state_key in", "\"\"\"Persist events to db Args: events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool):", "@defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed ancestors to remove from", "ignore backfill/outliers/etc) if result != latest_event_ids: forward_extremities_counter.observe(len(result)) stale = latest_event_ids", "if event.type == EventTypes.Member ], backfilled=backfilled, ) # Insert event_reference_hashes", "elif event.type == EventTypes.GuestAccess: # Insert into the event_search table.", "= self._event_persist_queues.setdefault(room_id, deque()) try: while True: yield queue.popleft() except IndexError:", "and own events as outliers logger.info(\"[purge] marking remaining events as", "event, _ in events_and_contexts] ) for event, _ in events_and_contexts:", "(bool): True if the events were backfilled \"\"\" depth_updates =", "# Insert into the event_search table. self._store_room_message_txn(txn, event) elif event.type", "txn.execute(sql, (last_id, upper_bound)) new_event_updates.extend(txn) return new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows", "except IndexError: # Queue has been drained. pass _EventCacheEntry =", "# Get all state groups that are referenced by events", "should_delete_params = () if not delete_local_events: should_delete_expr += \" AND", "room version, which is in the create event. # Normally", "FROM events WHERE type = 'm.room.message' AND sender LIKE ?", "send any events (due to not # having any backwards", "in partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id =", "events_to_purge\") event_rows = txn.fetchall() logger.info( \"[purge] found %i events before", "can just # return that. new_state_group = next(iter(new_state_groups)) old_state_group =", "also return that, # but it doesn't matter if we", "# groups to purge, etc., so lets make an index.", "ed.prev_event_id\" \" LEFT JOIN events_to_purge AS ep2 ON ed.event_id =", "easily parallelize these since different chunks # might contain the", "with Measure( self._clock, \"persist_events.get_new_state_after_events\" ): res = yield self._get_new_state_after_events( room_id,", "out state that has already # been cached in the", "stop the # SQL query getting too big if len(next_to_search)", "in chunks: # We can't easily parallelize these since different", "some tables already having # entries. self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts)", "we're not going to # purge. txn.execute( \"SELECT DISTINCT e.event_id", "are prev_events of existing (non-outlier/rejected) events. Args: event_ids (Iterable[str]): event", "JOIN event_edges AS eg ON eg.prev_event_id = eb.event_id INNER JOIN", "an event we were # persisting. state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\",", "to make sure that the database transactions # have a", "backwards # extremities. However, the events in event_backward_extremities # are", "of which %i can be deleted\", len(event_rows), sum(1 for e", "( \"url\" in event.content and isinstance(event.content[\"url\"], text_type) ), } for", "to_insert): where to_delete are the type/state_keys to remove from current_state_events", ") txn.execute(sql, (metadata_json, event.event_id)) # Add an entry to the", "*args, delete_existing=True, **kwargs) defer.returnValue(res) return f # inherits from EventFederationStore", "with the License. # You may obtain a copy of", "queue, of type _EventPersistQueueItem. The per_item_callback will continuously be called", "we've # only added or replaced state, never # removed", "prev events for. Note that these must have already been", "for ev, _ in ev_ctx_rm: prev_event_ids = set(ev.prev_event_ids()) if latest_event_ids", "Note that we insert events that are outliers and aren't", "otherwise we wouldn't be able to send any events (due", "continue # there should always be at least one forward", "\"topics\", ): txn.executemany( \"DELETE FROM %s WHERE event_id = ?\"", "next_to_search: # We bound size of groups we're looking up", "Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\", \"origin_entity\"], ) # The number", "prometheus_client import Counter, Histogram from twisted.internet import defer import synapse.metrics", "self._update_metadata_tables_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def _update_current_state_txn(self, txn, state_delta_by_room,", "event_edges INNER JOIN events USING (event_id) LEFT JOIN rejections USING", "us to not have to pull out the existing state", "_ in events_and_contexts], ) for table in (\"event_push_actions\",): txn.executemany( \"DELETE", "queue self._currently_persisting_rooms.discard(room_id) # set handle_queue_loop off in the background run_as_background_process(\"persist_events\",", "don't # want to set the event_persisted_position to that. synapse.metrics.event_persisted_position.set(", "redactions table. self._store_redaction(txn, event) elif event.type == EventTypes.RoomHistoryVisibility: # Insert", "already # been cached in the context. We'll pull stuff", "this before updating the current_state_events table so # that we", "the new \"current state\" for each room. # We do", "Args: func: function that returns a Deferred and accepts a", "txn.fetchall() if len(new_backfill_events) == limit: upper_bound = new_backfill_events[-1][0] else: upper_bound", "event_backward_extremities (room_id, event_id)\" \" VALUES (?, ?)\", [(room_id, event_id) for", "for the redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT INTO redactions", "except in compliance with the License. # You may obtain", "in new_latest_event_ids ) # If they old and new groups", "from state_group to ((type, key) -> event_id) state map state_groups_map", "2018-2019 New Vector Ltd # Copyright 2019 The Matrix.org Foundation", "room_id = ? AND event_id = ?\" % (table,), [(ev.room_id,", "backfilled \"\"\" depth_updates = {} for event, context in events_and_contexts:", "a list of type/state keys to be removed from the", "which state groups can be deleted and which need to", "} for event, _ in events_and_contexts for auth_id in event.auth_event_ids()", "extremeties) raise SynapseError( 400, \"topological_ordering is greater than forward extremeties\"", "a list of the event ids which are the forward", "NOT NULL,\" \" should_delete BOOLEAN NOT NULL\" \")\" ) #", "in rows: # Note: Each state group can have at", "DISTINCT state_group FROM events_to_purge INNER JOIN event_to_state_groups USING (event_id) \"\"\"", "\"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True, ) if not res: raise SynapseError(404,", "CONDITIONS OF ANY KIND, either express or implied. # See", "\" LIMIT ?\" ) if have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit))", "going to be deleted. Returns: tuple[set[int], set[int]]: The set of", "WHERE event_id IN (%s) AND NOT events.outlier \"\"\" % (", "state_key) not in to_insert ), ) txn.executemany( sql, ( (", "cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def _store_redaction(self, txn, event):", "Set of state groups to handle next. next_to_search = set(state_groups)", "= namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\") ) def __init__(self): self._event_persist_queues", "used to prefill the get_current_state_ids # cache current_state_for_room = {}", "single state set. missing_state = new_state_groups - set(state_groups_map) if missing_state:", "since the last call to this function, it will return", "have_backfill_events = last_backfill_id != current_backfill_id have_forward_events = last_forward_id != current_forward_id", "can # guess this by looking at the prev_events and", "\"\": room_version = ev.content.get(\"room_version\", \"1\") break if not room_version: room_version", "# cache current_state_for_room = {} # map room_id->(to_delete, to_insert) where", "if True, we will delete local events as well as", "missing_state = new_state_groups - set(state_groups_map) if missing_state: group_to_state = yield", "not have_forward_events: return defer.succeed(AllNewEventsResult([], [], [], [], [])) def get_all_new_events_txn(txn):", "room_id ) new_latest_event_ids = yield self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids )", "to do here return logger.info(\"Deleting existing\") for table in (", "recalculating the current state state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\") # The", "deleted # and which we have added, then we invlidate", "event_to_state_groups # events # rejections # room_depth # state_groups #", "these since different chunks # might contain the same event.", "if the latest extremities # were the same when we", "state, and to_insert # is a map (type,key)->event_id giving the", "event, _ in events_and_contexts], ) have_persisted = {event_id: outlier for", "(-last_id, -current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates) == limit:", "# Otherwise we need to pull the state group from", "as outliers\") txn.execute( \"UPDATE events SET outlier = ?\" \"", "USING (event_id)\" \" WHERE ? < stream_ordering AND stream_ordering <=", "defer.returnValue((to_delete, to_insert)) @log_function def _persist_events_txn( self, txn, events_and_contexts, backfilled, delete_existing=False,", "= current_id sql = ( \"SELECT event_stream_ordering, e.event_id, e.room_id, e.type,\"", "non-state events for table in ( \"events\", \"event_json\", \"event_auth\", \"event_edges\",", "it # persists events (because upsert), and once we run", "end up in a situation where workers see events before", "LEFT JOIN redactions as r ON e.event_id = r.redacts\" \"", "groups that are referenced. current_search -= referenced rows = self._simple_select_many_txn(", "stale forward extremities for each new event. Stale extremities #", "for event_id, prev_event_id, metadata, rejected in txn: if prev_event_id in", "count ret = yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self):", "txn, events_and_contexts): to_prefill = [] rows = [] N =", "[(ev.room_id, ev.event_id) for ev, _ in events_and_contexts], ) def _store_event_txn(self,", "txn.execute(sql, (last_forward_id, current_forward_id, limit)) new_forward_events = txn.fetchall() if len(new_forward_events) ==", "delete_existing=False ): \"\"\"Persist events to db Args: events_and_contexts (list[(EventBase, EventContext)]):", "persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter = Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\",", "not json.loads(r[1]).get(\"soft_failed\")) for chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_events_which_are_prevs\",", "creates a new event (as opposed # to receiving it", "none of the old # extremities are going to be", "that we are only persisting events for one room #", "# We now insert into stream_ordering_to_exterm a mapping from room_id,", "in is if the latest extremities # were the same", "Don't bother calculating state if they're just # a long", "event # persistence. # # We do this by calculating", "add_to_queue(self, room_id, events_and_contexts, backfilled): \"\"\"Add events to the queue, with", "those could both be moved in here) class EventsStore( StateGroupWorkerStore,", "but are separated by soft failed events. Args: event_ids (Iterable[str]):", "# so make sure to keep this actually last. txn.execute(\"DROP", "( stream_id, room_id, etype, state_key, ev_id, room_id, etype, state_key, )", "guess this by looking at the prev_events and checking #", "new forward extremities for each room. For each room, a", "txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\",", "if event_id1 is after event_id2 in the stream \"\"\" to_1,", "Insert the event_id into the rejections table self._store_rejections_txn(txn, event.event_id, context.rejected)", "current state, and a state set to be added to", ") for table in (\"event_push_actions\",): txn.executemany( \"DELETE FROM %s WHERE", "can resolve to a single state set. missing_state = new_state_groups", "values=[ { \"event_id\": ev_id, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1],", "JOIN event_relations USING (event_id)\" \" WHERE ? < event_stream_ordering\" \"", "= all( len(event.prev_event_ids()) == 1 and not event.is_state() for event,", "persisted, and returns the filtered list. events_and_contexts = self._update_outliers_txn( txn,", "the same event. :( # NB: Assumes that we are", "= yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks def", "if we've already calculated it. \"\"\" # map from state_group", "two state maps, the first being the full new current", "get_all_updated_current_state_deltas_txn, ) AllNewEventsResult = namedtuple( \"AllNewEventsResult\", [ \"new_forward_events\", \"new_backfill_events\", \"forward_ex_outliers\",", "state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) # Ok, we need to defer", "other events # or state groups, and if not we", "backfilled events have reached\"\"\" return -self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The current", "Collect metrics on the number of forward extremities that exist.", "given) if delta_ids is not None: # If there is", "{sg: state_groups_map[sg] for sg in new_state_groups} events_map = {ev.event_id: ev", "prev_events of any existing events. existing_prevs = yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs)", "the same when we created the event as they are", "the rejected event appears in an accepted # event's auth", "do this first. # # furthermore, we might already have", "to_delete is a list # of type/state keys to remove", "res = yield self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids, ) current_state,", "OpenMarket Ltd # Copyright 2018-2019 New Vector Ltd # Copyright", ") txn.execute(sql, (last_id, current_id, limit)) new_event_updates = txn.fetchall() if len(new_event_updates)", "purge. txn.execute( \"SELECT DISTINCT e.event_id FROM events_to_purge AS e\" \"", "# state_groups_state # we will build a temporary table listing", "we don't have the same event twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates(", ") self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled ) # _update_outliers_txn filters out", "If there has been a change then we only return", "new event. Stale extremities # are those that were in", ") prevs = set(row[\"state_group\"] for row in rows) # We", "of stale forward extremities for each new event. Stale extremities", "backward_ex_outliers = txn.fetchall() else: new_backfill_events = [] backward_ex_outliers = []", "know what the current # state is. defer.returnValue((state_groups_map[new_state_groups.pop()], None)) #", "self._purge_history_txn, room_id, token, delete_local_events, ) def _purge_history_txn(self, txn, room_id, token_str,", "the table first. txn.execute(\"DROP TABLE IF EXISTS events_to_purge\") txn.execute( \"CREATE", "item. end_item = queue[-1] if end_item.backfilled == backfilled: end_item.events_and_contexts.extend(events_and_contexts) return", "This is used to find extremities that are ancestors of", "same event twice. Pick the earliest non-outlier if there is", "* len(events_and_contexts)),), [event.event_id for event, _ in events_and_contexts], ) have_persisted", "event = ev_map[row[\"event_id\"]] if not row[\"rejects\"] and not row[\"redacts\"]: to_prefill.append(", "get_current_backfill_token(self): \"\"\"The current minimum token that backfilled events have reached\"\"\"", "!= existing_state.get(key) } defer.returnValue((to_delete, to_insert)) @log_function def _persist_events_txn( self, txn,", "permissions and # limitations under the License. import itertools import", "this bit.) assert new_latest_event_ids, \"No forward extremities left!\" new_forward_extremeties[room_id] =", "event_id FROM current_state_events WHERE room_id = ? AND type =", "% (ev.event_id,) ) continue if ctx.state_group in state_groups_map: continue #", "?\" % (table,), [(ev.room_id, ev.event_id) for ev, _ in events_and_contexts],", "# nothing to do here return logger.info(\"Deleting existing\") for table", "the # redacted event. self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts ) #", "a delta we know that we've # only added or", "\" ORDER BY stream_ordering DESC\" \" LIMIT ?\" ) if", ") # Now we actually update the current_state_events table txn.executemany(", "outlier in the database. We now have some state at", "going to # purge. txn.execute( \"SELECT DISTINCT e.event_id FROM events_to_purge", "state from the database missing_event_ids.add(event_id) if missing_event_ids: # Now pull", "type, state_key, event_id, prev_event_id) SELECT ?, ?, ?, ?, ?,", "] state_values = [] for event, context in state_events_and_contexts: vals", "# Note that we insert events that are outliers and", "room_id, # new stream_ordering to new forward extremeties in the", "update the current state etc. Returns: Deferred[int]: the stream ordering", "is a delta we know that we've # only added", "so_2 = yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) > (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000)", "iteritems(state_delta_by_room): to_delete, to_insert = current_state_tuple # First we add entries", "+ N]} if not ev_map: break sql = ( \"SELECT", "we # will block that for the rest of our", "if state groups are referenced sql = \"\"\" SELECT DISTINCT", "e LEFT JOIN state_events USING (event_id)\" \" WHERE (NOT outlier", "): logger.info(\"[purge] removing events from %s\", table) txn.execute( \"DELETE FROM", "state # unnecessarily). # # The stream_id for the update", "new_events_and_contexts = OrderedDict() for event, context in events_and_contexts: prev_event_context =", "they can be persisted in bulk with only one concurrent", "event_id, prev_event_id, metadata, rejected in txn: if prev_event_id in existing_prevs:", "return count ret = yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def", "recurses up the prev-event graph until it finds no more", "ancestors to remove from the extremities. Given a set of", "one prev group graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete = state_groups_seen -", "stream chunks = [ events_and_contexts[x : x + 100] for", "depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth) def _update_outliers_txn(self, txn, events_and_contexts):", "anything is added to the queue. If another callback is", "lacks an index on event_id, and has one on #", "etype, state_key) for etype, state_key in itertools.chain(to_delete, to_insert) ), )", "into the topics table and event_search table. self._store_room_topic_txn(txn, event) elif", "the # transaction on CREATE, so let's do this first.", "LEFT JOIN state_events USING (event_id)\" \" WHERE ? < stream_ordering", "state_key, event_id FROM current_state_delta_stream WHERE ? < stream_id AND stream_id", "of times we are reculating state when we could have", "events and contexts which are being added to the room", "logcontext to report to return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities,", "than updating if (etype, state_key) not in to_insert ), )", "= ?\", (room_id,), ) rows = txn.fetchall() max_depth = max(row[1]", "persist_events(self, events_and_contexts, backfilled=False): \"\"\" Write events to the database Args:", "iteritems(current_state) if ev_id != existing_state.get(key) } defer.returnValue((to_delete, to_insert)) @log_function def", "we pop, as OrderedDict is # ordered by first insertion.", "soft-failed ancestors to remove from the extremities. Given a set", "Returns: Deferred[List[str]]: filtered event ids \"\"\" results = [] def", "be called with new items, unless the queue becomnes empty.", "= yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from preserve_events\") res = yield", "and contexts which are being added to the room old_latest_event_ids", "the prev_events and checking # if they match the current", ") # We create the indices *after* insertion as that's", "the old # extremities are going to be in events_context).", "can be deleted\", len(event_rows), sum(1 for e in event_rows if", "get_all_new_events_txn) def purge_history(self, room_id, token, delete_local_events): \"\"\"Deletes room history before", "by working out what the new extremities are and then", "\"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\", \"room_names\", \"state_events\",", "update the state_groups table with that state. # insert into", "# have guessed what the delta would have been when", "up the prev-event graph until it finds no more soft-failed/rejected", "sql, ( ( stream_id, room_id, etype, state_key, ev_id, room_id, etype,", "== 1 and len(new_latest_event_ids) == 1 ) if len_1: all_single_prev_not_state", "LEFT JOIN state_events USING (event_id)\" \" LEFT JOIN event_relations USING", "to_token, limit)) return txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult", "change, # and we need to work out the delta", "these new events to that item. end_item = queue[-1] if", "events Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events", "one state group to another, lets check if # we", "by applicable law or agreed to in writing, software #", "ev_map = {e[0].event_id: e[0] for e in events_and_contexts[i : i", "\"\"\" % ( \",\".join(\"?\" for _ in current_search), ) txn.execute(sql,", "JOIN state_events USING (event_id)\" \" WHERE ? > stream_ordering AND", "def persisting_queue(item): with Measure(self._clock, \"persist_events\"): yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled )", "LIMIT ?\" ) if have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit)) new_backfill_events", "stream_orderings): event.internal_metadata.stream_ordering = stream chunks = [ events_and_contexts[x : x", "pattern of this method, it does *not* follow the synapse", "iteritems(to_insert) ], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id, ) # Invalidate", "be deleted and which need to be de-delta'ed (due to", "events_and_contexts: if context.rejected: # Insert the event_id into the rejections", "txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete all remote non-state events for table", "events_to_purge (\" \" event_id TEXT NOT NULL,\" \" should_delete BOOLEAN", "len(old_state_groups) == 1: # If we're going from one state", "the full # state in each room after adding these", "res = yield self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self), )", "**kwargs) defer.returnValue(res) return f # inherits from EventFederationStore so that", "# currently trying to persist it. room_version = None for", "allows us to not have to pull out the existing", "# We calculate the new entries for the backward extremeties", "for key in existing_state if key not in current_state] to_insert", "\"SELECT e.event_id, e.depth FROM events as e \" \"INNER JOIN", "events. Args: event_ids (Iterable[str]): event ids to filter Returns: Deferred[List[str]]:", "), \"json\": encode_json(event_dict(event)), \"format_version\": event.format_version, } for event, _ in", "True if the events were backfilled delete_existing (bool): True to", "( len(latest_event_ids) == 1 and len(new_latest_event_ids) == 1 ) if", "extremeties # for a room before a given stream_ordering self._simple_insert_many_txn(", "# SQL query getting too big if len(next_to_search) < 100:", "in events_context: if ctx.state_group is None: # This should only", "table. self._store_room_topic_txn(txn, event) elif event.type == EventTypes.Message: # Insert into", "Returns: list[(EventBase, EventContext)]: filtered list \"\"\" new_events_and_contexts = OrderedDict() for", "def persist_event(self, event, context, backfilled=False): \"\"\" Args: event (EventBase): context", "self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn,", "state_group_id = context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order, \"event_id\":", "for event, context in state_events_and_contexts: vals = { \"event_id\": event.event_id,", "state_groups # state_groups_state # we will build a temporary table", "defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks def persisting_queue(item): with Measure(self._clock,", "\"Could not find event %s\" % (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"]))", "eg ON eg.prev_event_id = eb.event_id INNER JOIN events AS e", "applicable law or agreed to in writing, software # distributed", "database missing_event_ids.add(event_id) if missing_event_ids: # Now pull out the state", "\" state_key, redacts\" \" FROM events AS e\" \" LEFT", "stick it at the end so that we don't block", "context) backfilled (bool): Whether the results are retrieved from federation", "useful when retrying due to IntegrityError. state_delta_for_room (dict[str, (list, dict)]):", "we do then we can just # return that. new_state_group", "(bool): Returns: Deferred: resolves when the events have been persisted", "adding. for ev, ctx in events_context: if event_id == ev.event_id", "extremity. # (except during the initial persistence of the send_join", "current state etc. Returns: Deferred[int]: the stream ordering of the", "minimum of the stream_ids # for the batch of the", "depth_updates.get(event.room_id, event.depth) ) for room_id, depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id,", "\" \"WHERE event_id IN (SELECT event_id from events_to_purge)\" ) for", "we can reinsert them. # This gets around any problems", "events as well as remote ones (instead of just marking", "rejected events. \"\"\" # Remove the rejected events from the", "forward extremities that exist. # Counter of number of extremities", "room # at a time. # map room_id->list[event_ids] giving the", "event_to_groups = yield self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups of old_latest_event_ids", "We have a delta from the existing to new current", "if not events_and_contexts: return if backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts)", "in (\"event_push_actions\",): logger.info(\"[purge] removing events from %s\", table) txn.execute( \"DELETE", "# # The stream_id for the update is chosen to", "resolve once the events are persisted. Runs its callbacks *without*", "consumeErrors=True) ) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function def", "in pulling out state that has already # been cached", "\"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\", \"guest_access\", \"history_visibility\", \"local_invites\",", "SELECT event_id, %s\" \" FROM events AS e LEFT JOIN", "room_memberships table. self._store_room_members_txn( txn, [ event for event, _ in", "WHERE room_id = ?\", (room_id,) ) # Update backward extremeties", "have soft-failed prev # events. If they do we need", "leaves the logcontext in place whether or not the returned", "go and check if they are referenced by other events", "# The number of times we are recalculating the current", "for. Note that these must have already been persisted. Returns:", "\"\"\" to_1, so_1 = yield self._get_event_ordering(event_id1) to_2, so_2 = yield", "your own fault. like_clause = \"%:\" + self.hs.hostname sql =", "aren't outliers and which aren't # being rejected. new_events =", "len(new_latest_event_ids) == 1 ) if len_1: all_single_prev_not_state = all( len(event.prev_event_ids())", "self._handle_redaction(txn, event.redacts) # Update the event_forward_extremities, event_backward_extremities and # event_edges", "new_forward_events[-1][0] else: upper_bound = current_forward_id sql = ( \"SELECT event_stream_ordering,", "the list result.update(event.event_id for event in new_events) # Now remove", ") # If they old and new groups are the", "defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id,", "key in existing_state if key not in current_state] to_insert =", "self._current_forward_extremities_amount, buckets=[1, 2, 3, 5, 7, 10, 15, 20, 50,", "the current state in memory then lets also return that,", "set(itertools.islice(next_to_search, 100)) next_to_search -= current_search # Check if state groups", "another callback is currently handling the queue then it will", "True if the events were backfilled \"\"\" depth_updates = {}", "to_1, so_1 = yield self._get_event_ordering(event_id1) to_2, so_2 = yield self._get_event_ordering(event_id2)", "for i in range(0, len(events_and_contexts), N): ev_map = {e[0].event_id: e[0]", "\"\"\" partitioned = {} for event, ctx in events_and_contexts: partitioned.setdefault(event.room_id,", "should_delete_params += (\"%:\" + self.hs.hostname, \"%:\" + self.hs.hostname) should_delete_params +=", "in rows) if max_depth < token.topological: # We need to", "\" WHERE e.event_id IN (%s)\" ) % (\",\".join([\"?\"] * len(ev_map)),)", "N = 200 for i in range(0, len(events_and_contexts), N): ev_map", "= new_latest_event_ids len_1 = ( len(latest_event_ids) == 1 and len(new_latest_event_ids)", "# Remove any events which are prev_events of any existing", "len(ev_map)),) txn.execute(sql, list(ev_map)) rows = self.cursor_to_dict(txn) for row in rows:", "get_all_new_forward_event_rows(self, last_id, current_id, limit): if last_id == current_id: return defer.succeed([])", "prevs = set(row[\"state_group\"] for row in rows) # We don't", "100, 200, 500, \"+Inf\"), ) def encode_json(json_object): \"\"\" Encode a", "can be persisted in bulk with only one concurrent transaction", "room_id, current_state_tuple in iteritems(state_delta_by_room): to_delete, to_insert = current_state_tuple # First", "\"License\"); # you may not use this file except in", "= latest_event_ids & result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids):", "This is a fairly handwavey check to see if we", "AND stream_ordering > ? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count, = txn.fetchone()", "returns the filtered list. events_and_contexts = self._update_outliers_txn( txn, events_and_contexts=events_and_contexts )", "# otherwise we end up with dangling extremities. existing_prevs =", "the delta then the new current state is only returned", "as a background process to make sure that the database", "self._event_persist_queues = {} self._currently_persisting_rooms = set() def add_to_queue(self, room_id, events_and_contexts,", "the event ids which are the forward extremities. \"\"\" all_events_and_contexts", "for each new event. Stale extremities # are those that", "EventContext)]): events to persist backfilled (bool): True if the events", "state_group to ((type, key) -> event_id) state map state_groups_map =", "in the context. We'll pull stuff out of the DB", ") self._simple_delete_txn( txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn( txn, table=\"state_groups_state\",", "finds no more soft-failed/rejected events. This is used to find", "cache self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self, txn, events_and_contexts): to_prefill = []", "logger.info(\"[purge] replacing backward extremities: %r\", new_backwards_extrems) txn.execute( \"DELETE FROM event_backward_extremities", "WHERE (NOT outlier OR (%s)) AND e.room_id = ? AND", "we are persisting backfilled (bool): True if the events were", "_store_rejected_events_txn filters out any events which were # rejected, and", "event_id = ?\" ) txn.execute(sql, (metadata_json, event.event_id)) # Add an", "cached, cachedInlineCallbacks from synapse.util.frozenutils import frozendict_json_encoder from synapse.util.logcontext import PreserveLoggingContext,", "# The number of times we are recalculating state when", "backfilled: end_item.events_and_contexts.extend(events_and_contexts) return end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem(", "res: raise SynapseError(404, \"Could not find event %s\" % (event_id,))", "room_id, etype, state_key, ) for etype, state_key in to_delete #", "events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) #", ") current_state, delta_ids = res # If either are not", "self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop(): try: queue = self._get_drainining_queue(room_id)", "current_search), ) txn.execute(sql, list(current_search)) referenced = set(sg for sg, in", "sent in the last day. If it has been significantly", "= ev_map[row[\"event_id\"]] if not row[\"rejects\"] and not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event,", "that returns a Deferred and accepts a `delete_existing` arg \"\"\"", ") persist_event_counter.inc(len(chunk)) if not backfilled: # backfilled events have negative", "# processing one of these events. # What we're interested", "can be deleted and which need to be de-delta'ed (due", "an estimate of the number of messages sent in the", "(room_id,), ) min_depth, = txn.fetchone() logger.info(\"[purge] updating room_depth to %d\",", "an exclusive lock on room_depth whenever it # persists events", "from events_to_purge)\" ) for event_id, _ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,))", "Matrix.org Foundation C.I.C. # # Licensed under the Apache License,", "self.runInteraction( \"purge_history\", self._purge_history_txn, room_id, token, delete_local_events, ) def _purge_history_txn(self, txn,", "events are only inserted into the events table, the events_json", "previous group graph = {} # Set of events that", "# We find out which membership events we may have", "ev, _ in events_and_contexts], ) def _store_event_txn(self, txn, events_and_contexts): \"\"\"Insert", "import Counter as c_counter, OrderedDict, deque, namedtuple from functools import", "filter Returns: Deferred[List[str]]: filtered event ids \"\"\" results = []", "don't # have to keep shovelling the list back and", "to be referenced by events referenced_groups = set() # Set", "via event_edges table. txn.execute( \"\"\" SELECT COALESCE(MIN(depth), 0) FROM event_backward_extremities", "if not row[\"rejects\"] and not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) )", "= yield self._state_resolution_handler.resolve_state_groups( room_id, room_version, state_groups, events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state,", "some number of room events into the necessary database tables.", "def _get_new_state_after_events( self, room_id, events_context, old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate the", "self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts ) # From this point onwards the", "to_insert) where to_delete is a list # of type/state keys", "use it to calculate the `prev_event_id`. (This # allows us", "and prev_sg in to_delete: to_dedelta.add(sg) return to_delete, to_dedelta @defer.inlineCallbacks def", "persistence. # # We do this by calculating the minimum", "def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks def persisting_queue(item): with Measure(self._clock, \"persist_events\"): yield", "be the minimum of the stream_ids # for the batch", "only one state group, then we know what the current", "an entry to the ex_outlier_stream table to replicate the #", "= yield self.get_current_state_ids(room_id) to_delete = [key for key in existing_state", "# (e.g. we ignore backfill/outliers/etc) if result != latest_event_ids: forward_extremities_counter.observe(len(result))", "# room_depth # state_groups # state_groups_state # we will build", "appear in events_and_context. backfilled (bool): True if the events were", "room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id,", "chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk )", "tables for new events Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts", "event %s has no state \" \"group\" % (ev.event_id,) )", "AS e\" \" INNER JOIN event_edges AS ed ON e.event_id", "has no state \" \"group\" % (ev.event_id,) ) continue if", "index. txn.execute(\"CREATE INDEX events_to_purge_id\" \" ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete", "event.internal_metadata.stream_ordering state_group_id = context.state_group self._simple_insert_txn( txn, table=\"ex_outlier_stream\", values={ \"event_stream_ordering\": stream_order,", "\"state_events\", \"rejections\", \"redactions\", \"room_memberships\", \"topics\", ): txn.executemany( \"DELETE FROM %s", "AND event_id IN (\" \" SELECT event_id FROM events_to_purge WHERE", "only persisting events for one room at a time. Returns:", "will block that for the rest of our transaction. #", "# Now we actually update the current_state_events table txn.executemany( \"DELETE", "new. stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged forward extremities", "as remote ones (instead of just marking them as outliers", "events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): delete_existing (bool): Returns: Deferred: resolves", "that these must have already been persisted. Returns: Deferred[set[str]] \"\"\"", "due to the normal usage pattern of this method, it", "not backfilled: # backfilled events have negative stream orderings, so", "# The number of stale forward extremities for each new", "will need to check whether the event was rejected. Args:", ") # The number of times we are reculating state", "check whether the event was rejected. Args: txn (twisted.enterprise.adbapi.Connection): db", "found %i state groups to delete\", len(state_groups_to_delete) ) logger.info( \"[purge]", "# having any backwards extremeties) raise SynapseError( 400, \"topological_ordering is", "event_json tables Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]):", "= ? \"\"\", (room_id,), ) min_depth, = txn.fetchone() logger.info(\"[purge] updating", "ones (instead of just marking them as outliers and deleting", "event.room_id, [(event, context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id =", "JOIN events_to_purge AS ep USING (event_id) WHERE state_group IN (%s)", "100] for x in range(0, len(events_and_contexts), 100) ] for chunk", "for row in rows) # We don't bother re-handling groups", "to_delete, to_dedelta @defer.inlineCallbacks def is_event_after(self, event_id1, event_id2): \"\"\"Returns True if", "_EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler() # Collect metrics on the number", "topics table and event_search table. self._store_room_topic_txn(txn, event) elif event.type ==", ") hs.get_clock().looping_call(read_forward_extremities, 60 * 60 * 1000) @defer.inlineCallbacks def _read_forward_extremities(self):", "_ in events_and_contexts] ) for event, _ in events_and_contexts: if", "up with dangling extremities. existing_prevs = yield self._get_prevs_before_rejected( e_id for", "latest_event_ids & result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter", "rows = txn.fetchall() max_depth = max(row[1] for row in rows)", "event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute( \"INSERT INTO redactions (event_id, redacts) VALUES", "ec for ec in events_and_contexts if ec[0].is_state() ] state_values =", "upsert), and once we run this update, we # will", "exclusive lock on room_depth whenever it # persists events (because", "in new events which aren't outliers and which aren't #", "the current_state_events table txn.executemany( \"DELETE FROM current_state_events\" \" WHERE room_id", "events AS e LEFT JOIN state_events USING (event_id)\" \" WHERE", "yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self): def _count(txn): sql", "5, 7, 10, 15, 20, 50, 100, 200, 500, \"+Inf\"),", "redacts) VALUES (?,?)\", (event.event_id, event.redacts), ) @defer.inlineCallbacks def count_daily_messages(self): \"\"\"", "that we're deleting rather than updating if (etype, state_key) not", "= ? AND topological_ordering < ?\" % (should_delete_expr, should_delete_expr), should_delete_params,", "[ events_and_contexts[x : x + 100] for x in range(0,", "well. This function should therefore be called whenever anything is", "the event cache self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self, txn, events_and_contexts): to_prefill", "make sure to keep this actually last. txn.execute(\"DROP TABLE events_to_purge\")", "events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if not backfilled:", "elif event.type == EventTypes.Message: # Insert into the event_search table.", "event, context in chunk: if context.app_service: origin_type = \"local\" origin_entity", "calculate the new entries for the backward extremeties by finding", "def read_forward_extremities(): # run as a background process to make", "\" \"WHERE f.room_id = ?\", (room_id,), ) rows = txn.fetchall()", "will commit the txn in sqlite, # so make sure", "map the event_ids to their state groups. First, let's #", "deque, namedtuple from functools import wraps from six import iteritems,", "WHERE event_id = ?\" % (table,), [(ev.event_id,) for ev, _", "handle_queue_loop off in the background run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self, room_id):", "list of new events we're adding. for ev, ctx in", "# Insert all the push actions into the event_push_actions table.", "\" \"group\" % (ev.event_id,) ) continue if ctx.state_group in state_groups_map:", "the redactions table. self._store_redaction(txn, event) elif event.type == EventTypes.RoomHistoryVisibility: #", "from synapse.storage.events_worker import EventsWorkerStore from synapse.storage.state import StateGroupWorkerStore from synapse.types", "for new events Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase,", "one on # (room_id, event_id) instead. for table in (\"event_push_actions\",):", "x + 100] for x in range(0, len(events_and_contexts), 100) ]", "a certain point Args: room_id (str): token (str): A topological", "= set(row[\"state_group\"] for row in rows) # We don't bother", "queue = self._event_persist_queues.pop(room_id, None) if queue: self._event_persist_queues[room_id] = queue self._currently_persisting_rooms.discard(room_id)", "of messages sent in the last day. If it has", "IndexError: # Queue has been drained. pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\",", "limit)) return txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult =", "if delta_ids is not None: # We have a delta", "going to persist. This includes events we've already persisted, etc,", "keys to remove from current state, and to_insert # is", "the database, but its also possible that we're # currently", "pop, as OrderedDict is # ordered by first insertion. new_events_and_contexts.pop(event.event_id,", "if ec[0] not in to_remove] @classmethod def _delete_existing_rows_txn(cls, txn, events_and_contexts):", "its context. # Otherwise we need to pull the state", "Args: txn state_groups (set[int]): Set of state groups referenced by", "the deferreds waiting on the item, exceptions will be passed", "def prefill(): for cache_entry in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def", "persisting events for one room at a time. \"\"\" #", "= events_and_contexts[-1][0].internal_metadata.stream_ordering self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, )", "an outlier any more. self._update_backward_extremeties(txn, [event]) return [ec for ec", "chunk: if context.app_service: origin_type = \"local\" origin_entity = context.app_service.id elif", "the various caches # Figure out the changes of membership", "# Delete all remote non-state events for table in (", "keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), ) prevs = set(row[\"state_group\"] for row in", "don't bother re-handling groups we've already seen prevs -= state_groups_seen", "AND state_key = ?\", ( (room_id, etype, state_key) for etype,", "# we have a delta for that transition. If we", "item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def _persist_events( self,", "DESC\" \" LIMIT ?\" ) if have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id,", "for ev, _ in events_and_contexts], ) def _store_event_txn(self, txn, events_and_contexts):", "event.redacts) # Update the event_forward_extremities, event_backward_extremities and # event_edges tables.", "frozendict_json_encoder.encode(json_object) if isinstance(out, bytes): out = out.decode(\"utf8\") return out class", "synapse.events import EventBase # noqa: F401 from synapse.events.snapshot import EventContext", "list[(EventBase, EventContext)]: filtered list \"\"\" new_events_and_contexts = OrderedDict() for event,", "EventContext)] new list, without the rejected events. \"\"\" # Remove", "end up with dangling extremities. existing_prevs = yield self._get_prevs_before_rejected( e_id", "the changes of membership to invalidate the # `get_rooms_for_user` cache.", "state_delta_for_room[room_id] = ([], delta_ids) elif current_state is not None: with", "new_state_groups - set(state_groups_map) if missing_state: group_to_state = yield self._get_state_for_groups(missing_state) state_groups_map.update(group_to_state)", "txn.execute(sql, (from_token, to_token, limit)) return txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn,", "== \"\": room_version = ev.content.get(\"room_version\", \"1\") break if not room_version:", "): \"\"\"Get all the new events that have arrived at", "to %d\", min_depth) txn.execute( \"UPDATE room_depth SET min_depth = ?", "LEFT JOIN event_relations USING (event_id)\" \" WHERE ? < stream_ordering", "WHERE room_id = ?\", (min_depth, room_id), ) # finally, drop", "\"format_version\": event.format_version, } for event, _ in events_and_contexts ], )", "EventTypes.Message: # Insert into the event_search table. self._store_room_message_txn(txn, event) elif", "you may not use this file except in compliance with", "forward # extremities in each room new_forward_extremeties = {} #", "# room state_delta_for_room = {} if not backfilled: with Measure(self._clock,", "\" \"AND e.room_id = f.room_id \" \"WHERE f.room_id = ?\",", "> event_stream_ordering\" \" AND event_stream_ordering >= ?\" \" ORDER BY", "that are referenced by events that are to be #", "ex-outliers (unless the new event was rejected). Args: txn (twisted.enterprise.adbapi.Connection):", "((event, context),)) except Exception: logger.exception(\"\") raise metadata_json = encode_json(event.internal_metadata.get_dict()) sql", "and leaves the logcontext in place whether or not the", "room_depth SET min_depth = ? WHERE room_id = ?\", (min_depth,", "we've already seen state_groups_seen = set(state_groups) # Set of state", "to return run_as_background_process( \"read_forward_extremities\", self._read_forward_extremities ) hs.get_clock().looping_call(read_forward_extremities, 60 * 60", "deferred = self._event_persist_queue.add_to_queue( event.room_id, [(event, context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield", "pull the state group from its context. # Otherwise we", "Measure logger = logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter =", "event was rejected. Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase,", "and their prev events, # otherwise we end up with", "# # We do this by calculating the minimum depth", "BY stream_ordering ASC\" \" LIMIT ?\" ) if have_forward_events: txn.execute(sql,", "they are referenced by other events # or state groups,", "= ? AND event_id IN (\" \" SELECT event_id FROM", "queue: try: ret = yield per_item_callback(item) except Exception: with PreserveLoggingContext():", "# event_backward_extremities # event_edges # event_forward_extremities # event_json # event_push_actions", "# the current state in memory then lets also return", "? AND state_key = ?\", ( (room_id, etype, state_key) for", "vals = { \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"state_key\":", "are the type/state_keys to remove from current_state_events and `to_insert` are", "a situation where workers see events before the # current_state_delta", "per_item_callback): \"\"\"Attempts to handle the queue for a room if", "upper_bound)) new_event_updates.extend(txn) return new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def", "outlier events. if not ev.internal_metadata.is_outlier(): raise Exception( \"Context for new", "txn, events_and_contexts): \"\"\"Update any outliers with new event info. This", "to_delete = [key for key in existing_state if key not", ") new_backwards_extrems = txn.fetchall() logger.info(\"[purge] replacing backward extremities: %r\", new_backwards_extrems)", "(event, context) else: new_events_and_contexts[event.event_id] = (event, context) return list(new_events_and_contexts.values()) def", "super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler() #", "if they're \"new\" events which might update the current state", "minimum depth of the backwards # extremities. However, the events", "have been persisted \"\"\" if not events_and_contexts: return if backfilled:", "stream_ordering >= ?\" \" ORDER BY stream_ordering ASC\" \" LIMIT", "from synapse.state import StateResolutionStore from synapse.storage.background_updates import BackgroundUpdateStore from synapse.storage.event_federation", "txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,) ) self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def _update_forward_extremities_txn( self,", "than forward extremeties\" ) logger.info(\"[purge] looking for events to delete\")", "it doesn't take much storage compared to storing the entire", "USING (event_id)\" \" WHERE ? < event_stream_ordering\" \" AND event_stream_ordering", "for received events which were rejected Args: txn (twisted.enterprise.adbapi.Connection): db", "setting, # we can just add these new events to", "self._get_prevs_before_rejected( e_id for event in new_events for e_id in event.prev_event_ids()", "of forward extremities for each new event. forward_extremities_counter = Histogram(", "don't have the same event twice. Pick the earliest non-outlier", "group, new state group) -> delta state dict state_group_deltas =", "\"history_visibility\", \"local_invites\", \"room_names\", \"state_events\", \"rejections\", \"redactions\", \"room_memberships\", \"topics\", ): txn.executemany(", "if hasattr(event, \"replaces_state\"): vals[\"prev_state\"] = event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values)", "= [key for key in existing_state if key not in", "keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[ { \"state_group\": sg,", "tables. Rejected events are only inserted into the events table,", "so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self, event_id): res = yield self._simple_select_one( table=\"events\",", "delta_ids)) # Now that we have calculated new_state_groups we need", "Args: events_and_contexts (list[(EventBase, EventContext)]): Returns: list[(EventBase, EventContext)]: filtered list \"\"\"", "is rejected then we don't care if the event #", "\"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events( self, room_id,", "backfilled \"\"\" # Insert all the push actions into the", "events_and_contexts (list[(EventBase, EventContext)]): events we are persisting Returns: list[(EventBase, EventContext)]", "continue state_delta_counter.inc() if len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc() # This is", "room_id, new_state in iteritems(current_state_for_room): self.get_current_state_ids.prefill((room_id,), new_state) for room_id, latest_event_ids in", "try: queue = self._get_drainining_queue(room_id) for item in queue: try: ret", "soft-failed prev # events. If they do we need to", "Runs its callbacks *without* a logcontext. \"\"\" queue = self._event_persist_queues.setdefault(room_id,", "200 for i in range(0, len(events_and_contexts), N): ev_map = {e[0].event_id:", "from synapse.types import RoomStreamToken, get_domain_from_id from synapse.util import batch_iter from", "dict)]): The current-state delta for each room. For each room,", "if not backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"): # Work out the", "info. This turns outliers into ex-outliers (unless the new event", "persist_event(self, event, context, backfilled=False): \"\"\" Args: event (EventBase): context (EventContext):", "upper_bound = new_forward_events[-1][0] else: upper_bound = current_forward_id sql = (", "event.event_id, context.rejected) to_remove.add(event) return [ec for ec in events_and_contexts if", "backfilled: # backfilled events have negative stream orderings, so we", "set() else: current_search = set(itertools.islice(next_to_search, 100)) next_to_search -= current_search #", "self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from preserve_events\") res = yield self._state_resolution_handler.resolve_state_groups( room_id,", "@classmethod def _filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that we don't have the", "elif self.hs.is_mine_id(event.sender): origin_type = \"local\" origin_entity = \"*client*\" else: origin_type", "and new groups are the same then we don't need", "{} for ev, ctx in events_context: if ctx.state_group is None:", "This is good enough as if you have silly characters", "self.hs.hostname sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM events WHERE", "has been significantly less or more than one day since", "prev_sg in to_delete: to_dedelta.add(sg) return to_delete, to_dedelta @defer.inlineCallbacks def is_event_after(self,", "\"\"\" ) referenced_state_groups = set(sg for sg, in txn) logger.info(", "for all # those users. members_changed = set( state_key for", "and ctx.state_group is not None: event_id_to_state_group[event_id] = ctx.state_group break else:", "the indices *after* insertion as that's a lot faster. #", "in events_and_contexts: # Remove the any existing cache entries for", "= namedtuple(\"_EventCacheEntry\", (\"event\", \"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps a database function", "event appears in an accepted # event's auth chain, but", "the room old_latest_event_ids (iterable[str]): the old forward extremities for the", "times we are recalculating the current state state_delta_counter = Counter(\"synapse_storage_events_state_delta\",", "AND state_key = ? ) \"\"\" txn.executemany( sql, ( (", "500, \"+Inf\"), ) # The number of stale forward extremities", "get_current_state_ids # cache current_state_for_room = {} # map room_id->(to_delete, to_insert)", "they're \"new\" events which might update the current state etc.", "into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) # We want to store event_auth", ") if have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id, limit)) new_forward_events = txn.fetchall()", "room_id, etype, state_key, ev_id, room_id, etype, state_key, ) for (etype,", "file except in compliance with the License. # You may", "does this work with backfilling? if hasattr(event, \"replaces_state\"): vals[\"prev_state\"] =", "txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit)) new_backfill_events = txn.fetchall() if len(new_backfill_events) ==", "persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def _persist_events( self, events_and_contexts, backfilled=False, delete_existing=False ):", "the results are retrieved from federation via backfill or not.", "EventBase # noqa: F401 from synapse.events.snapshot import EventContext # noqa:", "%i can be deleted\", len(event_rows), sum(1 for e in event_rows", "sg) curr_state = self._get_state_groups_from_groups_txn(txn, [sg]) curr_state = curr_state[sg] self._simple_delete_txn( txn,", "event_to_state_groups USING (event_id) \"\"\" ) referenced_state_groups = set(sg for sg,", "# set handle_queue_loop off in the background run_as_background_process(\"persist_events\", handle_queue_loop) def", "a state set to be added to the current state.", "event) elif event.type == EventTypes.RoomHistoryVisibility: # Insert into the event_search", "event_search table. self._store_history_visibility_txn(txn, event) elif event.type == EventTypes.GuestAccess: # Insert", "was rejected). Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]):", "The return value of the function will be given to", "deleting their state groups). \"\"\" return self.runInteraction( \"purge_history\", self._purge_history_txn, room_id,", "current state. If both are None then there has been", "a list # of type/state keys to remove from current", "in events_and_contexts if event.type == EventTypes.Member ], backfilled=backfilled, ) #", "partitioned = {} for event, ctx in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event,", "new_state_group), None) if delta_ids is not None: # We have", "existing current state. If both are None then there has", "state_groups_to_delete), ) logger.info(\"[purge] removing events from event_to_state_groups\") txn.execute( \"DELETE FROM", "== EventTypes.Topic: # Insert into the topics table and event_search", "have yet so we need to look at the events", "\"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\": event.depth, \"event_id\": event.event_id, \"room_id\": event.room_id,", "state, never # removed keys entirely. state_delta_for_room[room_id] = ([], delta_ids)", "= set(latest_event_ids) # start with the existing forward extremities result", "defer.returnValue((None, None)) if len(new_state_groups) == 1 and len(old_state_groups) == 1:", "in current_search), ) txn.execute(sql, list(current_search)) referenced = set(sg for sg,", "event_to_state_groups \" \"WHERE event_id IN (SELECT event_id from events_to_purge)\" )", "be no existing # extremities, so we'll `continue` above and", "not in to_remove] def _update_metadata_tables_txn( self, txn, events_and_contexts, all_events_and_contexts, backfilled", "redacts, relates_to_id\" \" FROM events AS e\" \" INNER JOIN", "% (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self, from_token, to_token,", "(room_id,), ) rows = txn.fetchall() max_depth = max(row[1] for row", "= set() for event, context in events_and_contexts: if event.event_id not", "queue = self._event_persist_queues.setdefault(room_id, deque()) if queue: # if the last", "ctx in ev_ctx_rm ) # Don't bother calculating state if", "= Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\", \"origin_entity\"], ) # The", "AND e.room_id = ? AND topological_ordering < ?\" % (should_delete_expr,", "{ \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"state_key\": event.state_key, }", "min_depth for each room Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts", "that reference to-be-deleted state # groups to non delta versions.", "has been a change then we only return the delta", "context),)) except Exception: logger.exception(\"\") raise metadata_json = encode_json(event.internal_metadata.get_dict()) sql =", "all events which are prev_events of any of the new", "event_id = ?\" % (table,), [(ev.event_id,) for ev, _ in", "table. this will commit the txn in sqlite, # so", "only update metrics for events that change forward extremities #", "txn} to_remove = set() for event, context in events_and_contexts: if", "giving the new forward # extremities in each room new_forward_extremeties", "_calculate_new_extremities(self, room_id, event_contexts, latest_event_ids): \"\"\"Calculates the new forward extremities for", "no state \" \"group\" % (ev.event_id,) ) continue if ctx.state_group", "self._clock.time_msec(), \"sender\": event.sender, \"contains_url\": ( \"url\" in event.content and isinstance(event.content[\"url\"],", "events_json table, and the rejections table. Things reading from those", "ev.event_id and ctx.state_group is not None: event_id_to_state_group[event_id] = ctx.state_group break", "for one room at a time. \"\"\" # we're only", "so # that we can use it to calculate the", "we were going to persist. This includes events we've already", "etype, state_key, ) for (etype, state_key), ev_id in iteritems(to_insert) ),", "events for one room at a time. \"\"\" # we're", "txn.executemany( \"DELETE FROM %s WHERE room_id = ? AND event_id", "txn.execute(sql, (self.stream_ordering_day_ago,)) count, = txn.fetchone() return count ret = yield", "\"persist_events\"): yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled ) self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks", "EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ): def __init__(self, db_conn, hs): super(EventsStore, self).__init__(db_conn,", "to_remove.add(event) return [ec for ec in events_and_contexts if ec[0] not", "ret = yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self): def", "last_backfill_id != current_backfill_id have_forward_events = last_forward_id != current_forward_id if not", "\"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"rejections\", ): logger.info(\"[purge] removing events from %s\",", "like_clause = \"%:\" + self.hs.hostname sql = \"\"\" SELECT COALESCE(COUNT(*),", "events_and_contexts: prev_event_context = new_events_and_contexts.get(event.event_id) if prev_event_context: if not event.internal_metadata.is_outlier(): if", "e\" \" INNER JOIN event_edges AS ed ON e.event_id =", "rows = self.cursor_to_dict(txn) for row in rows: event = ev_map[row[\"event_id\"]]", "as stream_orderings: for (event, context), stream in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering", "100): yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks def", "This should only happen for outlier events. if not ev.internal_metadata.is_outlier():", "# event_to_state_groups # events # rejections # room_depth # state_groups", "\" WHERE (NOT outlier OR (%s)) AND e.room_id = ?", "current_state_events WHERE room_id = ? AND type = ? AND", "big if len(next_to_search) < 100: current_search = next_to_search next_to_search =", "the delta would have been when # processing one of", "groups that need to be de-delta'ed \"\"\" # Graph of", "( \",\".join(\"?\" for _ in current_search), ) txn.execute(sql, list(current_search)) referenced", "history before a certain point Args: room_id (str): token (str):", "ctx)) deferreds = [] for room_id, evs_ctxs in iteritems(partitioned): d", "single ancestor non-state events. if all_single_prev_not_state: continue state_delta_counter.inc() if len(new_latest_event_ids)", "= set(old_latest_event_ids) event_id_to_state_group = {} for event_id in new_latest_event_ids: #", "count ret = yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The", "\"Number of unchanged forward extremities for each new event\", buckets=(0,", "this method, it does *not* follow the synapse logcontext rules,", "not. continue outlier_persisted = have_persisted[event.event_id] if not event.internal_metadata.is_outlier() and outlier_persisted:", "txn, table=\"event_json\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"internal_metadata\": encode_json(", "of times we are recalculating state when there is only", "number of forward extremities for each new event. forward_extremities_counter =", ") if len_1: all_single_prev_not_state = all( len(event.prev_event_ids()) == 1 and", "# being rejected. new_events = [ event for event, ctx", "context in events_and_contexts: if event.type == EventTypes.Redaction and event.redacts is", "_ in events_and_contexts], ) def _store_event_txn(self, txn, events_and_contexts): \"\"\"Insert new", "and then # calculating the state from that. events_by_room =", "events_and_contexts) def _add_to_cache(self, txn, events_and_contexts): to_prefill = [] rows =", "continue soft_failed = json.loads(metadata).get(\"soft_failed\") if soft_failed or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id)", "\"SELECT -event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE ?", "], ) logger.info(\"[purge] removing redundant state groups\") txn.executemany( \"DELETE FROM", "so we'll `continue` above and skip this bit.) assert new_latest_event_ids,", "context (EventContext): backfilled (bool): Returns: Deferred: resolves to (int, int):", "then lets also return that, # but it doesn't matter", "ex_outlier_stream\" \" WHERE ? > event_stream_ordering\" \" AND event_stream_ordering >=", "rows for the events from the database. This is useful", "last_id, current_id, limit): if last_id == current_id: return defer.succeed([]) def", "update the current_state_events table txn.executemany( \"DELETE FROM current_state_events\" \" WHERE", "set( state_key for ev_type, state_key in itertools.chain(to_delete, to_insert) if ev_type", "backfilled ): \"\"\"Update all the miscellaneous tables for new events", "been no change. If there has been a change then", "number of times we are recalculating the current state state_delta_counter", "we need to pull the state group from the database.", "# end up in a situation where workers see events", "new_events) # Now remove all events which are prev_events of", "stream_ordering AND stream_ordering >= ?\" \" ORDER BY stream_ordering DESC\"", "curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg} ) self._simple_delete_txn( txn, table=\"state_group_edges\",", "that backfilled events have reached\"\"\" return -self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The", "we're adding. for ev, ctx in events_context: if event_id ==", "eb.event_id INNER JOIN events AS e ON e.event_id = eg.event_id", "last. txn.execute(\"DROP TABLE events_to_purge\") logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self, txn, state_groups):", "connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting all_events_and_contexts (list[(EventBase,", "extremities: %r\", new_backwards_extrems) txn.execute( \"DELETE FROM event_backward_extremities WHERE room_id =", "remove all events which are prev_events of any of the", "if we don't. new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) # Now", "resolve our state sets. state_groups = {sg: state_groups_map[sg] for sg", "self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[ { \"state_group\": sg, \"room_id\": room_id, \"type\":", "in remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining state group %s\", sg) curr_state", "evs_ctxs in iteritems(partitioned): d = self._event_persist_queue.add_to_queue( room_id, evs_ctxs, backfilled=backfilled )", "len(new_backfill_events) == limit: upper_bound = new_backfill_events[-1][0] else: upper_bound = current_backfill_id", "if len(new_latest_event_ids) == 1: state_delta_single_event_counter.inc() # This is a fairly", "one. Args: events_and_contexts (list[(EventBase, EventContext)]): Returns: list[(EventBase, EventContext)]: filtered list", "redacted event. self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts ) # Remove from", "normal usage pattern of this method, it does *not* follow", ") latest_event_ids = set(latest_event_ids) if new_latest_event_ids == latest_event_ids: # No", "next_to_search next_to_search = set() else: current_search = set(itertools.islice(next_to_search, 100)) next_to_search", "txn, table=\"events\", values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\": event.depth,", "old and new groups are the same then we don't", "we're persisting, in which case we can # pull the", "import PreserveLoggingContext, make_deferred_yieldable from synapse.util.logutils import log_function from synapse.util.metrics import", "necessary. current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids is not None: state_groups_map[ctx.state_group]", "same event twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn( txn,", "extremities to count self._current_forward_extremities_amount = c_counter() BucketCollector( \"synapse_forward_extremities\", lambda: self._current_forward_extremities_amount,", "in new_state_groups} events_map = {ev.event_id: ev for ev, _ in", "The given callback will be invoked with for each item", "event_backward_extremities # are ones we don't have yet so we", "efficiently look up the forward extremeties # for a room", "in events_and_context. backfilled (bool): True if the events were backfilled", "Returns: list[(EventBase, EventContext)] new list, without the rejected events. \"\"\"", "the current state state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\") # The number", "extremities for each new event\", buckets=(0, 1, 2, 3, 5,", "of state groups we've already seen state_groups_seen = set(state_groups) #", "events_and_contexts: if event.event_id not in have_persisted: continue to_remove.add(event) if context.rejected:", "JOIN events USING (event_id) LEFT JOIN rejections USING (event_id) LEFT", "twice since we use the expression twice should_delete_params += (\"%:\"", ") defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events( self, room_id, events_context, old_latest_event_ids, new_latest_event_ids", "# an outlier in the database. We now have some", "self, room_id, events_context, old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate the current state", "key[1], } for key, ev_id in iteritems(to_insert) ], ) txn.call_after(", "self._update_min_depth_for_room_txn(txn, room_id, depth) def _update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update any outliers", "new event info. This turns outliers into ex-outliers (unless the", "+= \" AND event_id NOT LIKE ?\" # We include", "( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\"", "for event, ctx in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds =", "EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ): def __init__(self, db_conn, hs):", "?, ?, ( SELECT event_id FROM current_state_events WHERE room_id =", "EXISTS events_to_purge\") txn.execute( \"CREATE TEMPORARY TABLE events_to_purge (\" \" event_id", "to_insert)) @log_function def _persist_events_txn( self, txn, events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={},", "remove from the extremities. Given a set of events, find", "defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks @log_function", "): res = yield self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids, )", "to not have to pull out the existing state #", "in the stream \"\"\" to_1, so_1 = yield self._get_event_ordering(event_id1) to_2,", "and # limitations under the License. import itertools import logging", "= self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts ) # From this point onwards", "been a change then we only return the delta if", "event.internal_metadata.get_dict() ), \"json\": encode_json(event_dict(event)), \"format_version\": event.format_version, } for event, _", "etype, state_key, ) for etype, state_key in to_delete # We", "new events result.difference_update( e_id for event in new_events for e_id", "Measure(self._clock, \"_calculate_state_and_extrem\"): # Work out the new \"current state\" for", "prev_event_id IN (%s) AND NOT events.outlier AND rejections.event_id IS NULL", "events_and_contexts, backfilled): \"\"\"Update min_depth for each room Args: txn (twisted.enterprise.adbapi.Connection):", "it doesn't matter if we don't. new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state,", "each room. # We do this by working out what", "event.depth, depth_updates.get(event.room_id, event.depth) ) for room_id, depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn,", "Update the event_backward_extremities table now that this # event isn't", "_ in events_context} # We need to get the room", "\" AND event_stream_ordering <= ?\" \" ORDER BY event_stream_ordering DESC\"", "is not None: event_id_to_state_group[event_id] = ctx.state_group break else: # If", "call _update_backward_extremities # and _handle_mult_prev_events (though arguably those could both", "sg, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], \"event_id\": state_id, }", "events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete FROM events_to_purge\") event_rows = txn.fetchall() logger.info(", "will resolve once the events are persisted. Runs its callbacks", "@defer.inlineCallbacks @log_function def persist_event(self, event, context, backfilled=False): \"\"\" Args: event", "that we were going to persist. This includes events we've", "the rest of our transaction. # # So, let's stick", ") for etype, state_key in to_delete # We sanity check", "event.is_state() for event, ctx in ev_ctx_rm ) # Don't bother", "might already have the table from a previous (failed) #", "def _store_rejected_events_txn(self, txn, events_and_contexts): \"\"\"Add rows to the 'rejections' table", "\"new\" events which might update the current state etc. Returns:", "for ev, ctx in events_context: if ctx.state_group is None: #", "a given stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[ { \"room_id\": room_id,", "# single forward extremity state_delta_single_event_counter = Counter( \"synapse_storage_events_state_delta_single_event\", \"\" )", "max_depth = max(row[1] for row in rows) if max_depth <", "event_id, _ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete all remote", "# Graph of state group -> previous group graph =", "to the queue, with the given persist_event options. NB: due", "have at most one prev group graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete", "does *not* follow the synapse logcontext rules, and leaves the", ") def get_all_updated_current_state_deltas(self, from_token, to_token, limit): def get_all_updated_current_state_deltas_txn(txn): sql =", "key, ev_id in iteritems(to_insert) ], ) txn.call_after( self._curr_state_delta_stream_cache.entity_has_changed, room_id, stream_id,", "limitations under the License. import itertools import logging from collections", "on the item, exceptions will be passed to the deferreds", "\"\"\" return self.runInteraction( \"purge_history\", self._purge_history_txn, room_id, token, delete_local_events, ) def", "# but it doesn't matter if we don't. new_state =", "%s WHERE event_id = ?\" % (table,), [(ev.event_id,) for ev,", "@defer.inlineCallbacks def handle_queue_loop(): try: queue = self._get_drainining_queue(room_id) for item in", "state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\") # The number of times we", "extrems every 60 minutes def read_forward_extremities(): # run as a", "EventTypes.Member ], backfilled=backfilled, ) # Insert event_reference_hashes table. self._store_event_reference_hashes_txn( txn,", "to_remove] @classmethod def _delete_existing_rows_txn(cls, txn, events_and_contexts): if not events_and_contexts: #", "your own # hostname then thats your own fault. like_clause", "find all those that have been soft-failed or rejected. Returns", "BOOLEAN NOT NULL\" \")\" ) # First ensure that we're", "least one forward extremity. # (except during the initial persistence", "from relations table. self._handle_redaction(txn, event.redacts) # Update the event_forward_extremities, event_backward_extremities", "[(ev.event_id,) for ev, _ in events_and_contexts], ) for table in", "of the number of messages sent in the last day.", "*not* follow the synapse logcontext rules, and leaves the logcontext", "ensure we don't delete all the events from the database", "def encode_json(json_object): \"\"\" Encode a Python object as JSON and", "ctx in events_context: if event_id == ev.event_id and ctx.state_group is", "in events_and_contexts: if event.type == EventTypes.Name: # Insert into the", "in the events table. \"\"\" txn.execute( \"SELECT event_id, outlier FROM", "Deferred: resolves when the events have been persisted \"\"\" if", "# Mark all state and own events as outliers logger.info(\"[purge]", "bit.) assert new_latest_event_ids, \"No forward extremities left!\" new_forward_extremeties[room_id] = new_latest_event_ids", "so no change in state continue # there should always", "@_retry_on_integrity_error @defer.inlineCallbacks def _persist_events( self, events_and_contexts, backfilled=False, delete_existing=False ): \"\"\"Persist", "last_id == current_id: return defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql = (", "iteritems(events_by_room): latest_event_ids = yield self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids = yield", "* 60 * 1000) @defer.inlineCallbacks def _read_forward_extremities(self): def fetch(txn): txn.execute(", "the extremities. Given a set of events, find all those", "db connection events_and_contexts (list[(EventBase, EventContext)]): events we are persisting all_events_and_contexts", "sql = ( \"SELECT event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key,", "FROM events AS e LEFT JOIN state_events USING (event_id)\" \"", "= r.redacts\" \" WHERE e.event_id IN (%s)\" ) % (\",\".join([\"?\"]", "logger.info( \"[purge] de-delta-ing %i remaining state groups\", len(remaining_state_groups), ) #", ") # event_push_actions lacks an index on event_id, and has", "Mark all state and own events as outliers logger.info(\"[purge] marking", "to be deleted. Returns: tuple[set[int], set[int]]: The set of state", "the forward extremeties # for a room before a given", "self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts, backfilled=backfilled ) # _update_outliers_txn", "The Matrix.org Foundation C.I.C. # # Licensed under the Apache", "in new_events) # Now remove all events which are prev_events", "USING (event_id) LEFT JOIN rejections USING (event_id) LEFT JOIN event_json", "events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def _update_current_state_txn(self, txn, state_delta_by_room, stream_id): for", "< ?\" % (should_delete_expr, should_delete_expr), should_delete_params, ) # We create", "new state deltas for a room. Assumes that we are", "= set(itertools.islice(next_to_search, 100)) next_to_search -= current_search # Check if state", "just return that. If we happen to already have #", "string. \"\"\" out = frozendict_json_encoder.encode(json_object) if isinstance(out, bytes): out =", "a room given events to persist. Assumes that we are", "for the events from the database. This is useful when", "return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id, current_id, limit): if last_id ==", "only interested in new events which aren't outliers and which", ") # Insert event_reference_hashes table. self._store_event_reference_hashes_txn( txn, [event for event,", "then we invlidate the caches for all # those users.", "now insert into stream_ordering_to_exterm a mapping from room_id, # new", "it will use the # forward extremities as the prev_events,", "table. self._store_room_members_txn( txn, [ event for event, _ in events_and_contexts", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "the new. stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged forward", "logger.info(\"[purge] Finding new backward extremities\") # We calculate the new", "License. # You may obtain a copy of the License", "referenced state groups\", len(referenced_state_groups) ) logger.info(\"[purge] finding state groups that", "will continuously be called with new items, unless the queue", "across the # connection. Annoyingly the python sqlite driver commits", "ensure correct ordering we pop, as OrderedDict is # ordered", "? AND stream_ordering > ? \"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count,", "delete\") should_delete_expr = \"state_key IS NULL\" should_delete_params = () if", "delta state dict state_group_deltas = {} for ev, ctx in", "FROM state_groups WHERE id = ?\", ((sg,) for sg in", "for rejected events, as they're # used in state res", "events_to_purge AS ep2 ON ed.event_id = ep2.event_id\" \" WHERE ep2.event_id", ": i + N]} if not ev_map: break sql =", "state group, new state group) -> delta state dict state_group_deltas", "\"room_id\": room_id} for room_id, new_extrem in iteritems(new_forward_extremities) for ev_id in", "need to be de-delta'ed \"\"\" # Graph of state group", "IntegrityError. state_delta_for_room (dict[str, (list, dict)]): The current-state delta for each", "_retry_on_integrity_error(func): \"\"\"Wraps a database function so that it gets retried", "state_groups_map: continue # We're only interested in pulling out state", "new_event_updates.extend(txn) return new_event_updates return self.runInteraction( \"get_all_new_forward_event_rows\", get_all_new_forward_event_rows ) def get_all_new_backfill_event_rows(self,", "the delta when we calculated the state for an event", "to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_prevs_before_rejected\",", "FROM event_backward_extremities AS eb INNER JOIN event_edges AS eg ON", "# guess this by looking at the prev_events and checking", "Ok, we need to defer to the state handler to", "rejections # room_depth # state_groups # state_groups_state # we will", "import run_as_background_process from synapse.state import StateResolutionStore from synapse.storage.background_updates import BackgroundUpdateStore", "were backfilled \"\"\" depth_updates = {} for event, context in", "once the events are persisted. Runs its callbacks *without* a", "\" ORDER BY stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql,", "to it via event_edges table. txn.execute( \"\"\" SELECT COALESCE(MIN(depth), 0)", "= ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts,", "# event_push_actions lacks an index on event_id, and has one", "extremities for the room. new_latest_event_ids (iterable[str]): the new forward extremities", "defer.returnValue(res) return f # inherits from EventFederationStore so that we", "to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for event, context in chunk:", "we need to look at the events that # point", "self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event) # Insert into the room_memberships table.", "that wouldn't appear in events_and_context. backfilled (bool): True if the", "EventTypes.GuestAccess: # Insert into the event_search table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn,", "Insert into the event_search table. self._store_room_message_txn(txn, event) elif event.type ==", "USING (event_id)\" \" LEFT JOIN state_events USING (event_id)\" \" WHERE", "back and forth across the # connection. Annoyingly the python", "txn.execute( \"UPDATE room_depth SET min_depth = ? WHERE room_id =", "NB: Assumes that we are only persisting events for one", "`backfilled` setting, # we can just add these new events", "get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10) def get_all_new_events( self, last_backfill_id, last_forward_id, current_backfill_id,", "of events we need to fetch groups for. (We know", "get those which are prev_events of existing (non-outlier/rejected) events. Args:", "limit)) new_forward_events = txn.fetchall() if len(new_forward_events) == limit: upper_bound =", "DISTINCT e.event_id FROM events_to_purge AS e\" \" INNER JOIN event_edges", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "event\", buckets=(0, 1, 2, 3, 5, 7, 10, 15, 20,", "cutoff, of which %i can be deleted\", len(event_rows), sum(1 for", "== EventTypes.GuestAccess: # Insert into the event_search table. self._store_guest_access_txn(txn, event)", "are prev_events of any existing events. existing_prevs = yield self._get_events_which_are_prevs(result)", "The number of times we are recalculating the current state", "WHERE state_group IN (%s) AND ep.event_id IS NULL \"\"\" %", "current_state_tuple in iteritems(state_delta_by_room): to_delete, to_insert = current_state_tuple # First we", "room. For each room, a tuple (to_delete, to_insert), being a", "e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \" FROM events AS", "continuously be called with new items, unless the queue becomnes", "time. \"\"\" # we're only interested in new events which", "de-delta'ed \"\"\" # Graph of state group -> previous group", "SELECT event_id FROM current_state_events WHERE room_id = ? AND type", "queue then it will not be invoked. \"\"\" if room_id", "Note that these must have already been persisted. Returns: Deferred[set[str]]", "required by applicable law or agreed to in writing, software", "is # ordered by first insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] =", "table, and the rejections table. Things reading from those table", "self._update_outliers_txn( txn, events_and_contexts=events_and_contexts ) # From this point onwards the", "in events_and_contexts if ec[0] not in to_remove] def _update_metadata_tables_txn( self,", "room. # We do this by working out what the", "and not event.internal_metadata.is_soft_failed() ] latest_event_ids = set(latest_event_ids) # start with", "import ObservableDeferred from synapse.util.caches.descriptors import cached, cachedInlineCallbacks from synapse.util.frozenutils import", "extremeties\" ) logger.info(\"[purge] looking for events to delete\") should_delete_expr =", "events were backfilled delete_existing (bool): True to purge existing table", "table will need to check whether the event was rejected.", "all state and own events as outliers logger.info(\"[purge] marking remaining", ") for event_id, _ in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete", "agreed to in writing, software # distributed under the License", "{} for event, context in chunk: events_by_room.setdefault(event.room_id, []).append( (event, context)", "limit)) new_backfill_events = txn.fetchall() if len(new_backfill_events) == limit: upper_bound =", "the state group from its context. # Otherwise we need", ") txn.executemany( sql, ( ( stream_id, room_id, etype, state_key, ev_id,", "the state handler to resolve our state sets. state_groups =", "if backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else: stream_ordering_manager =", "there is a delta we know that we've # only", "delta = yield self._calculate_state_delta( room_id, current_state ) state_delta_for_room[room_id] = delta", "haven't # seen before. if delete_existing: # For paranoia reasons,", "each new event\", buckets=(0, 1, 2, 3, 5, 7, 10,", "if not room_version: room_version = yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from", "limit)) new_event_updates = txn.fetchall() if len(new_event_updates) == limit: upper_bound =", "happen for outlier events. if not ev.internal_metadata.is_outlier(): raise Exception( \"Context", "set to be added to the current state. new_forward_extremeties (dict[str,", "if prev_event_id in existing_prevs: continue soft_failed = json.loads(metadata).get(\"soft_failed\") if soft_failed", "group graphs for state # groups that are referenced. current_search", "graph until it finds no more soft-failed/rejected events. This is", "from those table will need to check whether the event", "EventContext)]): backfilled (bool): Returns: defer.Deferred: a deferred which will resolve", "rejections table. Things reading from those table will need to", "(event, context) ) for room_id, ev_ctx_rm in iteritems(events_by_room): latest_event_ids =", "change. If there has been a change then we only", "import log_function from synapse.util.metrics import Measure logger = logging.getLogger(__name__) persist_event_counter", "for sg in remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining state group %s\",", "# State groups of old_latest_event_ids old_state_groups = set( event_id_to_state_group[evid] for", "persists events (because upsert), and once we run this update,", "context, backfilled=False): \"\"\" Args: event (EventBase): context (EventContext): backfilled (bool):", "events_context} # We need to get the room version, which", "Insert into the event_search table. self._store_guest_access_txn(txn, event) self._handle_event_relations(txn, event) #", "extremities are and then # calculating the state from that.", "self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) # Ensure that we don't", "txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,)) self._simple_insert_many_txn( txn, table=\"event_forward_extremities\", values=[ {\"event_id\": ev_id, \"room_id\": room_id}", "to_dedelta = set() for sg in referenced_groups: prev_sg = graph.get(sg)", "event.internal_metadata.is_outlier(), \"origin_server_ts\": int(event.origin_server_ts), \"received_ts\": self._clock.time_msec(), \"sender\": event.sender, \"contains_url\": ( \"url\"", "returns the filtered list. events_and_contexts = self._store_rejected_events_txn( txn, events_and_contexts=events_and_contexts )", "= res # If either are not None then there", "soft failed/rejected events and their prev events (whether soft-failed/rejected or", "eg.prev_event_id = eb.event_id INNER JOIN events AS e ON e.event_id", "self.database_engine.module.IntegrityError: logger.exception(\"IntegrityError, retrying.\") res = yield func(self, *args, delete_existing=True, **kwargs)", "db_conn, hs): super(EventsStore, self).__init__(db_conn, hs) self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler =", "# it doesn't take much storage compared to storing the", "len(new_event_updates) == limit: upper_bound = new_event_updates[-1][0] else: upper_bound = current_id", "for new event %s has no state \" \"group\" %", "simply used to prefill the get_current_state_ids # cache current_state_for_room =", "event twice. events_and_contexts = self._filter_events_and_contexts_for_duplicates( events_and_contexts ) self._update_room_depths_txn( txn, events_and_contexts=events_and_contexts,", "\" state_key, redacts, relates_to_id\" \" FROM events AS e\" \"", "delta in each # room state_delta_for_room = {} if not", "(type,key)->event_id giving the state delta in each # room state_delta_for_room", "txn, table=\"state_group_edges\", keyvalues={\"state_group\": sg} ) self._simple_insert_many_txn( txn, table=\"state_groups_state\", values=[ {", "event_dict(event): d = event.get_dict() d.pop(\"redacted\", None) d.pop(\"redacted_because\", None) return d", "new state group) -> delta state dict state_group_deltas = {}", "before a given stream_ordering self._simple_insert_many_txn( txn, table=\"stream_ordering_to_exterm\", values=[ { \"room_id\":", "for room_id, new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id}", "sql = ( \"SELECT -event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\"", "_persist_events_txn( self, txn, events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert", "current_state_delta updates. # sql = \"\"\" INSERT INTO current_state_delta_stream (stream_id,", "set() def add_to_queue(self, room_id, events_and_contexts, backfilled): \"\"\"Add events to the", ") self._simple_insert_many_txn( txn, table=\"events\", values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth,", "current_state_ids = ctx.get_cached_current_state_ids() if current_state_ids is not None: state_groups_map[ctx.state_group] =", "AND type = ? AND state_key = ? ) \"\"\"", "], backfilled=backfilled, ) # Insert event_reference_hashes table. self._store_event_reference_hashes_txn( txn, [event", "{} for event, ctx in events_and_contexts: partitioned.setdefault(event.room_id, []).append((event, ctx)) deferreds", "e.event_id = ed.prev_event_id\" \" LEFT JOIN events_to_purge AS ep2 ON", "OR CONDITIONS OF ANY KIND, either express or implied. #", "event. # Normally that'd be in the database, but its", "extremeties by finding # events to be purged that are", "logger.info(\"[purge] finding state groups that can be deleted\") _ =", "Whether the results are retrieved from federation via backfill or", "{} for event_id in new_latest_event_ids: # First search in the", "prev_event_id in existing_prevs: continue soft_failed = json.loads(metadata).get(\"soft_failed\") if soft_failed or", "room_id, \"type\": key[0], \"state_key\": key[1], \"event_id\": state_id, } for key,", "versions. for sg in remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining state group", "LEFT JOIN event_relations USING (event_id)\" \" WHERE ? < event_stream_ordering\"", "\" \" WHERE NOT should_delete\" \")\", (True,), ) # synapse", "them # to the events table and the events_json table.", "txn.execute(sql, list(current_search)) referenced = set(sg for sg, in txn) referenced_groups", "events have negative stream orderings, so we don't # want", "new event\", buckets=(1, 2, 3, 5, 7, 10, 15, 20,", "20, 50, 100, 200, 500, \"+Inf\"), ) # The number", "= eb.event_id INNER JOIN events AS e ON e.event_id =", "room_id, type, state_key, event_id FROM current_state_delta_stream WHERE ? < stream_id", "= set() else: current_search = set(itertools.islice(next_to_search, 100)) next_to_search -= current_search", "origin_type = \"local\" origin_entity = context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type =", "stuff out of the DB later # if necessary. current_state_ids", "persisted \"\"\" if not events_and_contexts: return if backfilled: stream_ordering_manager =", "& result stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter the", "?\" ) txn.execute(sql, (last_id, current_id, limit)) new_event_updates = txn.fetchall() if", "list, without the rejected events. \"\"\" # Remove the rejected", "then go and check if they are referenced by other", "new_forward_extremities, max_stream_order ): for room_id, new_extrem in iteritems(new_forward_extremities): self._simple_delete_txn( txn,", "consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, ) ) return deferred.observe()", "\" AND event_id NOT LIKE ?\" # We include the", "outliers\") txn.execute( \"UPDATE events SET outlier = ?\" \" WHERE", "the state group from the database. # Set of events", "an accepted # event's auth chain, but its easier for", "existing_state = yield self.get_current_state_ids(room_id) to_delete = [key for key in", "ASC LIMIT ? \"\"\" txn.execute(sql, (from_token, to_token, limit)) return txn.fetchall()", "# If we couldn't find it, then we'll need to", "events which are already in the events table. \"\"\" txn.execute(", "# map room_id->list[event_ids] giving the new forward # extremities in", "the # change in outlier status to our workers. stream_order", "membership to invalidate the # `get_rooms_for_user` cache. # We find", "not events_and_contexts: # nothing to do here return logger.info(\"Deleting existing\")", "need to get # their state IDs so we can", "event_relations USING (event_id)\" \" WHERE ? > event_stream_ordering\" \" AND", "\"state_key\": key[1], } for key, ev_id in iteritems(to_insert) ], )", "LEFT JOIN event_json USING (event_id) WHERE event_id IN (%s) AND", "ev, _ in events_context} # We need to get the", "be invoked. \"\"\" if room_id in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks", "*without* a logcontext. \"\"\" queue = self._event_persist_queues.setdefault(room_id, deque()) if queue:", "context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id = yield self._stream_id_gen.get_current_token()", "# anything. if old_state_groups == new_state_groups: defer.returnValue((None, None)) if len(new_state_groups)", "includes events we've already persisted, etc, that wouldn't appear in", "state_groups table with that state. # insert into event_to_state_groups. try:", "federation via backfill or not. Used to determine if they're", "which the events are being added. Used for logging etc", "may not use this file except in compliance with the", "thats your own fault. like_clause = \"%:\" + self.hs.hostname sql", "if current_state is not None: current_state_for_room[room_id] = current_state yield self.runInteraction(", "out any events which were # rejected, and returns the", "need to pull the state group from the database. #", "failed/rejected events and their prev events (whether soft-failed/rejected or not),", "extremities\") # We calculate the new entries for the backward", "only necessary if the rejected event appears in an accepted", "in have_persisted: continue to_remove.add(event) if context.rejected: # If the event", "INNER JOIN event_edges AS eg ON eg.prev_event_id = eb.event_id INNER", "state_group FROM event_to_state_groups LEFT JOIN events_to_purge AS ep USING (event_id)", "start with the existing forward extremities result = set(latest_event_ids) #", "in batch_iter(event_ids, 100): yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs)", "only events that we haven't # seen before. if delete_existing:", "rejected). Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events", "need to map the event_ids to their state groups. First,", "yield self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids, ) current_state, delta_ids =", "key) -> event_id) state map state_groups_map = {} # Map", "persisting events for one room at a time. Returns: tuple[list,", "c_counter(list(x[0] for x in res)) @defer.inlineCallbacks def persist_events(self, events_and_contexts, backfilled=False):", "# # Licensed under the Apache License, Version 2.0 (the", "events as e \" \"INNER JOIN event_forward_extremities as f \"", "function will be given to the deferreds waiting on the", "max_entries=10) def get_all_new_events( self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit, ):", "extremities left!\" new_forward_extremeties[room_id] = new_latest_event_ids len_1 = ( len(latest_event_ids) ==", "now have some state at that # so we need", "auth_id in event.auth_event_ids() if event.is_state() ], ) # _store_rejected_events_txn filters", "== limit: upper_bound = new_backfill_events[-1][0] else: upper_bound = current_backfill_id sql", "yield self._get_event_ordering(event_id2) defer.returnValue((to_1, so_1) > (to_2, so_2)) @cachedInlineCallbacks(max_entries=5000) def _get_event_ordering(self,", "f.room_id = ?\", (room_id,), ) rows = txn.fetchall() max_depth =", "new_latest_event_ids, ) current_state, delta_ids = res # If either are", "= {e[0].event_id: e[0] for e in events_and_contexts[i : i +", "we do not # end up in a situation where", "a copy of an event that we had already stored", "state_groups_map = {} # Map from (prev state group, new", "if max_depth < token.topological: # We need to ensure we", "LIMIT ?\" ) txn.execute(sql, (last_id, current_id, limit)) new_event_updates = txn.fetchall()", "list[(EventBase, EventContext)] new list, without the rejected events. \"\"\" #", "index on event_id, and has one on # (room_id, event_id)", "res # If either are not None then there has", "the python sqlite driver commits the # transaction on CREATE,", "we don't # want to set the event_persisted_position to that.", "ev, ctx in events_context: if event_id == ev.event_id and ctx.state_group", "seen prevs -= state_groups_seen next_to_search |= prevs state_groups_seen |= prevs", "we are recalculating the current state state_delta_counter = Counter(\"synapse_storage_events_state_delta\", \"\")", "non-outlier if there is one, else the earliest one. Args:", "events_context: if event_id == ev.event_id and ctx.state_group is not None:", "def count_daily_active_rooms(self): def _count(txn): sql = \"\"\" SELECT COALESCE(COUNT(DISTINCT room_id),", "events SET outlier = ?\" \" WHERE event_id = ?\"", "not have to pull out the existing state # unnecessarily).", "of this method, it does *not* follow the synapse logcontext", "-event_stream_ordering, event_id, state_group\" \" FROM ex_outlier_stream\" \" WHERE ? >", "TEMPORARY TABLE events_to_purge (\" \" event_id TEXT NOT NULL,\" \"", "place whether or not the returned deferred is ready. Args:", "state delta in each # room state_delta_for_room = {} if", "txn, events_and_contexts, backfilled, delete_existing=False, state_delta_for_room={}, new_forward_extremeties={}, ): \"\"\"Insert some number", "INNER JOIN events USING (event_id) LEFT JOIN rejections USING (event_id)", "we have calculated new_state_groups we need to get # their", "the event_backward_extremities table now that this # event isn't an", "stream_ordering > ? \"\"\" txn.execute(sql, (like_clause, self.stream_ordering_day_ago)) count, = txn.fetchone()", "to the deferreds waiting on the item, exceptions will be", "BY stream_ordering DESC\" \" LIMIT ?\" ) if have_backfill_events: txn.execute(sql,", "all( len(event.prev_event_ids()) == 1 and not event.is_state() for event, ctx", "SELECT COALESCE(COUNT(*), 0) FROM events WHERE type = 'm.room.message' AND", "synapse.events.snapshot import EventContext # noqa: F401 from synapse.metrics import BucketCollector", "defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events( self, room_id, events_context, old_latest_event_ids, new_latest_event_ids ):", "hs.get_state_resolution_handler() # Collect metrics on the number of forward extremities", "new_events_and_contexts[event.event_id] = (event, context) else: new_events_and_contexts[event.event_id] = (event, context) return", "bother calculating state if they're just # a long chain", "is if the latest extremities # were the same when", "of times we are recalculating the current state state_delta_counter =", "100, 200, 500, \"+Inf\"], ) # Read the extrems every", "Args: events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): delete_existing (bool): Returns: Deferred:", "purge, etc., so lets make an index. txn.execute(\"CREATE INDEX events_to_purge_id\"", "SET outlier = ?\" \" WHERE event_id IN (\" \"", "= logging.getLogger(__name__) persist_event_counter = Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter = Counter( \"synapse_storage_events_persisted_events_sep\",", "get # their state IDs so we can resolve to", "60 minutes def read_forward_extremities(): # run as a background process", "if you have silly characters in your own # hostname", "= ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, ) )", "are persisting; that means we do not # end up", "state groups\", len(remaining_state_groups), ) # Now we turn the state", "@wraps(func) @defer.inlineCallbacks def f(self, *args, **kwargs): try: res = yield", "Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]: Returns a tuple of two state", "event.event_id) if not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, ) if", "\"room_id\": event.room_id, \"auth_id\": auth_id, } for event, _ in events_and_contexts", "out the delta (or use that # given) if delta_ids", "filtered list \"\"\" new_events_and_contexts = OrderedDict() for event, context in", "events_and_contexts (list[(EventBase, EventContext)]): events we are persisting all_events_and_contexts (list[(EventBase, EventContext)]):", "} for event, _ in events_and_contexts ], ) def _store_rejected_events_txn(self,", "event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"processed\": True, \"outlier\": event.internal_metadata.is_outlier(), \"origin_server_ts\":", "be purged that are pointed to by events we're not", "graph = {} # Set of events that we have", "old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate the current state dict after adding", "function that returns a Deferred and accepts a `delete_existing` arg", "(event, context), stream in zip(events_and_contexts, stream_orderings): event.internal_metadata.stream_ordering = stream chunks", "\"\"\" if room_id in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def handle_queue_loop():", "], ) # We now insert into stream_ordering_to_exterm a mapping", "each item in the queue, of type _EventPersistQueueItem. The per_item_callback", "None) new_events_and_contexts[event.event_id] = (event, context) else: new_events_and_contexts[event.event_id] = (event, context)", "{} self._currently_persisting_rooms = set() def add_to_queue(self, room_id, events_and_contexts, backfilled): \"\"\"Add", "= ?\" txn.execute(sql, (False, event.event_id)) # Update the event_backward_extremities table", "a time. \"\"\" # we're only interested in new events", "# might contain the same event. :( # NB: Assumes", "WHERE event_id IN (\" \" SELECT event_id FROM events_to_purge \"", "backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering,", "we don't have the same event twice. Pick the earliest", "the events were backfilled \"\"\" depth_updates = {} for event,", "# If either are not None then there has been", "event info. This turns outliers into ex-outliers (unless the new", "events we're adding. for ev, ctx in events_context: if event_id", "old_latest_event_ids ) # State groups of new_latest_event_ids new_state_groups = set(", "# inherits from EventFederationStore so that we can call _update_backward_extremities", "def persist_events(self, events_and_contexts, backfilled=False): \"\"\" Write events to the database", "to_recursively_check = batch while to_recursively_check: sql = \"\"\" SELECT event_id,", "we will delete local events as well as remote ones", "ev.type == EventTypes.Create and ev.state_key == \"\": room_version = ev.content.get(\"room_version\",", "let's stick it at the end so that we don't", "state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if not backfilled: # backfilled events", "until it finds no more soft-failed/rejected events. This is used", "ctx.state_group is None: # This should only happen for outlier", "should_delete\" \")\" % (table,), (room_id,), ) # Mark all state", "len(events_and_contexts) ) else: stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with stream_ordering_manager", "Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events we", "\"\"\" existing_state = yield self.get_current_state_ids(room_id) to_delete = [key for key", "per room. \"\"\" _EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\")", "# been cached in the context. We'll pull stuff out", "deleted and the set of state groups that need to", "any events which are prev_events of any existing events. existing_prevs", "de-delta-ing %i remaining state groups\", len(remaining_state_groups), ) # Now we", ") def _update_current_state_txn(self, txn, state_delta_by_room, stream_id): for room_id, current_state_tuple in", "for e_id in event.prev_event_ids() ) result.difference_update(existing_prevs) # We only update", "if last_id == current_id: return defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql =", "# or state groups, and if not we delete them.", "= curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\", keyvalues={\"state_group\": sg} ) self._simple_delete_txn( txn,", "as # an outlier in the database. We now have", "] latest_event_ids = set(latest_event_ids) # start with the existing forward", "(int, int): the stream ordering of ``event``, and the stream", "FROM event_to_state_groups \" \"WHERE event_id IN (SELECT event_id from events_to_purge)\"", "persist. This includes events we've already persisted, etc, that wouldn't", "pointed to by events we're not going to # purge.", "the event_id into the rejections table self._store_rejections_txn(txn, event.event_id, context.rejected) to_remove.add(event)", "x in res)) @defer.inlineCallbacks def persist_events(self, events_and_contexts, backfilled=False): \"\"\" Write", "else: upper_bound = current_backfill_id sql = ( \"SELECT -event_stream_ordering, event_id,", "event\", buckets=(1, 2, 3, 5, 7, 10, 15, 20, 50,", "the events are only events that we haven't # seen", "we've already seen prevs -= state_groups_seen next_to_search |= prevs state_groups_seen", "SELECT event_id, prev_event_id, internal_metadata, rejections.event_id IS NOT NULL FROM event_edges", "Args: event (EventBase): context (EventContext): backfilled (bool): Returns: Deferred: resolves", "if the events were backfilled delete_existing (bool): True to purge", ") \"\"\" txn.executemany( sql, ( ( stream_id, room_id, etype, state_key,", "in the background run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self, room_id): queue =", "(bool): True if the events were backfilled \"\"\" # Insert", "always be at least one forward extremity. # (except during", "( \"SELECT \" \" e.event_id as event_id, \" \" r.redacts", "continue if ctx.state_group in state_groups_map: continue # We're only interested", "don't delete all the events from the database # otherwise", "insert into stream_ordering_to_exterm a mapping from room_id, # new stream_ordering", "= \"\"\" INSERT INTO current_state_delta_stream (stream_id, room_id, type, state_key, event_id,", "topological_ordering < ?\" % (should_delete_expr, should_delete_expr), should_delete_params, ) # We", "= {sg: state_groups_map[sg] for sg in new_state_groups} events_map = {ev.event_id:", "the ex_outlier_stream table to replicate the # change in outlier", "state group, then we know what the current # state", "in writing, software # distributed under the License is distributed", "in an accepted # event's auth chain, but its easier", "event.type == EventTypes.Redaction: # Insert into the redactions table. self._store_redaction(txn,", "import BucketCollector from synapse.metrics.background_process_metrics import run_as_background_process from synapse.state import StateResolutionStore", "# furthermore, we might already have the table from a", "have_persisted[event.event_id] if not event.internal_metadata.is_outlier() and outlier_persisted: # We received a", "event_id, should_delete FROM events_to_purge\") event_rows = txn.fetchall() logger.info( \"[purge] found", "we have added, then we invlidate the caches for all", "in your own # hostname then thats your own fault.", "from one state group to another, lets check if #", "Conversely if we do know the delta then the new", "database Args: events_and_contexts: list of tuples of (event, context) backfilled", "# Remove the entries in the event_push_actions table for the", "JOIN redactions USING (event_id)\" \" LEFT JOIN state_events USING (event_id)\"", "handwavey check to see if we could # have guessed", "(\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id for event, _ in events_and_contexts], )", "list # of type/state keys to remove from current state,", "new event %s has no state \" \"group\" % (ev.event_id,)", "\"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10) def get_all_new_events( self, last_backfill_id, last_forward_id,", "contain the same event. :( # NB: Assumes that we", "stale_forward_extremities_counter.observe(len(stale)) defer.returnValue(result) @defer.inlineCallbacks def _get_events_which_are_prevs(self, event_ids): \"\"\"Filter the supplied list", "if prev_event_context: if not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): # To ensure", "origin_type = \"local\" origin_entity = \"*client*\" else: origin_type = \"remote\"", "def _get_event_ordering(self, event_id): res = yield self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"],", "persisting; that means we do not # end up in", "new event (as opposed # to receiving it over federation)", "we insert events that are outliers and aren't going to", "new forward extremities for a room given events to persist.", "now that we've added them # to the events table", "that we don't have the same event twice. Pick the", "txn, [ event for event, _ in events_and_contexts if event.type", "return it in a Unicode string. \"\"\" out = frozendict_json_encoder.encode(json_object)", "txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def", "then we can just # return that. new_state_group = next(iter(new_state_groups))", "persisting Returns: list[(EventBase, EventContext)] new list, without the rejected events.", "backward_ex_outliers, ) return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self, room_id, token, delete_local_events):", "which is in the create event. # Normally that'd be", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows ) @cached(num_args=5, max_entries=10) def get_all_new_events( self,", "events were backfilled \"\"\" depth_updates = {} for event, context", "per_item_callback(item) except Exception: with PreserveLoggingContext(): item.deferred.errback() else: with PreserveLoggingContext(): item.deferred.callback(ret)", "for event in new_events for e_id in event.prev_event_ids() ) #", "filtered event ids \"\"\" results = [] def _get_events_which_are_prevs_txn(txn, batch):", "are the updates to current_state_events. \"\"\" existing_state = yield self.get_current_state_ids(room_id)", "\" \"ON e.event_id = f.event_id \" \"AND e.room_id = f.room_id", "when the events have been persisted \"\"\" if not events_and_contexts:", "room_id, events_and_contexts, backfilled): \"\"\"Add events to the queue, with the", "state in each room after adding these events. # This", "Returns: Deferred[set[str]] \"\"\" # The set of event_ids to return.", ") # State groups of new_latest_event_ids new_state_groups = set( event_id_to_state_group[evid]", "expression twice should_delete_params += (\"%:\" + self.hs.hostname, \"%:\" + self.hs.hostname)", "\"SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \"", "of extremities as well as the new. stale_forward_extremities_counter = Histogram(", "e.depth FROM events as e \" \"INNER JOIN event_forward_extremities as", "not None: event_id_to_state_group[event_id] = ctx.state_group break else: # If we", "state groups can be deleted and which need to be", "be deleted\", len(event_rows), sum(1 for e in event_rows if e[1]),", "\"\"\" _EventPersistQueueItem = namedtuple( \"_EventPersistQueueItem\", (\"events_and_contexts\", \"backfilled\", \"deferred\") ) def", "the events that # point to it via event_edges table.", "`prev_event_id`. (This # allows us to not have to pull", "been persisted \"\"\" if not events_and_contexts: return if backfilled: stream_ordering_manager", "that. If we happen to already have # the current", "new_backfill_events[-1][0] else: upper_bound = current_backfill_id sql = ( \"SELECT -event_stream_ordering,", "turns outliers into ex-outliers (unless the new event was rejected).", "event, context in state_events_and_contexts: vals = { \"event_id\": event.event_id, \"room_id\":", "# We can't easily parallelize these since different chunks #", "= \"remote\" origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc() for room_id,", "insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] = (event, context) else: new_events_and_contexts[event.event_id] =", "? < event_stream_ordering\" \" AND event_stream_ordering <= ?\" \" ORDER", "reached\"\"\" return -self._backfill_id_gen.get_current_token() def get_current_events_token(self): \"\"\"The current maximum token that", "into the event_search table. self._store_history_visibility_txn(txn, event) elif event.type == EventTypes.GuestAccess:", "# Unless required by applicable law or agreed to in", "**kwargs): try: res = yield func(self, *args, **kwargs) except self.database_engine.module.IntegrityError:", "# We need to get the room version, which is", "= Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" ) # The number of forward", "self._get_state_group_for_events(missing_event_ids) event_id_to_state_group.update(event_to_groups) # State groups of old_latest_event_ids old_state_groups = set(", "SynapseError(404, \"Could not find event %s\" % (event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]),", "so we can resolve to a single state set. missing_state", "handle_queue(self, room_id, per_item_callback): \"\"\"Attempts to handle the queue for a", "groups can be deleted and which need to be de-delta'ed", "the Apache License, Version 2.0 (the \"License\"); # you may", "to return. This includes all soft-failed events # and their", "NULL\" should_delete_params = () if not delete_local_events: should_delete_expr += \"", "events for. Note that these must have already been persisted.", "the background run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self, room_id): queue = self._event_persist_queues.setdefault(room_id,", "= [] rows = [] N = 200 for i", "= Counter(\"synapse_storage_events_persisted_events\", \"\") event_counter = Counter( \"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\",", "new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) # Ensure that we don't have the", "ctx.state_group break else: # If we couldn't find it, then", "EventTypes.Create and ev.state_key == \"\": room_version = ev.content.get(\"room_version\", \"1\") break", "EventTypes.Topic: # Insert into the topics table and event_search table.", "in events_and_contexts if ec[0].is_state() ] state_values = [] for event,", "self._event_persist_queue.add_to_queue( event.room_id, [(event, context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id", "current_forward_id sql = ( \"SELECT event_stream_ordering, event_id, state_group\" \" FROM", "event_id) instead. for table in (\"event_push_actions\",): logger.info(\"[purge] removing events from", "\" WHERE ? < event_stream_ordering\" \" AND event_stream_ordering <= ?\"", "stream ordering of the latest persisted event \"\"\" partitioned =", "event_backward_extremities # event_edges # event_forward_extremities # event_json # event_push_actions #", "are the same then we don't need to do #", "elif event.type == EventTypes.Redaction: # Insert into the redactions table.", "use that # given) if delta_ids is not None: #", "for event, _ in events_and_contexts if event.type == EventTypes.Member ],", "ready. Args: room_id (str): events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): Returns:", "50, 100, 200, 500, \"+Inf\"), ) # The number of", "the old forward extremities for the room. new_latest_event_ids (iterable[str]): the", "\"room_names\", \"state_events\", \"rejections\", \"redactions\", \"room_memberships\", \"topics\", ): txn.executemany( \"DELETE FROM", "(event_id) WHERE state_group IN (%s) AND ep.event_id IS NULL \"\"\"", "federation) it will use the # forward extremities as the", "tuple[set[int], set[int]]: The set of state groups that can be", "persisted. Runs its callbacks *without* a logcontext. \"\"\" queue =", "# We bound size of groups we're looking up at", "here) class EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ): def __init__(self,", "chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks def _get_new_state_after_events( self, room_id, events_context, old_latest_event_ids,", "?\" \" WHERE event_id = ?\" txn.execute(sql, (False, event.event_id)) #", "state. # insert into event_to_state_groups. try: self._store_event_state_mappings_txn(txn, ((event, context),)) except", "check that we're deleting rather than updating if (etype, state_key)", "new current state and the second being the delta to", "earliest non-outlier if there is one, else the earliest one.", "case we can # pull the state group from its", "as e \" \"INNER JOIN event_forward_extremities as f \" \"ON", "(bool): delete_existing (bool): Returns: Deferred: resolves when the events have", "chunks = [ events_and_contexts[x : x + 100] for x", "max(row[1] for row in rows) if max_depth < token.topological: #", "all the new events that have arrived at the server", "room_id, members_changed) def _update_forward_extremities_txn( self, txn, new_forward_extremities, max_stream_order ): for", "in each room new_forward_extremeties = {} # map room_id->(type,state_key)->event_id tracking", "prev-event graph until it finds no more soft-failed/rejected events. This", "# This is good enough as if you have silly", "end_item.deferred.observe() deferred = ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred,", "see events before the # current_state_delta updates. # sql =", "event_to_state_groups\") txn.execute( \"DELETE FROM event_to_state_groups \" \"WHERE event_id IN (SELECT", "Insert into the room_memberships table. self._store_room_members_txn( txn, [ event for", "def fetch(txn): txn.execute( \"\"\" select count(*) c from event_forward_extremities group", "of any existing events. existing_prevs = yield self._get_events_which_are_prevs(result) result.difference_update(existing_prevs) #", "backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"): # Work out the new \"current", "new_events for e_id in event.prev_event_ids() ) result.difference_update(existing_prevs) # We only", "here return for event, context in events_and_contexts: if event.type ==", "room_id, events_context, old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate the current state dict", "to defer to the state handler to resolve our state", "soft-failed events # and their prev events. existing_prevs = set()", "and the second being the delta to the existing current", "state_delta_for_room = {} if not backfilled: with Measure(self._clock, \"_calculate_state_and_extrem\"): #", "\" LIMIT ?\" ) txn.execute(sql, (last_id, current_id, limit)) new_event_updates =", "new_backfill_events = txn.fetchall() if len(new_backfill_events) == limit: upper_bound = new_backfill_events[-1][0]", "for room_id in partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) )", "# Insert the event_id into the rejections table self._store_rejections_txn(txn, event.event_id,", "the parameter twice since we use the expression twice should_delete_params", "= 'm.room.message' AND stream_ordering > ? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count,", "= yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self): def _count_messages(txn):", "the database Args: events_and_contexts: list of tuples of (event, context)", "events so that we don't # have to keep shovelling", "iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), ) prevs = set(row[\"state_group\"] for row", "event_push_actions table for the # redacted event. self._remove_push_actions_for_event_id_txn( txn, event.room_id,", "sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key,", "lets prefill # the cache with it. if current_state is", "event.depth, \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\": event.type, \"processed\": True, \"outlier\":", "\"\"\" SELECT COALESCE(MIN(depth), 0) FROM event_backward_extremities AS eb INNER JOIN", "determine if they're \"new\" events which might update the current", "= [ events_and_contexts[x : x + 100] for x in", "are retrieved from federation via backfill or not. Used to", "_filter_events_and_contexts_for_duplicates(cls, events_and_contexts): \"\"\"Ensure that we don't have the same event", ") deferreds.append(d) for room_id in partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds,", "insertion as that's a lot faster. # create an index", "result.difference_update(existing_prevs) # We only update metrics for events that change", "table) txn.execute( \"DELETE FROM %s WHERE room_id = ? AND", "rejected events from the list now that we've added them", "for room %s\", room_id) with Measure( self._clock, \"persist_events.get_new_state_after_events\" ): res", "to look at the events that # point to it", "txn, events_and_contexts): \"\"\"Add rows to the 'rejections' table for received", "= \"state_key IS NULL\" should_delete_params = () if not delete_local_events:", "# Queue has been drained. pass _EventCacheEntry = namedtuple(\"_EventCacheEntry\", (\"event\",", "events_to_purge_should_delete\" \" ON events_to_purge(should_delete)\" ) # We do joins against", "entries to the current_state_delta_stream. We # do this before updating", "being the delta to the existing current state. If both", "to # purge. txn.execute( \"SELECT DISTINCT e.event_id FROM events_to_purge AS", "and not have_forward_events: return defer.succeed(AllNewEventsResult([], [], [], [], [])) def", "deleted\", len(event_rows), sum(1 for e in event_rows if e[1]), )", "\"\"\" SELECT DISTINCT state_group FROM event_to_state_groups LEFT JOIN events_to_purge AS", "= max( event.depth, depth_updates.get(event.room_id, event.depth) ) for room_id, depth in", "= [] for room_id, evs_ctxs in iteritems(partitioned): d = self._event_persist_queue.add_to_queue(", "# limitations under the License. import itertools import logging from", "BY event_stream_ordering DESC\" ) txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates", "room_id \"\"\" ) return txn.fetchall() res = yield self.runInteraction(\"read_forward_extremities\", fetch)", "after adding these events. # This is simply used to", "last_id == current_id: return defer.succeed([]) def get_all_new_forward_event_rows(txn): sql = (", "entirely. state_delta_for_room[room_id] = ([], delta_ids) elif current_state is not None:", "event.event_id)) # Add an entry to the ex_outlier_stream table to", "_store_redaction(self, txn, event): # invalidate the cache for the redacted", "that for the rest of our transaction. # # So,", "\"origin_entity\"], ) # The number of times we are recalculating", "\"synapse_storage_events_persisted_events_sep\", \"\", [\"type\", \"origin_type\", \"origin_entity\"], ) # The number of", ") # _store_rejected_events_txn filters out any events which were #", "last call to this function, it will return None. \"\"\"", "ON e.event_id = eg.event_id WHERE eb.room_id = ? \"\"\", (room_id,),", "(list[(EventBase, EventContext)]): Returns: list[(EventBase, EventContext)]: filtered list \"\"\" new_events_and_contexts =", "removing events from event_to_state_groups\") txn.execute( \"DELETE FROM event_to_state_groups \" \"WHERE", "referenced rows = self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\",", "drop the table first. txn.execute(\"DROP TABLE IF EXISTS events_to_purge\") txn.execute(", "[event.event_id for event, _ in events_and_contexts], ) have_persisted = {event_id:", "we invlidate the caches for all # those users. members_changed", "cache entries for the event_ids txn.call_after(self._invalidate_get_event_cache, event.event_id) if not backfilled:", "? \"\"\" txn.execute(sql, (self.stream_ordering_day_ago,)) count, = txn.fetchone() return count ret", "groups we've already seen prevs -= state_groups_seen next_to_search |= prevs", "for outlier events. if not ev.internal_metadata.is_outlier(): raise Exception( \"Context for", "old # extremities are going to be in events_context). missing_event_ids", "range(0, len(events_and_contexts), 100) ] for chunk in chunks: # We", "may have deleted # and which we have added, then", "parameter twice since we use the expression twice should_delete_params +=", "events WHERE type = 'm.room.message' AND sender LIKE ? AND", "are persisting Returns: list[(EventBase, EventContext)] new list, without the rejected", "context. We'll pull stuff out of the DB later #", "don't continue iterating up the state group graphs for state", "# We sanity check that we're deleting rather than updating", "EventTypes.Redaction: # Insert into the redactions table. self._store_redaction(txn, event) elif", "up events so that they can be persisted in bulk", "event \"\"\" deferred = self._event_persist_queue.add_to_queue( event.room_id, [(event, context)], backfilled=backfilled )", "# and which we have added, then we invlidate the", "persistence of the send_join # results, in which case there", "to map the event_ids to their state groups. First, let's", "table txn.executemany( \"DELETE FROM current_state_events\" \" WHERE room_id = ?", "are those that were in the previous set of extremities", "ev.content.get(\"room_version\", \"1\") break if not room_version: room_version = yield self.get_room_version(room_id)", "defer.succeed(AllNewEventsResult([], [], [], [], [])) def get_all_new_events_txn(txn): sql = (", "is used to find extremities that are ancestors of new", "and not event.is_state() for event, ctx in ev_ctx_rm ) #", "into the event and event_json tables Args: txn (twisted.enterprise.adbapi.Connection): db", "more soft-failed/rejected events. This is used to find extremities that", "what the new extremities are and then # calculating the", "tracking the full # state in each room after adding", "one we're persisting, in which case we can # pull", "= ctx.get_cached_current_state_ids() if current_state_ids is not None: state_groups_map[ctx.state_group] = current_state_ids", "IF EXISTS events_to_purge\") txn.execute( \"CREATE TEMPORARY TABLE events_to_purge (\" \"", "extremities. \"\"\" all_events_and_contexts = events_and_contexts min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering max_stream_order =", "invoked. \"\"\" if room_id in self._currently_persisting_rooms: return self._currently_persisting_rooms.add(room_id) @defer.inlineCallbacks def", "(bool): Whether the results are retrieved from federation via backfill", "and len(old_state_groups) == 1: # If we're going from one", "Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) # We want to store", "chain, but its easier for now just to store them", "state_key = ?\", ( (room_id, etype, state_key) for etype, state_key", "the updates to current_state_events. \"\"\" existing_state = yield self.get_current_state_ids(room_id) to_delete", "for sg in new_state_groups} events_map = {ev.event_id: ev for ev,", "txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\", get_all_new_backfill_event_rows", "latest_event_ids == prev_event_ids: state_delta_reuse_delta_counter.inc() break logger.info(\"Calculating state delta for room", "delta_ids is not None: # If there is a delta", "state_delta_for_room[room_id] = delta # If we have the current_state then", "context. # Otherwise we need to pull the state group", "that'd be in the database, but its also possible that", "of its prev groups being scheduled for deletion). Args: txn", "_get_prevs_before_rejected(self, event_ids): \"\"\"Get soft-failed ancestors to remove from the extremities.", "ev.internal_metadata.is_outlier(): raise Exception( \"Context for new event %s has no", "No change in extremities, so no change in state continue", "from federation via backfill or not. Used to determine if", "to that item. end_item = queue[-1] if end_item.backfilled == backfilled:", "[])) def get_all_new_events_txn(txn): sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id,", "assert new_latest_event_ids, \"No forward extremities left!\" new_forward_extremeties[room_id] = new_latest_event_ids len_1", "If there is a delta we know that we've #", "events table, the events_json table, and the rejections table. Things", "to delete\", len(state_groups_to_delete) ) logger.info( \"[purge] de-delta-ing %i remaining state", "groups\", len(remaining_state_groups), ) # Now we turn the state groups", "if not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, ) if not", "txn, state_delta_by_room, stream_id): for room_id, current_state_tuple in iteritems(state_delta_by_room): to_delete, to_insert", "get_all_new_backfill_event_rows(txn): sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \"", "= ([], delta_ids) elif current_state is not None: with Measure(", "in the last day. If it has been significantly less", "we are reculating state when we could have resonably #", "already been # persisted, and returns the filtered list. events_and_contexts", ") def __init__(self): self._event_persist_queues = {} self._currently_persisting_rooms = set() def", "-*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd #", "it has been significantly less or more than one day", "WHERE should_delete\" \")\" % (table,), (room_id,), ) # Mark all", "= new_forward_events[-1][0] else: upper_bound = current_forward_id sql = ( \"SELECT", "updating if (etype, state_key) not in to_insert ), ) txn.executemany(", "events_and_contexts): \"\"\"Ensure that we don't have the same event twice.", "set(row[\"state_group\"] for row in rows) # We don't bother re-handling", "just add these new events to that item. end_item =", "\"\"\"Add rows to the 'rejections' table for received events which", "import EventContext # noqa: F401 from synapse.metrics import BucketCollector from", "to the state handler to resolve our state sets. state_groups", "or not), and recurses up the prev-event graph until it", "for event in new_events) # Now remove all events which", "must have already been persisted. Returns: Deferred[set[str]] \"\"\" # The", "% (table,), [(ev.room_id, ev.event_id) for ev, _ in events_and_contexts], )", "= ?\" % (table,), [(ev.event_id,) for ev, _ in events_and_contexts],", "relates_to_id\" \" FROM events AS e\" \" LEFT JOIN redactions", "events_to_purge(should_delete)\" ) # We do joins against events_to_purge for e.g.", "import SynapseError from synapse.events import EventBase # noqa: F401 from", "events are only ones that weren't # rejected. self._update_metadata_tables_txn( txn,", ") else: stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts) ) with stream_ordering_manager as", "WHERE id = ?\", ((sg,) for sg in state_groups_to_delete), )", "_update_outliers_txn filters out any events which have already been #", "IN (\" \" SELECT event_id FROM events_to_purge WHERE should_delete\" \")\"", "events_to_purge\") logger.info(\"[purge] done\") def _find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used when purging", "state_groups, events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None)) @defer.inlineCallbacks def _calculate_state_delta(self, room_id,", "at most one prev group graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete =", "referenced = set(sg for sg, in txn) referenced_groups |= referenced", "return if backfilled: stream_ordering_manager = self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else: stream_ordering_manager", "will build a temporary table listing the events so that", "= ?\", (min_depth, room_id), ) # finally, drop the temp", "(from_token, to_token, limit)) return txn.fetchall() return self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, )", "prev # events. If they do we need to remove", "bound size of groups we're looking up at once, to", "room_id in partitioned: self._maybe_start_persisting(room_id) yield make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id", "\"rejections\", \"redactions\", \"room_memberships\", \"topics\", ): txn.executemany( \"DELETE FROM %s WHERE", "self._simple_insert_many_txn( txn, table=\"event_json\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"internal_metadata\":", "# a long chain of single ancestor non-state events. if", "first insertion. new_events_and_contexts.pop(event.event_id, None) new_events_and_contexts[event.event_id] = (event, context) else: new_events_and_contexts[event.event_id]", "= 200 for i in range(0, len(events_and_contexts), N): ev_map =", "table. to_remove = set() for event, context in events_and_contexts: if", "event_id_to_state_group[evid] for evid in old_latest_event_ids ) # State groups of", "the current state dict after adding some new events to", "for event, _ in events_and_contexts ], ) self._simple_insert_many_txn( txn, table=\"events\",", "event for event, ctx in event_contexts if not event.internal_metadata.is_outlier() and", "groups that are referenced by events that are to be", "deferred.observe() def handle_queue(self, room_id, per_item_callback): \"\"\"Attempts to handle the queue", "(event, context) return list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn, events_and_contexts, backfilled): \"\"\"Update", "delete events before delete_local_events (bool): if True, we will delete", "txn.fetchall() res = yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount = c_counter(list(x[0] for", "retrying due to IntegrityError. state_delta_for_room (dict[str, (list, dict)]): The current-state", "need to work out the delta (or use that #", "then there has been no change. If there has been", "\"UPDATE room_depth SET min_depth = ? WHERE room_id = ?\",", "event_id, outlier FROM events WHERE event_id in (%s)\" % (\",\".join([\"?\"]", "\"purge_history\", self._purge_history_txn, room_id, token, delete_local_events, ) def _purge_history_txn(self, txn, room_id,", "don't. new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) # Now that we", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "entries in the event_push_actions table for the # redacted event.", "events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, ) ) return deferred.observe() def handle_queue(self, room_id,", "state_groups_map.update(group_to_state) if len(new_state_groups) == 1: # If there is only", "= f.event_id \" \"AND e.room_id = f.room_id \" \"WHERE f.room_id", "e \" \"INNER JOIN event_forward_extremities as f \" \"ON e.event_id", "in events_context} # We need to get the room version,", ") txn.executemany( \"DELETE FROM state_groups WHERE id = ?\", ((sg,)", "# _store_rejected_events_txn filters out any events which were # rejected,", "f(self, *args, **kwargs): try: res = yield func(self, *args, **kwargs)", "the queue then it will not be invoked. \"\"\" if", "delta_ids is not None: # We have a delta from", "# nothing to do here return def event_dict(event): d =", "soft failed events. Args: event_ids (Iterable[str]): Events to find prev", "been cached in the context. We'll pull stuff out of", "count_daily_messages(self): \"\"\" Returns an estimate of the number of messages", "most one prev group graph[row[\"state_group\"]] = row[\"prev_state_group\"] to_delete = state_groups_seen", "defer.returnValue((res.state, None)) @defer.inlineCallbacks def _calculate_state_delta(self, room_id, current_state): \"\"\"Calculate the new", "for etype, state_key in itertools.chain(to_delete, to_insert) ), ) self._simple_insert_many_txn( txn,", ") result.difference_update(existing_prevs) # We only update metrics for events that", "event_id in new_latest_event_ids: # First search in the list of", "existing to new current state, # so lets just return", "value of the function will be given to the deferreds", "per_item_callback will continuously be called with new items, unless the", "have already been # persisted, and returns the filtered list.", "are referenced by events that are to be # deleted.", "auth chain, but its easier for now just to store", "events_json table. to_remove = set() for event, context in events_and_contexts:", "found to be referenced by events referenced_groups = set() #", "noqa: F401 from synapse.events.snapshot import EventContext # noqa: F401 from", "we can # pull the state group from its context.", "that we're # currently trying to persist it. room_version =", "twisted.internet import defer import synapse.metrics from synapse.api.constants import EventTypes from", "events that we are persisting; that means we do not", "accepted # event's auth chain, but its easier for now", "# Check if state groups are referenced sql = \"\"\"", "ON events_to_purge(event_id)\") txn.execute(\"SELECT event_id, should_delete FROM events_to_purge\") event_rows = txn.fetchall()", "in referenced_groups: prev_sg = graph.get(sg) if prev_sg and prev_sg in", "latest_event_ids ) latest_event_ids = set(latest_event_ids) if new_latest_event_ids == latest_event_ids: #", "of two state maps, the first being the full new", "\"\"\"Insert some number of room events into the necessary database", "Returns an estimate of the number of messages sent in", "buckets=(0, 1, 2, 3, 5, 7, 10, 15, 20, 50,", "and event_search tables. self._store_room_name_txn(txn, event) elif event.type == EventTypes.Topic: #", "be de-delta'ed \"\"\" # Graph of state group -> previous", "set(state_groups) # Set of state groups to handle next. next_to_search", "events we need to fetch groups for. (We know none", "We now have some state at that # so we", "actions into the event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, )", "its prev groups being scheduled for deletion). Args: txn state_groups", "result.update(event.event_id for event in new_events) # Now remove all events", "joins against events_to_purge for e.g. calculating state # groups to", "NULL,\" \" should_delete BOOLEAN NOT NULL\" \")\" ) # First", "itertools.chain(to_delete, to_insert) ), ) self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[ { \"event_id\":", "finding redundant state groups\") # Get all state groups that", "which we have added, then we invlidate the caches for", "current_id: return defer.succeed([]) def get_all_new_forward_event_rows(txn): sql = ( \"SELECT e.stream_ordering,", "ex_outlier_stream USING (event_id)\" \" LEFT JOIN redactions USING (event_id)\" \"", "new forward # extremities in each room new_forward_extremeties = {}", "for sg in referenced_groups: prev_sg = graph.get(sg) if prev_sg and", "logger.info(\"[purge] removing events from %s\", table) txn.execute( \"DELETE FROM %s", "when retrying due to IntegrityError. state_delta_for_room (dict[str, (list, dict)]): The", "[] sql = ( \"SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,\" \"", "None: # We have a delta from the existing to", "len(events_and_contexts) ) with stream_ordering_manager as stream_orderings: for (event, context), stream", "# Work out the new \"current state\" for each room.", "and isinstance(event.content[\"url\"], text_type) ), } for event, _ in events_and_contexts", "event.state_key, } # TODO: How does this work with backfilling?", "func: function that returns a Deferred and accepts a `delete_existing`", "== EventTypes.Member ], backfilled=backfilled, ) # Insert event_reference_hashes table. self._store_event_reference_hashes_txn(", "to which the events are being added. Used for logging", "events_and_contexts) # We want to store event_auth mappings for rejected", "for ev, _ in events_and_contexts], ) for table in (\"event_push_actions\",):", "# Insert event_reference_hashes table. self._store_event_reference_hashes_txn( txn, [event for event, _", "map from state_group to ((type, key) -> event_id) state map", "BucketCollector from synapse.metrics.background_process_metrics import run_as_background_process from synapse.state import StateResolutionStore from", "sqlite, # so make sure to keep this actually last.", "\" should_delete BOOLEAN NOT NULL\" \")\" ) # First ensure", "we could # have guessed what the delta would have", "canonicaljson import json from prometheus_client import Counter, Histogram from twisted.internet", "remaining state groups\", len(remaining_state_groups), ) # Now we turn the", "), ) self._simple_insert_many_txn( txn, table=\"current_state_events\", values=[ { \"event_id\": ev_id, \"room_id\":", "groups to non delta versions. for sg in remaining_state_groups: logger.info(\"[purge]", "\" WHERE event_id = ?\" ) txn.execute(sql, (metadata_json, event.event_id)) #", "the backward extremeties by finding # events to be purged", "relates_to_id\" \" FROM events AS e\" \" INNER JOIN ex_outlier_stream", "events_and_contexts, backfilled): \"\"\"Add events to the queue, with the given", "def get_all_new_events( self, last_backfill_id, last_forward_id, current_backfill_id, current_forward_id, limit, ): \"\"\"Get", "current_state then lets prefill # the cache with it. if", "txn.executemany( \"DELETE FROM current_state_events\" \" WHERE room_id = ? AND", "calculated the delta when we calculated the state for an", "USING (event_id) WHERE prev_event_id IN (%s) AND NOT events.outlier AND", "This allows us to later efficiently look up the forward", "This is only necessary if the rejected event appears in", "# deleted, as nothing will happen to them. txn.execute( \"INSERT", "new list, without events which are already in the events", "\" WHERE ? > stream_ordering AND stream_ordering >= ?\" \"", "= ? AND type = ? AND state_key = ?", "None for ev, _ in events_context: if ev.type == EventTypes.Create", "table for received events which were rejected Args: txn (twisted.enterprise.adbapi.Connection):", "if len(new_state_groups) == 1 and len(old_state_groups) == 1: # If", "the normal usage pattern of this method, it does *not*", "Python object as JSON and return it in a Unicode", "pruned: # event_auth # event_backward_extremities # event_edges # event_forward_extremities #", "in existing_prevs: continue soft_failed = json.loads(metadata).get(\"soft_failed\") if soft_failed or rejected:", "handle next. next_to_search = set(state_groups) while next_to_search: # We bound", "sets. state_groups = {sg: state_groups_map[sg] for sg in new_state_groups} events_map", "are only events that we haven't # seen before. if", "their state IDs so we can resolve to a single", "e\" \" LEFT JOIN redactions USING (event_id)\" \" LEFT JOIN", "were # persisting. state_delta_reuse_delta_counter = Counter( \"synapse_storage_events_state_delta_reuse_delta\", \"\" ) #", "origin_type = \"remote\" origin_entity = get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc() for", "backward extremities: %r\", new_backwards_extrems) txn.execute( \"DELETE FROM event_backward_extremities WHERE room_id", "events_to_purge INNER JOIN event_to_state_groups USING (event_id) \"\"\" ) referenced_state_groups =", "# This is only necessary if the rejected event appears", "# Insert into the room_names and event_search tables. self._store_room_name_txn(txn, event)", "state group -> previous group graph = {} # Set", "in ( \"events\", \"event_auth\", \"event_json\", \"event_edges\", \"event_forward_extremities\", \"event_reference_hashes\", \"event_search\", \"event_to_state_groups\",", "txn.executemany( \"DELETE FROM %s WHERE event_id = ?\" % (table,),", "return defer.succeed(AllNewEventsResult([], [], [], [], [])) def get_all_new_events_txn(txn): sql =", "should_delete_expr = \"state_key IS NULL\" should_delete_params = () if not", "= \"local\" origin_entity = \"*client*\" else: origin_type = \"remote\" origin_entity", "to already have # the current state in memory then", "both be moved in here) class EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore,", "for auth_id in event.auth_event_ids() if event.is_state() ], ) # _store_rejected_events_txn", "\"synapse_storage_events_state_delta_single_event\", \"\" ) # The number of times we are", "by other events # or state groups, and if not", "of tuples of (event, context) backfilled (bool): Whether the results", "?\", ((sg,) for sg in state_groups_to_delete), ) logger.info(\"[purge] removing events", "state_id in iteritems(curr_state) ], ) logger.info(\"[purge] removing redundant state groups\")", "ec in events_and_contexts if ec[0].is_state() ] state_values = [] for", "= {event_id: outlier for event_id, outlier in txn} to_remove =", "make_deferred_yieldable( defer.gatherResults(deferreds, consumeErrors=True) ) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue(max_persisted_id) @defer.inlineCallbacks", "None, room_id, etype, state_key, ) for etype, state_key in to_delete", "self.hs.hostname, \"%:\" + self.hs.hostname) should_delete_params += (room_id, token.topological) # Note", "to find extremities that are ancestors of new events, but", "ev, _ in events_context: if ev.type == EventTypes.Create and ev.state_key", "event.type == EventTypes.Message: # Insert into the event_search table. self._store_room_message_txn(txn,", "delete local events as well as remote ones (instead of", "self.runInteraction( \"get_all_updated_current_state_deltas\", get_all_updated_current_state_deltas_txn, ) AllNewEventsResult = namedtuple( \"AllNewEventsResult\", [ \"new_forward_events\",", "max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self, room_id): @defer.inlineCallbacks", "use the expression twice should_delete_params += (\"%:\" + self.hs.hostname, \"%:\"", "[(event, context)], backfilled=backfilled ) self._maybe_start_persisting(event.room_id) yield make_deferred_yieldable(deferred) max_persisted_id = yield", "room_id, depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth) def _update_outliers_txn(self, txn,", "invalidate the cache for the redacted event txn.call_after(self._invalidate_get_event_cache, event.redacts) txn.execute(", "a Python object as JSON and return it in a", "We # do this before updating the current_state_events table so", "state when we could have resonably # calculated the delta", "just marking them as outliers and deleting their state groups).", "paranoia reasons, we go and delete all the existing entries", "send_join # results, in which case there will be no", "500, \"+Inf\"), ) def encode_json(json_object): \"\"\" Encode a Python object", "?\" \" WHERE event_id IN (\" \" SELECT event_id FROM", "let's drop the table first. txn.execute(\"DROP TABLE IF EXISTS events_to_purge\")", "calculated. Conversely if we do know the delta then the", "by events that are to be # deleted. We then", "event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts) # We want to store event_auth mappings", "(set[int]): Set of state groups referenced by events that are", "ObservableDeferred(defer.Deferred(), consumeErrors=True) queue.append( self._EventPersistQueueItem( events_and_contexts=events_and_contexts, backfilled=backfilled, deferred=deferred, ) ) return", "EventContext)]): events we are persisting \"\"\" if not events_and_contexts: #", "end so that we don't block event # persistence. #", "for event, ctx in ev_ctx_rm ) # Don't bother calculating", "not context.rejected: depth_updates[event.room_id] = max( event.depth, depth_updates.get(event.room_id, event.depth) ) for", "# anyway). self._simple_insert_many_txn( txn, table=\"event_auth\", values=[ { \"event_id\": event.event_id, \"room_id\":", "state_events USING (event_id)\" \" LEFT JOIN event_relations USING (event_id)\" \"", "txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts, backfilled=backfilled, ) def _update_current_state_txn(self, txn, state_delta_by_room, stream_id):", "cache with it. if current_state is not None: current_state_for_room[room_id] =", "This includes all soft-failed events # and their prev events.", ") txn.execute(sql, (-last_id, -upper_bound)) new_event_updates.extend(txn.fetchall()) return new_event_updates return self.runInteraction( \"get_all_new_backfill_event_rows\",", "to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) ) def prefill(): for cache_entry in to_prefill:", "in iteritems(new_forward_extremities): self._simple_delete_txn( txn, table=\"event_forward_extremities\", keyvalues={\"room_id\": room_id} ) txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,))", "INTO event_backward_extremities (room_id, event_id)\" \" VALUES (?, ?)\", [(room_id, event_id)", "isn't an outlier any more. self._update_backward_extremeties(txn, [event]) return [ec for", "len(new_state_groups) == 1: # If there is only one state", "in events_and_contexts ], ) self._simple_insert_many_txn( txn, table=\"events\", values=[ { \"stream_ordering\":", "# extremities. However, the events in event_backward_extremities # are ones", "context) return list(new_events_and_contexts.values()) def _update_room_depths_txn(self, txn, events_and_contexts, backfilled): \"\"\"Update min_depth", "INNER JOIN ex_outlier_stream USING (event_id)\" \" LEFT JOIN redactions USING", "the room. # This allows us to later efficiently look", "Vector Ltd # Copyright 2019 The Matrix.org Foundation C.I.C. #", "event_stream_ordering\" \" AND event_stream_ordering <= ?\" \" ORDER BY event_stream_ordering", "if not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): # To ensure correct ordering", "), ) # Now we actually update the current_state_events table", "events table. \"\"\" txn.execute( \"SELECT event_id, outlier FROM events WHERE", "in new_events for e_id in event.prev_event_ids() ) result.difference_update(existing_prevs) # We", "= yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_active_rooms(self): def _count(txn):", "resolves when the events have been persisted \"\"\" if not", "current_state is not None: current_state_for_room[room_id] = current_state yield self.runInteraction( \"persist_events\",", "existing (non-outlier/rejected) events. Args: event_ids (Iterable[str]): event ids to filter", "(event_id,)) defer.returnValue( (int(res[\"topological_ordering\"]), int(res[\"stream_ordering\"])) ) def get_all_updated_current_state_deltas(self, from_token, to_token, limit):", "if last_id == current_id: return defer.succeed([]) def get_all_new_forward_event_rows(txn): sql =", "curr_state = self._get_state_groups_from_groups_txn(txn, [sg]) curr_state = curr_state[sg] self._simple_delete_txn( txn, table=\"state_groups_state\",", "events_and_contexts], ) for table in (\"event_push_actions\",): txn.executemany( \"DELETE FROM %s", "returned if we've already calculated it. \"\"\" # map from", "copy of an event that we had already stored as", "and aren't going to be # deleted, as nothing will", "\" FROM ex_outlier_stream\" \" WHERE ? > event_stream_ordering\" \" AND", "to be de-delta'ed (due to one of its prev groups", "limit, ): \"\"\"Get all the new events that have arrived", "for row in rows: # Note: Each state group can", "self._simple_insert_many_txn( txn, table=\"event_auth\", values=[ { \"event_id\": event.event_id, \"room_id\": event.room_id, \"auth_id\":", "stream_ordering_to_exterm a mapping from room_id, # new stream_ordering to new", "lets make an index. txn.execute(\"CREATE INDEX events_to_purge_id\" \" ON events_to_purge(event_id)\")", "not backfilled: txn.call_after( self._events_stream_cache.entity_has_changed, event.room_id, event.internal_metadata.stream_ordering, ) if not event.internal_metadata.is_outlier()", "then we know what the current # state is. defer.returnValue((state_groups_map[new_state_groups.pop()],", "python sqlite driver commits the # transaction on CREATE, so", "= f.room_id \" \"WHERE f.room_id = ?\", (room_id,), ) rows", "at the prev_events and checking # if they match the", "\"\"\"Calculate the new state deltas for a room. Assumes that", "yield per_item_callback(item) except Exception: with PreserveLoggingContext(): item.deferred.errback() else: with PreserveLoggingContext():", "remove from current state, and to_insert # is a map", "need to pull # the state from the database missing_event_ids.add(event_id)", "else: upper_bound = current_id sql = ( \"SELECT event_stream_ordering, e.event_id,", "import wraps from six import iteritems, text_type from six.moves import", "events_and_contexts: if event.type == EventTypes.Name: # Insert into the room_names", "their prev events. existing_prevs = set() def _get_prevs_before_rejected_txn(txn, batch): to_recursively_check", "for ev, _ in events_context: if ev.type == EventTypes.Create and", "extremities # are those that were in the previous set", "Tables that should be pruned: # event_auth # event_backward_extremities #", "current_search # Check if state groups are referenced sql =", "forward extremeties in the room. # This allows us to", "\"\"\"Filter the supplied list of event_ids to get those which", "self._update_current_state_txn(txn, state_delta_for_room, min_stream_order) self._update_forward_extremities_txn( txn, new_forward_extremities=new_forward_extremeties, max_stream_order=max_stream_order, ) # Ensure", "values=state_values) # Prefill the event cache self._add_to_cache(txn, events_and_contexts) def _add_to_cache(self,", "for _ in current_search), ) txn.execute(sql, list(current_search)) referenced = set(sg", ") # From this point onwards the events are only", "then we'll need to pull # the state from the", "iteritems(curr_state) ], ) logger.info(\"[purge] removing redundant state groups\") txn.executemany( \"DELETE", "None: # Remove the entries in the event_push_actions table for", "temporary table listing the events so that we don't #", "for the room. Returns: Deferred[tuple[dict[(str,str), str]|None, dict[(str,str), str]|None]]: Returns a", "LEFT JOIN rejections as rej USING (event_id)\" \" LEFT JOIN", "interested in is if the latest extremities # were the", "is in the create event. # Normally that'd be in", "min_depth) txn.execute( \"UPDATE room_depth SET min_depth = ? WHERE room_id", "all_events_and_contexts, backfilled ): \"\"\"Update all the miscellaneous tables for new", "the room_names and event_search tables. self._store_room_name_txn(txn, event) elif event.type ==", "get_all_new_backfill_event_rows(self, last_id, current_id, limit): if last_id == current_id: return defer.succeed([])", "the stream ordering of the latest persisted event \"\"\" deferred", "lock on room_depth whenever it # persists events (because upsert),", "token = RoomStreamToken.parse(token_str) # Tables that should be pruned: #", ") state_events_and_contexts = [ ec for ec in events_and_contexts if", "we don't have yet so we need to look at", "that it gets retried on IntegrityError, with `delete_existing=True` passed in.", "origin_entity = \"*client*\" else: origin_type = \"remote\" origin_entity = get_domain_from_id(event.sender)", "as r ON e.event_id = r.redacts\" \" WHERE e.event_id IN", "state_key) for etype, state_key in itertools.chain(to_delete, to_insert) ), ) self._simple_insert_many_txn(", "to by events we're not going to # purge. txn.execute(", "else: with PreserveLoggingContext(): item.deferred.callback(ret) finally: queue = self._event_persist_queues.pop(room_id, None) if", "_update_outliers_txn(self, txn, events_and_contexts): \"\"\"Update any outliers with new event info.", "(event_id)\" \" LEFT JOIN redactions as r ON e.event_id =", "an outlier or not. continue outlier_persisted = have_persisted[event.event_id] if not", "nothing to do here return logger.info(\"Deleting existing\") for table in", "= get_domain_from_id(event.sender) event_counter.labels(event.type, origin_type, origin_entity).inc() for room_id, new_state in iteritems(current_state_for_room):", "delete_local_events: should_delete_expr += \" AND event_id NOT LIKE ?\" #", ") if not res: raise SynapseError(404, \"Could not find event", "This is simply used to prefill the get_current_state_ids # cache", "have_backfill_events and not have_forward_events: return defer.succeed(AllNewEventsResult([], [], [], [], []))", "a long chain of single ancestor non-state events. if all_single_prev_not_state:", "not None: state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group, ctx.state_group)] =", "ORDER BY stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql, (last_id,", "backfilled=False): \"\"\" Write events to the database Args: events_and_contexts: list", "_count_messages) defer.returnValue(ret) @defer.inlineCallbacks def count_daily_sent_messages(self): def _count_messages(txn): # This is", "EventContext)]): Returns: list[(EventBase, EventContext)]: filtered list \"\"\" new_events_and_contexts = OrderedDict()", "the table from a previous (failed) # purge attempt, so", "txn.fetchall() max_depth = max(row[1] for row in rows) if max_depth", "? AND state_key = ? ) \"\"\" txn.executemany( sql, (", "txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]): events to persist", "to remove them and their prev events, # otherwise we", "= {} self._currently_persisting_rooms = set() def add_to_queue(self, room_id, events_and_contexts, backfilled):", "self.runInteraction( \"_get_events_which_are_prevs\", _get_events_which_are_prevs_txn, chunk ) defer.returnValue(results) @defer.inlineCallbacks def _get_prevs_before_rejected(self, event_ids):", "the new events result.difference_update( e_id for event in new_events for", "currently trying to persist it. room_version = None for ev,", "= ?\", ((sg,) for sg in state_groups_to_delete), ) txn.executemany( \"DELETE", "delta for room %s\", room_id) with Measure( self._clock, \"persist_events.get_new_state_after_events\" ):", "all the push actions into the event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn,", "Counter( \"synapse_storage_events_state_delta_single_event\", \"\" ) # The number of times we", "@defer.inlineCallbacks def _get_new_state_after_events( self, room_id, events_context, old_latest_event_ids, new_latest_event_ids ): \"\"\"Calculate", "txn, events_and_contexts): if not events_and_contexts: # nothing to do here", "rows = self._simple_select_many_txn( txn, table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"),", "state_groups_map[sg] for sg in new_state_groups} events_map = {ev.event_id: ev for", "events_to_purge for e.g. calculating state # groups to purge, etc.,", "set(latest_event_ids) # add all the new events to the list", "\"\"\" SELECT COALESCE(COUNT(*), 0) FROM events WHERE type = 'm.room.message'", "# change in outlier status to our workers. stream_order =", "events. if not ev.internal_metadata.is_outlier(): raise Exception( \"Context for new event", "to get those which are prev_events of existing (non-outlier/rejected) events.", "looking up at once, to stop the # SQL query", "batch_iter(event_ids, 100): yield self.runInteraction( \"_get_prevs_before_rejected\", _get_prevs_before_rejected_txn, chunk ) defer.returnValue(existing_prevs) @defer.inlineCallbacks", "and forth across the # connection. Annoyingly the python sqlite", "in events_and_contexts] ) state_events_and_contexts = [ ec for ec in", "ASC\" \" LIMIT ?\" ) txn.execute(sql, (last_id, current_id, limit)) new_event_updates", "(\" \" event_id TEXT NOT NULL,\" \" should_delete BOOLEAN NOT", "def _calculate_new_extremities(self, room_id, event_contexts, latest_event_ids): \"\"\"Calculates the new forward extremities", "\"redacted_event\")) def _retry_on_integrity_error(func): \"\"\"Wraps a database function so that it", "than one day since the last call to this function,", "a time. # map room_id->list[event_ids] giving the new forward #", "table=\"state_group_edges\", column=\"prev_state_group\", iterable=current_search, keyvalues={}, retcols=(\"prev_state_group\", \"state_group\"), ) prevs = set(row[\"state_group\"]", "the create event. # Normally that'd be in the database,", "soft-failed/rejected or not), and recurses up the prev-event graph until", "be deleted and the set of state groups that need", "and deleting their state groups). \"\"\" return self.runInteraction( \"purge_history\", self._purge_history_txn,", "?\" ) if have_forward_events: txn.execute(sql, (last_forward_id, current_forward_id, limit)) new_forward_events =", "= set(latest_event_ids) if new_latest_event_ids == latest_event_ids: # No change in", "\"\"\" INSERT INTO current_state_delta_stream (stream_id, room_id, type, state_key, event_id, prev_event_id)", "push actions into the event_push_actions table. self._set_push_actions_for_event_and_users_txn( txn, events_and_contexts=events_and_contexts, all_events_and_contexts=all_events_and_contexts,", "only inserted into the events table, the events_json table, and", "events_context: if ev.type == EventTypes.Create and ev.state_key == \"\": room_version", "# so lets just return that. If we happen to", "batch): to_recursively_check = batch while to_recursively_check: sql = \"\"\" SELECT", "= txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_sent_messages\", _count_messages) defer.returnValue(ret)", "\"DELETE FROM %s WHERE room_id = ? AND event_id IN", "stream_id, room_id, type, state_key, event_id FROM current_state_delta_stream WHERE ? <", "True: yield queue.popleft() except IndexError: # Queue has been drained.", "eg.event_id WHERE eb.room_id = ? \"\"\", (room_id,), ) min_depth, =", "= self._update_outliers_txn( txn, events_and_contexts=events_and_contexts ) # From this point onwards", "do this by working out what the new extremities are", "sg in state_groups_to_delete), ) txn.executemany( \"DELETE FROM state_groups WHERE id", "events_map, state_res_store=StateResolutionStore(self), ) defer.returnValue((res.state, None)) @defer.inlineCallbacks def _calculate_state_delta(self, room_id, current_state):", "logger.info(\"[purge] looking for events to delete\") should_delete_expr = \"state_key IS", "return out class _EventPeristenceQueue(object): \"\"\"Queues up events so that they", "if not events_and_contexts: # nothing to do here return logger.info(\"Deleting", "state is only returned if we've already calculated it. \"\"\"", "for events that change forward extremities # (e.g. we ignore", "context in events_and_contexts: if context.rejected: # Insert the event_id into", "so we need to look at the events that #", "not. Used to determine if they're \"new\" events which might", "= current_state yield self.runInteraction( \"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room,", "get_all_new_forward_event_rows(txn): sql = ( \"SELECT e.stream_ordering, e.event_id, e.room_id, e.type,\" \"", "state groups to handle next. next_to_search = set(state_groups) while next_to_search:", "e_id in event.prev_event_ids() ) result.difference_update(existing_prevs) # We only update metrics", "recalculating state when there is only a # single forward", "event): # invalidate the cache for the redacted event txn.call_after(self._invalidate_get_event_cache,", "# results, in which case there will be no existing", "event) elif event.type == EventTypes.Topic: # Insert into the topics", ") sql = \"UPDATE events SET outlier = ?\" \"", "of new events we're adding. for ev, ctx in events_context:", "redundant state groups\") # Get all state groups that are", "eb.room_id = ? \"\"\", (room_id,), ) min_depth, = txn.fetchone() logger.info(\"[purge]", "by soft failed events. Args: event_ids (Iterable[str]): Events to find", "# noqa: F401 from synapse.metrics import BucketCollector from synapse.metrics.background_process_metrics import", "forward extremeties\" ) logger.info(\"[purge] looking for events to delete\") should_delete_expr", "block that for the rest of our transaction. # #", "i + N]} if not ev_map: break sql = (", "from synapse.events import EventBase # noqa: F401 from synapse.events.snapshot import", "json.loads(metadata).get(\"soft_failed\") if soft_failed or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for chunk in", "e.stream_ordering, e.event_id, e.room_id, e.type,\" \" state_key, redacts\" \" FROM events", "len(events_and_contexts), 100) ] for chunk in chunks: # We can't", "`continue` above and skip this bit.) assert new_latest_event_ids, \"No forward", "out the new \"current state\" for each room. # We", "arrived at the server either as new events or as", "express or implied. # See the License for the specific", "return self.runInteraction(\"get_all_new_events\", get_all_new_events_txn) def purge_history(self, room_id, token, delete_local_events): \"\"\"Deletes room", "\"DELETE FROM state_groups_state WHERE state_group = ?\", ((sg,) for sg", "is currently handling the queue then it will not be", "of existing (non-outlier/rejected) events. Args: event_ids (Iterable[str]): event ids to", "create an index on should_delete because later we'll be looking", "SELECT DISTINCT state_group FROM events_to_purge INNER JOIN event_to_state_groups USING (event_id)", "min_depth, = txn.fetchone() logger.info(\"[purge] updating room_depth to %d\", min_depth) txn.execute(", ") self._event_persist_queue.handle_queue(room_id, persisting_queue) @_retry_on_integrity_error @defer.inlineCallbacks def _persist_events( self, events_and_contexts, backfilled=False,", "old forward extremities for the room. new_latest_event_ids (iterable[str]): the new", "ev, ctx in events_context: if ctx.state_group is None: # This", "_ in events_and_contexts] ) state_events_and_contexts = [ ec for ec", "if context.rejected: # Insert the event_id into the rejections table", "row[\"rejects\"] and not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) ) def prefill():", "\"persist_events.get_new_state_after_events\" ): res = yield self._get_new_state_after_events( room_id, ev_ctx_rm, latest_event_ids, new_latest_event_ids,", "need to be de-delta'ed (due to one of its prev", "SELECT DISTINCT state_group FROM event_to_state_groups LEFT JOIN events_to_purge AS ep", "extremities in each room new_forward_extremeties = {} # map room_id->(type,state_key)->event_id", "ec[0] not in to_remove] @classmethod def _delete_existing_rows_txn(cls, txn, events_and_contexts): if", "for. (We know none of the old # extremities are", "isinstance(event.content[\"url\"], text_type) ), } for event, _ in events_and_contexts ],", "\" LEFT JOIN state_events USING (event_id)\" \" WHERE ? <", "First we add entries to the current_state_delta_stream. We # do", "new groups are the same then we don't need to", "in to_insert ), ) txn.executemany( sql, ( ( stream_id, room_id,", "interested in pulling out state that has already # been", "token, delete_local_events, ) def _purge_history_txn(self, txn, room_id, token_str, delete_local_events): token", "# map room_id->(type,state_key)->event_id tracking the full # state in each", "event_id}, allow_none=True, ) if not res: raise SynapseError(404, \"Could not", "check to see if we could # have guessed what", "the previous set of extremities as well as the new.", "any events (due to not # having any backwards extremeties)", "get_domain_from_id from synapse.util import batch_iter from synapse.util.async_helpers import ObservableDeferred from", ") # _update_outliers_txn filters out any events which have already", "event_stream_ordering >= ?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql,", "extremities for each new event\", buckets=(1, 2, 3, 5, 7,", "be at least one forward extremity. # (except during the", "= context.app_service.id elif self.hs.is_mine_id(event.sender): origin_type = \"local\" origin_entity = \"*client*\"", "prefill # the cache with it. if current_state is not", "# We don't bother re-handling groups we've already seen prevs", "import defer import synapse.metrics from synapse.api.constants import EventTypes from synapse.api.errors", "= self._backfill_id_gen.get_next_mult( len(events_and_contexts) ) else: stream_ordering_manager = self._stream_id_gen.get_next_mult( len(events_and_contexts) )", "events which have already been # persisted, and returns the", "from %s\", table) txn.execute( \"DELETE FROM %s WHERE room_id =", "== current_id: return defer.succeed([]) def get_all_new_backfill_event_rows(txn): sql = ( \"SELECT", "txn.execute( \"\"\" SELECT COALESCE(MIN(depth), 0) FROM event_backward_extremities AS eb INNER", "as JSON and return it in a Unicode string. \"\"\"", "txn.execute( \"SELECT DISTINCT e.event_id FROM events_to_purge AS e\" \" INNER", "in event.prev_event_ids() ) # Remove any events which are prev_events", "\"\"\" results = [] def _get_events_which_are_prevs_txn(txn, batch): sql = \"\"\"", "ec in events_and_contexts if ec[0] not in to_remove] @classmethod def", "in state_events_and_contexts: vals = { \"event_id\": event.event_id, \"room_id\": event.room_id, \"type\":", "new_state_groups: defer.returnValue((None, None)) if len(new_state_groups) == 1 and len(old_state_groups) ==", "in new_backwards_extrems], ) logger.info(\"[purge] finding redundant state groups\") # Get", "the new events that have arrived at the server either", "events from %s\", table) txn.execute( \"DELETE FROM %s WHERE room_id", "txn, state_groups): \"\"\"Used when purging history to figure out which", "as event_id, \" \" r.redacts as redacts,\" \" rej.event_id as", "it will not be invoked. \"\"\" if room_id in self._currently_persisting_rooms:", "WHERE e.event_id IN (%s)\" ) % (\",\".join([\"?\"] * len(ev_map)),) txn.execute(sql,", "So, let's stick it at the end so that we", "# This allows us to later efficiently look up the", "NOT NULL FROM event_edges INNER JOIN events USING (event_id) LEFT", "\"DELETE FROM %s WHERE event_id = ?\" % (table,), [(ev.event_id,)", "values=[ { \"stream_ordering\": event.internal_metadata.stream_ordering, \"topological_ordering\": event.depth, \"depth\": event.depth, \"event_id\": event.event_id,", "# was an outlier or not. continue outlier_persisted = have_persisted[event.event_id]", "ev.event_id) for ev, _ in events_and_contexts], ) def _store_event_txn(self, txn,", "\" \" e.event_id as event_id, \" \" r.redacts as redacts,\"", "# We only update metrics for events that change forward", "room_version = yield self.get_room_version(room_id) logger.debug(\"calling resolve_state_groups from preserve_events\") res =", "# pull the state group from its context. # Otherwise", "(unless the new event was rejected). Args: txn (twisted.enterprise.adbapi.Connection): db", "have the same event twice. Pick the earliest non-outlier if", "the supplied list of event_ids to get those which are", "\"persist_events\", self._persist_events_txn, events_and_contexts=chunk, backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if", "all the miscellaneous tables for new events Args: txn (twisted.enterprise.adbapi.Connection):", "continue to_remove.add(event) if context.rejected: # If the event is rejected", "# event_search # event_to_state_groups # events # rejections # room_depth", "let's do this first. # # furthermore, we might already", "internal_metadata, rejections.event_id IS NOT NULL FROM event_edges INNER JOIN events", "rejected, and returns the filtered list. events_and_contexts = self._store_rejected_events_txn( txn,", "batch while to_recursively_check: sql = \"\"\" SELECT event_id, prev_event_id, internal_metadata,", "?\" \" ORDER BY stream_ordering ASC\" \" LIMIT ?\" )", "event_id == ev.event_id and ctx.state_group is not None: event_id_to_state_group[event_id] =", "yield make_deferred_yieldable(deferred) max_persisted_id = yield self._stream_id_gen.get_current_token() defer.returnValue((event.internal_metadata.stream_ordering, max_persisted_id)) def _maybe_start_persisting(self,", "ep2.event_id\" \" WHERE ep2.event_id IS NULL\" ) new_backwards_extrems = txn.fetchall()", ") txn.execute(sql, (-last_backfill_id, -upper_bound)) backward_ex_outliers = txn.fetchall() else: new_backfill_events =", "stream_ordering <= ?\" \" ORDER BY stream_ordering ASC\" \" LIMIT", "\"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged forward extremities for each new event\",", "get the room version, which is in the create event.", "WHERE event_id = ?\" txn.execute(sql, (False, event.event_id)) # Update the", "the events so that we don't # have to keep", "FROM events WHERE type = 'm.room.message' AND stream_ordering > ?", "a deferred which will resolve once the events are persisted.", "then lets prefill # the cache with it. if current_state", "number of room events into the necessary database tables. Rejected", "\"synapse_storage_events_state_delta_reuse_delta\", \"\" ) # The number of forward extremities for", "deferreds = [] for room_id, evs_ctxs in iteritems(partitioned): d =", "# Now remove all events which are prev_events of any", "persist it. room_version = None for ev, _ in events_context:", "to set the event_persisted_position to that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for", "import StateResolutionStore from synapse.storage.background_updates import BackgroundUpdateStore from synapse.storage.event_federation import EventFederationStore", "calculated it. \"\"\" # map from state_group to ((type, key)", "iteritems(to_insert) ), ) # Now we actually update the current_state_events", "filters out any events which have already been # persisted,", "not row[\"redacts\"]: to_prefill.append( _EventCacheEntry(event=event, redacted_event=None) ) def prefill(): for cache_entry", "we are only persisting events for one room at a", "Measure( self._clock, \"persist_events.get_new_state_after_events\" ): res = yield self._get_new_state_after_events( room_id, ev_ctx_rm,", "events before delete_local_events (bool): if True, we will delete local", "if not already being handled. The given callback will be", "\" \" r.redacts as redacts,\" \" rej.event_id as rejects \"", "not in to_insert ), ) txn.executemany( sql, ( ( stream_id,", "well as the new. stale_forward_extremities_counter = Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of", "iteritems(new_forward_extremeties): self.get_latest_event_ids_in_room.prefill( (room_id,), list(latest_event_ids) ) @defer.inlineCallbacks def _calculate_new_extremities(self, room_id, event_contexts,", "from synapse.storage.state import StateGroupWorkerStore from synapse.types import RoomStreamToken, get_domain_from_id from", "a tuple of two state maps, the first being the", "room_id, \"event_id\": event_id, \"stream_ordering\": max_stream_order, } for room_id, new_extrem in", "raise metadata_json = encode_json(event.internal_metadata.get_dict()) sql = ( \"UPDATE event_json SET", "last_forward_id, current_backfill_id, current_forward_id, limit, ): \"\"\"Get all the new events", "in here) class EventsStore( StateGroupWorkerStore, EventFederationStore, EventsWorkerStore, BackgroundUpdateStore, ): def", "so that we don't # have to keep shovelling the", "that. events_by_room = {} for event, context in chunk: events_by_room.setdefault(event.room_id,", "now just to store them (and # it doesn't take", "None)) # Ok, we need to defer to the state", "prev_sg = graph.get(sg) if prev_sg and prev_sg in to_delete: to_dedelta.add(sg)", "a room. Assumes that we are only persisting events for", "of number of extremities to count self._current_forward_extremities_amount = c_counter() BucketCollector(", "the state_groups table with that state. # insert into event_to_state_groups.", "this by working out what the new extremities are and", "that. synapse.metrics.event_persisted_position.set( chunk[-1][0].internal_metadata.stream_ordering ) for event, context in chunk: if", "room %s\", room_id) with Measure( self._clock, \"persist_events.get_new_state_after_events\" ): res =", "state sets. state_groups = {sg: state_groups_map[sg] for sg in new_state_groups}", "have a delta for that transition. If we do then", "LIKE ?\" # We include the parameter twice since we", "by events referenced_groups = set() # Set of state groups", "AND NOT events.outlier \"\"\" % ( \",\".join(\"?\" for _ in", "import range from canonicaljson import json from prometheus_client import Counter,", "in new_extrem ], ) # We now insert into stream_ordering_to_exterm", "deferreds as well. This function should therefore be called whenever", "then it will not be invoked. \"\"\" if room_id in", "current_state, delta_ids = res # If either are not None", "Foundation C.I.C. # # Licensed under the Apache License, Version", "change forward extremities # (e.g. we ignore backfill/outliers/etc) if result", "? AND topological_ordering < ?\" % (should_delete_expr, should_delete_expr), should_delete_params, )", "LEFT JOIN rejections USING (event_id) LEFT JOIN event_json USING (event_id)", "event_id NOT LIKE ?\" # We include the parameter twice", "# the should_delete / shouldn't_delete subsets txn.execute( \"CREATE INDEX events_to_purge_should_delete\"", "\"state_key IS NULL\" should_delete_params = () if not delete_local_events: should_delete_expr", "a tuple (to_delete, to_insert), being a list of type/state keys", "this work with backfilling? if hasattr(event, \"replaces_state\"): vals[\"prev_state\"] = event.replaces_state", "these events. # What we're interested in is if the", "None: # This should only happen for outlier events. if", "\"INSERT INTO event_backward_extremities (room_id, event_id)\" \" VALUES (?, ?)\", [(room_id,", "Invalidate the various caches # Figure out the changes of", "we don't # have to keep shovelling the list back", "OrderedDict, deque, namedtuple from functools import wraps from six import", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "to the current state. new_forward_extremeties (dict[str, list[str]]): The new forward", "non-state events. if all_single_prev_not_state: continue state_delta_counter.inc() if len(new_latest_event_ids) == 1:", "are to be # deleted. We then go and check", "that should be pruned: # event_auth # event_backward_extremities # event_edges", "events from event_to_state_groups\") txn.execute( \"DELETE FROM event_to_state_groups \" \"WHERE event_id", "seen state_groups_seen = set(state_groups) # Set of state groups to", "in event_rows: txn.call_after(self._get_state_group_for_event.invalidate, (event_id,)) # Delete all remote non-state events", "happen to already have # the current state in memory", "should_delete_params, ) # We create the indices *after* insertion as", "not ctx.rejected and not event.internal_metadata.is_soft_failed() ] latest_event_ids = set(latest_event_ids) #", "the # `get_rooms_for_user` cache. # We find out which membership", "\"\"\" Encode a Python object as JSON and return it", "database function so that it gets retried on IntegrityError, with", "event_reference_hashes table. self._store_event_reference_hashes_txn( txn, [event for event, _ in events_and_contexts]", "event_edges tables. self._handle_mult_prev_events( txn, events=[event for event, _ in events_and_contexts]", "forward extremities # (e.g. we ignore backfill/outliers/etc) if result !=", "txn.fetchone() return count ret = yield self.runInteraction(\"count_messages\", _count_messages) defer.returnValue(ret) @defer.inlineCallbacks", "self._simple_select_one( table=\"events\", retcols=[\"topological_ordering\", \"stream_ordering\"], keyvalues={\"event_id\": event_id}, allow_none=True, ) if not", "existing forward extremities result = set(latest_event_ids) # add all the", "break else: # If we couldn't find it, then we'll", "current_state] to_insert = { key: ev_id for key, ev_id in", "the stream ordering of the latest persisted event \"\"\" partitioned", "BY stream_ordering ASC\" \" LIMIT ?\" ) txn.execute(sql, (-last_id, -current_id,", "events we may have deleted # and which we have", "%i remaining state groups\", len(remaining_state_groups), ) # Now we turn", "process to make sure that the database transactions # have", "\" FROM events AS e\" \" INNER JOIN ex_outlier_stream USING", "# otherwise we wouldn't be able to send any events", "\"\"\" ) return txn.fetchall() res = yield self.runInteraction(\"read_forward_extremities\", fetch) self._current_forward_extremities_amount", "to_delete: to_dedelta.add(sg) return to_delete, to_dedelta @defer.inlineCallbacks def is_event_after(self, event_id1, event_id2):", "as they're # used in state res v2. # This", "if ec[0].is_state() ] state_values = [] for event, context in", "new event was rejected). Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts", "being the full new current state and the second being", "reading from those table will need to check whether the", "self.runInteraction(\"count_daily_active_rooms\", _count) defer.returnValue(ret) def get_current_backfill_token(self): \"\"\"The current minimum token that", "purge_history(self, room_id, token, delete_local_events): \"\"\"Deletes room history before a certain", "the first being the full new current state and the", "Version 2.0 (the \"License\"); # you may not use this", "-= state_groups_seen next_to_search |= prevs state_groups_seen |= prevs for row", "# First ensure that we're not about to delete all", "e.room_id, e.type,\" \" state_key, redacts, relates_to_id\" \" FROM events AS", "backfilled=backfilled, delete_existing=delete_existing, state_delta_for_room=state_delta_for_room, new_forward_extremeties=new_forward_extremeties, ) persist_event_counter.inc(len(chunk)) if not backfilled: #", "every 60 minutes def read_forward_extremities(): # run as a background", "read_forward_extremities(): # run as a background process to make sure", "minimum token that backfilled events have reached\"\"\" return -self._backfill_id_gen.get_current_token() def", "all state groups that are referenced by events that are", "sg in remaining_state_groups: logger.info(\"[purge] de-delta-ing remaining state group %s\", sg)", "(%s)\" % (\",\".join([\"?\"] * len(events_and_contexts)),), [event.event_id for event, _ in", "# Set of events we need to fetch groups for.", "sanity check that we're deleting rather than updating if (etype,", "furthermore, we might already have the table from a previous", "FROM events_to_purge AS e\" \" INNER JOIN event_edges AS ed", "(str): room to which the events are being added. Used", "self._delete_existing_rows_txn(txn, events_and_contexts=events_and_contexts) self._store_event_txn(txn, events_and_contexts=events_and_contexts) # Insert into event_to_state_groups. self._store_event_state_mappings_txn(txn, events_and_contexts)", "were backfilled \"\"\" # Insert all the push actions into", "soft_failed = json.loads(metadata).get(\"soft_failed\") if soft_failed or rejected: to_recursively_check.append(prev_event_id) existing_prevs.add(prev_event_id) for", "run_as_background_process(\"persist_events\", handle_queue_loop) def _get_drainining_queue(self, room_id): queue = self._event_persist_queues.setdefault(room_id, deque()) try:", "logger.info(\"[purge] de-delta-ing remaining state group %s\", sg) curr_state = self._get_state_groups_from_groups_txn(txn,", "PreserveLoggingContext(): item.deferred.errback() else: with PreserveLoggingContext(): item.deferred.callback(ret) finally: queue = self._event_persist_queues.pop(room_id,", "table. self._store_room_message_txn(txn, event) elif event.type == EventTypes.Redaction: # Insert into", "in to_prefill: self._get_event_cache.prefill((cache_entry[0].event_id,), cache_entry) txn.call_after(prefill) def _store_redaction(self, txn, event): #", "are recalculating state when there is only a # single", "IS NOT NULL FROM event_edges INNER JOIN events USING (event_id)", "is not None: # We have a delta from the", "def count_daily_sent_messages(self): def _count_messages(txn): # This is good enough as", "events_and_contexts (list[(EventBase, EventContext)]): backfilled (bool): Returns: defer.Deferred: a deferred which", "the events table and the events_json table. to_remove = set()", "only interested in pulling out state that has already #", "our transaction. # # So, let's stick it at the", "LEFT JOIN event_json USING (event_id) WHERE prev_event_id IN (%s) AND", "sql = \"\"\" SELECT event_id, prev_event_id, internal_metadata, rejections.event_id IS NOT", "hs) self._event_persist_queue = _EventPeristenceQueue() self._state_resolution_handler = hs.get_state_resolution_handler() # Collect metrics", "# of type/state keys to remove from current state, and", "state_group_deltas[(ctx.prev_group, ctx.state_group)] = ctx.delta_ids # We need to map the", "txn.execute( \"CREATE TEMPORARY TABLE events_to_purge (\" \" event_id TEXT NOT", "e ON e.event_id = eg.event_id WHERE eb.room_id = ? \"\"\",", "# persisted, and returns the filtered list. events_and_contexts = self._update_outliers_txn(", "Now we turn the state groups that reference to-be-deleted state", "new_event_updates[-1][0] else: upper_bound = current_id sql = ( \"SELECT -event_stream_ordering,", "with new items, unless the queue becomnes empty. The return", "?, ?, ?, ?, ?, ( SELECT event_id FROM current_state_events", "but its also possible that we're # currently trying to", "): \"\"\"Persist events to db Args: events_and_contexts (list[(EventBase, EventContext)]): backfilled", "been persisted. Returns: Deferred[set[str]] \"\"\" # The set of event_ids", "now. When this server creates a new event (as opposed", "in memory then lets also return that, # but it", "def _find_unreferenced_groups_during_purge(self, txn, state_groups): \"\"\"Used when purging history to figure", "for each new event. forward_extremities_counter = Histogram( \"synapse_storage_events_forward_extremities_persisted\", \"Number of", "(iterable[str]): the old forward extremities for the room. new_latest_event_ids (iterable[str]):", "we don't. new_state = state_groups_map.get(new_state_group) defer.returnValue((new_state, delta_ids)) # Now that", "of groups we're looking up at once, to stop the", "have_backfill_events: txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit)) new_backfill_events = txn.fetchall() if len(new_backfill_events)", "from (prev state group, new state group) -> delta state", "ids to filter Returns: Deferred[List[str]]: filtered event ids \"\"\" results", "LEFT JOIN state_events USING (event_id)\" \" WHERE (NOT outlier OR", "``event``, and the stream ordering of the latest persisted event", "Measure( self._clock, \"persist_events.calculate_state_delta\" ): delta = yield self._calculate_state_delta( room_id, current_state", "token that events have reached\"\"\" return self._stream_id_gen.get_current_token() def get_all_new_forward_event_rows(self, last_id,", "txn, room_id, token_str, delete_local_events): token = RoomStreamToken.parse(token_str) # Tables that", "self._store_event_reference_hashes_txn( txn, [event for event, _ in events_and_contexts] ) state_events_and_contexts", "(member,) ) self._invalidate_state_caches_and_stream(txn, room_id, members_changed) def _update_forward_extremities_txn( self, txn, new_forward_extremities,", "do not # end up in a situation where workers", "are being added to the room old_latest_event_ids (iterable[str]): the old", "it to calculate the `prev_event_id`. (This # allows us to", "The per_item_callback will continuously be called with new items, unless", "the current_state then lets prefill # the cache with it.", "events.outlier \"\"\" % ( \",\".join(\"?\" for _ in to_recursively_check), )", "groups. First, let's # check if the event is one", "have calculated new_state_groups we need to get # their state", "redactions (event_id, redacts) VALUES (?,?)\", (event.event_id, event.redacts), ) @defer.inlineCallbacks def", "= next(iter(new_state_groups)) old_state_group = next(iter(old_state_groups)) delta_ids = state_group_deltas.get((old_state_group, new_state_group), None)", "interested in new events which aren't outliers and which aren't", "for _ in batch), ) txn.execute(sql, batch) results.extend(r[0] for r", "map state_groups_map = {} # Map from (prev state group,", "event.type == EventTypes.RoomHistoryVisibility: # Insert into the event_search table. self._store_history_visibility_txn(txn,", "self.stream_ordering_day_ago)) count, = txn.fetchone() return count ret = yield self.runInteraction(\"count_daily_sent_messages\",", "pull # the state from the database missing_event_ids.add(event_id) if missing_event_ids:", "We create the indices *after* insertion as that's a lot", "event.redacts is not None: # Remove the entries in the", "don't block event # persistence. # # We do this", "tuple of two state maps, the first being the full", "== EventTypes.Member ) for member in members_changed: txn.call_after( self.get_rooms_for_user_with_stream_ordering.invalidate, (member,)", "select count(*) c from event_forward_extremities group by room_id \"\"\" )", ") for room_id, depth in iteritems(depth_updates): self._update_min_depth_for_room_txn(txn, room_id, depth) def", "last_forward_id != current_forward_id if not have_backfill_events and not have_forward_events: return", "\"UPDATE events SET outlier = ?\" \" WHERE event_id IN", "Returns: list[(EventBase, EventContext)] new list, without events which are already", "purge existing table rows for the events from the database.", "need to get the room version, which is in the", "# do this before updating the current_state_events table so #", "\"\"\" def _count_messages(txn): sql = \"\"\" SELECT COALESCE(COUNT(*), 0) FROM", "is not None: with Measure( self._clock, \"persist_events.calculate_state_delta\" ): delta =", "event_id FROM events_to_purge WHERE should_delete\" \")\" % (table,) ) #", "Set of events that we have found to be referenced", "cachedInlineCallbacks from synapse.util.frozenutils import frozendict_json_encoder from synapse.util.logcontext import PreserveLoggingContext, make_deferred_yieldable", "persisting \"\"\" if not events_and_contexts: # nothing to do here", "in bulk with only one concurrent transaction per room. \"\"\"", "If there is only one state group, then we know", "# at a time. # map room_id->list[event_ids] giving the new", "event ids which are the forward extremities. \"\"\" all_events_and_contexts =", "= new_events_and_contexts.get(event.event_id) if prev_event_context: if not event.internal_metadata.is_outlier(): if prev_event_context[0].internal_metadata.is_outlier(): #", "break sql = ( \"SELECT \" \" e.event_id as event_id,", "events, as they're # used in state res v2. #", "Each state group can have at most one prev group", "?, ?, ?, ( SELECT event_id FROM current_state_events WHERE room_id", "events. \"\"\" # Remove the rejected events from the list", "referenced_state_groups = set(sg for sg, in txn) logger.info( \"[purge] found", "added. Used for logging etc events_context (list[(EventBase, EventContext)]): events and", "updating room_depth to %d\", min_depth) txn.execute( \"UPDATE room_depth SET min_depth", "# We received a copy of an event that we", "event is rejected then we don't care if the event", "SELECT ?, ?, ?, ?, ?, ( SELECT event_id FROM", "but it doesn't matter if we don't. new_state = state_groups_map.get(new_state_group)", "\"event_id\": ev_id, \"room_id\": room_id, \"type\": key[0], \"state_key\": key[1], } for", "This includes events we've already persisted, etc, that wouldn't appear", "# rejected, and returns the filtered list. events_and_contexts = self._store_rejected_events_txn(", "have to keep shovelling the list back and forth across", "self.get_latest_event_ids_in_room( room_id ) new_latest_event_ids = yield self._calculate_new_extremities( room_id, ev_ctx_rm, latest_event_ids", "AS e\" \" INNER JOIN ex_outlier_stream USING (event_id)\" \" LEFT", "without events which are already in the events table. \"\"\"", "gets around any problems with some tables already having #", "it in a Unicode string. \"\"\" out = frozendict_json_encoder.encode(json_object) if", "new events which aren't outliers and which aren't # being", "state, # so lets just return that. If we happen", "re-handling groups we've already seen prevs -= state_groups_seen next_to_search |=", "new events Args: txn (twisted.enterprise.adbapi.Connection): db connection events_and_contexts (list[(EventBase, EventContext)]):", "has been a change, # and we need to work", "WHERE type = 'm.room.message' AND stream_ordering > ? \"\"\" txn.execute(sql,", "current_state_ids is not None: state_groups_map[ctx.state_group] = current_state_ids if ctx.prev_group: state_group_deltas[(ctx.prev_group,", "events_by_room = {} for event, context in chunk: events_by_room.setdefault(event.room_id, []).append(", "= {} # map room_id->(type,state_key)->event_id tracking the full # state", "hasattr(event, \"replaces_state\"): vals[\"prev_state\"] = event.replaces_state state_values.append(vals) self._simple_insert_many_txn(txn, table=\"state_events\", values=state_values) #", "@defer.inlineCallbacks def persisting_queue(item): with Measure(self._clock, \"persist_events\"): yield self._persist_events( item.events_and_contexts, backfilled=item.backfilled", "with for each item in the queue, of type _EventPersistQueueItem.", "= Histogram( \"synapse_storage_events_stale_forward_extremities_persisted\", \"Number of unchanged forward extremities for each", "\"\"\"Add events to the queue, with the given persist_event options.", "queue = self._get_drainining_queue(room_id) for item in queue: try: ret =", "FROM %s WHERE event_id = ?\" % (table,), [(ev.event_id,) for", "Delete all remote non-state events for table in ( \"events\",", "group graph = {} # Set of events that we", "= new_state_groups - set(state_groups_map) if missing_state: group_to_state = yield self._get_state_for_groups(missing_state)", "the number of messages sent in the last day. If", "from synapse.events.snapshot import EventContext # noqa: F401 from synapse.metrics import", "self._remove_push_actions_for_event_id_txn( txn, event.room_id, event.redacts ) # Remove from relations table.", "?\" \" ORDER BY event_stream_ordering DESC\" ) txn.execute(sql, (last_id, upper_bound))", "group by room_id \"\"\" ) return txn.fetchall() res = yield" ]
[ "2017 Google Inc. All Rights Reserved. # # Licensed under", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser, 'metric_name_scope', defaults,", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "All Rights Reserved. # # Licensed under the Apache License,", "2.0 (the \"License\"); # you may not use this file", "file except in compliance with the License. # You may", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "# limitations under the License. \"\"\"Metrics support manager.\"\"\" import logging", "import logging from buildtool import in_memory_metrics from buildtool import prometheus_metrics", "\"\"\"Returns the BaseMetricsRegistry once startup_metrics is called.\"\"\" if MetricsManager.__metrics_registry is", "help='Where to store metrics.') @staticmethod def startup_metrics(options): \"\"\"Startup metrics module", "by this tool') add_parser_argument( parser, 'monitoring_enabled', defaults, False, type=bool, help='Enable", "distributed under the License is distributed on an \"AS IS\"", "MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod def shutdown_metrics(): \"\"\"Write final metrics out", "defaults, False, type=bool, help='Enable monitoring to stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency',", "metrics.') @staticmethod def startup_metrics(options): \"\"\"Startup metrics module with concrete system.\"\"\"", "Inc. All Rights Reserved. # # Licensed under the Apache", "in_memory_metrics from buildtool import prometheus_metrics from buildtool import stackdriver_metrics from", "once startup_metrics is called.\"\"\" if MetricsManager.__metrics_registry is None: raise Exception('startup_metrics", "'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas = monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with systme=\"%s\"',", "with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry = klas(options) if options.monitoring_enabled and options.monitoring_flush_frequency", "None: raise Exception('startup_metrics was not called.') return MetricsManager.__metrics_registry @staticmethod def", "the specific language governing permissions and # limitations under the", "stackdriver_metrics.StackdriverMetricsRegistry } klas = monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with systme=\"%s\"', klas.__name__)", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas = monitoring_systems[options.monitoring_system]", "shutdown_metrics(): \"\"\"Write final metrics out to metrics server.\"\"\" registry =", "defaults) add_parser_argument( parser, 'metric_name_scope', defaults, 'buildtool', help='scope prefix for metrics", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "support manager.\"\"\" import logging from buildtool import in_memory_metrics from buildtool", "prometheus_metrics from buildtool import stackdriver_metrics from buildtool.util import add_parser_argument class", "except in compliance with the License. # You may obtain", "this tool') add_parser_argument( parser, 'monitoring_enabled', defaults, False, type=bool, help='Enable monitoring", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "parser, 'monitoring_flush_frequency', defaults, 5, help='Frequency at which to push metrics", "5, help='Frequency at which to push metrics in seconds.') add_parser_argument(", "out to metrics server.\"\"\" registry = MetricsManager.singleton() registry.stop_pusher_thread() registry.flush_updated_metrics() registry.flush_final_metrics()", "klas(options) if options.monitoring_enabled and options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry", "= monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry = klas(options)", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "MetricsManager.__metrics_registry @staticmethod def shutdown_metrics(): \"\"\"Write final metrics out to metrics", "metrics module with concrete system.\"\"\" monitoring_systems = { 'file': in_memory_metrics.InMemoryMetricsRegistry,", "not use this file except in compliance with the License.", "return MetricsManager.__metrics_registry @staticmethod def shutdown_metrics(): \"\"\"Write final metrics out to", "under the License. \"\"\"Metrics support manager.\"\"\" import logging from buildtool", "BaseMetricsRegistry singleton.\"\"\" __metrics_registry = None @staticmethod def singleton(): \"\"\"Returns the", "MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser, defaults): \"\"\"Init argparser with metrics-related options.\"\"\"", "logging from buildtool import in_memory_metrics from buildtool import prometheus_metrics from", "and options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod def shutdown_metrics():", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "Google Inc. All Rights Reserved. # # Licensed under the", "to store metrics.') @staticmethod def startup_metrics(options): \"\"\"Startup metrics module with", "which to push metrics in seconds.') add_parser_argument( parser, 'monitoring_system', defaults,", "you may not use this file except in compliance with", "0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod def shutdown_metrics(): \"\"\"Write final metrics", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "init_argument_parser(parser, defaults): \"\"\"Init argparser with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser,", "return MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser, defaults): \"\"\"Init argparser with metrics-related", "MetricsManager.__metrics_registry = klas(options) if options.monitoring_enabled and options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread()", "if MetricsManager.__metrics_registry is None: raise Exception('startup_metrics was not called.') return", "'metric_name_scope', defaults, 'buildtool', help='scope prefix for metrics generated by this", "parser, 'monitoring_enabled', defaults, False, type=bool, help='Enable monitoring to stackdriver.') add_parser_argument(", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "MetricsManager(object): \"\"\"Acts as factory for specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry =", "False, type=bool, help='Enable monitoring to stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency', defaults,", "metrics out to metrics server.\"\"\" registry = MetricsManager.singleton() registry.stop_pusher_thread() registry.flush_updated_metrics()", "parser, 'metric_name_scope', defaults, 'buildtool', help='scope prefix for metrics generated by", "module with concrete system.\"\"\" monitoring_systems = { 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus':", "stackdriver_metrics from buildtool.util import add_parser_argument class MetricsManager(object): \"\"\"Acts as factory", "\"\"\"Startup metrics module with concrete system.\"\"\" monitoring_systems = { 'file':", "CONDITIONS OF ANY KIND, either express or implied. # See", "@staticmethod def singleton(): \"\"\"Returns the BaseMetricsRegistry once startup_metrics is called.\"\"\"", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "the BaseMetricsRegistry once startup_metrics is called.\"\"\" if MetricsManager.__metrics_registry is None:", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "Rights Reserved. # # Licensed under the Apache License, Version", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "singleton.\"\"\" __metrics_registry = None @staticmethod def singleton(): \"\"\"Returns the BaseMetricsRegistry", "import add_parser_argument class MetricsManager(object): \"\"\"Acts as factory for specialized BaseMetricsRegistry", "add_parser_argument class MetricsManager(object): \"\"\"Acts as factory for specialized BaseMetricsRegistry singleton.\"\"\"", "# You may obtain a copy of the License at", "MetricsManager.__metrics_registry is None: raise Exception('startup_metrics was not called.') return MetricsManager.__metrics_registry", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas = monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with", "options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser, 'metric_name_scope',", "under the License is distributed on an \"AS IS\" BASIS,", "the License. \"\"\"Metrics support manager.\"\"\" import logging from buildtool import", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "buildtool import prometheus_metrics from buildtool import stackdriver_metrics from buildtool.util import", "concrete system.\"\"\" monitoring_systems = { 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver':", "def singleton(): \"\"\"Returns the BaseMetricsRegistry once startup_metrics is called.\"\"\" if", "__metrics_registry = None @staticmethod def singleton(): \"\"\"Returns the BaseMetricsRegistry once", "Reserved. # # Licensed under the Apache License, Version 2.0", "\"\"\"Write final metrics out to metrics server.\"\"\" registry = MetricsManager.singleton()", "is called.\"\"\" if MetricsManager.__metrics_registry is None: raise Exception('startup_metrics was not", "buildtool.util import add_parser_argument class MetricsManager(object): \"\"\"Acts as factory for specialized", "defaults, 'file', choices=['file', 'prometheus', 'stackdriver'], help='Where to store metrics.') @staticmethod", "@staticmethod def startup_metrics(options): \"\"\"Startup metrics module with concrete system.\"\"\" monitoring_systems", "prefix for metrics generated by this tool') add_parser_argument( parser, 'monitoring_enabled',", "defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser, 'metric_name_scope', defaults, 'buildtool', help='scope prefix", "buildtool import stackdriver_metrics from buildtool.util import add_parser_argument class MetricsManager(object): \"\"\"Acts", "the License for the specific language governing permissions and #", "with concrete system.\"\"\" monitoring_systems = { 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry,", "defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser, 'metric_name_scope', defaults, 'buildtool',", "governing permissions and # limitations under the License. \"\"\"Metrics support", "(the \"License\"); # you may not use this file except", "from buildtool.util import add_parser_argument class MetricsManager(object): \"\"\"Acts as factory for", "Apache License, Version 2.0 (the \"License\"); # you may not", "def shutdown_metrics(): \"\"\"Write final metrics out to metrics server.\"\"\" registry", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "help='scope prefix for metrics generated by this tool') add_parser_argument( parser,", "for specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry = None @staticmethod def singleton():", "OR CONDITIONS OF ANY KIND, either express or implied. #", "defaults): \"\"\"Init argparser with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults)", "\"\"\"Acts as factory for specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry = None", "parser, 'monitoring_system', defaults, 'file', choices=['file', 'prometheus', 'stackdriver'], help='Where to store", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Exception('startup_metrics was not called.') return MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser, defaults):", "def init_argument_parser(parser, defaults): \"\"\"Init argparser with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults)", "the License is distributed on an \"AS IS\" BASIS, #", "defaults, 5, help='Frequency at which to push metrics in seconds.')", "monitoring_systems = { 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry }", "in compliance with the License. # You may obtain a", "language governing permissions and # limitations under the License. \"\"\"Metrics", "add_parser_argument( parser, 'monitoring_enabled', defaults, False, type=bool, help='Enable monitoring to stackdriver.')", "in seconds.') add_parser_argument( parser, 'monitoring_system', defaults, 'file', choices=['file', 'prometheus', 'stackdriver'],", "'monitoring_flush_frequency', defaults, 5, help='Frequency at which to push metrics in", "was not called.') return MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser, defaults): \"\"\"Init", "'monitoring_enabled', defaults, False, type=bool, help='Enable monitoring to stackdriver.') add_parser_argument( parser,", "software # distributed under the License is distributed on an", "import prometheus_metrics from buildtool import stackdriver_metrics from buildtool.util import add_parser_argument", "from buildtool import stackdriver_metrics from buildtool.util import add_parser_argument class MetricsManager(object):", "raise Exception('startup_metrics was not called.') return MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser,", "add_parser_argument( parser, 'monitoring_system', defaults, 'file', choices=['file', 'prometheus', 'stackdriver'], help='Where to", "= None @staticmethod def singleton(): \"\"\"Returns the BaseMetricsRegistry once startup_metrics", "store metrics.') @staticmethod def startup_metrics(options): \"\"\"Startup metrics module with concrete", "# # Unless required by applicable law or agreed to", "= { 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas", "> 0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod def shutdown_metrics(): \"\"\"Write final", "prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser, 'metric_name_scope', defaults, 'buildtool', help='scope", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "metrics in seconds.') add_parser_argument( parser, 'monitoring_system', defaults, 'file', choices=['file', 'prometheus',", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "\"\"\"Metrics support manager.\"\"\" import logging from buildtool import in_memory_metrics from", "monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry = klas(options) if", "choices=['file', 'prometheus', 'stackdriver'], help='Where to store metrics.') @staticmethod def startup_metrics(options):", "in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas = monitoring_systems[options.monitoring_system] logging.info('Initializing", "Version 2.0 (the \"License\"); # you may not use this", "push metrics in seconds.') add_parser_argument( parser, 'monitoring_system', defaults, 'file', choices=['file',", "Copyright 2017 Google Inc. All Rights Reserved. # # Licensed", "argparser with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults)", "final metrics out to metrics server.\"\"\" registry = MetricsManager.singleton() registry.stop_pusher_thread()", "law or agreed to in writing, software # distributed under", "options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod def shutdown_metrics(): \"\"\"Write", "is None: raise Exception('startup_metrics was not called.') return MetricsManager.__metrics_registry @staticmethod", "klas = monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry =", "manager.\"\"\" import logging from buildtool import in_memory_metrics from buildtool import", "BaseMetricsRegistry once startup_metrics is called.\"\"\" if MetricsManager.__metrics_registry is None: raise", "stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser, 'metric_name_scope', defaults, 'buildtool', help='scope prefix for", "called.\"\"\" if MetricsManager.__metrics_registry is None: raise Exception('startup_metrics was not called.')", "metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument( parser,", "'buildtool', help='scope prefix for metrics generated by this tool') add_parser_argument(", "with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser, defaults) add_parser_argument(", "'stackdriver'], help='Where to store metrics.') @staticmethod def startup_metrics(options): \"\"\"Startup metrics", "implied. # See the License for the specific language governing", "from buildtool import in_memory_metrics from buildtool import prometheus_metrics from buildtool", "'monitoring_system', defaults, 'file', choices=['file', 'prometheus', 'stackdriver'], help='Where to store metrics.')", "None @staticmethod def singleton(): \"\"\"Returns the BaseMetricsRegistry once startup_metrics is", "help='Frequency at which to push metrics in seconds.') add_parser_argument( parser,", "system.\"\"\" monitoring_systems = { 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry", "under the Apache License, Version 2.0 (the \"License\"); # you", "specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry = None @staticmethod def singleton(): \"\"\"Returns", "\"License\"); # you may not use this file except in", "systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry = klas(options) if options.monitoring_enabled and options.monitoring_flush_frequency >", "not called.') return MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser, defaults): \"\"\"Init argparser", "tool') add_parser_argument( parser, 'monitoring_enabled', defaults, False, type=bool, help='Enable monitoring to", "and # limitations under the License. \"\"\"Metrics support manager.\"\"\" import", "License. \"\"\"Metrics support manager.\"\"\" import logging from buildtool import in_memory_metrics", "singleton(): \"\"\"Returns the BaseMetricsRegistry once startup_metrics is called.\"\"\" if MetricsManager.__metrics_registry", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "for metrics generated by this tool') add_parser_argument( parser, 'monitoring_enabled', defaults,", "type=bool, help='Enable monitoring to stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 5,", "help='Enable monitoring to stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 5, help='Frequency", "factory for specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry = None @staticmethod def", "'prometheus', 'stackdriver'], help='Where to store metrics.') @staticmethod def startup_metrics(options): \"\"\"Startup", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "buildtool import in_memory_metrics from buildtool import prometheus_metrics from buildtool import", "klas.__name__) MetricsManager.__metrics_registry = klas(options) if options.monitoring_enabled and options.monitoring_flush_frequency > 0:", "called.') return MetricsManager.__metrics_registry @staticmethod def init_argument_parser(parser, defaults): \"\"\"Init argparser with", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "startup_metrics(options): \"\"\"Startup metrics module with concrete system.\"\"\" monitoring_systems = {", "{ 'file': in_memory_metrics.InMemoryMetricsRegistry, 'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas =", "'prometheus': prometheus_metrics.PrometheusMetricsRegistry, 'stackdriver': stackdriver_metrics.StackdriverMetricsRegistry } klas = monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring", "# Copyright 2017 Google Inc. All Rights Reserved. # #", "'file', choices=['file', 'prometheus', 'stackdriver'], help='Where to store metrics.') @staticmethod def", "to push metrics in seconds.') add_parser_argument( parser, 'monitoring_system', defaults, 'file',", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "logging.info('Initializing monitoring with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry = klas(options) if options.monitoring_enabled", "to in writing, software # distributed under the License is", "@staticmethod def init_argument_parser(parser, defaults): \"\"\"Init argparser with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 5, help='Frequency at which to push", "limitations under the License. \"\"\"Metrics support manager.\"\"\" import logging from", "if options.monitoring_enabled and options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod", "\"\"\"Init argparser with metrics-related options.\"\"\" in_memory_metrics.init_argument_parser(parser, defaults) prometheus_metrics.init_argument_parser(parser, defaults) stackdriver_metrics.init_argument_parser(parser,", "You may obtain a copy of the License at #", "at which to push metrics in seconds.') add_parser_argument( parser, 'monitoring_system',", "} klas = monitoring_systems[options.monitoring_system] logging.info('Initializing monitoring with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "startup_metrics is called.\"\"\" if MetricsManager.__metrics_registry is None: raise Exception('startup_metrics was", "to stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 5, help='Frequency at which", "@staticmethod def shutdown_metrics(): \"\"\"Write final metrics out to metrics server.\"\"\"", "required by applicable law or agreed to in writing, software", "seconds.') add_parser_argument( parser, 'monitoring_system', defaults, 'file', choices=['file', 'prometheus', 'stackdriver'], help='Where", "= klas(options) if options.monitoring_enabled and options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread() return", "monitoring with systme=\"%s\"', klas.__name__) MetricsManager.__metrics_registry = klas(options) if options.monitoring_enabled and", "import in_memory_metrics from buildtool import prometheus_metrics from buildtool import stackdriver_metrics", "from buildtool import prometheus_metrics from buildtool import stackdriver_metrics from buildtool.util", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "as factory for specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry = None @staticmethod", "class MetricsManager(object): \"\"\"Acts as factory for specialized BaseMetricsRegistry singleton.\"\"\" __metrics_registry", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "permissions and # limitations under the License. \"\"\"Metrics support manager.\"\"\"", "the Apache License, Version 2.0 (the \"License\"); # you may", "import stackdriver_metrics from buildtool.util import add_parser_argument class MetricsManager(object): \"\"\"Acts as", "monitoring to stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 5, help='Frequency at", "metrics generated by this tool') add_parser_argument( parser, 'monitoring_enabled', defaults, False,", "defaults, 'buildtool', help='scope prefix for metrics generated by this tool')", "add_parser_argument( parser, 'metric_name_scope', defaults, 'buildtool', help='scope prefix for metrics generated", "generated by this tool') add_parser_argument( parser, 'monitoring_enabled', defaults, False, type=bool,", "<reponame>premm1983/Spinnaker<gh_stars>0 # Copyright 2017 Google Inc. All Rights Reserved. #", "def startup_metrics(options): \"\"\"Startup metrics module with concrete system.\"\"\" monitoring_systems =", "options.monitoring_enabled and options.monitoring_flush_frequency > 0: MetricsManager.__metrics_registry.start_pusher_thread() return MetricsManager.__metrics_registry @staticmethod def", "stackdriver.') add_parser_argument( parser, 'monitoring_flush_frequency', defaults, 5, help='Frequency at which to" ]
[ "archive) and packages it with the target's resource files. The", "[] # Glossary of used aapt flags. Aapt handles a", "AaptTask from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from", "compiled code and assets. This class gathers compiled classes (an", "resource files. The output is an unsigned .apk, an Android", "while collecting resources. # : '-I' packages to add to", "import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnit", "in invalid_targets: # 'input_dirs' is the folder containing the Android", "are treated as input directories to gather files from. args.extend([self.aapt_tool(target.build_tools_version)])", "# 'gen_out' holds resource folders (e.g. 'res') gen_out = []", ": '--ignored-assets' patterns for the aapt to skip. This is", "with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app) with self.invalidated(targets) as invalidation_check:", "operation (see class docstring for more info). # : '-M'", "to add to base \"include\" set, here the android.jar of", "resource folders (e.g. 'res') gen_out = [] mapping = self.context.products.get('dex')", "args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name + '-unsigned.apk')])", "\"\"\"Build an android bundle with compiled code and assets. This", "import subprocess from twitter.common import log from pants.backend.android.targets.android_binary import AndroidBinary", "resource_dir, inputs): args = [] # Glossary of used aapt", "# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed", "2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the", "in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target in invalid_targets: # 'input_dirs' is", "'-S' points to the resource_dir to \"spider\" down while collecting", "to skip. This is the default w/ 'BUILD*' added. #", "subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result = process.wait() if result != 0:", "execute(self): safe_mkdir(self.workdir) # TODO(mateor) map stderr and stdout to workunit", "the .apk file to output # : additional positional arguments", ": '-F' The name and location of the .apk file", "os import subprocess from twitter.common import log from pants.backend.android.targets.android_binary import", "print_function, unicode_literals) import os import subprocess from twitter.common import log", "as input directories to gather files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M',", "pants.backend.android.targets.android_binary import AndroidBinary from pants.backend.android.targets.android_resources import AndroidResources from pants.backend.android.tasks.aapt_task import", "'res') gen_out = [] mapping = self.context.products.get('dex') for basedir in", "under the Apache License, Version 2.0 (see LICENSE). from __future__", "down while collecting resources. # : '-I' packages to add", "for basedir in mapping.get(target): input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather the 'resource_dir'", "to \"spider\" down while collecting resources. # : '-I' packages", "pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import", "containing the Android dex file input_dirs = [] # 'gen_out'", "import safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build an android bundle with compiled", "# : '--ignored-assets' patterns for the aapt to skip. This", "prepare(self, round_manager): round_manager.require_data('dex') def render_args(self, target, resource_dir, inputs): args =", "'-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args)) return args def execute(self): safe_mkdir(self.workdir) #", "to base \"include\" set, here the android.jar of the target-sdk.", "'gen_out' holds resource folders (e.g. 'res') gen_out = [] mapping", "for target in invalid_targets: # 'input_dirs' is the folder containing", "'-F' The name and location of the .apk file to", "target.app_name + '-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args)) return args def execute(self):", "CR 859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app) with self.invalidated(targets)", "get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnit from", "log.debug('Executing: {0}'.format(args)) return args def execute(self): safe_mkdir(self.workdir) # TODO(mateor) map", "if result != 0: raise TaskError('Android aapt tool exited non-zero", "location of the .apk file to output # : additional", "input directories to gather files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest])", "project. # : '-S' points to the resource_dir to \"spider\"", "pants.util.dirutil import safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build an android bundle with", "docstring for more info). # : '-M' is the AndroidManifest.xml", "set, here the android.jar of the target-sdk. # : '--ignored-assets'", "non-zero ({code})'.format(code=result)) for target in targets: self.context.products.get('apk').add(target, self.workdir).append(target.app_name + \"-unsigned.apk\")", "product_types(cls): return ['apk'] @staticmethod def is_app(target): return isinstance(target, AndroidBinary) def", "args.extend(['-F', os.path.join(self.workdir, target.app_name + '-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args)) return args", "with the target's resource files. The output is an unsigned", "mapping = self.context.products.get('dex') for basedir in mapping.get(target): input_dirs.append(basedir) def gather_resources(target):", "flags. Aapt handles a ton of action, this will continue", "map stderr and stdout to workunit streams (see CR 859)", "project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License,", "the AndroidManifest.xml of the project. # : '-S' points to", "Licensed under the Apache License, Version 2.0 (see LICENSE). from", "aapt operation (see class docstring for more info). # :", "from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals)", "!= 0: raise TaskError('Android aapt tool exited non-zero ({code})'.format(code=result)) for", "the Apache License, Version 2.0 (see LICENSE). from __future__ import", ": '-M' is the AndroidManifest.xml of the project. # :", "args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name +", "self.invalidated(targets) as invalidation_check: invalid_targets = [] for vt in invalidation_check.invalid_vts:", "import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import os", "skip. This is the default w/ 'BUILD*' added. # :", "to gather files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir)", "target.resource_dir)) target.walk(gather_resources) process = subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result = process.wait()", "files. The output is an unsigned .apk, an Android application", "import WorkUnit from pants.util.dirutil import safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build an", "<gh_stars>10-100 # coding=utf-8 # Copyright 2014 Pants project contributors (see", "\"include\" set, here the android.jar of the target-sdk. # :", "pants.base.exceptions import TaskError from pants.base.workunit import WorkUnit from pants.util.dirutil import", "'BUILD*' added. # : '-F' The name and location of", "Glossary of used aapt flags. Aapt handles a ton of", "(see class docstring for more info). # : '-M' is", "of used aapt flags. Aapt handles a ton of action,", "is an unsigned .apk, an Android application package file. \"\"\"", ": '-I' packages to add to base \"include\" set, here", "self.context.targets(self.is_app) with self.invalidated(targets) as invalidation_check: invalid_targets = [] for vt", "CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see", "from pants.backend.android.tasks.aapt_task import AaptTask from pants.base.build_environment import get_buildroot from pants.base.exceptions", "is the main aapt operation (see class docstring for more", "bundle with compiled code and assets. This class gathers compiled", "to output # : additional positional arguments are treated as", "and location of the .apk file to output # :", "with compiled code and assets. This class gathers compiled classes", "the android.jar of the target-sdk. # : '--ignored-assets' patterns for", "WorkUnit from pants.util.dirutil import safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build an android", "The output is an unsigned .apk, an Android application package", "additional positional arguments are treated as input directories to gather", "__future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import", "files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)])", "TaskError('Android aapt tool exited non-zero ({code})'.format(code=result)) for target in targets:", "= subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result = process.wait() if result !=", "pants.base.workunit import WorkUnit from pants.util.dirutil import safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build", "from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnit from pants.util.dirutil", "output is an unsigned .apk, an Android application package file.", "os.path.join(self.workdir, target.app_name + '-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args)) return args def", "to expand. # : 'package' is the main aapt operation", "0: raise TaskError('Android aapt tool exited non-zero ({code})'.format(code=result)) for target", "packages it with the target's resource files. The output is", "The name and location of the .apk file to output", "the resource_dir to \"spider\" down while collecting resources. # :", "target's resource files. The output is an unsigned .apk, an", "is the AndroidManifest.xml of the project. # : '-S' points", "of the project. # : '-S' points to the resource_dir", "output # : additional positional arguments are treated as input", "result = process.wait() if result != 0: raise TaskError('Android aapt", "targets = self.context.targets(self.is_app) with self.invalidated(targets) as invalidation_check: invalid_targets = []", "[] for vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target in invalid_targets:", "self).__init__(*args, **kwargs) def prepare(self, round_manager): round_manager.require_data('dex') def render_args(self, target, resource_dir,", "= [] # 'gen_out' holds resource folders (e.g. 'res') gen_out", ".apk file to output # : additional positional arguments are", "action, this will continue to expand. # : 'package' is", "def __init__(self, *args, **kwargs): super(AaptBuilder, self).__init__(*args, **kwargs) def prepare(self, round_manager):", "the target's resource files. The output is an unsigned .apk,", "target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name", "the target\"\"\" if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process =", "info). # : '-M' is the AndroidManifest.xml of the project.", "expand. # : 'package' is the main aapt operation (see", "args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name + '-unsigned.apk')]) args.extend(inputs)", "target.walk(gather_resources) process = subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result = process.wait() if", "args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name + '-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args))", "+ '-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args)) return args def execute(self): safe_mkdir(self.workdir)", "gen_out, input_dirs)) result = process.wait() if result != 0: raise", "pants.backend.android.tasks.aapt_task import AaptTask from pants.base.build_environment import get_buildroot from pants.base.exceptions import", "aapt flags. Aapt handles a ton of action, this will", "here the android.jar of the target-sdk. # : '--ignored-assets' patterns", "continue to expand. # : 'package' is the main aapt", "[] mapping = self.context.products.get('dex') for basedir in mapping.get(target): input_dirs.append(basedir) def", "process.wait() if result != 0: raise TaskError('Android aapt tool exited", "input_dirs = [] # 'gen_out' holds resource folders (e.g. 'res')", "holds resource folders (e.g. 'res') gen_out = [] mapping =", "= [] for vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target in", "return args def execute(self): safe_mkdir(self.workdir) # TODO(mateor) map stderr and", "License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators,", "\"\"\" @classmethod def product_types(cls): return ['apk'] @staticmethod def is_app(target): return", "android bundle with compiled code and assets. This class gathers", "class gathers compiled classes (an Android dex archive) and packages", "def is_app(target): return isinstance(target, AndroidBinary) def __init__(self, *args, **kwargs): super(AaptBuilder,", "self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name + '-unsigned.apk')]) args.extend(inputs) log.debug('Executing: {0}'.format(args)) return", "def product_types(cls): return ['apk'] @staticmethod def is_app(target): return isinstance(target, AndroidBinary)", "(an Android dex archive) and packages it with the target's", "in mapping.get(target): input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather the 'resource_dir' of the", "folders (e.g. 'res') gen_out = [] mapping = self.context.products.get('dex') for", "(see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0", "package file. \"\"\" @classmethod def product_types(cls): return ['apk'] @staticmethod def", "import AndroidResources from pants.backend.android.tasks.aapt_task import AaptTask from pants.base.build_environment import get_buildroot", "2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import,", "the aapt to skip. This is the default w/ 'BUILD*'", "for more info). # : '-M' is the AndroidManifest.xml of", "isinstance(target, AndroidBinary) def __init__(self, *args, **kwargs): super(AaptBuilder, self).__init__(*args, **kwargs) def", "log from pants.backend.android.targets.android_binary import AndroidBinary from pants.backend.android.targets.android_resources import AndroidResources from", "[] # 'gen_out' holds resource folders (e.g. 'res') gen_out =", "AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process = subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result", "result != 0: raise TaskError('Android aapt tool exited non-zero ({code})'.format(code=result))", "import AndroidBinary from pants.backend.android.targets.android_resources import AndroidResources from pants.backend.android.tasks.aapt_task import AaptTask", "'-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir,", "**kwargs) def prepare(self, round_manager): round_manager.require_data('dex') def render_args(self, target, resource_dir, inputs):", "gathers compiled classes (an Android dex archive) and packages it", "**kwargs): super(AaptBuilder, self).__init__(*args, **kwargs) def prepare(self, round_manager): round_manager.require_data('dex') def render_args(self,", "This is the default w/ 'BUILD*' added. # : '-F'", "'-I' packages to add to base \"include\" set, here the", "w/ 'BUILD*' added. # : '-F' The name and location", "stdout to workunit streams (see CR 859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]):", "absolute_import, with_statement, print_function, unicode_literals) import os import subprocess from twitter.common", "added. # : '-F' The name and location of the", "AndroidBinary from pants.backend.android.targets.android_resources import AndroidResources from pants.backend.android.tasks.aapt_task import AaptTask from", "compiled classes (an Android dex archive) and packages it with", "render_args(self, target, resource_dir, inputs): args = [] # Glossary of", ": additional positional arguments are treated as input directories to", "round_manager): round_manager.require_data('dex') def render_args(self, target, resource_dir, inputs): args = []", "basedir in mapping.get(target): input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather the 'resource_dir' of", "resources. # : '-I' packages to add to base \"include\"", "used aapt flags. Aapt handles a ton of action, this", "aapt tool exited non-zero ({code})'.format(code=result)) for target in targets: self.context.products.get('apk').add(target,", "invalid_targets: # 'input_dirs' is the folder containing the Android dex", "target\"\"\" if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process = subprocess.Popen(self.render_args(target,", "to the resource_dir to \"spider\" down while collecting resources. #", "from pants.backend.android.targets.android_resources import AndroidResources from pants.backend.android.tasks.aapt_task import AaptTask from pants.base.build_environment", "'input_dirs' is the folder containing the Android dex file input_dirs", "and stdout to workunit streams (see CR 859) with self.context.new_workunit(name='apk-bundle',", "file. \"\"\" @classmethod def product_types(cls): return ['apk'] @staticmethod def is_app(target):", "classes (an Android dex archive) and packages it with the", "the target-sdk. # : '--ignored-assets' patterns for the aapt to", "(nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import os import", "= [] mapping = self.context.products.get('dex') for basedir in mapping.get(target): input_dirs.append(basedir)", "Aapt handles a ton of action, this will continue to", "is_app(target): return isinstance(target, AndroidBinary) def __init__(self, *args, **kwargs): super(AaptBuilder, self).__init__(*args,", "round_manager.require_data('dex') def render_args(self, target, resource_dir, inputs): args = [] #", ": 'package' is the main aapt operation (see class docstring", "self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app) with self.invalidated(targets) as invalidation_check: invalid_targets", "args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets])", "as invalidation_check: invalid_targets = [] for vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets)", "target in invalid_targets: # 'input_dirs' is the folder containing the", "pants.backend.android.targets.android_resources import AndroidResources from pants.backend.android.tasks.aapt_task import AaptTask from pants.base.build_environment import", "subprocess from twitter.common import log from pants.backend.android.targets.android_binary import AndroidBinary from", "*args, **kwargs): super(AaptBuilder, self).__init__(*args, **kwargs) def prepare(self, round_manager): round_manager.require_data('dex') def", "return ['apk'] @staticmethod def is_app(target): return isinstance(target, AndroidBinary) def __init__(self,", "an unsigned .apk, an Android application package file. \"\"\" @classmethod", "the project. # : '-S' points to the resource_dir to", "Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division,", "input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather the 'resource_dir' of the target\"\"\" if", "assets. This class gathers compiled classes (an Android dex archive)", "# : '-I' packages to add to base \"include\" set,", "unsigned .apk, an Android application package file. \"\"\" @classmethod def", "add to base \"include\" set, here the android.jar of the", ": '-S' points to the resource_dir to \"spider\" down while", "\"spider\" down while collecting resources. # : '-I' packages to", "AndroidResources from pants.backend.android.tasks.aapt_task import AaptTask from pants.base.build_environment import get_buildroot from", "twitter.common import log from pants.backend.android.targets.android_binary import AndroidBinary from pants.backend.android.targets.android_resources import", "invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target in invalid_targets: # 'input_dirs' is the", "with_statement, print_function, unicode_literals) import os import subprocess from twitter.common import", "points to the resource_dir to \"spider\" down while collecting resources.", "and assets. This class gathers compiled classes (an Android dex", "treated as input directories to gather files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package',", "= self.context.targets(self.is_app) with self.invalidated(targets) as invalidation_check: invalid_targets = [] for", "directories to gather files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest]) args.extend(['-S'])", "for vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target in invalid_targets: #", "contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version", "# : 'package' is the main aapt operation (see class", "'resource_dir' of the target\"\"\" if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources)", "self.context.products.get('dex') for basedir in mapping.get(target): input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather the", "Android dex file input_dirs = [] # 'gen_out' holds resource", "This class gathers compiled classes (an Android dex archive) and", "unicode_literals) import os import subprocess from twitter.common import log from", "ton of action, this will continue to expand. # :", "safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build an android bundle with compiled code", "['apk'] @staticmethod def is_app(target): return isinstance(target, AndroidBinary) def __init__(self, *args,", "workunit streams (see CR 859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets =", "safe_mkdir(self.workdir) # TODO(mateor) map stderr and stdout to workunit streams", "__init__(self, *args, **kwargs): super(AaptBuilder, self).__init__(*args, **kwargs) def prepare(self, round_manager): round_manager.require_data('dex')", "an android bundle with compiled code and assets. This class", "# : additional positional arguments are treated as input directories", "Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache", "class AaptBuilder(AaptTask): \"\"\"Build an android bundle with compiled code and", "Android application package file. \"\"\" @classmethod def product_types(cls): return ['apk']", "import TaskError from pants.base.workunit import WorkUnit from pants.util.dirutil import safe_mkdir", "# Licensed under the Apache License, Version 2.0 (see LICENSE).", "target-sdk. # : '--ignored-assets' patterns for the aapt to skip.", "input_dirs)) result = process.wait() if result != 0: raise TaskError('Android", "is the default w/ 'BUILD*' added. # : '-F' The", "(see CR 859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app) with", "invalid_targets = [] for vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target", "arguments are treated as input directories to gather files from.", "the 'resource_dir' of the target\"\"\" if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir))", "@classmethod def product_types(cls): return ['apk'] @staticmethod def is_app(target): return isinstance(target,", "# : '-S' points to the resource_dir to \"spider\" down", "from pants.backend.android.targets.android_binary import AndroidBinary from pants.backend.android.targets.android_resources import AndroidResources from pants.backend.android.tasks.aapt_task", "Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under", "tool exited non-zero ({code})'.format(code=result)) for target in targets: self.context.products.get('apk').add(target, self.workdir).append(target.app_name", "the default w/ 'BUILD*' added. # : '-F' The name", "the Android dex file input_dirs = [] # 'gen_out' holds", "file to output # : additional positional arguments are treated", "target, resource_dir, inputs): args = [] # Glossary of used", "coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). #", "folder containing the Android dex file input_dirs = [] #", "'-M' is the AndroidManifest.xml of the project. # : '-S'", "packages to add to base \"include\" set, here the android.jar", "resource_dir to \"spider\" down while collecting resources. # : '-I'", "TODO(mateor) map stderr and stdout to workunit streams (see CR", "if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process = subprocess.Popen(self.render_args(target, gen_out,", "args.extend(inputs) log.debug('Executing: {0}'.format(args)) return args def execute(self): safe_mkdir(self.workdir) # TODO(mateor)", "this will continue to expand. # : 'package' is the", "def execute(self): safe_mkdir(self.workdir) # TODO(mateor) map stderr and stdout to", "gather files from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I',", ".apk, an Android application package file. \"\"\" @classmethod def product_types(cls):", "generators, division, absolute_import, with_statement, print_function, unicode_literals) import os import subprocess", "TaskError from pants.base.workunit import WorkUnit from pants.util.dirutil import safe_mkdir class", "args = [] # Glossary of used aapt flags. Aapt", "def gather_resources(target): \"\"\"Gather the 'resource_dir' of the target\"\"\" if isinstance(target,", "division, absolute_import, with_statement, print_function, unicode_literals) import os import subprocess from", "aapt to skip. This is the default w/ 'BUILD*' added.", "# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).", "from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit", "the main aapt operation (see class docstring for more info).", "from. args.extend([self.aapt_tool(target.build_tools_version)]) args.extend(['package', '-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets',", "@staticmethod def is_app(target): return isinstance(target, AndroidBinary) def __init__(self, *args, **kwargs):", "isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process = subprocess.Popen(self.render_args(target, gen_out, input_dirs))", "an Android application package file. \"\"\" @classmethod def product_types(cls): return", "LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function,", "'--ignored-assets' patterns for the aapt to skip. This is the", "import os import subprocess from twitter.common import log from pants.backend.android.targets.android_binary", "a ton of action, this will continue to expand. #", "inputs): args = [] # Glossary of used aapt flags.", "from pants.base.workunit import WorkUnit from pants.util.dirutil import safe_mkdir class AaptBuilder(AaptTask):", "from twitter.common import log from pants.backend.android.targets.android_binary import AndroidBinary from pants.backend.android.targets.android_resources", "invalidation_check: invalid_targets = [] for vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for", "to workunit streams (see CR 859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets", "it with the target's resource files. The output is an", "AaptBuilder(AaptTask): \"\"\"Build an android bundle with compiled code and assets.", "'package' is the main aapt operation (see class docstring for", "streams (see CR 859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app)", "# 'input_dirs' is the folder containing the Android dex file", "of action, this will continue to expand. # : 'package'", "return isinstance(target, AndroidBinary) def __init__(self, *args, **kwargs): super(AaptBuilder, self).__init__(*args, **kwargs)", "handles a ton of action, this will continue to expand.", "= [] # Glossary of used aapt flags. Aapt handles", "with self.invalidated(targets) as invalidation_check: invalid_targets = [] for vt in", "process = subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result = process.wait() if result", "is the folder containing the Android dex file input_dirs =", "gen_out = [] mapping = self.context.products.get('dex') for basedir in mapping.get(target):", "gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process = subprocess.Popen(self.render_args(target, gen_out, input_dirs)) result =", "raise TaskError('Android aapt tool exited non-zero ({code})'.format(code=result)) for target in", "\"\"\"Gather the 'resource_dir' of the target\"\"\" if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(),", "from pants.util.dirutil import safe_mkdir class AaptBuilder(AaptTask): \"\"\"Build an android bundle", "AndroidBinary) def __init__(self, *args, **kwargs): super(AaptBuilder, self).__init__(*args, **kwargs) def prepare(self,", "code and assets. This class gathers compiled classes (an Android", "AndroidManifest.xml of the project. # : '-S' points to the", "def prepare(self, round_manager): round_manager.require_data('dex') def render_args(self, target, resource_dir, inputs): args", "labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app) with self.invalidated(targets) as invalidation_check: invalid_targets =", "of the target\"\"\" if isinstance(target, AndroidResources): gen_out.append(os.path.join(get_buildroot(), target.resource_dir)) target.walk(gather_resources) process", "(see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,", "# Glossary of used aapt flags. Aapt handles a ton", "the folder containing the Android dex file input_dirs = []", "will continue to expand. # : 'package' is the main", "patterns for the aapt to skip. This is the default", "dex file input_dirs = [] # 'gen_out' holds resource folders", "class docstring for more info). # : '-M' is the", "# TODO(mateor) map stderr and stdout to workunit streams (see", "default w/ 'BUILD*' added. # : '-F' The name and", "main aapt operation (see class docstring for more info). #", "of the target-sdk. # : '--ignored-assets' patterns for the aapt", "super(AaptBuilder, self).__init__(*args, **kwargs) def prepare(self, round_manager): round_manager.require_data('dex') def render_args(self, target,", "for the aapt to skip. This is the default w/", "more info). # : '-M' is the AndroidManifest.xml of the", "file input_dirs = [] # 'gen_out' holds resource folders (e.g.", "859) with self.context.new_workunit(name='apk-bundle', labels=[WorkUnit.MULTITOOL]): targets = self.context.targets(self.is_app) with self.invalidated(targets) as", "exited non-zero ({code})'.format(code=result)) for target in targets: self.context.products.get('apk').add(target, self.workdir).append(target.app_name +", "dex archive) and packages it with the target's resource files.", "import AaptTask from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError", "# : '-F' The name and location of the .apk", "positional arguments are treated as input directories to gather files", "gather_resources(target): \"\"\"Gather the 'resource_dir' of the target\"\"\" if isinstance(target, AndroidResources):", "stderr and stdout to workunit streams (see CR 859) with", "def render_args(self, target, resource_dir, inputs): args = [] # Glossary", "of the .apk file to output # : additional positional", "Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes,", "self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F', os.path.join(self.workdir, target.app_name + '-unsigned.apk')]) args.extend(inputs) log.debug('Executing:", "vt in invalidation_check.invalid_vts: invalid_targets.extend(vt.targets) for target in invalid_targets: # 'input_dirs'", "(e.g. 'res') gen_out = [] mapping = self.context.products.get('dex') for basedir", "base \"include\" set, here the android.jar of the target-sdk. #", "Android dex archive) and packages it with the target's resource", "invalid_targets.extend(vt.targets) for target in invalid_targets: # 'input_dirs' is the folder", "# : '-M' is the AndroidManifest.xml of the project. #", "= process.wait() if result != 0: raise TaskError('Android aapt tool", "collecting resources. # : '-I' packages to add to base", "application package file. \"\"\" @classmethod def product_types(cls): return ['apk'] @staticmethod", "mapping.get(target): input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather the 'resource_dir' of the target\"\"\"", "import log from pants.backend.android.targets.android_binary import AndroidBinary from pants.backend.android.targets.android_resources import AndroidResources", "android.jar of the target-sdk. # : '--ignored-assets' patterns for the", "{0}'.format(args)) return args def execute(self): safe_mkdir(self.workdir) # TODO(mateor) map stderr", "and packages it with the target's resource files. The output", "args.extend(['package', '-M', target.manifest]) args.extend(['-S']) args.extend(resource_dir) args.extend(['-I', self.android_jar_tool(target.target_sdk)]) args.extend(['--ignore-assets', self.ignored_assets]) args.extend(['-F',", "args def execute(self): safe_mkdir(self.workdir) # TODO(mateor) map stderr and stdout", "= self.context.products.get('dex') for basedir in mapping.get(target): input_dirs.append(basedir) def gather_resources(target): \"\"\"Gather", "name and location of the .apk file to output #" ]
[ "seed = np.zeros((self.data.adj_mat.shape[0], 1)) if not seed_weighting: seed[entity_ids] = 1.", "with highest score) # Sort by scores unique_facts = {}", "printed. ' 'A number of warnings are expected for a", "in unique_facts and score > unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel, score)", "fwd_dir in unique_facts and score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel,", "2.0 (the \"License\"); # you may not use this file", "[ int(self.data.ent2id[x]) for x in entities if x in self.data.ent2id", "Sort by scores unique_facts = {} for (sub, obj, rel,", "existing entity pair else: unique_facts[(sub, obj)] = (rel, score) unique_facts", "') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for x in extracted_ents ])) facts", "int(self.data.ent2id[x]) for x in entities if x in self.data.ent2id ]", "number of warnings are expected for a normal NQ evaluation.')", "Args: entities: A list of Wikidata entities topk: Max entities", "< 1e-6, limit extracted ents till there zero_idx = np.where(ppr_scores[extracted_ents]", "from PPR alpha: Node probability for PPR seed_weighting: Boolean for", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "entities, topk, alpha, seed_weighting=True): \"\"\"Get subgraph describing a neighbourhood around", "entity_ids ])) freq_dict = {x: entity_ids.count(x) for x in entity_ids}", "tf.logging.info('Extracted ents: ') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for x in extracted_ents", "def get_topk_extracted_ent(self, seeds, alpha, topk): \"\"\"Extract topk entities given seeds.", "extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted facts: ') tf.logging.info(str(facts)) # Extract 1", "to data processing will be printed. ' 'A number of", "processing will be printed. ' 'A number of warnings are", "from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io", "extracted ents till there zero_idx = np.where(ppr_scores[extracted_ents] < 1e-6)[0] if", "list of scores of selected entities \"\"\" ppr_scores = csr_personalized_pagerank(seeds,", "the PPR algorithm. This class has the following functionality: 1.", "a normal NQ evaluation.') class ApproximatePageRank(object): \"\"\"APR main lib which", "list of selected entities extracted_scores: list of scores of selected", "self.get_topk_extracted_ent( seed, alpha, topk) if FLAGS.verbose_logging: tf.logging.info('Extracted ents: ') tf.logging.info(", "1. Load the KB graph, 2. Given list of seed", "use this file except in compliance with the License. #", "fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags = tf.flags", "# Copyright 2020 The Google Research Authors. # # Licensed", "# limitations under the License. \"\"\"This file contains a class", "# Sort by scores unique_facts = {} for (sub, obj,", "entities, get topk entities from PPR. 3. Get unique facts", "topk entities given seeds. Args: seeds: An Ex1 vector with", "CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds, alpha, topk): \"\"\"Extract", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "to extract Returns: extracted_ents: list of selected entities extracted_scores: list", "import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import CsrData", "flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False, 'If true, all of the warnings", "seeds by freq in passage Returns: unique_facts: A list of", "License. # You may obtain a copy of the License", "self.data.ent2id ] if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x in entity_ids", "y seed = seed / seed.sum() extracted_ents, extracted_scores = self.get_topk_extracted_ent(", "around the PPR algorithm. This class has the following functionality:", "/ seed.sum() extracted_ents, extracted_scores = self.get_topk_extracted_ent( seed, alpha, topk) if", "under the License is distributed on an \"AS IS\" BASIS,", "x in self.data.ent2id ] if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x", "alpha: Node probability for PPR seed_weighting: Boolean for performing weighting", "highest score) # Sort by scores unique_facts = {} for", "License for the specific language governing permissions and # limitations", "# Remove existing entity pair else: unique_facts[(sub, obj)] = (rel,", "list of Wikidata entities topk: Max entities to extract from", "tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x in entity_ids ])) freq_dict = {x:", "tf.logging.info('Extracted facts: ') tf.logging.info(str(facts)) # Extract 1 unique fact per", "passage Returns: unique_facts: A list of unique facts around the", "ppr algo.\"\"\" def __init__(self): self.data = CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir)", "CsrData flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False,", "1e-6)[0] if zero_idx.shape[0] > 0: extracted_ents = extracted_ents[:zero_idx[0]] return extracted_ents,", "FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids = [ int(self.data.ent2id[x]) for x in", "will be printed. ' 'A number of warnings are expected", "np.where(ppr_scores[extracted_ents] < 1e-6)[0] if zero_idx.shape[0] > 0: extracted_ents = extracted_ents[:zero_idx[0]]", "from __future__ import division from __future__ import print_function import numpy", "the License. \"\"\"This file contains a class which acts as", "unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel, score) elif rev_dir in unique_facts and", "unique fact per pair of entities (fact with highest score)", "entity_ids} seed = np.zeros((self.data.adj_mat.shape[0], 1)) if not seed_weighting: seed[entity_ids] =", "import division from __future__ import print_function import numpy as np", "weight on every seed entity alpha: probability for PPR topk:", "/ len(set(entity_ids)) else: for x, y in freq_dict.items(): seed[x] =", "from __future__ import absolute_import from __future__ import division from __future__", "seed_weighting: seed[entity_ids] = 1. / len(set(entity_ids)) else: for x, y", "'If true, all of the warnings related to data processing", "in compliance with the License. # You may obtain a", "First value < 1e-6, limit extracted ents till there zero_idx", "in unique_facts and score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel, score)", "software # distributed under the License is distributed on an", "subgraph describing a neighbourhood around given entities. Args: entities: A", "unique_facts and score > unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel, score) del", "topk): \"\"\"Extract topk entities given seeds. Args: seeds: An Ex1", "seeds. Args: seeds: An Ex1 vector with weight on every", "from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags =", "= ppr_scores[sorted_idx[:topk]] # Check for really low values # Get", "< 1e-6)[0] if zero_idx.shape[0] > 0: extracted_ents = extracted_ents[:zero_idx[0]] return", "NQ evaluation.') class ApproximatePageRank(object): \"\"\"APR main lib which is used", "self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents, extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted facts: ')", "Max entities to extract from PPR alpha: Node probability for", "Google Research Authors. # # Licensed under the Apache License,", "pair of entities (fact with highest score) # Sort by", "seed, alpha, topk) if FLAGS.verbose_logging: tf.logging.info('Extracted ents: ') tf.logging.info( str([", "entity pair else: unique_facts[(sub, obj)] = (rel, score) unique_facts =", "seeds. \"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids = [ int(self.data.ent2id[x])", "Get idx of First value < 1e-6, limit extracted ents", "graph, 2. Given list of seed entities, get topk entities", "PPR seed_weighting: Boolean for performing weighting seeds by freq in", "idx of First value < 1e-6, limit extracted ents till", "1 unique fact per pair of entities (fact with highest", "value < 1e-6, limit extracted ents till there zero_idx =", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "= (obj, sub) if fwd_dir in unique_facts and score >", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "Ex1 vector with weight on every seed entity alpha: probability", "is used to wrap functions around ppr algo.\"\"\" def __init__(self):", "for performing weighting seeds by freq in passage Returns: unique_facts:", "from PPR. 3. Get unique facts between all extracted entities.", "= y seed = seed / seed.sum() extracted_ents, extracted_scores =", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "entity alpha: probability for PPR topk: max top entities to", "to in writing, software # distributed under the License is", "in entities if x in self.data.ent2id ] if FLAGS.verbose_logging: tf.logging.info(", "get_topk_extracted_ent(self, seeds, alpha, topk): \"\"\"Extract topk entities given seeds. Args:", "in extracted_ents ])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents,", "# See the License for the specific language governing permissions", "extract Returns: extracted_ents: list of selected entities extracted_scores: list of", "Wikidata entities topk: Max entities to extract from PPR alpha:", "list of unique facts around the seeds. \"\"\" if FLAGS.verbose_logging:", "or agreed to in writing, software # distributed under the", "of warnings are expected for a normal NQ evaluation.') class", "freq_dict = {x: entity_ids.count(x) for x in entity_ids} seed =", "fwd_dir = (sub, obj) rev_dir = (obj, sub) if fwd_dir", "required by applicable law or agreed to in writing, software", "extracted_ents: list of selected entities extracted_scores: list of scores of", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "there zero_idx = np.where(ppr_scores[extracted_ents] < 1e-6)[0] if zero_idx.shape[0] > 0:", "file contains a class which acts as a wrapper around", "class which acts as a wrapper around the PPR algorithm.", "ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents =", "score > unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel, score) del unique_facts[rev_dir] #", "extracted_scores = ppr_scores[sorted_idx[:topk]] # Check for really low values #", "2. Given list of seed entities, get topk entities from", "KB graph, 2. Given list of seed entities, get topk", "np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]] # Check for", "really low values # Get idx of First value <", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "expected for a normal NQ evaluation.') class ApproximatePageRank(object): \"\"\"APR main", "distributed under the License is distributed on an \"AS IS\"", "contains a class which acts as a wrapper around the", "tf.logging.info(str(facts)) # Extract 1 unique fact per pair of entities", "2020 The Google Research Authors. # # Licensed under the", "An Ex1 vector with weight on every seed entity alpha:", "= {} for (sub, obj, rel, score) in facts: fwd_dir", "entity_ids.count(x) for x in entity_ids} seed = np.zeros((self.data.adj_mat.shape[0], 1)) if", "used to wrap functions around ppr algo.\"\"\" def __init__(self): self.data", "normal NQ evaluation.') class ApproximatePageRank(object): \"\"\"APR main lib which is", "express or implied. # See the License for the specific", "ppr_scores[sorted_idx[:topk]] # Check for really low values # Get idx", "except in compliance with the License. # You may obtain", "which is used to wrap functions around ppr algo.\"\"\" def", "obj, rel, score) in facts: fwd_dir = (sub, obj) rev_dir", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "x in extracted_ents ])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names,", "probability for PPR seed_weighting: Boolean for performing weighting seeds by", "# Extract 1 unique fact per pair of entities (fact", "not use this file except in compliance with the License.", "for x in entity_ids} seed = np.zeros((self.data.adj_mat.shape[0], 1)) if not", "facts: fwd_dir = (sub, obj) rev_dir = (obj, sub) if", "PPR algorithm. This class has the following functionality: 1. Load", "writing, software # distributed under the License is distributed on", "seed / seed.sum() extracted_ents, extracted_scores = self.get_topk_extracted_ent( seed, alpha, topk)", "def get_facts(self, entities, topk, alpha, seed_weighting=True): \"\"\"Get subgraph describing a", "you may not use this file except in compliance with", "in entity_ids} seed = np.zeros((self.data.adj_mat.shape[0], 1)) if not seed_weighting: seed[entity_ids]", "seed entity alpha: probability for PPR topk: max top entities", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "wrapper around the PPR algorithm. This class has the following", "of Wikidata entities topk: Max entities to extract from PPR", "rev_dir in unique_facts and score > unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel,", "\"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids = [ int(self.data.ent2id[x]) for", "wrap functions around ppr algo.\"\"\" def __init__(self): self.data = CsrData()", "= csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk]", "for x in entities if x in self.data.ent2id ] if", "values # Get idx of First value < 1e-6, limit", "as np import tensorflow as tf from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank", "top entities to extract Returns: extracted_ents: list of selected entities", "as a wrapper around the PPR algorithm. This class has", "of seed entities, get topk entities from PPR. 3. Get", "extracted_ents, extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted facts: ') tf.logging.info(str(facts)) # Extract", "main lib which is used to wrap functions around ppr", "extracted_scores: list of scores of selected entities \"\"\" ppr_scores =", "CONDITIONS OF ANY KIND, either express or implied. # See", "extracted_ents ])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents, extracted_scores)", "> unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel, score) del unique_facts[rev_dir] # Remove", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "to wrap functions around ppr algo.\"\"\" def __init__(self): self.data =", "Returns: extracted_ents: list of selected entities extracted_scores: list of scores", "extracted_scores def get_facts(self, entities, topk, alpha, seed_weighting=True): \"\"\"Get subgraph describing", "entities (fact with highest score) # Sort by scores unique_facts", "unique_facts[rev_dir] # Remove existing entity pair else: unique_facts[(sub, obj)] =", "weighting seeds by freq in passage Returns: unique_facts: A list", "False, 'If true, all of the warnings related to data", "between all extracted entities. \"\"\" from __future__ import absolute_import from", "entities. \"\"\" from __future__ import absolute_import from __future__ import division", "in freq_dict.items(): seed[x] = y seed = seed / seed.sum()", "seed = seed / seed.sum() extracted_ents, extracted_scores = self.get_topk_extracted_ent( seed,", "ents: ') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for x in extracted_ents ]))", "for x in entity_ids ])) freq_dict = {x: entity_ids.count(x) for", "\"\"\"Extract topk entities given seeds. Args: seeds: An Ex1 vector", "tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False, 'If true, all", "extracted_ents, extracted_scores = self.get_topk_extracted_ent( seed, alpha, topk) if FLAGS.verbose_logging: tf.logging.info('Extracted", "class has the following functionality: 1. Load the KB graph,", "= 1. / len(set(entity_ids)) else: for x, y in freq_dict.items():", "and score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel, score) elif rev_dir", "seed.sum() extracted_ents, extracted_scores = self.get_topk_extracted_ent( seed, alpha, topk) if FLAGS.verbose_logging:", "print_function import numpy as np import tensorflow as tf from", "alpha, seed_weighting=True): \"\"\"Get subgraph describing a neighbourhood around given entities.", "describing a neighbourhood around given entities. Args: entities: A list", "freq in passage Returns: unique_facts: A list of unique facts", "unique facts around the seeds. \"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting subgraph')", "(rel, score) elif rev_dir in unique_facts and score > unique_facts[rev_dir][1]:", "probability for PPR topk: max top entities to extract Returns:", "OR CONDITIONS OF ANY KIND, either express or implied. #", "__future__ import print_function import numpy as np import tensorflow as", "'verbose_logging', False, 'If true, all of the warnings related to", "License. \"\"\"This file contains a class which acts as a", "the License is distributed on an \"AS IS\" BASIS, #", "This class has the following functionality: 1. Load the KB", "till there zero_idx = np.where(ppr_scores[extracted_ents] < 1e-6)[0] if zero_idx.shape[0] >", "as tf from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor", "score) elif rev_dir in unique_facts and score > unique_facts[rev_dir][1]: unique_facts[fwd_dir]", "x in entity_ids} seed = np.zeros((self.data.adj_mat.shape[0], 1)) if not seed_weighting:", "max top entities to extract Returns: extracted_ents: list of selected", "def __init__(self): self.data = CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self,", "seed entities, get topk entities from PPR. 3. Get unique", "algo.\"\"\" def __init__(self): self.data = CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def", "Check for really low values # Get idx of First", "= CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds, alpha, topk):", "get_facts(self, entities, topk, alpha, seed_weighting=True): \"\"\"Get subgraph describing a neighbourhood", "entities. Args: entities: A list of Wikidata entities topk: Max", "Extract 1 unique fact per pair of entities (fact with", "for x in extracted_ents ])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict,", "warnings are expected for a normal NQ evaluation.') class ApproximatePageRank(object):", "csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents, extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted facts:", "> unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel, score) elif rev_dir in unique_facts", "law or agreed to in writing, software # distributed under", "which acts as a wrapper around the PPR algorithm. This", "language governing permissions and # limitations under the License. \"\"\"This", "\"\"\" from __future__ import absolute_import from __future__ import division from", "if zero_idx.shape[0] > 0: extracted_ents = extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores", "by scores unique_facts = {} for (sub, obj, rel, score)", "not seed_weighting: seed[entity_ids] = 1. / len(set(entity_ids)) else: for x,", "np.zeros((self.data.adj_mat.shape[0], 1)) if not seed_weighting: seed[entity_ids] = 1. / len(set(entity_ids))", "to extract from PPR alpha: Node probability for PPR seed_weighting:", "Given list of seed entities, get topk entities from PPR.", "of selected entities \"\"\" ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx", "limit extracted ents till there zero_idx = np.where(ppr_scores[extracted_ents] < 1e-6)[0]", "(rel, score) del unique_facts[rev_dir] # Remove existing entity pair else:", "subgraph') entity_ids = [ int(self.data.ent2id[x]) for x in entities if", "neighbourhood around given entities. Args: entities: A list of Wikidata", "on every seed entity alpha: probability for PPR topk: max", "may obtain a copy of the License at # #", "seed[x] = y seed = seed / seed.sum() extracted_ents, extracted_scores", "alpha: probability for PPR topk: max top entities to extract", "(sub, obj, rel, score) in facts: fwd_dir = (sub, obj)", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "in entity_ids ])) freq_dict = {x: entity_ids.count(x) for x in", "sub) if fwd_dir in unique_facts and score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir]", "unique_facts[fwd_dir] = (rel, score) elif rev_dir in unique_facts and score", "\"\"\"Get subgraph describing a neighbourhood around given entities. Args: entities:", "may not use this file except in compliance with the", "the warnings related to data processing will be printed. '", "around given entities. Args: entities: A list of Wikidata entities", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "tensorflow as tf from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import", "fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import", "y in freq_dict.items(): seed[x] = y seed = seed /", "this file except in compliance with the License. # You", "seeds, alpha, topk): \"\"\"Extract topk entities given seeds. Args: seeds:", "import absolute_import from __future__ import division from __future__ import print_function", "\"\"\"This file contains a class which acts as a wrapper", "if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x in entity_ids ])) freq_dict", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "ApproximatePageRank(object): \"\"\"APR main lib which is used to wrap functions", "entities \"\"\" ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx = np.argsort(ppr_scores)[::-1]", "for really low values # Get idx of First value", "= {x: entity_ids.count(x) for x in entity_ids} seed = np.zeros((self.data.adj_mat.shape[0],", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "unique_facts and score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel, score) elif", "division from __future__ import print_function import numpy as np import", "be printed. ' 'A number of warnings are expected for", "for a normal NQ evaluation.') class ApproximatePageRank(object): \"\"\"APR main lib", "= (sub, obj) rev_dir = (obj, sub) if fwd_dir in", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents, extracted_scores) if", "entities given seeds. Args: seeds: An Ex1 vector with weight", "entities from PPR. 3. Get unique facts between all extracted", "score) del unique_facts[rev_dir] # Remove existing entity pair else: unique_facts[(sub,", "if x in self.data.ent2id ] if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for", "alpha, topk): \"\"\"Extract topk entities given seeds. Args: seeds: An", "' 'A number of warnings are expected for a normal", "PPR topk: max top entities to extract Returns: extracted_ents: list", "extract from PPR alpha: Node probability for PPR seed_weighting: Boolean", "') tf.logging.info(str(facts)) # Extract 1 unique fact per pair of", "= np.where(ppr_scores[extracted_ents] < 1e-6)[0] if zero_idx.shape[0] > 0: extracted_ents =", "import tensorflow as tf from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo", "= extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores def get_facts(self, entities, topk, alpha,", "tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for x in extracted_ents ])) facts =", "functions around ppr algo.\"\"\" def __init__(self): self.data = CsrData() self.data.load_csr_data(", "score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir] = (rel, score) elif rev_dir in", "the KB graph, 2. Given list of seed entities, get", "all extracted entities. \"\"\" from __future__ import absolute_import from __future__", "import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags = tf.flags FLAGS", "per pair of entities (fact with highest score) # Sort", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "unique_facts[(sub, obj)] = (rel, score) unique_facts = list(unique_facts.items()) return unique_facts", "selected entities \"\"\" ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx =", "Boolean for performing weighting seeds by freq in passage Returns:", "= [ int(self.data.ent2id[x]) for x in entities if x in", "= self.get_topk_extracted_ent( seed, alpha, topk) if FLAGS.verbose_logging: tf.logging.info('Extracted ents: ')", "score) in facts: fwd_dir = (sub, obj) rev_dir = (obj,", "every seed entity alpha: probability for PPR topk: max top", "or implied. # See the License for the specific language", "of selected entities extracted_scores: list of scores of selected entities", "seed_weighting=True): \"\"\"Get subgraph describing a neighbourhood around given entities. Args:", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "] if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x in entity_ids ]))", "Load the KB graph, 2. Given list of seed entities,", "self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds, alpha, topk): \"\"\"Extract topk", "1)) if not seed_weighting: seed[entity_ids] = 1. / len(set(entity_ids)) else:", "# coding=utf-8 # Copyright 2020 The Google Research Authors. #", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "true, all of the warnings related to data processing will", "if FLAGS.verbose_logging: tf.logging.info('Extracted facts: ') tf.logging.info(str(facts)) # Extract 1 unique", "around ppr algo.\"\"\" def __init__(self): self.data = CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki,", "if FLAGS.verbose_logging: tf.logging.info('Extracted ents: ') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for x", "(the \"License\"); # you may not use this file except", "related to data processing will be printed. ' 'A number", "algorithm. This class has the following functionality: 1. Load the", "# you may not use this file except in compliance", "score) # Sort by scores unique_facts = {} for (sub,", "extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores def get_facts(self, entities, topk, alpha, seed_weighting=True):", "evaluation.') class ApproximatePageRank(object): \"\"\"APR main lib which is used to", "scores of selected entities \"\"\" ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha)", "seeds: An Ex1 vector with weight on every seed entity", "> 0: extracted_ents = extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores def get_facts(self,", "= flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False, 'If true, all of the", "x in entities if x in self.data.ent2id ] if FLAGS.verbose_logging:", "the following functionality: 1. Load the KB graph, 2. Given", "(obj, sub) if fwd_dir in unique_facts and score > unique_facts[fwd_dir][1]:", "# # Unless required by applicable law or agreed to", "by freq in passage Returns: unique_facts: A list of unique", "A list of unique facts around the seeds. \"\"\" if", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]] #", "topk, alpha, seed_weighting=True): \"\"\"Get subgraph describing a neighbourhood around given", "facts around the seeds. \"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids", "Copyright 2020 The Google Research Authors. # # Licensed under", "facts between all extracted entities. \"\"\" from __future__ import absolute_import", "Version 2.0 (the \"License\"); # you may not use this", "data processing will be printed. ' 'A number of warnings", "0: extracted_ents = extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores def get_facts(self, entities,", "{x: entity_ids.count(x) for x in entity_ids} seed = np.zeros((self.data.adj_mat.shape[0], 1))", "rev_dir = (obj, sub) if fwd_dir in unique_facts and score", "in facts: fwd_dir = (sub, obj) rev_dir = (obj, sub)", "csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk] extracted_scores", "around the seeds. \"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids =", "in self.data.ent2id ] if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x in", "if fwd_dir in unique_facts and score > unique_facts[fwd_dir][1]: unique_facts[fwd_dir] =", "__future__ import absolute_import from __future__ import division from __future__ import", "FLAGS = flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False, 'If true, all of", "implied. # See the License for the specific language governing", "'A number of warnings are expected for a normal NQ", "full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds, alpha, topk): \"\"\"Extract topk entities", "Node probability for PPR seed_weighting: Boolean for performing weighting seeds", "(fact with highest score) # Sort by scores unique_facts =", "under the Apache License, Version 2.0 (the \"License\"); # you", "Get unique facts between all extracted entities. \"\"\" from __future__", "entities extracted_scores: list of scores of selected entities \"\"\" ppr_scores", "facts: ') tf.logging.info(str(facts)) # Extract 1 unique fact per pair", "governing permissions and # limitations under the License. \"\"\"This file", "1. / len(set(entity_ids)) else: for x, y in freq_dict.items(): seed[x]", "len(set(entity_ids)) else: for x, y in freq_dict.items(): seed[x] = y", "by applicable law or agreed to in writing, software #", "with weight on every seed entity alpha: probability for PPR", "if FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids = [ int(self.data.ent2id[x]) for x", "class ApproximatePageRank(object): \"\"\"APR main lib which is used to wrap", "entities: A list of Wikidata entities topk: Max entities to", "and score > unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel, score) del unique_facts[rev_dir]", "topk entities from PPR. 3. Get unique facts between all", "entities topk: Max entities to extract from PPR alpha: Node", "tf from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from", "if not seed_weighting: seed[entity_ids] = 1. / len(set(entity_ids)) else: for", "tf.logging.info('Getting subgraph') entity_ids = [ int(self.data.ent2id[x]) for x in entities", "str([self.data.entity_names['e'][str(x)]['name'] for x in entity_ids ])) freq_dict = {x: entity_ids.count(x)", "freq_dict, self.data.entity_names, extracted_ents, extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted facts: ') tf.logging.info(str(facts))", "acts as a wrapper around the PPR algorithm. This class", "under the License. \"\"\"This file contains a class which acts", "a class which acts as a wrapper around the PPR", "= csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents, extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted", "(sub, obj) rev_dir = (obj, sub) if fwd_dir in unique_facts", "{} for (sub, obj, rel, score) in facts: fwd_dir =", "extracted entities. \"\"\" from __future__ import absolute_import from __future__ import", "return extracted_ents, extracted_scores def get_facts(self, entities, topk, alpha, seed_weighting=True): \"\"\"Get", "str([ self.data.entity_names['e'][str(x)]['name'] for x in extracted_ents ])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr,", "a wrapper around the PPR algorithm. This class has the", "zero_idx = np.where(ppr_scores[extracted_ents] < 1e-6)[0] if zero_idx.shape[0] > 0: extracted_ents", "unique facts between all extracted entities. \"\"\" from __future__ import", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Unless required by applicable law or agreed to in writing,", "extracted_ents = extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores def get_facts(self, entities, topk,", "unique_facts = {} for (sub, obj, rel, score) in facts:", "functionality: 1. Load the KB graph, 2. Given list of", "del unique_facts[rev_dir] # Remove existing entity pair else: unique_facts[(sub, obj)]", "else: unique_facts[(sub, obj)] = (rel, score) unique_facts = list(unique_facts.items()) return", "the specific language governing permissions and # limitations under the", "# Get idx of First value < 1e-6, limit extracted", "applicable law or agreed to in writing, software # distributed", "the seeds. \"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting subgraph') entity_ids = [", "= np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]] # Check", "zero_idx.shape[0] > 0: extracted_ents = extracted_ents[:zero_idx[0]] return extracted_ents, extracted_scores def", "warnings related to data processing will be printed. ' 'A", "selected entities extracted_scores: list of scores of selected entities \"\"\"", "elif rev_dir in unique_facts and score > unique_facts[rev_dir][1]: unique_facts[fwd_dir] =", "of scores of selected entities \"\"\" ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr,", "fact per pair of entities (fact with highest score) #", "rel, score) in facts: fwd_dir = (sub, obj) rev_dir =", "vector with weight on every seed entity alpha: probability for", "in writing, software # distributed under the License is distributed", "3. Get unique facts between all extracted entities. \"\"\" from", "ents till there zero_idx = np.where(ppr_scores[extracted_ents] < 1e-6)[0] if zero_idx.shape[0]", "seed[entity_ids] = 1. / len(set(entity_ids)) else: for x, y in", "FLAGS.verbose_logging: tf.logging.info('Extracted facts: ') tf.logging.info(str(facts)) # Extract 1 unique fact", "facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict, freq_dict, self.data.entity_names, extracted_ents, extracted_scores) if FLAGS.verbose_logging:", "x in entity_ids ])) freq_dict = {x: entity_ids.count(x) for x", "scores unique_facts = {} for (sub, obj, rel, score) in", "unique_facts: A list of unique facts around the seeds. \"\"\"", "Remove existing entity pair else: unique_facts[(sub, obj)] = (rel, score)", "FLAGS.verbose_logging: tf.logging.info('Extracted ents: ') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for x in", "A list of Wikidata entities topk: Max entities to extract", "Authors. # # Licensed under the Apache License, Version 2.0", "= np.zeros((self.data.adj_mat.shape[0], 1)) if not seed_weighting: seed[entity_ids] = 1. /", "self.data = CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds, alpha,", "seed_weighting: Boolean for performing weighting seeds by freq in passage", "get topk entities from PPR. 3. Get unique facts between", "csr_personalized_pagerank from fat.fat_bert_nq.ppr.apr_algo import csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "obj) rev_dir = (obj, sub) if fwd_dir in unique_facts and", "unique_facts[rev_dir][1]: unique_facts[fwd_dir] = (rel, score) del unique_facts[rev_dir] # Remove existing", "of the warnings related to data processing will be printed.", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "csr_topk_fact_extractor from fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags = tf.flags FLAGS =", "unique_facts[fwd_dir] = (rel, score) del unique_facts[rev_dir] # Remove existing entity", "given entities. Args: entities: A list of Wikidata entities topk:", "of First value < 1e-6, limit extracted ents till there", "self.data.entity_names['e'][str(x)]['name'] for x in extracted_ents ])) facts = csr_topk_fact_extractor(self.data.adj_mat_t_csr, self.data.rel_dict,", "fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool(", "for x, y in freq_dict.items(): seed[x] = y seed =", "the License for the specific language governing permissions and #", "Args: seeds: An Ex1 vector with weight on every seed", "in passage Returns: unique_facts: A list of unique facts around", "Apache License, Version 2.0 (the \"License\"); # you may not", "topk) if FLAGS.verbose_logging: tf.logging.info('Extracted ents: ') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name'] for", "either express or implied. # See the License for the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "permissions and # limitations under the License. \"\"\"This file contains", "FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name'] for x in entity_ids ])) freq_dict =", "has the following functionality: 1. Load the KB graph, 2.", "freq_dict.items(): seed[x] = y seed = seed / seed.sum() extracted_ents,", "x, y in freq_dict.items(): seed[x] = y seed = seed", "list of seed entities, get topk entities from PPR. 3.", "from __future__ import print_function import numpy as np import tensorflow", "np import tensorflow as tf from fat.fat_bert_nq.ppr.apr_algo import csr_personalized_pagerank from", "entities if x in self.data.ent2id ] if FLAGS.verbose_logging: tf.logging.info( str([self.data.entity_names['e'][str(x)]['name']", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "import CsrData flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool( 'verbose_logging',", "1e-6, limit extracted ents till there zero_idx = np.where(ppr_scores[extracted_ents] <", "entities to extract Returns: extracted_ents: list of selected entities extracted_scores:", "PPR. 3. Get unique facts between all extracted entities. \"\"\"", "__init__(self): self.data = CsrData() self.data.load_csr_data( full_wiki=FLAGS.full_wiki, files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds,", "given seeds. Args: seeds: An Ex1 vector with weight on", "= (rel, score) del unique_facts[rev_dir] # Remove existing entity pair", "\"\"\"APR main lib which is used to wrap functions around", "entities to extract from PPR alpha: Node probability for PPR", "pair else: unique_facts[(sub, obj)] = (rel, score) unique_facts = list(unique_facts.items())", "alpha, topk) if FLAGS.verbose_logging: tf.logging.info('Extracted ents: ') tf.logging.info( str([ self.data.entity_names['e'][str(x)]['name']", "for PPR topk: max top entities to extract Returns: extracted_ents:", "absolute_import from __future__ import division from __future__ import print_function import", "import print_function import numpy as np import tensorflow as tf", "flags.DEFINE_bool( 'verbose_logging', False, 'If true, all of the warnings related", "numpy as np import tensorflow as tf from fat.fat_bert_nq.ppr.apr_algo import", "\"License\"); # you may not use this file except in", "import numpy as np import tensorflow as tf from fat.fat_bert_nq.ppr.apr_algo", "self.data.adj_mat_t_csr, alpha) sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk] extracted_scores =", "sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]] # Check for really low values", "coding=utf-8 # Copyright 2020 The Google Research Authors. # #", "performing weighting seeds by freq in passage Returns: unique_facts: A", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "extracted_scores = self.get_topk_extracted_ent( seed, alpha, topk) if FLAGS.verbose_logging: tf.logging.info('Extracted ents:", "of unique facts around the seeds. \"\"\" if FLAGS.verbose_logging: tf.logging.info('Getting", "files_dir=FLAGS.apr_files_dir) def get_topk_extracted_ent(self, seeds, alpha, topk): \"\"\"Extract topk entities given", "self.data.entity_names, extracted_ents, extracted_scores) if FLAGS.verbose_logging: tf.logging.info('Extracted facts: ') tf.logging.info(str(facts)) #", "low values # Get idx of First value < 1e-6,", "topk: Max entities to extract from PPR alpha: Node probability", "\"\"\" ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents", "of entities (fact with highest score) # Sort by scores", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "__future__ import division from __future__ import print_function import numpy as", "= tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False, 'If true,", "alpha) sorted_idx = np.argsort(ppr_scores)[::-1] extracted_ents = sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]]", "= seed / seed.sum() extracted_ents, extracted_scores = self.get_topk_extracted_ent( seed, alpha,", "# Check for really low values # Get idx of", "limitations under the License. \"\"\"This file contains a class which", "The Google Research Authors. # # Licensed under the Apache", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "following functionality: 1. Load the KB graph, 2. Given list", "extracted_ents = sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]] # Check for really", "and # limitations under the License. \"\"\"This file contains a", "Returns: unique_facts: A list of unique facts around the seeds.", "= sorted_idx[:topk] extracted_scores = ppr_scores[sorted_idx[:topk]] # Check for really low", "You may obtain a copy of the License at #", "lib which is used to wrap functions around ppr algo.\"\"\"", "flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool( 'verbose_logging', False, 'If", "for (sub, obj, rel, score) in facts: fwd_dir = (sub,", "else: for x, y in freq_dict.items(): seed[x] = y seed", "extracted_ents, extracted_scores def get_facts(self, entities, topk, alpha, seed_weighting=True): \"\"\"Get subgraph", "PPR alpha: Node probability for PPR seed_weighting: Boolean for performing", "for PPR seed_weighting: Boolean for performing weighting seeds by freq", "topk: max top entities to extract Returns: extracted_ents: list of", "the Apache License, Version 2.0 (the \"License\"); # you may", "= (rel, score) elif rev_dir in unique_facts and score >", "a neighbourhood around given entities. Args: entities: A list of", "from fat.fat_bert_nq.ppr.kb_csr_io import CsrData flags = tf.flags FLAGS = flags.FLAGS", "])) freq_dict = {x: entity_ids.count(x) for x in entity_ids} seed", "all of the warnings related to data processing will be", "entity_ids = [ int(self.data.ent2id[x]) for x in entities if x", "Research Authors. # # Licensed under the Apache License, Version", "are expected for a normal NQ evaluation.') class ApproximatePageRank(object): \"\"\"APR" ]
[ "elif plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year] = 0 return perennial_plan def", "= bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy() num_beds = len(beds) #time dimension", "ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return ax def visualize_plan(bed_info,bed_index,years): for year in", "make_neighbor call perennial_plan[plant,bed,year:] = 1 #sets plant to 1 in", "= pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective') fig,", "it from previous years elif plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year] =", "bed_info.sun.to_numpy() num_beds = len(beds) #time dimension num_years = 3 years", "them in the same bed \"\"\" disease_plan = plan.copy() #mask", "in bed in current and subsequent years during a previous", "= bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy() num_beds =", "info plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index' plants = plant_info.name.to_numpy()", "planted already in this bed was a perennial, remove it", "multiple years. Multiplies the plan for problem plants by 0", "f, ax = plt.subplots(figsize=(10, 6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([])", "'bed_index' beds = bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy()", "not match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for p in plant_index: for", "Image import matplotlib.pyplot as plt import numpy as np import", "encourages plants with higher preferences to be planted in higher", "the total qty of plants in the current plan for", "do not match. \"\"\" return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill", "of Current Solution by Iteration') # ax2 = plt.twinx() #", "plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy() #bed info bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name", "it will be 1 in same bed thereafter.\"\"\" perennial_plan =", "plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) ax.set_title('Objective Values of", "perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average preference", "6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return ax", "to determine cases where same thing was planted in the", "Current Solution by Iteration') # ax2 = plt.twinx() # sb.scatterplot(data=df.drop_duplicates(['index','total_plants']),x='index',y='objective',edgecolor=None,ax=ax2,color='black',s=5)", "borderaxespad=0) ax.set_title('Objective Values of Current Solution by Iteration') # ax2", "#### #plant info plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index' plants", "of plants that are being planted across all beds. Then", "preferences to be planted in higher quantities.\"\"\" plan_yummy = plan.copy()", "perennial, plant it this year and every year thereafter if", "what axis is which plant_axis = 0 bed_axis = 1", "plants in the current plan for each plant. Maximization encourages", "#the most satisfied you could be (planting fruit or vegetable", "plt import numpy as np import pandas as pd import", "num_beds = len(beds) #time dimension num_years = 3 years =", "in all beds every year) max_yums = num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums):", "in bed_index: plant_idx = np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}']", "= pd.Series(bed_plan) return bed_info def visualize_obj_iters(current_plan_obj_values): objectives = [] yummy_scores", "= bed_info.sun.to_numpy() num_beds = len(beds) #time dimension num_years = 3", "np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy() #bed info bed_info = pd.read_csv('../data/bed_data.csv')", "given bed/year, it will be 1 in same bed thereafter.\"\"\"", "bed_plan = [] for b in bed_index: plant_idx = np.argmax(best_plan[:,b,t])", "sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) ax.set_title('Objective Values of Current", "disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan ##### Objectives ##### #the most", "plan for each plant. Maximization encourages plants with higher preferences", "number of unique plants that are actually planted in the", "yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def compute_variety_score(plan,num_plants): \"\"\"Sums the number", "perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask to determine if the", "plan.copy() #mask to determine cases where same thing was planted", "the same bed \"\"\" disease_plan = plan.copy() #mask to determine", "plants to be planted.\"\"\" plan_variety = plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis))", "by 0 in subsequent years where we planned to put", "variety_score #### Analysis & Visualization #### def visualize_garden(bed_info): garden_layout =", "plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def compute_variety_score(plan,num_plants):", "np.ones(shape=(num_plants,num_beds,num_years)) for p in plant_index: for b in bed_index: p_sun", "highest preference in all beds every year) max_yums = num_beds*num_years*np.max(preferences)", "the number of unique plants that are actually planted in", "plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1) return", "may have been planted in bed in current and subsequent", "Visualization #### def visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3)", "> 0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1) return variety_score #### Analysis &", "0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan ##### Objectives ##### #the", "is which plant_axis = 0 bed_axis = 1 year_axis =", "[\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax = plt.subplots(figsize=(10, 6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([])", "this bed was a perennial, remove it from previous years", "of plants with non-zero planting plan. Maximization encourages more unique", "'plant_index' plants = plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy() num_plants = len(plants)", "0 where sun requirements do not match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years))", "plants. If 1 in a given bed/year, it will be", "year before plant_last_year = perennial_plan[:,bed,year-1].argmax() #if the plant is a", "in bed every year after the current year #if what", "numpy as np import pandas as pd import seaborn as", "= plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average preference for", "plt.rcParams.update({'font.size': 13}) return ax def visualize_plan(bed_info,bed_index,years): for year in years:", "plant_index = plant_info.index.to_numpy() num_plants = len(plants) plant_sun_req = plant_info.sun.to_numpy() perennials", "plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average preference for each", "the plant is a perennial, plant it this year and", "ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) ax.set_title('Objective", "df = df.melt(id_vars=['index'],var_name='objective') fig, ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1),", "#### Initial Setup #### #plant info plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name", "#mask to determine cases where same thing was planted in", "yums def compute_variety_score(plan,num_plants): \"\"\"Sums the number of unique plants that", "where sun requirements for plant and bed do not match.", "visualize_obj_iters(current_plan_obj_values): objectives = [] yummy_scores = [] variety_scores = []", "loc='upper left', borderaxespad=0) ax.set_title('Objective Values of Current Solution by Iteration')", "bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy() num_beds = len(beds)", "years elif plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year] = 0 return perennial_plan", "bed yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply plan for specific problem", "garden_layout = bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f,", "= bed_info.iloc[bed].x y = bed_info.iloc[bed].y plt.text(x + 0.5, y +", "import pandas as pd import seaborn as sb sb.set_style(\"dark\") ####", "= disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan ##### Objectives ##### #the most satisfied", "perennial_plan[:,bed,year:] = 0 # zeros out anything else that may", "plt.subplots(figsize=(10, 6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return", "#if the plant is a perennial, plant it this year", "preferences = plant_info.avg_pref.to_numpy() #bed info bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name =", "do not match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for p in plant_index:", "for b in bed_index: p_sun = plant_sun_req[p] b_sun = bed_sun_req[b]", "pd.Series(bed_plan) return bed_info def visualize_obj_iters(current_plan_obj_values): objectives = [] yummy_scores =", "will be 1 in same bed thereafter.\"\"\" perennial_plan = plan.copy()", "variety_score = round(num_plants_in_plan/num_plants*100,1) return variety_score #### Analysis & Visualization ####", "average of the preferences of each plant, weighted by the", "planting plan. Maximization encourages more unique plants to be planted.\"\"\"", "and bed do not match. \"\"\" return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials):", "as plt import numpy as np import pandas as pd", "that are actually planted in the garden. Counts the number", "def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask to determine if the same", "the year before plant_last_year = perennial_plan[:,bed,year-1].argmax() #if the plant is", "def visualize_plan(bed_info,bed_index,years): for year in years: garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year", "= 1 year_axis = 2 ##### Constraints ##### #initialize sun", "that are being planted across all beds. Then counts the", "bed was a perennial, remove it from previous years elif", "2 ##### Constraints ##### #initialize sun constraint. 1 where plant", "IPython.display import Image import matplotlib.pyplot as plt import numpy as", "= plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted", "every year thereafter if plant in perennials: perennial_plan[:,bed,year:] = 0", "bed over multiple years. Multiplies the plan for problem plants", "= sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return ax def visualize_plan(bed_info,bed_index,years):", "bed_info.iloc[bed].y plt.text(x + 0.5, y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def", "= np.array(range(1,num_years+1)) year_index = np.array(range(num_years)) #for keeping track of what", "[] for i in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df =", "yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df", "bed_info def visualize_obj_iters(current_plan_obj_values): objectives = [] yummy_scores = [] variety_scores", "beds. Then counts the number of plants with non-zero planting", "track of what axis is which plant_axis = 0 bed_axis", "preference for each plant family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0])", "#plant info plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index' plants =", "you could be (planting fruit or vegetable with highest preference", "keeping track of what axis is which plant_axis = 0", "by 0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan ##### Objectives #####", "a previous make_neighbor call perennial_plan[plant,bed,year:] = 1 #sets plant to", "of unique plants that are actually planted in the garden.", "the same bed over multiple years. Multiplies the plan for", "#if what was planted already in this bed was a", "b in bed_index: p_sun = plant_sun_req[p] b_sun = bed_sun_req[b] if", "where we planned to put them in the same bed", "be 0 where sun requirements for plant and bed do", "def compute_variety_score(plan,num_plants): \"\"\"Sums the number of unique plants that are", "objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True)", "plant_index: for b in bed_index: p_sun = plant_sun_req[p] b_sun =", "compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted average of the preferences of each", "#bed info bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index' beds =", "= plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums", "= [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax = plt.subplots(figsize=(10, 6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False)", "disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan ##### Objectives ##### #the most satisfied you", "vegetable with highest preference in all beds every year) max_yums", "if the same veg was planted in the same bed", "in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns =", "determine cases where same thing was planted in the same", "annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in year_index: bed_plan = [] for b", "could be (planting fruit or vegetable with highest preference in", "bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax =", "same bed \"\"\" disease_plan = plan.copy() #mask to determine cases", "plan for problem plants by 0 in subsequent years where", "over multiple years. Multiplies the plan for problem plants by", "df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective')", "for specific problem plants by 0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return", "13}) return ax def visualize_plan(bed_info,bed_index,years): for year in years: garden_viz", "be planted in bed. 0 where sun requirements do not", "as np import pandas as pd import seaborn as sb", "return bed_info def visualize_obj_iters(current_plan_obj_values): objectives = [] yummy_scores = []", "def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in year_index: bed_plan = [] for", "##### #initialize sun constraint. 1 where plant can feasibly be", "round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def compute_variety_score(plan,num_plants): \"\"\"Sums the number of unique", "= 1 #sets plant to 1 in bed every year", "enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan to be 0 where sun requirements", "= visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for bed in bed_index: x =", "all beds. Then counts the number of plants with non-zero", "perennial_plan[plant,bed,year:] = 1 #sets plant to 1 in bed every", "sys import time from IPython.display import Image import matplotlib.pyplot as", "requirements for plant and bed do not match. \"\"\" return", "from IPython.display import Image import matplotlib.pyplot as plt import numpy", "b in bed_index: plant_idx = np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant)", "['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy() #bed info", "= pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index' beds = bed_info.bed.to_numpy() bed_index =", "0 bed_axis = 1 year_axis = 2 ##### Constraints #####", "have been planted in bed in current and subsequent years", "plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index' plants = plant_info.name.to_numpy() plant_index", "bed \"\"\" disease_plan = plan.copy() #mask to determine cases where", "= bed_sun_req[b] if p_sun != b_sun: sun_constraint[p,b,:] = 0 def", "[] for b in bed_index: plant_idx = np.argmax(best_plan[:,b,t]) plant =", "to be 0 where sun requirements for plant and bed", "bed_index: p_sun = plant_sun_req[p] b_sun = bed_sun_req[b] if p_sun !=", "with non-zero planting plan. Maximization encourages more unique plants to", "preference in all beds every year) max_yums = num_beds*num_years*np.max(preferences) def", "thereafter.\"\"\" perennial_plan = plan.copy() #what was planted the year before", "perennial_plan[:,bed,year-1].argmax() #if the plant is a perennial, plant it this", "veg was planted in the same bed over multiple years.", "plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return bed_info def", "years where we planned to put them in the same", "Then counts the number of plants with non-zero planting plan.", "during a previous make_neighbor call perennial_plan[plant,bed,year:] = 1 #sets plant", "!= b_sun: sun_constraint[p,b,:] = 0 def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan", "plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def", "years. Multiplies the plan for problem plants by 0 in", "for b in bed_index: plant_idx = np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name']", "problem plants by 0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan #####", "plan for perennial plants. If 1 in a given bed/year,", "p in plant_index: for b in bed_index: p_sun = plant_sun_req[p]", "same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply plan for specific problem plants by", "beds every year) max_yums = num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the", "determine if the same veg was planted in the same", "are being planted across all beds. Then counts the number", "plan_yummy = plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return", "bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy() num_beds = len(beds) #time dimension num_years", "average preference for each plant family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] =", "import seaborn as sb sb.set_style(\"dark\") #### Initial Setup #### #plant", "Objectives ##### #the most satisfied you could be (planting fruit", "planted across all beds. Then counts the number of plants", "#calculate weighted average preference for each plant family = ['evan','gina','liesse','lizzie','jack']", "plant_info.index.to_numpy() num_plants = len(plants) plant_sun_req = plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list()", "weighted average preference for each plant family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref']", "Force plan to be 0 where sun requirements for plant", "1 where plant can feasibly be planted in bed. 0", "plant_idx = np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan)", "1 #sets plant to 1 in bed every year after", "being planted across all beds. Then counts the number of", "zeros out anything else that may have been planted in", "was planted in the same bed yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1", "plan. Maximization encourages more unique plants to be planted.\"\"\" plan_variety", "= 0 def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan to be 0", "in perennials: perennial_plan[plant_last_year,bed,:year] = 0 return perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates", "to put them in the same bed \"\"\" disease_plan =", "of plants in the current plan for each plant. Maximization", "= 'plant_index' plants = plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy() num_plants =", "return yums def compute_variety_score(plan,num_plants): \"\"\"Sums the number of unique plants", "= round(num_plants_in_plan/num_plants*100,1) return variety_score #### Analysis & Visualization #### def", "bed do not match. \"\"\" return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward", "in perennials: perennial_plan[:,bed,year:] = 0 # zeros out anything else", "np.array(range(1,num_years+1)) year_index = np.array(range(num_years)) #for keeping track of what axis", "def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan to be 0 where sun", "y = bed_info.iloc[bed].y plt.text(x + 0.5, y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0],", "bed_index: plant_idx = np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] =", "planted.\"\"\" plan_variety = plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score", "round(num_plants_in_plan/num_plants*100,1) return variety_score #### Analysis & Visualization #### def visualize_garden(bed_info):", "= 3 years = np.array(range(1,num_years+1)) year_index = np.array(range(num_years)) #for keeping", "len(beds) #time dimension num_years = 3 years = np.array(range(1,num_years+1)) year_index", "plant it this year and every year thereafter if plant", "years: garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for bed in bed_index:", "import matplotlib.pyplot as plt import numpy as np import pandas", "most satisfied you could be (planting fruit or vegetable with", "0 # zeros out anything else that may have been", "in higher quantities.\"\"\" plan_yummy = plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums", "df.melt(id_vars=['index'],var_name='objective') fig, ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left',", "Values of Current Solution by Iteration') # ax2 = plt.twinx()", "yummy_scores = [] variety_scores = [] for i in current_plan_obj_values:", "if p_sun != b_sun: sun_constraint[p,b,:] = 0 def enforce_sun_constraint(plan,sun_constraint): \"\"\"", "and subsequent years during a previous make_neighbor call perennial_plan[plant,bed,year:] =", "return perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask to determine if", "where plant can feasibly be planted in bed. 0 where", "plants with non-zero planting plan. Maximization encourages more unique plants", "horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in year_index: bed_plan = []", "total qty of plants in the current plan for each", "#sets plant to 1 in bed every year after the", "palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax = plt.subplots(figsize=(10, 6)) ax =", "Multiplies the plan for problem plants by 0 in subsequent", "visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for bed in bed_index: x = bed_info.iloc[bed].x", "current and subsequent years during a previous make_neighbor call perennial_plan[plant,bed,year:]", "same thing was planted in the same bed yoy same_veg_in_bed_yoy", "a mask to determine if the same veg was planted", "= plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1)", "= [] variety_scores = [] for i in current_plan_obj_values: objectives.append(i[1]['objective'])", "\"\"\" return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan for perennial", "= ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy() #bed", "in the current plan for each plant. Maximization encourages plants", "garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for bed in bed_index: x", "of the preferences of each plant, weighted by the total", "##### Objectives ##### #the most satisfied you could be (planting", "year_axis = 2 ##### Constraints ##### #initialize sun constraint. 1", "plants that are being planted across all beds. Then counts", "been planted in bed in current and subsequent years during", "= bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax", "for i in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T", "0.5, y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t", "t in year_index: bed_plan = [] for b in bed_index:", "num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted average of the preferences", "bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in year_index: bed_plan =", "bed every year after the current year #if what was", "weighted average of the preferences of each plant, weighted by", "specific problem plants by 0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan", "with highest preference in all beds every year) max_yums =", "plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy() num_plants = len(plants) plant_sun_req = plant_info.sun.to_numpy()", "def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan for perennial plants. If 1", "call perennial_plan[plant,bed,year:] = 1 #sets plant to 1 in bed", "= [] yummy_scores = [] variety_scores = [] for i", "it this year and every year thereafter if plant in", "sun constraint. 1 where plant can feasibly be planted in", "can feasibly be planted in bed. 0 where sun requirements", "planted in bed. 0 where sun requirements do not match.", "plant to 1 in bed every year after the current", "this year and every year thereafter if plant in perennials:", "bed in current and subsequent years during a previous make_neighbor", "problem plants by 0 in subsequent years where we planned", "match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for p in plant_index: for b", "planned to put them in the same bed \"\"\" disease_plan", "& Visualization #### def visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial", "in the same bed over multiple years. Multiplies the plan", "variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df =", "by the total qty of plants in the current plan", "len(plants) plant_sun_req = plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list()", "in years: garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for bed in", "= disease_plan.cumsum(axis=year_axis)>1 #multiply plan for specific problem plants by 0", "sun requirements for plant and bed do not match. \"\"\"", "plant family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences =", "= np.ones(shape=(num_plants,num_beds,num_years)) for p in plant_index: for b in bed_index:", "bed_info.index.name = 'bed_index' beds = bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy() bed_sun_req", "in bed. 0 where sun requirements do not match. sun_constraint", "np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return bed_info", "sb sb.set_style(\"dark\") #### Initial Setup #### #plant info plant_info =", "plant is a perennial, plant it this year and every", "= np.argmax(best_plan[:,b,t]) plant = plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return", "sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for p in plant_index: for b in", "as sb sb.set_style(\"dark\") #### Initial Setup #### #plant info plant_info", "= plant_info.index.to_numpy() num_plants = len(plants) plant_sun_req = plant_info.sun.to_numpy() perennials =", "the same bed yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply plan for", "in bed_index: p_sun = plant_sun_req[p] b_sun = bed_sun_req[b] if p_sun", "plan.copy() #what was planted the year before plant_last_year = perennial_plan[:,bed,year-1].argmax()", "more unique plants to be planted.\"\"\" plan_variety = plan.copy() num_plants_in_plan", "anything else that may have been planted in bed in", "y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in", "plant_last_year = perennial_plan[:,bed,year-1].argmax() #if the plant is a perennial, plant", "0 in subsequent years where we planned to put them", "planted in bed in current and subsequent years during a", "sun requirements do not match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for p", "for plant and bed do not match. \"\"\" return plan*sun_constraint", "= plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy() num_plants = len(plants) plant_sun_req =", "the weighted average of the preferences of each plant, weighted", "all beds every year) max_yums = num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes", "= plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return bed_info def visualize_obj_iters(current_plan_obj_values):", "(plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1) return variety_score #### Analysis", "planted in the same bed yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply", "we planned to put them in the same bed \"\"\"", "sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return ax def visualize_plan(bed_info,bed_index,years): for", "non-zero planting plan. Maximization encourages more unique plants to be", "higher quantities.\"\"\" plan_yummy = plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums =", "the same veg was planted in the same bed over", "Analysis & Visualization #### def visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full sun':1,'Partial", "that may have been planted in bed in current and", "fill plan for perennial plants. If 1 in a given", "in plant_index: for b in bed_index: p_sun = plant_sun_req[p] b_sun", "in this bed was a perennial, remove it from previous", "bed. 0 where sun requirements do not match. sun_constraint =", "planted the year before plant_last_year = perennial_plan[:,bed,year-1].argmax() #if the plant", "= len(beds) #time dimension num_years = 3 years = np.array(range(1,num_years+1))", "max_yums = num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted average of", "= ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective') fig, ax = plt.subplots(figsize=(20,8))", "with higher preferences to be planted in higher quantities.\"\"\" plan_yummy", "Constraints ##### #initialize sun constraint. 1 where plant can feasibly", "num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1) return variety_score", "import numpy as np import pandas as pd import seaborn", "number of plants with non-zero planting plan. Maximization encourages more", "plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def compute_variety_score(plan,num_plants): \"\"\"Sums the", "= df.melt(id_vars=['index'],var_name='objective') fig, ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper", "1 in a given bed/year, it will be 1 in", "satisfied you could be (planting fruit or vegetable with highest", "planted in the same bed over multiple years. Multiplies the", "\"\"\" Force plan to be 0 where sun requirements for", "Counts the number of plants that are being planted across", "return ax def visualize_plan(bed_info,bed_index,years): for year in years: garden_viz =", "for perennial plants. If 1 in a given bed/year, it", "of each plant, weighted by the total qty of plants", "in current and subsequent years during a previous make_neighbor call", "previous years elif plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year] = 0 return", "bed_sun_req = bed_info.sun.to_numpy() num_beds = len(beds) #time dimension num_years =", "as pd import seaborn as sb sb.set_style(\"dark\") #### Initial Setup", "counts the number of plants with non-zero planting plan. Maximization", "= plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average preference for each plant family", "bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return bed_info def visualize_obj_iters(current_plan_obj_values): objectives =", "be planted.\"\"\" plan_variety = plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum()", "encourages more unique plants to be planted.\"\"\" plan_variety = plan.copy()", "put them in the same bed \"\"\" disease_plan = plan.copy()", "= plant_sun_req[p] b_sun = bed_sun_req[b] if p_sun != b_sun: sun_constraint[p,b,:]", "same bed yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply plan for specific", "sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax = plt.subplots(figsize=(10, 6))", "problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average preference for each plant", "If 1 in a given bed/year, it will be 1", "plant can feasibly be planted in bed. 0 where sun", "0 return perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask to determine", "planted in the garden. Counts the number of plants that", "out anything else that may have been planted in bed", "##### Constraints ##### #initialize sun constraint. 1 where plant can", "{year}') for bed in bed_index: x = bed_info.iloc[bed].x y =", "\"\"\"Forward fill plan for perennial plants. If 1 in a", "perennial_plan[plant_last_year,bed,:year] = 0 return perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask", "bed in bed_index: x = bed_info.iloc[bed].x y = bed_info.iloc[bed].y plt.text(x", "plant, weighted by the total qty of plants in the", "in year_index: bed_plan = [] for b in bed_index: plant_idx", "plants with higher preferences to be planted in higher quantities.\"\"\"", "variety_scores = [] for i in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score'])", "to 1 in bed every year after the current year", "= [] for i in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df", "bed_index = bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy() num_beds = len(beds) #time", "ax.set_title('Objective Values of Current Solution by Iteration') # ax2 =", "import sys import time from IPython.display import Image import matplotlib.pyplot", "bed thereafter.\"\"\" perennial_plan = plan.copy() #what was planted the year", "to be planted in higher quantities.\"\"\" plan_yummy = plan.copy() plan_by_plant", "the garden. Counts the number of plants that are being", "[] variety_scores = [] for i in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score'])", "plant and bed do not match. \"\"\" return plan*sun_constraint def", "0 def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan to be 0 where", "disease_plan ##### Objectives ##### #the most satisfied you could be", "which plant_axis = 0 bed_axis = 1 year_axis = 2", "feasibly be planted in bed. 0 where sun requirements do", "is a perennial, plant it this year and every year", "each plant. Maximization encourages plants with higher preferences to be", "enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask to determine if the same veg", "beds = bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy() bed_sun_req = bed_info.sun.to_numpy() num_beds", "remove it from previous years elif plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year]", "be planted in higher quantities.\"\"\" plan_yummy = plan.copy() plan_by_plant =", "year_index: bed_plan = [] for b in bed_index: plant_idx =", "= plt.subplots(figsize=(10, 6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13})", "= perennial_plan[:,bed,year-1].argmax() #if the plant is a perennial, plant it", "current year #if what was planted already in this bed", "sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax = plt.subplots(figsize=(10,", "visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"]", "0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in year_index: bed_plan", "df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective') fig, ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05,", "= (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1) return variety_score ####", "for each plant family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True)", "\"\"\"Creates a mask to determine if the same veg was", "the current plan for each plant. Maximization encourages plants with", "pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective') fig, ax", "return disease_plan ##### Objectives ##### #the most satisfied you could", "def visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette =", "for bed in bed_index: x = bed_info.iloc[bed].x y = bed_info.iloc[bed].y", "= bed_info.iloc[bed].y plt.text(x + 0.5, y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center')", "subsequent years where we planned to put them in the", "info bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index' beds = bed_info.bed.to_numpy()", "i in current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns", "and every year thereafter if plant in perennials: perennial_plan[:,bed,year:] =", "yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply plan for specific problem plants", "bed_info.iloc[bed].x y = bed_info.iloc[bed].y plt.text(x + 0.5, y + 0.5,", "else that may have been planted in bed in current", "plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan for perennial plants. If", "1 in bed every year after the current year #if", "years = np.array(range(1,num_years+1)) year_index = np.array(range(num_years)) #for keeping track of", "year #if what was planted already in this bed was", "the plan for problem plants by 0 in subsequent years", "for t in year_index: bed_plan = [] for b in", "perennial, remove it from previous years elif plant_last_year in perennials:", "number of plants that are being planted across all beds.", "import Image import matplotlib.pyplot as plt import numpy as np", "enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan for perennial plants. If 1 in", "current plan for each plant. Maximization encourages plants with higher", "plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) ax.set_title('Objective Values of Current Solution", "bed_index: x = bed_info.iloc[bed].x y = bed_info.iloc[bed].y plt.text(x + 0.5,", "a perennial, remove it from previous years elif plant_last_year in", "pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index' plants = plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy()", "preferences of each plant, weighted by the total qty of", "in same bed thereafter.\"\"\" perennial_plan = plan.copy() #what was planted", "year thereafter if plant in perennials: perennial_plan[:,bed,year:] = 0 #", "perennial_plan = plan.copy() #what was planted the year before plant_last_year", "a perennial, plant it this year and every year thereafter", "be 1 in same bed thereafter.\"\"\" perennial_plan = plan.copy() #what", "ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return ax def", "planted in higher quantities.\"\"\" plan_yummy = plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis))", "ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size': 13}) return ax def visualize_plan(bed_info,bed_index,years): for year", "b_sun: sun_constraint[p,b,:] = 0 def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan to", "thereafter if plant in perennials: perennial_plan[:,bed,year:] = 0 # zeros", "for year in years: garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for", "qty of plants in the current plan for each plant.", "= 2 ##### Constraints ##### #initialize sun constraint. 1 where", "fig, ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)", "3 years = np.array(range(1,num_years+1)) year_index = np.array(range(num_years)) #for keeping track", "years during a previous make_neighbor call perennial_plan[plant,bed,year:] = 1 #sets", "same veg was planted in the same bed over multiple", "[] yummy_scores = [] variety_scores = [] for i in", "= pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index' plants = plant_info.name.to_numpy() plant_index =", "mask to determine if the same veg was planted in", "left', borderaxespad=0) ax.set_title('Objective Values of Current Solution by Iteration') #", "if plant in perennials: perennial_plan[:,bed,year:] = 0 # zeros out", "for p in plant_index: for b in bed_index: p_sun =", "objectives = [] yummy_scores = [] variety_scores = [] for", "to determine if the same veg was planted in the", "np.array(range(num_years)) #for keeping track of what axis is which plant_axis", "weighted by the total qty of plants in the current", "plant. Maximization encourages plants with higher preferences to be planted", "higher preferences to be planted in higher quantities.\"\"\" plan_yummy =", "import os import sys import time from IPython.display import Image", "plan_variety = plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) > 0).sum() variety_score =", "constraint. 1 where plant can feasibly be planted in bed.", "return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan for perennial plants.", "+ 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for t in year_index:", "thing was planted in the same bed yoy same_veg_in_bed_yoy =", "plants by 0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants]) return disease_plan ##### Objectives", "#### Analysis & Visualization #### def visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full", "def visualize_obj_iters(current_plan_obj_values): objectives = [] yummy_scores = [] variety_scores =", "pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index' beds = bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy()", "#for keeping track of what axis is which plant_axis =", "plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average preference for each plant family =", "after the current year #if what was planted already in", "every year) max_yums = num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted", "cases where same thing was planted in the same bed", "pd import seaborn as sb sb.set_style(\"dark\") #### Initial Setup ####", "#### def visualize_garden(bed_info): garden_layout = bed_info.sun.map({'Full sun':1,'Partial sun':2,'Partial shade':3}).to_numpy().reshape(14,3) palette", "the preferences of each plant, weighted by the total qty", "where same thing was planted in the same bed yoy", "are actually planted in the garden. Counts the number of", "was planted in the same bed over multiple years. Multiplies", "\"\"\"Takes the weighted average of the preferences of each plant,", "in the same bed yoy same_veg_in_bed_yoy = disease_plan.cumsum(axis=year_axis)>1 #multiply plan", "each plant, weighted by the total qty of plants in", "0 where sun requirements for plant and bed do not", "where sun requirements do not match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for", "before plant_last_year = perennial_plan[:,bed,year-1].argmax() #if the plant is a perennial,", "plant_sun_req[p] b_sun = bed_sun_req[b] if p_sun != b_sun: sun_constraint[p,b,:] =", "family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy()", "the number of plants with non-zero planting plan. Maximization encourages", "bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return bed_info def visualize_obj_iters(current_plan_obj_values): objectives = []", "plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy() #bed info bed_info", "sun_constraint[p,b,:] = 0 def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force plan to be", "year and every year thereafter if plant in perennials: perennial_plan[:,bed,year:]", "unique plants that are actually planted in the garden. Counts", "Setup #### #plant info plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name = 'plant_index'", "Initial Setup #### #plant info plant_info = pd.read_csv('../data/plant_data.csv') plant_info.index.name =", "year) max_yums = num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted average", "in subsequent years where we planned to put them in", "same bed over multiple years. Multiplies the plan for problem", "shade':3}).to_numpy().reshape(14,3) palette = [\"#ffa200\",\"#fcbd53\",\"#ffd58f\"] f, ax = plt.subplots(figsize=(10, 6)) ax", "['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective') fig, ax = plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5)", "bed/year, it will be 1 in same bed thereafter.\"\"\" perennial_plan", "compute_variety_score(plan,num_plants): \"\"\"Sums the number of unique plants that are actually", "pandas as pd import seaborn as sb sb.set_style(\"dark\") #### Initial", "##### #the most satisfied you could be (planting fruit or", "#what was planted the year before plant_last_year = perennial_plan[:,bed,year-1].argmax() #if", "for problem plants by 0 in subsequent years where we", "actually planted in the garden. Counts the number of plants", "perennials: perennial_plan[plant_last_year,bed,:year] = 0 return perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a", "plant_sun_req = plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate", "year after the current year #if what was planted already", "to be planted.\"\"\" plan_variety = plan.copy() num_plants_in_plan = (plan_variety.sum(axis=(bed_axis,year_axis)) >", "current_plan_obj_values: objectives.append(i[1]['objective']) yummy_scores.append(i[1]['yummy_score']) variety_scores.append(i[1]['variety_score']) df = pd.DataFrame([objectives,yummy_scores,variety_scores]).T#,yummy_scores,variety_scores]).T df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score']", "= len(plants) plant_sun_req = plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants =", "every year after the current year #if what was planted", "= plan.copy() #mask to determine cases where same thing was", "perennials: perennial_plan[:,bed,year:] = 0 # zeros out anything else that", "ax = plt.subplots(figsize=(10, 6)) ax = sb.heatmap(garden_layout,linewidths=5,linecolor='white',cmap=sb.color_palette(palette),cbar=False) ax.xaxis.set_ticklabels([]) ax.yaxis.set_ticklabels([]) plt.rcParams.update({'font.size':", "year_index = np.array(range(num_years)) #for keeping track of what axis is", "seaborn as sb sb.set_style(\"dark\") #### Initial Setup #### #plant info", "sb.set_style(\"dark\") #### Initial Setup #### #plant info plant_info = pd.read_csv('../data/plant_data.csv')", "garden_viz.set_title(f'Year {year}') for bed in bed_index: x = bed_info.iloc[bed].x y", "= [] for b in bed_index: plant_idx = np.argmax(best_plan[:,b,t]) plant", "in the same bed \"\"\" disease_plan = plan.copy() #mask to", "axis is which plant_axis = 0 bed_axis = 1 year_axis", "time from IPython.display import Image import matplotlib.pyplot as plt import", "bed_axis = 1 year_axis = 2 ##### Constraints ##### #initialize", "x = bed_info.iloc[bed].x y = bed_info.iloc[bed].y plt.text(x + 0.5, y", "os import sys import time from IPython.display import Image import", "= num_beds*num_years*np.max(preferences) def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted average of the", "match. \"\"\" return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan for", "dimension num_years = 3 years = np.array(range(1,num_years+1)) year_index = np.array(range(num_years))", "fruit or vegetable with highest preference in all beds every", "matplotlib.pyplot as plt import numpy as np import pandas as", "Maximization encourages more unique plants to be planted.\"\"\" plan_variety =", "p_sun = plant_sun_req[p] b_sun = bed_sun_req[b] if p_sun != b_sun:", "\"\"\"Sums the number of unique plants that are actually planted", "plt.text(x + 0.5, y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index):", "same bed thereafter.\"\"\" perennial_plan = plan.copy() #what was planted the", "garden. Counts the number of plants that are being planted", "return variety_score #### Analysis & Visualization #### def visualize_garden(bed_info): garden_layout", "num_plants = len(plants) plant_sun_req = plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants", "# zeros out anything else that may have been planted", "1 in same bed thereafter.\"\"\" perennial_plan = plan.copy() #what was", "plants by 0 in subsequent years where we planned to", "what was planted already in this bed was a perennial,", "plant_axis = 0 bed_axis = 1 year_axis = 2 #####", "= 0 bed_axis = 1 year_axis = 2 ##### Constraints", "plant in perennials: perennial_plan[:,bed,year:] = 0 # zeros out anything", "be (planting fruit or vegetable with highest preference in all", "def compute_yummy_score(plan,preferences,max_yums): \"\"\"Takes the weighted average of the preferences of", "in bed_index: x = bed_info.iloc[bed].x y = bed_info.iloc[bed].y plt.text(x +", "from previous years elif plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year] = 0", "#time dimension num_years = 3 years = np.array(range(1,num_years+1)) year_index =", "= 0 return perennial_plan def enforce_disease_constraint(plan,problem_plants): \"\"\"Creates a mask to", "or vegetable with highest preference in all beds every year)", "disease_plan = plan.copy() #mask to determine cases where same thing", "visualize_plan(bed_info,bed_index,years): for year in years: garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year {year}')", "+ 0.5, y + 0.5, bed_info.loc[(bed_info.x==x)&(bed_info.y==y)][f'year_{year}'].iloc[0], horizontalalignment='center',verticalalignment='center') def annual_bed_plan(best_plan,bed_info,plant_info,bed_index,year_index): for", "was planted already in this bed was a perennial, remove", "num_years = 3 years = np.array(range(1,num_years+1)) year_index = np.array(range(num_years)) #for", "= plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def compute_variety_score(plan,num_plants): \"\"\"Sums", "in a given bed/year, it will be 1 in same", "np import pandas as pd import seaborn as sb sb.set_style(\"dark\")", "plant_info.index.name = 'plant_index' plants = plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy() num_plants", "plants that are actually planted in the garden. Counts the", "plant_info.avg_pref.to_numpy() #bed info bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index' beds", "subsequent years during a previous make_neighbor call perennial_plan[plant,bed,year:] = 1", "(planting fruit or vegetable with highest preference in all beds", "was planted the year before plant_last_year = perennial_plan[:,bed,year-1].argmax() #if the", "unique plants to be planted.\"\"\" plan_variety = plan.copy() num_plants_in_plan =", "plants = plant_info.name.to_numpy() plant_index = plant_info.index.to_numpy() num_plants = len(plants) plant_sun_req", "Maximization encourages plants with higher preferences to be planted in", "plan to be 0 where sun requirements for plant and", "= round(np.dot(preferences,plan_by_plant)/max_yums*100,1) return yums def compute_variety_score(plan,num_plants): \"\"\"Sums the number of", "= plant_info.avg_pref.to_numpy() #bed info bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index'", "0).sum() variety_score = round(num_plants_in_plan/num_plants*100,1) return variety_score #### Analysis & Visualization", "<gh_stars>0 import os import sys import time from IPython.display import", "import time from IPython.display import Image import matplotlib.pyplot as plt", "plant_last_year in perennials: perennial_plan[plant_last_year,bed,:year] = 0 return perennial_plan def enforce_disease_constraint(plan,problem_plants):", "plant_info.sun.to_numpy() perennials = plant_info[plant_info.perennial==1].index.to_list() problem_plants = plant_info[plant_info.problem_plant==1].index.to_list() #calculate weighted average", "perennial plants. If 1 in a given bed/year, it will", "the number of plants that are being planted across all", "#multiply plan for specific problem plants by 0 disease_plan[problem_plants] =", "each plant family = ['evan','gina','liesse','lizzie','jack'] plant_info['avg_pref'] = np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences", "b_sun = bed_sun_req[b] if p_sun != b_sun: sun_constraint[p,b,:] = 0", "not match. \"\"\" return plan*sun_constraint def enforce_perennial_constraint(plan,plant,bed,year,perennials): \"\"\"Forward fill plan", "bed_info = pd.read_csv('../data/bed_data.csv') bed_info.index.name = 'bed_index' beds = bed_info.bed.to_numpy() bed_index", "requirements do not match. sun_constraint = np.ones(shape=(num_plants,num_beds,num_years)) for p in", "#initialize sun constraint. 1 where plant can feasibly be planted", "disease_plan.cumsum(axis=year_axis)>1 #multiply plan for specific problem plants by 0 disease_plan[problem_plants]", "bed_sun_req[b] if p_sun != b_sun: sun_constraint[p,b,:] = 0 def enforce_sun_constraint(plan,sun_constraint):", "a given bed/year, it will be 1 in same bed", "was a perennial, remove it from previous years elif plant_last_year", "= np.array(range(num_years)) #for keeping track of what axis is which", "in the garden. Counts the number of plants that are", "\"\"\" disease_plan = plan.copy() #mask to determine cases where same", "p_sun != b_sun: sun_constraint[p,b,:] = 0 def enforce_sun_constraint(plan,sun_constraint): \"\"\" Force", "previous make_neighbor call perennial_plan[plant,bed,year:] = 1 #sets plant to 1", "the current year #if what was planted already in this", "= plan.copy() #what was planted the year before plant_last_year =", "already in this bed was a perennial, remove it from", "1), loc='upper left', borderaxespad=0) ax.set_title('Objective Values of Current Solution by", "quantities.\"\"\" plan_yummy = plan.copy() plan_by_plant = plan_yummy.sum(axis=(bed_axis,year_axis)) yums = round(np.dot(preferences,plan_by_plant)/max_yums*100,1)", "ax def visualize_plan(bed_info,bed_index,years): for year in years: garden_viz = visualize_garden(bed_info)", "plan for specific problem plants by 0 disease_plan[problem_plants] = disease_plan[problem_plants]*(abs(1-same_veg_in_bed_yoy)[problem_plants])", "of what axis is which plant_axis = 0 bed_axis =", "df.columns = ['obj_value','yummy_scores','variety_scores']#,'yummy_score','variety_score'] df.reset_index(inplace=True) df = df.melt(id_vars=['index'],var_name='objective') fig, ax =", "= np.average(plant_info[family],axis=1,weights=[.5,.5,0,0,0]) plant_info.drop(family,axis=1,inplace=True) preferences = plant_info.avg_pref.to_numpy() #bed info bed_info =", "1 year_axis = 2 ##### Constraints ##### #initialize sun constraint.", "= plt.subplots(figsize=(20,8)) sb.scatterplot(data=df,x='index',y='value',hue='objective',edgecolor=None,s=5) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0) ax.set_title('Objective Values", "= 'bed_index' beds = bed_info.bed.to_numpy() bed_index = bed_info.index.to_numpy() bed_sun_req =", "year in years: garden_viz = visualize_garden(bed_info) garden_viz.set_title(f'Year {year}') for bed", "plant_info.iloc[plant_idx]['name'] bed_plan.append(plant) bed_info[f'year_{t+1}'] = pd.Series(bed_plan) return bed_info def visualize_obj_iters(current_plan_obj_values): objectives", "for each plant. Maximization encourages plants with higher preferences to", "across all beds. Then counts the number of plants with", "= 0 # zeros out anything else that may have" ]
[ "model.register_backward_hook(backward_counter) average_forwards, average_backwards = [], [] # number of forward", "not None: callback.reset_windows() adv_inputs = inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks, 0)", "0 or adv_inputs.max() > 1: warnings.warn('Values of produced adversarials are", "metrics.keys()} metrics = {k: v().to(device) if (isclass(v.func) if isinstance(v, partial)", "threshold=16, edgeitems=3, linewidth=120) # To print arrays with less precision", "as labels. \"\"\" random = torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float) random.scatter_(1,", "fail = bool(success.mean() != 1) print('Attack success: {:.2%}'.format(success.mean()) + fail", "- Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(), metrics['logit_diff_adv'].numpy().mean())) print('NLL of target/pred class:", "l1_distances), ('l2', l2_distances), ]) def compute_attack_metrics(model: nn.Module, attack_data: Dict[str, Union[Tensor,", "Number of classes to generate the random targets from. Returns", "labels, adv_inputs]] all_predictions = [[] for _ in range(6)] distances", "/ len(chunks[0]), } return data _default_metrics = OrderedDict([ ('linf', linf_distances),", "None, 'preds': preds, 'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig, 'success': success, 'probs_orig':", "for chunk in [inputs_chunk, adv_chunk]] list(map(append, all_predictions, [*clean_preds, *adv_preds])) for", "Generates all possible targets that are different from the original", "tensor in [inputs[not_adv], adv_labels[not_adv]]] total_time = 0 for (inputs_chunk, label_chunk)", "= torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other =", "of classes to generate the random targets from. Returns -------", "{:.3f} - Median: {:.3f}'.format(distance, data, data.mean(), np.median(data)) + fail *", "= torch.tensor(other_labels) return all_possible_targets def run_attack(model: nn.Module, inputs: Tensor, labels:", "- max_Logit(other classes): {} - Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(), metrics['logit_diff_adv'].numpy().mean()))", "= torch.cat(advs_chunks, 0) data = { 'inputs': inputs, 'labels': labels,", "Dict[str, Union[Tensor, float]], batch_size: Optional[int] = None, metrics: Dict[str, Callable]", "\"\"\" Generates one random target in (num_classes - 1) possibilities", "run_attack(model: nn.Module, inputs: Tensor, labels: Tensor, attack: Callable, targets: Optional[Tensor]", "{k: v().to(device) if (isclass(v.func) if isinstance(v, partial) else False) else", "already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv, 0) start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)", "BackwardCounter, predict_inputs def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor: \"\"\"", "preds_adv, 'accuracy_orig': accuracy_orig, 'success': success, 'probs_orig': prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv':", "torch.cuda.Event(enable_timing=True) forward_counter, backward_counter = ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >=", "list(map(append, all_predictions, [*clean_preds, *adv_preds])) for metric, metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk,", "for each label that is different from the original label.", "average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial) and", "torch import Tensor, nn from torch.nn import functional as F", "targets for each label. shape: (len(labels), num_classes - 1). \"\"\"", "possibilities for each label that is different from the original", "the random targets from. Returns ------- targets: Tensor Random target", "real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other = (logits_adv - labels_infhot).max(1).values diff_vs_max_adv", "{} - Average: {:.3f} - Median: {:.3f}'.format(distance, data, data.mean(), np.median(data))", "the same shape as labels. \"\"\" random = torch.rand(len(labels), num_classes,", "fail * ' - {}'.format(success)) for distance, values in metrics['distances'].items():", "1) possibilities for each label that is different from the", "l0_distances, l1_distances, l2_distances, linf_distances from adv_lib.utils import ForwardCounter, BackwardCounter, predict_inputs", "is different from the original label. Parameters ---------- labels: Tensor", "= False, labels if targets is not None: targeted, adv_labels", "with less precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in: {:.2f}s", "False) else v for k, v in metrics.items()} append =", "attack_type = 'targets' if metrics['targeted'] else 'correct' print('Logit({} class) -", "labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other", "forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial) and (callback := attack.keywords.get('callback'))", "list, data: list.append(data.cpu()) for inputs_chunk, labels_chunk, adv_chunk in zip(*chunks): inputs_chunk,", "original label. Parameters ---------- labels: Tensor Original labels. Generated targets", "metrics['success'].numpy() fail = bool(success.mean() != 1) print('Attack success: {:.2%}'.format(success.mean()) +", "list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels) return all_possible_targets def run_attack(model: nn.Module, inputs:", "[inputs_chunk, adv_chunk]] list(map(append, all_predictions, [*clean_preds, *adv_preds])) for metric, metric_func in", "from. Returns ------- targets: Tensor Random target for each label.", "num_classes - 1). \"\"\" all_possible_targets = torch.zeros(len(labels), num_classes - 1,", "len(inputs) chunks = [tensor.split(batch_size) for tensor in [inputs, labels, adv_inputs]]", "labels = targets else: success = (preds_adv != labels) prob_orig", "= { 'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted': targets", "in [inputs[not_adv], adv_labels[not_adv]]] total_time = 0 for (inputs_chunk, label_chunk) in", "targets that are different from the original labels. Parameters ----------", "label. shape: (len(labels), num_classes - 1). \"\"\" all_possible_targets = torch.zeros(len(labels),", "[], [] # number of forward and backward calls per", "isclass from typing import Callable, Optional, Dict, Union import numpy", "[tensor.split(batch_size) for tensor in [inputs, labels, adv_inputs]] all_predictions = [[]", "Returns ------- targets: Tensor Random targets for each label. shape:", "------- targets: Tensor Random targets for each label. shape: (len(labels),", "True, targets batch_size = batch_size or len(inputs) # run attack", "for tensor in [inputs, adv_labels]] for (inputs_chunk, label_chunk) in zip(*chunks):", "= ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else:", "for (inputs_chunk, label_chunk) in zip(*chunks): batch_chunk_d, label_chunk_d = [to_device(tensor) for", "in metrics.items()} append = lambda list, data: list.append(data.cpu()) for inputs_chunk,", "[torch.cat(l) for l in all_predictions] for metric in metrics.keys(): distances[metric]", "num_classes - 1, dtype=torch.long) all_classes = set(range(num_classes)) for i in", "isinstance(v, partial) else False) else v for k, v in", "batch_size or len(inputs) chunks = [tensor.split(batch_size) for tensor in [inputs,", "Tensor, nn from torch.nn import functional as F from adv_lib.distances.lp_norms", "]) def compute_attack_metrics(model: nn.Module, attack_data: Dict[str, Union[Tensor, float]], batch_size: Optional[int]", "else False) else v for k, v in metrics.items()} append", "1000 # times for cuda Events are in milliseconds average_forwards.append(forward_counter.num_samples_called", "from the original label. Parameters ---------- labels: Tensor Original labels.", "zip(*chunks): inputs_chunk, adv_chunk = map(to_device, [inputs_chunk, adv_chunk]) clean_preds, adv_preds =", "total_time = 0 for (inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])):", "in the [0, 1] range -> Clipping to [0, 1].')", "nll_adv, 'distances': distances, } return data def print_metrics(metrics: dict) ->", "* ' - {}'.format(success)) for distance, values in metrics['distances'].items(): data", "logits_adv, probs_adv, preds_adv = [torch.cat(l) for l in all_predictions] for", "------- targets: Tensor Random target for each label. Has the", "inspect import isclass from typing import Callable, Optional, Dict, Union", "print('{}: {} - Average: {:.3f} - Median: {:.3f}'.format(distance, data, data.mean(),", "if isinstance(v, partial) else False) else v for k, v", "label. Parameters ---------- labels: Tensor Original labels. Generated targets will", "labels) prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot", "F.cross_entropy(logits_adv, labels, reduction='none') data = { 'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'],", "success, 'probs_orig': prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll': nll, 'nll_adv':", "Callable, Optional, Dict, Union import numpy as np import torch", "targets: Optional[Tensor] = None, batch_size: Optional[int] = None) -> dict:", "[] for k in metrics.keys()} metrics = {k: v().to(device) if", "Callable, targets: Optional[Tensor] = None, batch_size: Optional[int] = None) ->", "Optional[int] = None, metrics: Dict[str, Callable] = _default_metrics) -> Dict[str,", "v in metrics.items()} append = lambda list, data: list.append(data.cpu()) for", "is_adv = (preds == label_chunk_d) if targeted else (preds !=", "prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll': nll, 'nll_adv': nll_adv, 'distances': distances, }", "attack(model, batch_chunk_d, label_chunk_d, targeted=targeted) # performance monitoring end.record() torch.cuda.synchronize() total_time", "diff_vs_max_adv, 'nll': nll, 'nll_adv': nll_adv, 'distances': distances, } return data", "'num_forwards': sum(average_forwards) / len(chunks[0]), 'num_backwards': sum(average_backwards) / len(chunks[0]), } return", "= map(attack_data.get, ['inputs', 'labels', 'targets', 'adv_inputs']) if adv_inputs.min() < 0", "1). \"\"\" all_possible_targets = torch.zeros(len(labels), num_classes - 1, dtype=torch.long) all_classes", "< 0 or adv_inputs.max() > 1: warnings.warn('Values of produced adversarials", "tensor in [inputs_chunk, label_chunk]] preds = model(batch_chunk_d).argmax(1) is_adv = (preds", "(preds != label_chunk_d) already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv, 0) start, end", "start.record() advs_chunk_d = attack(model, batch_chunk_d, label_chunk_d, targeted=targeted) # performance monitoring", "or len(inputs) chunks = [tensor.split(batch_size) for tensor in [inputs, labels,", "{:.3f}'.format(data[success].mean())) attack_type = 'targets' if metrics['targeted'] else 'correct' print('Logit({} class)", "- Median: {:.3f}'.format(distance, data, data.mean(), np.median(data)) + fail * '", "generate the random targets from. Returns ------- targets: Tensor Random", "backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial) and (callback := attack.keywords.get('callback')) is", "metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs, preds, logits_adv, probs_adv, preds_adv =", "range(len(labels)): this_label = labels[i].item() other_labels = list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels)", "= [] chunks = [tensor.split(batch_size) for tensor in [inputs[not_adv], adv_labels[not_adv]]]", "} return data def print_metrics(metrics: dict) -> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format},", "forward_counter, backward_counter = ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >= LooseVersion('1.8'):", "done in: {:.2f}s with {:.4g} forwards and {:.4g} backwards.'.format( metrics['time'],", "= [[] for _ in range(6)] distances = {k: []", "float]]: inputs, labels, targets, adv_inputs = map(attack_data.get, ['inputs', 'labels', 'targets',", "{}'.format(success)) for distance, values in metrics['distances'].items(): data = values.numpy() print('{}:", "label_chunk_d, targeted=targeted) # performance monitoring end.record() torch.cuda.synchronize() total_time += (start.elapsed_time(end))", "logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other = (logits_adv - labels_infhot).max(1).values diff_vs_max_adv = (real", "functools import partial from inspect import isclass from typing import", "= list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels) return all_possible_targets def run_attack(model: nn.Module,", "advs_chunks = [] chunks = [tensor.split(batch_size) for tensor in [inputs[not_adv],", "= lambda list, data: list.append(data.cpu()) for inputs_chunk, labels_chunk, adv_chunk in", "(logits_adv - labels_infhot).max(1).values diff_vs_max_adv = (real - other) nll =", "zip(*chunks): batch_chunk_d, label_chunk_d = [to_device(tensor) for tensor in [inputs_chunk, label_chunk]]", "average_backwards = [], [] # number of forward and backward", "metric, metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs, preds, logits_adv,", "labels: Tensor Original labels. Generated targets will be different from", "{ 'inputs': inputs, 'labels': labels, 'targets': adv_labels if targeted else", "_ in range(6)] distances = {k: [] for k in", "(num_classes - 1) possibilities for each label that is different", "- 1, dtype=torch.long) all_classes = set(range(num_classes)) for i in range(len(labels)):", "typing import Callable, Optional, Dict, Union import numpy as np", "in zip(*chunks): batch_chunk_d, label_chunk_d = [to_device(tensor) for tensor in [inputs_chunk,", "all possible targets that are different from the original labels.", "len(chunks[0]), } return data _default_metrics = OrderedDict([ ('linf', linf_distances), ('l0',", "[inputs, labels, adv_inputs]] all_predictions = [[] for _ in range(6)]", "for distance, values in metrics['distances'].items(): data = values.numpy() print('{}: {}", "with {:.4g} forwards and {:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success", "torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other = (logits_adv", "and {:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success = metrics['success'].numpy() fail", "Tensor, num_classes: int) -> Tensor: \"\"\" Generates one random target", "backward calls per sample advs_chunks = [] chunks = [tensor.split(batch_size)", "(inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d = [to_device(tensor.clone())", "adv_labels if targeted else None, 'adv_inputs': adv_inputs, 'time': total_time, 'num_forwards':", "Tensor Random targets for each label. shape: (len(labels), num_classes -", "None: success = (preds_adv == targets) labels = targets else:", "import l0_distances, l1_distances, l2_distances, linf_distances from adv_lib.utils import ForwardCounter, BackwardCounter,", "int) -> Tensor: \"\"\" Generates one random target in (num_classes", "= values.numpy() print('{}: {} - Average: {:.3f} - Median: {:.3f}'.format(distance,", "= inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks, 0) data = { 'inputs':", "batch_size = batch_size or len(inputs) chunks = [tensor.split(batch_size) for tensor", "collections import OrderedDict from distutils.version import LooseVersion from functools import", "Generated targets will be different from labels. num_classes: int Number", "possible targets that are different from the original labels. Parameters", "linf_distances), ('l0', l0_distances), ('l1', l1_distances), ('l2', l2_distances), ]) def compute_attack_metrics(model:", "the random targets from. Returns ------- targets: Tensor Random targets", "= 'targets' if metrics['targeted'] else 'correct' print('Logit({} class) - max_Logit(other", "Dict, Union import numpy as np import torch import tqdm", "{} - Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(), metrics['logit_diff_adv'].numpy().mean())) print('NLL of target/pred", "lambda tensor: tensor.to(device) targeted, adv_labels = False, labels if targets", "max=1) device = next(model.parameters()).device to_device = lambda tensor: tensor.to(device) batch_size", "inputs: Tensor, labels: Tensor, attack: Callable, targets: Optional[Tensor] = None,", "adv_labels = False, labels if targets is not None: targeted,", "from. Returns ------- targets: Tensor Random targets for each label.", "monitoring end.record() torch.cuda.synchronize() total_time += (start.elapsed_time(end)) / 1000 # times", "preds_adv = [torch.cat(l) for l in all_predictions] for metric in", "= [predict_inputs(model, chunk.to(device)) for chunk in [inputs_chunk, adv_chunk]] list(map(append, all_predictions,", "# number of forward and backward calls per sample advs_chunks", "Dict[str, Callable] = _default_metrics) -> Dict[str, Union[Tensor, float]]: inputs, labels,", "v().to(device) if (isclass(v.func) if isinstance(v, partial) else False) else v", "('linf', linf_distances), ('l0', l0_distances), ('l1', l1_distances), ('l2', l2_distances), ]) def", "[inputs, adv_labels]] for (inputs_chunk, label_chunk) in zip(*chunks): batch_chunk_d, label_chunk_d =", "Tensor: \"\"\" Generates one random target in (num_classes - 1)", "in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d = [to_device(tensor.clone()) for tensor", "+= (start.elapsed_time(end)) / 1000 # times for cuda Events are", "model(batch_chunk_d).argmax(1) is_adv = (preds == label_chunk_d) if targeted else (preds", "= [tensor.split(batch_size) for tensor in [inputs, labels, adv_inputs]] all_predictions =", "- labels_infhot).max(1).values diff_vs_max_adv = (real - other) nll = F.cross_entropy(logits,", "else 'correct' print('Logit({} class) - max_Logit(other classes): {} - Average:", "float('inf')) real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other = (logits_adv - labels_infhot).max(1).values", "Dict[str, Union[Tensor, float]]: inputs, labels, targets, adv_inputs = map(attack_data.get, ['inputs',", "chunks = [tensor.split(batch_size) for tensor in [inputs[not_adv], adv_labels[not_adv]]] total_time =", "(len(labels), num_classes - 1). \"\"\" all_possible_targets = torch.zeros(len(labels), num_classes -", "probs, preds, logits_adv, probs_adv, preds_adv = [torch.cat(l) for l in", "= model(batch_chunk_d).argmax(1) is_adv = (preds == label_chunk_d) if targeted else", "label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d = [to_device(tensor.clone()) for", "1] range -> Clipping to [0, 1].') adv_inputs.clamp_(min=0, max=1) device", "warnings from collections import OrderedDict from distutils.version import LooseVersion from", "adv_chunk = map(to_device, [inputs_chunk, adv_chunk]) clean_preds, adv_preds = [predict_inputs(model, chunk.to(device))", "' - {}'.format(success)) for distance, values in metrics['distances'].items(): data =", "same shape as labels. \"\"\" random = torch.rand(len(labels), num_classes, device=labels.device,", "ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d = [to_device(tensor.clone()) for tensor in [inputs_chunk,", "in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs, preds, logits_adv, probs_adv, preds_adv", "== label_chunk_d) if targeted else (preds != label_chunk_d) already_adv.append(is_adv.cpu()) not_adv", "targets) labels = targets else: success = (preds_adv != labels)", "the original labels. Parameters ---------- labels: Tensor Original labels. Generated", "only on non already adversarial samples already_adv = [] chunks", "for cuda Events are in milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called", "in metrics['distances'].items(): data = values.numpy() print('{}: {} - Average: {:.3f}", "targets is not None: success = (preds_adv == targets) labels", "nn.Module, inputs: Tensor, labels: Tensor, attack: Callable, targets: Optional[Tensor] =", "/ len(chunks[0]), 'num_backwards': sum(average_backwards) / len(chunks[0]), } return data _default_metrics", "'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted': targets is not", "distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs, preds, logits_adv, probs_adv, preds_adv = [torch.cat(l)", "False, labels if targets is not None: targeted, adv_labels =", "= [to_device(tensor.clone()) for tensor in [inputs_chunk, label_chunk]] start.record() advs_chunk_d =", "'labels', 'targets', 'adv_inputs']) if adv_inputs.min() < 0 or adv_inputs.max() >", "success = (preds_adv != labels) prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv", "distances = {k: [] for k in metrics.keys()} metrics =", "= logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other = (logits_adv - labels_infhot).max(1).values diff_vs_max_adv =", "def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor: \"\"\" Generates one", "0) return random.argmax(1) def get_all_targets(labels: Tensor, num_classes: int): \"\"\" Generates", "- 1) possibilities for each label that is different from", "LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards, average_backwards = [], [] #", "targets: Tensor Random target for each label. Has the same", "'distances': distances, } return data def print_metrics(metrics: dict) -> None:", "labels, reduction='none') data = { 'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards':", "label. Has the same shape as labels. \"\"\" random =", "model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards, average_backwards", "batch_chunk_d, label_chunk_d = [to_device(tensor) for tensor in [inputs_chunk, label_chunk]] preds", "# To print arrays with less precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig']))", "for k, v in metrics.items()} append = lambda list, data:", "(isclass(v.func) if isinstance(v, partial) else False) else v for k,", "to [0, 1].') adv_inputs.clamp_(min=0, max=1) device = next(model.parameters()).device to_device =", "backward_counter = ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter)", "1: warnings.warn('Values of produced adversarials are not in the [0,", "Returns ------- targets: Tensor Random target for each label. Has", "torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0) return random.argmax(1) def", "def run_attack(model: nn.Module, inputs: Tensor, labels: Tensor, attack: Callable, targets:", "shape: (len(labels), num_classes - 1). \"\"\" all_possible_targets = torch.zeros(len(labels), num_classes", "print('Attack done in: {:.2f}s with {:.4g} forwards and {:.4g} backwards.'.format(", "'targeted': targets is not None, 'preds': preds, 'adv_preds': preds_adv, 'accuracy_orig':", "* ' | Avg over success: {:.3f}'.format(data[success].mean())) attack_type = 'targets'", "num_classes: int Number of classes to generate the random targets", "non already adversarial samples already_adv = [] chunks = [tensor.split(batch_size)", "= None, metrics: Dict[str, Callable] = _default_metrics) -> Dict[str, Union[Tensor,", "next(model.parameters()).device to_device = lambda tensor: tensor.to(device) targeted, adv_labels = False,", "class) - max_Logit(other classes): {} - Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(),", "chunk.to(device)) for chunk in [inputs_chunk, adv_chunk]] list(map(append, all_predictions, [*clean_preds, *adv_preds]))", "Random targets for each label. shape: (len(labels), num_classes - 1).", "import warnings from collections import OrderedDict from distutils.version import LooseVersion", "chunks = [tensor.split(batch_size) for tensor in [inputs, adv_labels]] for (inputs_chunk,", "inputs_chunk).detach().cpu()) logits, probs, preds, logits_adv, probs_adv, preds_adv = [torch.cat(l) for", "# times for cuda Events are in milliseconds average_forwards.append(forward_counter.num_samples_called /", "return data _default_metrics = OrderedDict([ ('linf', linf_distances), ('l0', l0_distances), ('l1',", "that is different from the original label. Parameters ---------- labels:", "= (preds_adv != labels) prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv =", "if targeted else (preds != label_chunk_d) already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv,", "targets batch_size = batch_size or len(inputs) # run attack only", "def get_all_targets(labels: Tensor, num_classes: int): \"\"\" Generates all possible targets", "targets will be different from labels. num_classes: int Number of", "-> Clipping to [0, 1].') adv_inputs.clamp_(min=0, max=1) device = next(model.parameters()).device", "None, metrics: Dict[str, Callable] = _default_metrics) -> Dict[str, Union[Tensor, float]]:", "nn from torch.nn import functional as F from adv_lib.distances.lp_norms import", "forwards and {:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success = metrics['success'].numpy()", "'targets': adv_labels if targeted else None, 'adv_inputs': adv_inputs, 'time': total_time,", "{:.2%}'.format(success.mean()) + fail * ' - {}'.format(success)) for distance, values", "= batch_size or len(inputs) # run attack only on non", "tensor in [inputs_chunk, label_chunk]] start.record() advs_chunk_d = attack(model, batch_chunk_d, label_chunk_d,", "attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted': targets is not None, 'preds': preds,", "callback.reset_windows() adv_inputs = inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks, 0) data =", "reduction='none') data = { 'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'],", "total_time += (start.elapsed_time(end)) / 1000 # times for cuda Events", "OrderedDict([ ('linf', linf_distances), ('l0', l0_distances), ('l1', l1_distances), ('l2', l2_distances), ])", "= batch_size or len(inputs) chunks = [tensor.split(batch_size) for tensor in", "labels).float().mean().item() if targets is not None: success = (preds_adv ==", "is not None: targeted, adv_labels = True, targets batch_size =", "run attack only on non already adversarial samples already_adv =", "0) data = { 'inputs': inputs, 'labels': labels, 'targets': adv_labels", "= lambda tensor: tensor.to(device) targeted, adv_labels = False, labels if", "nn.Module, attack_data: Dict[str, Union[Tensor, float]], batch_size: Optional[int] = None, metrics:", "tensor in [inputs, adv_labels]] for (inputs_chunk, label_chunk) in zip(*chunks): batch_chunk_d,", "label_chunk_d = [to_device(tensor) for tensor in [inputs_chunk, label_chunk]] preds =", "= [to_device(tensor) for tensor in [inputs_chunk, label_chunk]] preds = model(batch_chunk_d).argmax(1)", "*adv_preds])) for metric, metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs,", "l2_distances), ]) def compute_attack_metrics(model: nn.Module, attack_data: Dict[str, Union[Tensor, float]], batch_size:", "numpy as np import torch import tqdm from torch import", "number of forward and backward calls per sample advs_chunks =", "adv_labels[not_adv]]] total_time = 0 for (inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80,", "print('Attack success: {:.2%}'.format(success.mean()) + fail * ' - {}'.format(success)) for", "tensor.to(device) targeted, adv_labels = False, labels if targets is not", "int): \"\"\" Generates all possible targets that are different from", "partial from inspect import isclass from typing import Callable, Optional,", "chunk in [inputs_chunk, adv_chunk]] list(map(append, all_predictions, [*clean_preds, *adv_preds])) for metric,", "labels if targets is not None: targeted, adv_labels = True,", "torch.zeros(len(labels), num_classes - 1, dtype=torch.long) all_classes = set(range(num_classes)) for i", "in range(6)] distances = {k: [] for k in metrics.keys()}", "labels_infhot).max(1).values diff_vs_max_adv = (real - other) nll = F.cross_entropy(logits, labels,", "metrics['num_backwards'])) success = metrics['success'].numpy() fail = bool(success.mean() != 1) print('Attack", "distance, values in metrics['distances'].items(): data = values.numpy() print('{}: {} -", "for i in range(len(labels)): this_label = labels[i].item() other_labels = list(all_classes.difference({this_label}))", "is not None, 'preds': preds, 'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig, 'success':", "- {}'.format(success)) for distance, values in metrics['distances'].items(): data = values.numpy()", "tensor.to(device) batch_size = batch_size or len(inputs) chunks = [tensor.split(batch_size) for", "\"\"\" Generates all possible targets that are different from the", "Union import numpy as np import torch import tqdm from", "random targets from. Returns ------- targets: Tensor Random targets for", "targeted else (preds != label_chunk_d) already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv, 0)", "inputs, labels, targets, adv_inputs = map(attack_data.get, ['inputs', 'labels', 'targets', 'adv_inputs'])", "labels_chunk, adv_chunk in zip(*chunks): inputs_chunk, adv_chunk = map(to_device, [inputs_chunk, adv_chunk])", "1, dtype=torch.long) all_classes = set(range(num_classes)) for i in range(len(labels)): this_label", "is not None: success = (preds_adv == targets) labels =", "metrics.items()} append = lambda list, data: list.append(data.cpu()) for inputs_chunk, labels_chunk,", "print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in: {:.2f}s with {:.4g} forwards", "end.record() torch.cuda.synchronize() total_time += (start.elapsed_time(end)) / 1000 # times for", "torch.cat(advs_chunks, 0) data = { 'inputs': inputs, 'labels': labels, 'targets':", "prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll': nll, 'nll_adv': nll_adv, 'distances':", "np.median(data)) + fail * ' | Avg over success: {:.3f}'.format(data[success].mean()))", "[inputs_chunk, adv_chunk]) clean_preds, adv_preds = [predict_inputs(model, chunk.to(device)) for chunk in", "target in (num_classes - 1) possibilities for each label that", "data.mean(), np.median(data)) + fail * ' | Avg over success:", "= None) -> dict: device = next(model.parameters()).device to_device = lambda", "produced adversarials are not in the [0, 1] range ->", "map(attack_data.get, ['inputs', 'labels', 'targets', 'adv_inputs']) if adv_inputs.min() < 0 or", "[0, 1] range -> Clipping to [0, 1].') adv_inputs.clamp_(min=0, max=1)", "= (logits_adv - labels_infhot).max(1).values diff_vs_max_adv = (real - other) nll", "from torch import Tensor, nn from torch.nn import functional as", "num_classes: int) -> Tensor: \"\"\" Generates one random target in", "each label that is different from the original label. Parameters", "data, data.mean(), np.median(data)) + fail * ' | Avg over", "= True, targets batch_size = batch_size or len(inputs) # run", "batch_chunk_d, label_chunk_d = [to_device(tensor.clone()) for tensor in [inputs_chunk, label_chunk]] start.record()", "different from the original labels. Parameters ---------- labels: Tensor Original", "adv_inputs = inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks, 0) data = {", "Tensor, attack: Callable, targets: Optional[Tensor] = None, batch_size: Optional[int] =", "or len(inputs) # run attack only on non already adversarial", "== targets) labels = targets else: success = (preds_adv !=", "data = { 'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted':", "performance monitoring end.record() torch.cuda.synchronize() total_time += (start.elapsed_time(end)) / 1000 #", "if targeted else None, 'adv_inputs': adv_inputs, 'time': total_time, 'num_forwards': sum(average_forwards)", "adv_inputs.min() < 0 or adv_inputs.max() > 1: warnings.warn('Values of produced", "'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig, 'success': success, 'probs_orig': prob_orig, 'probs_adv': prob_adv,", "different from labels. num_classes: int Number of classes to generate", "max_Logit(other classes): {} - Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(), metrics['logit_diff_adv'].numpy().mean())) print('NLL", "(inputs_chunk, label_chunk) in zip(*chunks): batch_chunk_d, label_chunk_d = [to_device(tensor) for tensor", "success: {:.3f}'.format(data[success].mean())) attack_type = 'targets' if metrics['targeted'] else 'correct' print('Logit({}", "end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter = ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter)", "Random target for each label. Has the same shape as", "adversarial samples already_adv = [] chunks = [tensor.split(batch_size) for tensor", "partial) and (callback := attack.keywords.get('callback')) is not None: callback.reset_windows() adv_inputs", "Optional[Tensor] = None, batch_size: Optional[int] = None) -> dict: device", "l1_distances, l2_distances, linf_distances from adv_lib.utils import ForwardCounter, BackwardCounter, predict_inputs def", "if (isclass(v.func) if isinstance(v, partial) else False) else v for", "import functional as F from adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances,", "dict: device = next(model.parameters()).device to_device = lambda tensor: tensor.to(device) targeted,", "inputs_chunk, labels_chunk, adv_chunk in zip(*chunks): inputs_chunk, adv_chunk = map(to_device, [inputs_chunk,", "partial) else False) else v for k, v in metrics.items()}", "that are different from the original labels. Parameters ---------- labels:", "functional as F from adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances, linf_distances", "= {k: [] for k in metrics.keys()} metrics = {k:", "Generates one random target in (num_classes - 1) possibilities for", "adv_lib.utils import ForwardCounter, BackwardCounter, predict_inputs def generate_random_targets(labels: Tensor, num_classes: int)", "list.append(data.cpu()) for inputs_chunk, labels_chunk, adv_chunk in zip(*chunks): inputs_chunk, adv_chunk =", ">= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards, average_backwards = [], []", "less precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in: {:.2f}s with", "Union[Tensor, float]]: inputs, labels, targets, adv_inputs = map(attack_data.get, ['inputs', 'labels',", "Original labels. Generated targets will be different from labels. num_classes:", "= next(model.parameters()).device to_device = lambda tensor: tensor.to(device) targeted, adv_labels =", "not in the [0, 1] range -> Clipping to [0,", "original labels. Parameters ---------- labels: Tensor Original labels. Generated targets", "l0_distances), ('l1', l1_distances), ('l2', l2_distances), ]) def compute_attack_metrics(model: nn.Module, attack_data:", "lambda list, data: list.append(data.cpu()) for inputs_chunk, labels_chunk, adv_chunk in zip(*chunks):", "num_classes, device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0) return random.argmax(1) def get_all_targets(labels:", "target for each label. Has the same shape as labels.", "} return data _default_metrics = OrderedDict([ ('linf', linf_distances), ('l0', l0_distances),", "adv_inputs.clamp_(min=0, max=1) device = next(model.parameters()).device to_device = lambda tensor: tensor.to(device)", "Tensor, labels: Tensor, attack: Callable, targets: Optional[Tensor] = None, batch_size:", "Events are in milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d))", "metrics = {k: v().to(device) if (isclass(v.func) if isinstance(v, partial) else", "!= labels) prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1)", "sum(average_backwards) / len(chunks[0]), } return data _default_metrics = OrderedDict([ ('linf',", "None) -> dict: device = next(model.parameters()).device to_device = lambda tensor:", "# performance monitoring end.record() torch.cuda.synchronize() total_time += (start.elapsed_time(end)) / 1000", "[inputs_chunk, label_chunk]] start.record() advs_chunk_d = attack(model, batch_chunk_d, label_chunk_d, targeted=targeted) #", "forward and backward calls per sample advs_chunks = [] chunks", "batch_size or len(inputs) # run attack only on non already", "None: callback.reset_windows() adv_inputs = inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks, 0) data", "[to_device(tensor.clone()) for tensor in [inputs_chunk, label_chunk]] start.record() advs_chunk_d = attack(model,", "'time': total_time, 'num_forwards': sum(average_forwards) / len(chunks[0]), 'num_backwards': sum(average_backwards) / len(chunks[0]),", "already adversarial samples already_adv = [] chunks = [tensor.split(batch_size) for", "adv_chunk]) clean_preds, adv_preds = [predict_inputs(model, chunk.to(device)) for chunk in [inputs_chunk,", "Average: {:.3f} - Median: {:.3f}'.format(distance, data, data.mean(), np.median(data)) + fail", "ForwardCounter, BackwardCounter, predict_inputs def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor:", "will be different from labels. num_classes: int Number of classes", "k in metrics.keys()} metrics = {k: v().to(device) if (isclass(v.func) if", "targets is not None, 'preds': preds, 'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig,", "0) accuracy_orig = (preds == labels).float().mean().item() if targets is not", "= attack(model, batch_chunk_d, label_chunk_d, targeted=targeted) # performance monitoring end.record() torch.cuda.synchronize()", "torch.cat(distances[metric], 0) accuracy_orig = (preds == labels).float().mean().item() if targets is", "each label. shape: (len(labels), num_classes - 1). \"\"\" all_possible_targets =", "{k: [] for k in metrics.keys()} metrics = {k: v().to(device)", "- 1). \"\"\" all_possible_targets = torch.zeros(len(labels), num_classes - 1, dtype=torch.long)", "label_chunk]] start.record() advs_chunk_d = attack(model, batch_chunk_d, label_chunk_d, targeted=targeted) # performance", "Optional, Dict, Union import numpy as np import torch import", "range -> Clipping to [0, 1].') adv_inputs.clamp_(min=0, max=1) device =", "in range(len(labels)): this_label = labels[i].item() other_labels = list(all_classes.difference({this_label})) all_possible_targets[i] =", "-> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120) # To print", "labels, 'targets': adv_labels if targeted else None, 'adv_inputs': adv_inputs, 'time':", "prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot =", "Median: {:.3f}'.format(distance, data, data.mean(), np.median(data)) + fail * ' |", "adv_chunk in zip(*chunks): inputs_chunk, adv_chunk = map(to_device, [inputs_chunk, adv_chunk]) clean_preds,", "[] chunks = [tensor.split(batch_size) for tensor in [inputs, adv_labels]] for", "for _ in range(6)] distances = {k: [] for k", "labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1)", "batch_chunk_d, label_chunk_d, targeted=targeted) # performance monitoring end.record() torch.cuda.synchronize() total_time +=", "= map(to_device, [inputs_chunk, adv_chunk]) clean_preds, adv_preds = [predict_inputs(model, chunk.to(device)) for", "edgeitems=3, linewidth=120) # To print arrays with less precision print('Original", "for l in all_predictions] for metric in metrics.keys(): distances[metric] =", "accuracy_orig = (preds == labels).float().mean().item() if targets is not None:", "= (preds == labels).float().mean().item() if targets is not None: success", "in: {:.2f}s with {:.4g} forwards and {:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'],", "def compute_attack_metrics(model: nn.Module, attack_data: Dict[str, Union[Tensor, float]], batch_size: Optional[int] =", "device = next(model.parameters()).device to_device = lambda tensor: tensor.to(device) targeted, adv_labels", "torch.cuda.synchronize() total_time += (start.elapsed_time(end)) / 1000 # times for cuda", "[*clean_preds, *adv_preds])) for metric, metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits,", "F from adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances, linf_distances from adv_lib.utils", "sample advs_chunks = [] chunks = [tensor.split(batch_size) for tensor in", "in [inputs_chunk, adv_chunk]] list(map(append, all_predictions, [*clean_preds, *adv_preds])) for metric, metric_func", "success = metrics['success'].numpy() fail = bool(success.mean() != 1) print('Attack success:", "'success': success, 'probs_orig': prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll': nll,", "targets: Tensor Random targets for each label. shape: (len(labels), num_classes", "Parameters ---------- labels: Tensor Original labels. Generated targets will be", "in milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset()", "backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success = metrics['success'].numpy() fail = bool(success.mean()", "Tensor, num_classes: int): \"\"\" Generates all possible targets that are", "average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if", "float]], batch_size: Optional[int] = None, metrics: Dict[str, Callable] = _default_metrics)", "'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted': targets is not None, 'preds':", "= (preds == label_chunk_d) if targeted else (preds != label_chunk_d)", "None, batch_size: Optional[int] = None) -> dict: device = next(model.parameters()).device", "to_device = lambda tensor: tensor.to(device) batch_size = batch_size or len(inputs)", "tqdm from torch import Tensor, nn from torch.nn import functional", "else: success = (preds_adv != labels) prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1)", "= F.cross_entropy(logits, labels, reduction='none') nll_adv = F.cross_entropy(logits_adv, labels, reduction='none') data", "else: model.register_backward_hook(backward_counter) average_forwards, average_backwards = [], [] # number of", "random.scatter_(1, labels.unsqueeze(-1), 0) return random.argmax(1) def get_all_targets(labels: Tensor, num_classes: int):", "from torch.nn import functional as F from adv_lib.distances.lp_norms import l0_distances,", "/ 1000 # times for cuda Events are in milliseconds", "else None, 'adv_inputs': adv_inputs, 'time': total_time, 'num_forwards': sum(average_forwards) / len(chunks[0]),", "advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial) and (callback := attack.keywords.get('callback')) is not", "import isclass from typing import Callable, Optional, Dict, Union import", "== labels).float().mean().item() if targets is not None: success = (preds_adv", "arrays with less precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in:", "+ fail * ' - {}'.format(success)) for distance, values in", "import tqdm from torch import Tensor, nn from torch.nn import", "= metrics['success'].numpy() fail = bool(success.mean() != 1) print('Attack success: {:.2%}'.format(success.mean())", "per sample advs_chunks = [] chunks = [tensor.split(batch_size) for tensor", "attack.keywords.get('callback')) is not None: callback.reset_windows() adv_inputs = inputs.clone() adv_inputs[not_adv] =", "for each label. Has the same shape as labels. \"\"\"", "predict_inputs def generate_random_targets(labels: Tensor, num_classes: int) -> Tensor: \"\"\" Generates", "not_adv = ~torch.cat(already_adv, 0) start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter,", "inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks, 0) data = { 'inputs': inputs,", "(preds_adv == targets) labels = targets else: success = (preds_adv", "'targets', 'adv_inputs']) if adv_inputs.min() < 0 or adv_inputs.max() > 1:", "targeted, adv_labels = False, labels if targets is not None:", "print arrays with less precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done", "'nll': nll, 'nll_adv': nll_adv, 'distances': distances, } return data def", "random target in (num_classes - 1) possibilities for each label", "num_classes: int): \"\"\" Generates all possible targets that are different", "for tensor in [inputs[not_adv], adv_labels[not_adv]]] total_time = 0 for (inputs_chunk,", "= labels[i].item() other_labels = list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels) return all_possible_targets", "= next(model.parameters()).device to_device = lambda tensor: tensor.to(device) batch_size = batch_size", "for (inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d =", "metrics['targeted'] else 'correct' print('Logit({} class) - max_Logit(other classes): {} -", "and (callback := attack.keywords.get('callback')) is not None: callback.reset_windows() adv_inputs =", "compute_attack_metrics(model: nn.Module, attack_data: Dict[str, Union[Tensor, float]], batch_size: Optional[int] = None,", "all_predictions] for metric in metrics.keys(): distances[metric] = torch.cat(distances[metric], 0) accuracy_orig", "in metrics.keys()} metrics = {k: v().to(device) if (isclass(v.func) if isinstance(v,", "random = torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0) return", "as F from adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances, linf_distances from", "{ 'time': attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted': targets is", "labels, targets, adv_inputs = map(attack_data.get, ['inputs', 'labels', 'targets', 'adv_inputs']) if", "be different from labels. num_classes: int Number of classes to", "= 0 for (inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d,", "Has the same shape as labels. \"\"\" random = torch.rand(len(labels),", "in [inputs_chunk, label_chunk]] start.record() advs_chunk_d = attack(model, batch_chunk_d, label_chunk_d, targeted=targeted)", "import OrderedDict from distutils.version import LooseVersion from functools import partial", "targets from. Returns ------- targets: Tensor Random target for each", "torch.nn import functional as F from adv_lib.distances.lp_norms import l0_distances, l1_distances,", "None, 'adv_inputs': adv_inputs, 'time': total_time, 'num_forwards': sum(average_forwards) / len(chunks[0]), 'num_backwards':", "from functools import partial from inspect import isclass from typing", "print_metrics(metrics: dict) -> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120) #", "data = values.numpy() print('{}: {} - Average: {:.3f} - Median:", "next(model.parameters()).device to_device = lambda tensor: tensor.to(device) batch_size = batch_size or", "/ len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack,", "= (preds_adv == targets) labels = targets else: success =", "shape as labels. \"\"\" random = torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float)", "[[] for _ in range(6)] distances = {k: [] for", "(real - other) nll = F.cross_entropy(logits, labels, reduction='none') nll_adv =", "LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards, average_backwards = [],", "- other) nll = F.cross_entropy(logits, labels, reduction='none') nll_adv = F.cross_entropy(logits_adv,", "!= 1) print('Attack success: {:.2%}'.format(success.mean()) + fail * ' -", "attack_data: Dict[str, Union[Tensor, float]], batch_size: Optional[int] = None, metrics: Dict[str,", "(callback := attack.keywords.get('callback')) is not None: callback.reset_windows() adv_inputs = inputs.clone()", "clean_preds, adv_preds = [predict_inputs(model, chunk.to(device)) for chunk in [inputs_chunk, adv_chunk]]", "ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter)", "dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0) return random.argmax(1) def get_all_targets(labels: Tensor, num_classes:", "targets, adv_inputs = map(attack_data.get, ['inputs', 'labels', 'targets', 'adv_inputs']) if adv_inputs.min()", "for metric, metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs, preds,", "{:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in: {:.2f}s with {:.4g} forwards and {:.4g}", "from adv_lib.utils import ForwardCounter, BackwardCounter, predict_inputs def generate_random_targets(labels: Tensor, num_classes:", "label_chunk]] preds = model(batch_chunk_d).argmax(1) is_adv = (preds == label_chunk_d) if", "BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards,", "len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial) and (callback :=", "in [inputs_chunk, label_chunk]] preds = model(batch_chunk_d).argmax(1) is_adv = (preds ==", "= [], [] # number of forward and backward calls", "preds, logits_adv, probs_adv, preds_adv = [torch.cat(l) for l in all_predictions]", "(preds == labels).float().mean().item() if targets is not None: success =", "nll = F.cross_entropy(logits, labels, reduction='none') nll_adv = F.cross_entropy(logits_adv, labels, reduction='none')", "> 1: warnings.warn('Values of produced adversarials are not in the", "targets from. Returns ------- targets: Tensor Random targets for each", "[to_device(tensor) for tensor in [inputs_chunk, label_chunk]] preds = model(batch_chunk_d).argmax(1) is_adv", "start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter = ForwardCounter(), BackwardCounter()", "for tensor in [inputs, labels, adv_inputs]] all_predictions = [[] for", "from distutils.version import LooseVersion from functools import partial from inspect", "else v for k, v in metrics.items()} append = lambda", "import numpy as np import torch import tqdm from torch", "range(6)] distances = {k: [] for k in metrics.keys()} metrics", "already_adv = [] chunks = [tensor.split(batch_size) for tensor in [inputs,", "nll_adv = F.cross_entropy(logits_adv, labels, reduction='none') data = { 'time': attack_data['time'],", "[] # number of forward and backward calls per sample", "'num_backwards': attack_data['num_backwards'], 'targeted': targets is not None, 'preds': preds, 'adv_preds':", "data _default_metrics = OrderedDict([ ('linf', linf_distances), ('l0', l0_distances), ('l1', l1_distances),", "in all_predictions] for metric in metrics.keys(): distances[metric] = torch.cat(distances[metric], 0)", "in metrics.keys(): distances[metric] = torch.cat(distances[metric], 0) accuracy_orig = (preds ==", "# run attack only on non already adversarial samples already_adv", "_default_metrics = OrderedDict([ ('linf', linf_distances), ('l0', l0_distances), ('l1', l1_distances), ('l2',", "inputs_chunk, adv_chunk = map(to_device, [inputs_chunk, adv_chunk]) clean_preds, adv_preds = [predict_inputs(model,", "values in metrics['distances'].items(): data = values.numpy() print('{}: {} - Average:", "= (real - other) nll = F.cross_entropy(logits, labels, reduction='none') nll_adv", "!= label_chunk_d) already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv, 0) start, end =", "if LooseVersion(torch.__version__) >= LooseVersion('1.8'): model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards, average_backwards =", "adv_inputs = map(attack_data.get, ['inputs', 'labels', 'targets', 'adv_inputs']) if adv_inputs.min() <", "[0, 1].') adv_inputs.clamp_(min=0, max=1) device = next(model.parameters()).device to_device = lambda", "metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu()) logits, probs, preds, logits_adv, probs_adv,", "/ len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial) and (callback", "or adv_inputs.max() > 1: warnings.warn('Values of produced adversarials are not", "'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll': nll, 'nll_adv': nll_adv, 'distances': distances,", "attack_data['num_backwards'], 'targeted': targets is not None, 'preds': preds, 'adv_preds': preds_adv,", "batch_size = batch_size or len(inputs) # run attack only on", "'accuracy_orig': accuracy_orig, 'success': success, 'probs_orig': prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv,", "values.numpy() print('{}: {} - Average: {:.3f} - Median: {:.3f}'.format(distance, data,", "for tensor in [inputs_chunk, label_chunk]] start.record() advs_chunk_d = attack(model, batch_chunk_d,", "metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success = metrics['success'].numpy() fail = bool(success.mean() !=", "= [] chunks = [tensor.split(batch_size) for tensor in [inputs, adv_labels]]", "tensor: tensor.to(device) batch_size = batch_size or len(inputs) chunks = [tensor.split(batch_size)", "for inputs_chunk, labels_chunk, adv_chunk in zip(*chunks): inputs_chunk, adv_chunk = map(to_device,", "other = (logits_adv - labels_infhot).max(1).values diff_vs_max_adv = (real - other)", "average_forwards, average_backwards = [], [] # number of forward and", "-> dict: device = next(model.parameters()).device to_device = lambda tensor: tensor.to(device)", "l in all_predictions] for metric in metrics.keys(): distances[metric] = torch.cat(distances[metric],", "[inputs[not_adv], adv_labels[not_adv]]] total_time = 0 for (inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks),", "to generate the random targets from. Returns ------- targets: Tensor", "_default_metrics) -> Dict[str, Union[Tensor, float]]: inputs, labels, targets, adv_inputs =", "inputs, 'labels': labels, 'targets': adv_labels if targeted else None, 'adv_inputs':", "{:.3f}'.format(distance, data, data.mean(), np.median(data)) + fail * ' | Avg", "not None: targeted, adv_labels = True, targets batch_size = batch_size", "if isinstance(attack, partial) and (callback := attack.keywords.get('callback')) is not None:", "of produced adversarials are not in the [0, 1] range", "nll, 'nll_adv': nll_adv, 'distances': distances, } return data def print_metrics(metrics:", "not None, 'preds': preds, 'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig, 'success': success,", "'preds': preds, 'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig, 'success': success, 'probs_orig': prob_orig,", "[tensor.split(batch_size) for tensor in [inputs[not_adv], adv_labels[not_adv]]] total_time = 0 for", "label_chunk_d = [to_device(tensor.clone()) for tensor in [inputs_chunk, label_chunk]] start.record() advs_chunk_d", "adv_labels = True, targets batch_size = batch_size or len(inputs) #", "targets is not None: targeted, adv_labels = True, targets batch_size", "import partial from inspect import isclass from typing import Callable,", "= set(range(num_classes)) for i in range(len(labels)): this_label = labels[i].item() other_labels", "Tensor Random target for each label. Has the same shape", "adv_preds = [predict_inputs(model, chunk.to(device)) for chunk in [inputs_chunk, adv_chunk]] list(map(append,", "classes): {} - Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(), metrics['logit_diff_adv'].numpy().mean())) print('NLL of", "labels. Generated targets will be different from labels. num_classes: int", "isinstance(attack, partial) and (callback := attack.keywords.get('callback')) is not None: callback.reset_windows()", "[inputs_chunk, label_chunk]] preds = model(batch_chunk_d).argmax(1) is_adv = (preds == label_chunk_d)", "from the original labels. Parameters ---------- labels: Tensor Original labels.", "for tensor in [inputs_chunk, label_chunk]] preds = model(batch_chunk_d).argmax(1) is_adv =", "= torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter = ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if", "all_classes = set(range(num_classes)) for i in range(len(labels)): this_label = labels[i].item()", "= probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real =", "cuda Events are in milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called /", "classes to generate the random targets from. Returns ------- targets:", "if targets is not None: success = (preds_adv == targets)", "data = { 'inputs': inputs, 'labels': labels, 'targets': adv_labels if", "metric in metrics.keys(): distances[metric] = torch.cat(distances[metric], 0) accuracy_orig = (preds", "= torch.zeros(len(labels), num_classes - 1, dtype=torch.long) all_classes = set(range(num_classes)) for", "Clipping to [0, 1].') adv_inputs.clamp_(min=0, max=1) device = next(model.parameters()).device to_device", "('l0', l0_distances), ('l1', l1_distances), ('l2', l2_distances), ]) def compute_attack_metrics(model: nn.Module,", "1].') adv_inputs.clamp_(min=0, max=1) device = next(model.parameters()).device to_device = lambda tensor:", "= lambda tensor: tensor.to(device) batch_size = batch_size or len(inputs) chunks", "distances, } return data def print_metrics(metrics: dict) -> None: np.set_printoptions(formatter={'float':", "= None, batch_size: Optional[int] = None) -> dict: device =", "'labels': labels, 'targets': adv_labels if targeted else None, 'adv_inputs': adv_inputs,", "= torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0) return random.argmax(1)", "to_device = lambda tensor: tensor.to(device) targeted, adv_labels = False, labels", "Union[Tensor, float]], batch_size: Optional[int] = None, metrics: Dict[str, Callable] =", "'{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120) # To print arrays with less", "probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1),", "(preds_adv != labels) prob_orig = probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1,", "linewidth=120) # To print arrays with less precision print('Original accuracy:", "1) print('Attack success: {:.2%}'.format(success.mean()) + fail * ' - {}'.format(success))", "-> Dict[str, Union[Tensor, float]]: inputs, labels, targets, adv_inputs = map(attack_data.get,", "preds = model(batch_chunk_d).argmax(1) is_adv = (preds == label_chunk_d) if targeted", "adv_labels]] for (inputs_chunk, label_chunk) in zip(*chunks): batch_chunk_d, label_chunk_d = [to_device(tensor)", "= [tensor.split(batch_size) for tensor in [inputs[not_adv], adv_labels[not_adv]]] total_time = 0", "probs_adv, preds_adv = [torch.cat(l) for l in all_predictions] for metric", "and backward calls per sample advs_chunks = [] chunks =", "label_chunk_d) already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv, 0) start, end = torch.cuda.Event(enable_timing=True),", "metrics.keys(): distances[metric] = torch.cat(distances[metric], 0) accuracy_orig = (preds == labels).float().mean().item()", "Avg over success: {:.3f}'.format(data[success].mean())) attack_type = 'targets' if metrics['targeted'] else", "advs_chunk_d = attack(model, batch_chunk_d, label_chunk_d, targeted=targeted) # performance monitoring end.record()", "from collections import OrderedDict from distutils.version import LooseVersion from functools", "from labels. num_classes: int Number of classes to generate the", "\"\"\" all_possible_targets = torch.zeros(len(labels), num_classes - 1, dtype=torch.long) all_classes =", "return random.argmax(1) def get_all_targets(labels: Tensor, num_classes: int): \"\"\" Generates all", "total=len(chunks[0])): batch_chunk_d, label_chunk_d = [to_device(tensor.clone()) for tensor in [inputs_chunk, label_chunk]]", "import Callable, Optional, Dict, Union import numpy as np import", "in [inputs, labels, adv_inputs]] all_predictions = [[] for _ in", "labels. \"\"\" random = torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1),", "batch_size: Optional[int] = None) -> dict: device = next(model.parameters()).device to_device", "accuracy_orig, 'success': success, 'probs_orig': prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll':", "for each label. shape: (len(labels), num_classes - 1). \"\"\" all_possible_targets", "return all_possible_targets def run_attack(model: nn.Module, inputs: Tensor, labels: Tensor, attack:", "adv_inputs.max() > 1: warnings.warn('Values of produced adversarials are not in", "for metric in metrics.keys(): distances[metric] = torch.cat(distances[metric], 0) accuracy_orig =", "are not in the [0, 1] range -> Clipping to", "'targets' if metrics['targeted'] else 'correct' print('Logit({} class) - max_Logit(other classes):", "'logit_diff_adv': diff_vs_max_adv, 'nll': nll, 'nll_adv': nll_adv, 'distances': distances, } return", "if targets is not None: targeted, adv_labels = True, targets", "adv_inputs[not_adv] = torch.cat(advs_chunks, 0) data = { 'inputs': inputs, 'labels':", "len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu()) if isinstance(attack, partial)", "Optional[int] = None) -> dict: device = next(model.parameters()).device to_device =", "all_possible_targets[i] = torch.tensor(other_labels) return all_possible_targets def run_attack(model: nn.Module, inputs: Tensor,", "milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(), backward_counter.reset() advs_chunks.append(advs_chunk_d.cpu())", "'nll_adv': nll_adv, 'distances': distances, } return data def print_metrics(metrics: dict)", "metrics['num_forwards'], metrics['num_backwards'])) success = metrics['success'].numpy() fail = bool(success.mean() != 1)", "device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0) return random.argmax(1) def get_all_targets(labels: Tensor,", "[tensor.split(batch_size) for tensor in [inputs, adv_labels]] for (inputs_chunk, label_chunk) in", "tensor in [inputs, labels, adv_inputs]] all_predictions = [[] for _", "probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real = logits_adv.gather(1,", "print('Logit({} class) - max_Logit(other classes): {} - Average: {:.2f}'.format( attack_type,", "attack only on non already adversarial samples already_adv = []", "dtype=torch.long) all_classes = set(range(num_classes)) for i in range(len(labels)): this_label =", "times for cuda Events are in milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d))", "from inspect import isclass from typing import Callable, Optional, Dict,", "fail * ' | Avg over success: {:.3f}'.format(data[success].mean())) attack_type =", "labels, reduction='none') nll_adv = F.cross_entropy(logits_adv, labels, reduction='none') data = {", "v for k, v in metrics.items()} append = lambda list,", "adv_chunk]] list(map(append, all_predictions, [*clean_preds, *adv_preds])) for metric, metric_func in metrics.items():", "set(range(num_classes)) for i in range(len(labels)): this_label = labels[i].item() other_labels =", "{:.2f}s with {:.4g} forwards and {:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards']))", "are different from the original labels. Parameters ---------- labels: Tensor", "metrics['distances'].items(): data = values.numpy() print('{}: {} - Average: {:.3f} -", "' | Avg over success: {:.3f}'.format(data[success].mean())) attack_type = 'targets' if", "not None: success = (preds_adv == targets) labels = targets", "None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120) # To print arrays", "[] chunks = [tensor.split(batch_size) for tensor in [inputs[not_adv], adv_labels[not_adv]]] total_time", "for k in metrics.keys()} metrics = {k: v().to(device) if (isclass(v.func)", "if adv_inputs.min() < 0 or adv_inputs.max() > 1: warnings.warn('Values of", "| Avg over success: {:.3f}'.format(data[success].mean())) attack_type = 'targets' if metrics['targeted']", "= F.cross_entropy(logits_adv, labels, reduction='none') data = { 'time': attack_data['time'], 'num_forwards':", "reduction='none') nll_adv = F.cross_entropy(logits_adv, labels, reduction='none') data = { 'time':", "the [0, 1] range -> Clipping to [0, 1].') adv_inputs.clamp_(min=0,", "adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances, linf_distances from adv_lib.utils import ForwardCounter,", "generate_random_targets(labels: Tensor, num_classes: int) -> Tensor: \"\"\" Generates one random", "map(to_device, [inputs_chunk, adv_chunk]) clean_preds, adv_preds = [predict_inputs(model, chunk.to(device)) for chunk", "bool(success.mean() != 1) print('Attack success: {:.2%}'.format(success.mean()) + fail * '", "model.register_full_backward_hook(backward_counter) else: model.register_backward_hook(backward_counter) average_forwards, average_backwards = [], [] # number", "adversarials are not in the [0, 1] range -> Clipping", "label that is different from the original label. Parameters ----------", "labels: Tensor, attack: Callable, targets: Optional[Tensor] = None, batch_size: Optional[int]", "def print_metrics(metrics: dict) -> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120)", "as np import torch import tqdm from torch import Tensor,", ":= attack.keywords.get('callback')) is not None: callback.reset_windows() adv_inputs = inputs.clone() adv_inputs[not_adv]", "attack: Callable, targets: Optional[Tensor] = None, batch_size: Optional[int] = None)", "is not None: callback.reset_windows() adv_inputs = inputs.clone() adv_inputs[not_adv] = torch.cat(advs_chunks,", "labels.unsqueeze(-1), 0) return random.argmax(1) def get_all_targets(labels: Tensor, num_classes: int): \"\"\"", "calls per sample advs_chunks = [] chunks = [tensor.split(batch_size) for", "['inputs', 'labels', 'targets', 'adv_inputs']) if adv_inputs.min() < 0 or adv_inputs.max()", "Callable] = _default_metrics) -> Dict[str, Union[Tensor, float]]: inputs, labels, targets,", "else (preds != label_chunk_d) already_adv.append(is_adv.cpu()) not_adv = ~torch.cat(already_adv, 0) start,", "'adv_inputs': adv_inputs, 'time': total_time, 'num_forwards': sum(average_forwards) / len(chunks[0]), 'num_backwards': sum(average_backwards)", "'probs_orig': prob_orig, 'probs_adv': prob_adv, 'logit_diff_adv': diff_vs_max_adv, 'nll': nll, 'nll_adv': nll_adv,", "other) nll = F.cross_entropy(logits, labels, reduction='none') nll_adv = F.cross_entropy(logits_adv, labels,", "random targets from. Returns ------- targets: Tensor Random target for", "targeted=targeted) # performance monitoring end.record() torch.cuda.synchronize() total_time += (start.elapsed_time(end)) /", "data: list.append(data.cpu()) for inputs_chunk, labels_chunk, adv_chunk in zip(*chunks): inputs_chunk, adv_chunk", "labels. num_classes: int Number of classes to generate the random", "dict) -> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120) # To", "F.cross_entropy(logits, labels, reduction='none') nll_adv = F.cross_entropy(logits_adv, labels, reduction='none') data =", "labels.unsqueeze(1), float('inf')) real = logits_adv.gather(1, labels.unsqueeze(1)).squeeze(1) other = (logits_adv -", "distutils.version import LooseVersion from functools import partial from inspect import", "torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter = ForwardCounter(), BackwardCounter() model.register_forward_pre_hook(forward_counter) if LooseVersion(torch.__version__)", "'num_backwards': sum(average_backwards) / len(chunks[0]), } return data _default_metrics = OrderedDict([", "torch import tqdm from torch import Tensor, nn from torch.nn", "= [torch.cat(l) for l in all_predictions] for metric in metrics.keys():", "return data def print_metrics(metrics: dict) -> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16,", "get_all_targets(labels: Tensor, num_classes: int): \"\"\" Generates all possible targets that", "the original label. Parameters ---------- labels: Tensor Original labels. Generated", "None: targeted, adv_labels = True, targets batch_size = batch_size or", "(start.elapsed_time(end)) / 1000 # times for cuda Events are in", "in [inputs, adv_labels]] for (inputs_chunk, label_chunk) in zip(*chunks): batch_chunk_d, label_chunk_d", "---------- labels: Tensor Original labels. Generated targets will be different", "precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in: {:.2f}s with {:.4g}", "all_predictions = [[] for _ in range(6)] distances = {k:", "import torch import tqdm from torch import Tensor, nn from", "0 for (inputs_chunk, label_chunk) in tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d", "int Number of classes to generate the random targets from.", "{:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success = metrics['success'].numpy() fail =", "Average: {:.2f}'.format( attack_type, metrics['logit_diff_adv'].numpy(), metrics['logit_diff_adv'].numpy().mean())) print('NLL of target/pred class: {:.3f}'.format(metrics['nll_adv'].numpy().mean()))", "metrics: Dict[str, Callable] = _default_metrics) -> Dict[str, Union[Tensor, float]]: inputs,", "diff_vs_max_adv = (real - other) nll = F.cross_entropy(logits, labels, reduction='none')", "('l2', l2_distances), ]) def compute_attack_metrics(model: nn.Module, attack_data: Dict[str, Union[Tensor, float]],", "Tensor Original labels. Generated targets will be different from labels.", "labels[i].item() other_labels = list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels) return all_possible_targets def", "chunks = [tensor.split(batch_size) for tensor in [inputs, labels, adv_inputs]] all_predictions", "batch_size: Optional[int] = None, metrics: Dict[str, Callable] = _default_metrics) ->", "[predict_inputs(model, chunk.to(device)) for chunk in [inputs_chunk, adv_chunk]] list(map(append, all_predictions, [*clean_preds,", "{:.4g} forwards and {:.4g} backwards.'.format( metrics['time'], metrics['num_forwards'], metrics['num_backwards'])) success =", "preds, 'adv_preds': preds_adv, 'accuracy_orig': accuracy_orig, 'success': success, 'probs_orig': prob_orig, 'probs_adv':", "(preds == label_chunk_d) if targeted else (preds != label_chunk_d) already_adv.append(is_adv.cpu())", "this_label = labels[i].item() other_labels = list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels) return", "To print arrays with less precision print('Original accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack", "each label. Has the same shape as labels. \"\"\" random", "device = next(model.parameters()).device to_device = lambda tensor: tensor.to(device) batch_size =", "import ForwardCounter, BackwardCounter, predict_inputs def generate_random_targets(labels: Tensor, num_classes: int) ->", "torch.tensor(other_labels) return all_possible_targets def run_attack(model: nn.Module, inputs: Tensor, labels: Tensor,", "targets else: success = (preds_adv != labels) prob_orig = probs.gather(1,", "labels.unsqueeze(1)).squeeze(1) other = (logits_adv - labels_infhot).max(1).values diff_vs_max_adv = (real -", "linf_distances from adv_lib.utils import ForwardCounter, BackwardCounter, predict_inputs def generate_random_targets(labels: Tensor,", "from typing import Callable, Optional, Dict, Union import numpy as", "data def print_metrics(metrics: dict) -> None: np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3,", "- Average: {:.3f} - Median: {:.3f}'.format(distance, data, data.mean(), np.median(data)) +", "other_labels = list(all_classes.difference({this_label})) all_possible_targets[i] = torch.tensor(other_labels) return all_possible_targets def run_attack(model:", "distances[metric] = torch.cat(distances[metric], 0) accuracy_orig = (preds == labels).float().mean().item() if", "samples already_adv = [] chunks = [tensor.split(batch_size) for tensor in", "\"\"\" random = torch.rand(len(labels), num_classes, device=labels.device, dtype=torch.float) random.scatter_(1, labels.unsqueeze(-1), 0)", "('l1', l1_distances), ('l2', l2_distances), ]) def compute_attack_metrics(model: nn.Module, attack_data: Dict[str,", "tensor: tensor.to(device) targeted, adv_labels = False, labels if targets is", "total_time, 'num_forwards': sum(average_forwards) / len(chunks[0]), 'num_backwards': sum(average_backwards) / len(chunks[0]), }", "tqdm.tqdm(zip(*chunks), ncols=80, total=len(chunks[0])): batch_chunk_d, label_chunk_d = [to_device(tensor.clone()) for tensor in", "in zip(*chunks): inputs_chunk, adv_chunk = map(to_device, [inputs_chunk, adv_chunk]) clean_preds, adv_preds", "targeted else None, 'adv_inputs': adv_inputs, 'time': total_time, 'num_forwards': sum(average_forwards) /", "accuracy: {:.2%}'.format(metrics['accuracy_orig'])) print('Attack done in: {:.2f}s with {:.4g} forwards and", "if metrics['targeted'] else 'correct' print('Logit({} class) - max_Logit(other classes): {}", "label_chunk_d) if targeted else (preds != label_chunk_d) already_adv.append(is_adv.cpu()) not_adv =", "import LooseVersion from functools import partial from inspect import isclass", "= _default_metrics) -> Dict[str, Union[Tensor, float]]: inputs, labels, targets, adv_inputs", "adv_inputs, 'time': total_time, 'num_forwards': sum(average_forwards) / len(chunks[0]), 'num_backwards': sum(average_backwards) /", "= {k: v().to(device) if (isclass(v.func) if isinstance(v, partial) else False)", "= torch.cat(distances[metric], 0) accuracy_orig = (preds == labels).float().mean().item() if targets", "over success: {:.3f}'.format(data[success].mean())) attack_type = 'targets' if metrics['targeted'] else 'correct'", "attack_data['time'], 'num_forwards': attack_data['num_forwards'], 'num_backwards': attack_data['num_backwards'], 'targeted': targets is not None,", "import Tensor, nn from torch.nn import functional as F from", "labels. Parameters ---------- labels: Tensor Original labels. Generated targets will", "success: {:.2%}'.format(success.mean()) + fail * ' - {}'.format(success)) for distance,", "on non already adversarial samples already_adv = [] chunks =", "LooseVersion from functools import partial from inspect import isclass from", "in (num_classes - 1) possibilities for each label that is", "one random target in (num_classes - 1) possibilities for each", "0) start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter = ForwardCounter(),", "append = lambda list, data: list.append(data.cpu()) for inputs_chunk, labels_chunk, adv_chunk", "= targets else: success = (preds_adv != labels) prob_orig =", "are in milliseconds average_forwards.append(forward_counter.num_samples_called / len(batch_chunk_d)) average_backwards.append(backward_counter.num_samples_called / len(batch_chunk_d)) forward_counter.reset(),", "l2_distances, linf_distances from adv_lib.utils import ForwardCounter, BackwardCounter, predict_inputs def generate_random_targets(labels:", "targeted, adv_labels = True, targets batch_size = batch_size or len(inputs)", "warnings.warn('Values of produced adversarials are not in the [0, 1]", "i in range(len(labels)): this_label = labels[i].item() other_labels = list(all_classes.difference({this_label})) all_possible_targets[i]", "all_possible_targets def run_attack(model: nn.Module, inputs: Tensor, labels: Tensor, attack: Callable,", "logits, probs, preds, logits_adv, probs_adv, preds_adv = [torch.cat(l) for l", "= [tensor.split(batch_size) for tensor in [inputs, adv_labels]] for (inputs_chunk, label_chunk)", "np.set_printoptions(formatter={'float': '{:0.3f}'.format}, threshold=16, edgeitems=3, linewidth=120) # To print arrays with", "of forward and backward calls per sample advs_chunks = []", "'inputs': inputs, 'labels': labels, 'targets': adv_labels if targeted else None,", "all_possible_targets = torch.zeros(len(labels), num_classes - 1, dtype=torch.long) all_classes = set(range(num_classes))", "'adv_inputs']) if adv_inputs.min() < 0 or adv_inputs.max() > 1: warnings.warn('Values", "prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf')) real", "= ~torch.cat(already_adv, 0) start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter", "sum(average_forwards) / len(chunks[0]), 'num_backwards': sum(average_backwards) / len(chunks[0]), } return data", "np import torch import tqdm from torch import Tensor, nn", "adv_inputs]] all_predictions = [[] for _ in range(6)] distances =", "+ fail * ' | Avg over success: {:.3f}'.format(data[success].mean())) attack_type", "lambda tensor: tensor.to(device) batch_size = batch_size or len(inputs) chunks =", "-> Tensor: \"\"\" Generates one random target in (num_classes -", "OrderedDict from distutils.version import LooseVersion from functools import partial from", "~torch.cat(already_adv, 0) start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) forward_counter, backward_counter =", "different from the original label. Parameters ---------- labels: Tensor Original", "all_predictions, [*clean_preds, *adv_preds])) for metric, metric_func in metrics.items(): distances[metric].append(metric_func(adv_chunk, inputs_chunk).detach().cpu())", "label_chunk) in zip(*chunks): batch_chunk_d, label_chunk_d = [to_device(tensor) for tensor in", "'correct' print('Logit({} class) - max_Logit(other classes): {} - Average: {:.2f}'.format(", "= bool(success.mean() != 1) print('Attack success: {:.2%}'.format(success.mean()) + fail *", "= probs.gather(1, labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1,", "random.argmax(1) def get_all_targets(labels: Tensor, num_classes: int): \"\"\" Generates all possible", "success = (preds_adv == targets) labels = targets else: success", "= { 'inputs': inputs, 'labels': labels, 'targets': adv_labels if targeted", "= OrderedDict([ ('linf', linf_distances), ('l0', l0_distances), ('l1', l1_distances), ('l2', l2_distances),", "len(inputs) # run attack only on non already adversarial samples", "from adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances, linf_distances from adv_lib.utils import", "len(chunks[0]), 'num_backwards': sum(average_backwards) / len(chunks[0]), } return data _default_metrics =", "labels.unsqueeze(1)).squeeze(1) prob_adv = probs_adv.gather(1, labels.unsqueeze(1)).squeeze(1) labels_infhot = torch.zeros_like(logits_adv).scatter_(1, labels.unsqueeze(1), float('inf'))", "k, v in metrics.items()} append = lambda list, data: list.append(data.cpu())" ]
[ "shape file authors: <NAME> email:<EMAIL> add time: 26 February, 2020", "polygons in to shape file authors: <NAME> email:<EMAIL> add time:", "compare two groups of polygons ' parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\",", "basic import basic_src.map_projection as map_projection import parameters import polygons_cd_multi import", "# if options.para_file is None: # print('error, no parameters file')", "DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as io_function import basic_src.basic as", "options.output is not None: main_shp_name = options.output # get expanding", "# conduct change detection if options.output is not None: main_shp_name", "shrinking parts output_path_expand = 'expand_' + main_shp_name output_path_shrink = 'shrink_'", "+ main_shp_name output_path_shrink = 'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink)", "io_function.is_file_exist(old_shp_path) # check projection of the shape file, should be", "2020-02-26\") parser.description = 'Introduction: compare two groups of polygons '", "2: parser.print_help() sys.exit(2) # # set parameters files # if", "% (old_shp_proj4, new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change detection", "\"--para\", action=\"store\", dest=\"para_file\", help=\"the parameters file\") parser.add_option('-o', '--output', action=\"store\", dest", "check files do exist assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) # check", "= options.output # get expanding and shrinking parts output_path_expand =", "parameters file') # parser.print_help() # sys.exit(2) # else: # parameters.set_saved_parafile_path(options.para_file)", "sys.exit(2) # # set parameters files # if options.para_file is", "\"usage: %prog [options] old_shape_file new_shape_file \" parser = OptionParser(usage=usage, version=\"1.0", "import polygons_cd_multi import polygons_cd def main(options, args): old_shp_path = args[0]", "%prog [options] old_shape_file new_shape_file \" parser = OptionParser(usage=usage, version=\"1.0 2020-02-26\")", "the same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4", "of the shape file, should be the same old_shp_proj4 =", "polygons_cd \"\"\" introduction: compare two polygons in to shape file", "parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\", help=\"the parameters file\") parser.add_option('-o', '--output', action=\"store\",", "parser.add_option('-o', '--output', action=\"store\", dest = 'output', help='the path to save", "options.output # get expanding and shrinking parts output_path_expand = 'expand_'", "polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if __name__ == \"__main__\": usage = \"usage:", "to save the change detection results') (options, args) = parser.parse_args()", "shape file, should be the same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4", "action=\"store\", dest = 'output', help='the path to save the change", "as basic import basic_src.map_projection as map_projection import parameters import polygons_cd_multi", "(options, args) = parser.parse_args() if len(sys.argv) < 2: parser.print_help() sys.exit(2)", "action=\"store\", dest=\"para_file\", help=\"the parameters file\") parser.add_option('-o', '--output', action=\"store\", dest =", "2020 \"\"\" import sys,os from optparse import OptionParser # added", "of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as io_function import basic_src.basic", "'expand_' + main_shp_name output_path_shrink = 'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path,", "<NAME> email:<EMAIL> add time: 26 February, 2020 \"\"\" import sys,os", "args[0] new_shp_path = args[1] # check files do exist assert", "\" parser = OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description = 'Introduction: compare", "'Introduction: compare two groups of polygons ' parser.add_option(\"-p\", \"--para\", action=\"store\",", "None: # print('error, no parameters file') # parser.print_help() # sys.exit(2)", "# parser.print_help() # sys.exit(2) # else: # parameters.set_saved_parafile_path(options.para_file) basic.setlogfile('polygons_changeDetection.log') main(options,", "= map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 != new_shp_proj4: raise", "old_shp_path = args[0] new_shp_path = args[1] # check files do", "change detection results') (options, args) = parser.parse_args() if len(sys.argv) <", "time: 26 February, 2020 \"\"\" import sys,os from optparse import", "!= new_shp_proj4: raise ValueError('error, projection insistence between %s and %s'", "insistence between %s and %s' % (old_shp_proj4, new_shp_proj4)) main_shp_name =", "args) = parser.parse_args() if len(sys.argv) < 2: parser.print_help() sys.exit(2) #", "projection of the shape file, should be the same old_shp_proj4", "February, 2020 \"\"\" import sys,os from optparse import OptionParser #", "parser = OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description = 'Introduction: compare two", "email:<EMAIL> add time: 26 February, 2020 \"\"\" import sys,os from", "expanding and shrinking parts output_path_expand = 'expand_' + main_shp_name output_path_shrink", "OptionParser # added path of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function", "assert io_function.is_file_exist(old_shp_path) # check projection of the shape file, should", "authors: <NAME> email:<EMAIL> add time: 26 February, 2020 \"\"\" import", "path of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as io_function import", "parser.description = 'Introduction: compare two groups of polygons ' parser.add_option(\"-p\",", "sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as io_function import basic_src.basic as basic", "' parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\", help=\"the parameters file\") parser.add_option('-o', '--output',", "should be the same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path)", "files do exist assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) # check projection", "\"\"\" introduction: compare two polygons in to shape file authors:", "(old_shp_proj4, new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change detection if", "compare two polygons in to shape file authors: <NAME> email:<EMAIL>", "%s' % (old_shp_proj4, new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change", "file, should be the same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 =", "= 'expand_' + main_shp_name output_path_shrink = 'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path,", "and %s' % (old_shp_proj4, new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct", "[options] old_shape_file new_shape_file \" parser = OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description", "sys,os from optparse import OptionParser # added path of DeeplabforRS", "be the same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if", "raise ValueError('error, projection insistence between %s and %s' % (old_shp_proj4,", "results') (options, args) = parser.parse_args() if len(sys.argv) < 2: parser.print_help()", "old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 != new_shp_proj4:", "map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 != new_shp_proj4: raise ValueError('error,", "import sys,os from optparse import OptionParser # added path of", "if old_shp_proj4 != new_shp_proj4: raise ValueError('error, projection insistence between %s", "None: main_shp_name = options.output # get expanding and shrinking parts", "if options.output is not None: main_shp_name = options.output # get", "polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change detection if options.output is not None:", "same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path) new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 !=", "get expanding and shrinking parts output_path_expand = 'expand_' + main_shp_name", "usage = \"usage: %prog [options] old_shape_file new_shape_file \" parser =", "= parser.parse_args() if len(sys.argv) < 2: parser.print_help() sys.exit(2) # #", "parser.print_help() sys.exit(2) # # set parameters files # if options.para_file", "len(sys.argv) < 2: parser.print_help() sys.exit(2) # # set parameters files", "\"\"\" import sys,os from optparse import OptionParser # added path", "map_projection import parameters import polygons_cd_multi import polygons_cd def main(options, args):", "detection results') (options, args) = parser.parse_args() if len(sys.argv) < 2:", "in to shape file authors: <NAME> email:<EMAIL> add time: 26", "print('error, no parameters file') # parser.print_help() # sys.exit(2) # else:", "= polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change detection if options.output is not", "26 February, 2020 \"\"\" import sys,os from optparse import OptionParser", "parts output_path_expand = 'expand_' + main_shp_name output_path_shrink = 'shrink_' +", "# Filename: polygons_cd \"\"\" introduction: compare two polygons in to", "basic_src.basic as basic import basic_src.map_projection as map_projection import parameters import", "= 'Introduction: compare two groups of polygons ' parser.add_option(\"-p\", \"--para\",", "projection insistence between %s and %s' % (old_shp_proj4, new_shp_proj4)) main_shp_name", "args[1] # check files do exist assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path)", "output_path_expand,output_path_shrink) if __name__ == \"__main__\": usage = \"usage: %prog [options]", "options.para_file is None: # print('error, no parameters file') # parser.print_help()", "main_shp_name output_path_shrink = 'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if", "main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if __name__ == \"__main__\": usage =", "import OptionParser # added path of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import", "+ main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if __name__ == \"__main__\": usage", "'output', help='the path to save the change detection results') (options,", "and shrinking parts output_path_expand = 'expand_' + main_shp_name output_path_shrink =", "= map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 != new_shp_proj4: raise ValueError('error, projection insistence", "set parameters files # if options.para_file is None: # print('error,", "dest = 'output', help='the path to save the change detection", "import basic_src.io_function as io_function import basic_src.basic as basic import basic_src.map_projection", "def main(options, args): old_shp_path = args[0] new_shp_path = args[1] #", "assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) # check projection of the shape", "dest=\"para_file\", help=\"the parameters file\") parser.add_option('-o', '--output', action=\"store\", dest = 'output',", "'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if __name__ == \"__main__\":", "new_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 != new_shp_proj4: raise ValueError('error, projection", "args): old_shp_path = args[0] new_shp_path = args[1] # check files", "if len(sys.argv) < 2: parser.print_help() sys.exit(2) # # set parameters", "parameters file\") parser.add_option('-o', '--output', action=\"store\", dest = 'output', help='the path", "io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) # check projection of the shape file,", "%s and %s' % (old_shp_proj4, new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) #", "# # set parameters files # if options.para_file is None:", "main_shp_name = options.output # get expanding and shrinking parts output_path_expand", "= args[1] # check files do exist assert io_function.is_file_exist(new_shp_path) assert", "# added path of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as", "help='the path to save the change detection results') (options, args)", "path to save the change detection results') (options, args) =", "new_shp_path, output_path_expand,output_path_shrink) if __name__ == \"__main__\": usage = \"usage: %prog", "import basic_src.map_projection as map_projection import parameters import polygons_cd_multi import polygons_cd", "between %s and %s' % (old_shp_proj4, new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path)", "basic_src.io_function as io_function import basic_src.basic as basic import basic_src.map_projection as", "change detection if options.output is not None: main_shp_name = options.output", "add time: 26 February, 2020 \"\"\" import sys,os from optparse", "parameters import polygons_cd_multi import polygons_cd def main(options, args): old_shp_path =", "of polygons ' parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\", help=\"the parameters file\")", "# get expanding and shrinking parts output_path_expand = 'expand_' +", "__name__ == \"__main__\": usage = \"usage: %prog [options] old_shape_file new_shape_file", "files # if options.para_file is None: # print('error, no parameters", "not None: main_shp_name = options.output # get expanding and shrinking", "= args[0] new_shp_path = args[1] # check files do exist", "OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description = 'Introduction: compare two groups of", "version=\"1.0 2020-02-26\") parser.description = 'Introduction: compare two groups of polygons", "if __name__ == \"__main__\": usage = \"usage: %prog [options] old_shape_file", "to shape file authors: <NAME> email:<EMAIL> add time: 26 February,", "no parameters file') # parser.print_help() # sys.exit(2) # else: #", "Filename: polygons_cd \"\"\" introduction: compare two polygons in to shape", "'--output', action=\"store\", dest = 'output', help='the path to save the", "parser.parse_args() if len(sys.argv) < 2: parser.print_help() sys.exit(2) # # set", "is not None: main_shp_name = options.output # get expanding and", "ValueError('error, projection insistence between %s and %s' % (old_shp_proj4, new_shp_proj4))", "parser.print_help() # sys.exit(2) # else: # parameters.set_saved_parafile_path(options.para_file) basic.setlogfile('polygons_changeDetection.log') main(options, args)", "polygons_cd def main(options, args): old_shp_path = args[0] new_shp_path = args[1]", "output_path_expand = 'expand_' + main_shp_name output_path_shrink = 'shrink_' + main_shp_name", "the shape file, should be the same old_shp_proj4 = map_projection.get_raster_or_vector_srs_info_proj4(old_shp_path)", "io_function import basic_src.basic as basic import basic_src.map_projection as map_projection import", "conduct change detection if options.output is not None: main_shp_name =", "new_shape_file \" parser = OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description = 'Introduction:", "exist assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) # check projection of the", "basic_src.map_projection as map_projection import parameters import polygons_cd_multi import polygons_cd def", "main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change detection if options.output is", "= OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description = 'Introduction: compare two groups", "check projection of the shape file, should be the same", "= 'output', help='the path to save the change detection results')", "output_path_shrink = 'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if __name__", "polygons_cd_multi import polygons_cd def main(options, args): old_shp_path = args[0] new_shp_path", "main(options, args): old_shp_path = args[0] new_shp_path = args[1] # check", "file\") parser.add_option('-o', '--output', action=\"store\", dest = 'output', help='the path to", "# check files do exist assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) #", "new_shp_proj4)) main_shp_name = polygons_cd_multi.get_main_shp_name(old_shp_path,new_shp_path) # conduct change detection if options.output", "#!/usr/bin/env python # Filename: polygons_cd \"\"\" introduction: compare two polygons", "new_shp_proj4: raise ValueError('error, projection insistence between %s and %s' %", "old_shape_file new_shape_file \" parser = OptionParser(usage=usage, version=\"1.0 2020-02-26\") parser.description =", "import basic_src.basic as basic import basic_src.map_projection as map_projection import parameters", "do exist assert io_function.is_file_exist(new_shp_path) assert io_function.is_file_exist(old_shp_path) # check projection of", "# check projection of the shape file, should be the", "\"__main__\": usage = \"usage: %prog [options] old_shape_file new_shape_file \" parser", "as map_projection import parameters import polygons_cd_multi import polygons_cd def main(options,", "# print('error, no parameters file') # parser.print_help() # sys.exit(2) #", "added path of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as io_function", "< 2: parser.print_help() sys.exit(2) # # set parameters files #", "file authors: <NAME> email:<EMAIL> add time: 26 February, 2020 \"\"\"", "old_shp_proj4 != new_shp_proj4: raise ValueError('error, projection insistence between %s and", "groups of polygons ' parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\", help=\"the parameters", "map_projection.get_raster_or_vector_srs_info_proj4(new_shp_path) if old_shp_proj4 != new_shp_proj4: raise ValueError('error, projection insistence between", "as io_function import basic_src.basic as basic import basic_src.map_projection as map_projection", "import parameters import polygons_cd_multi import polygons_cd def main(options, args): old_shp_path", "introduction: compare two polygons in to shape file authors: <NAME>", "import polygons_cd def main(options, args): old_shp_path = args[0] new_shp_path =", "file') # parser.print_help() # sys.exit(2) # else: # parameters.set_saved_parafile_path(options.para_file) basic.setlogfile('polygons_changeDetection.log')", "# set parameters files # if options.para_file is None: #", "== \"__main__\": usage = \"usage: %prog [options] old_shape_file new_shape_file \"", "polygons ' parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\", help=\"the parameters file\") parser.add_option('-o',", "new_shp_path = args[1] # check files do exist assert io_function.is_file_exist(new_shp_path)", "optparse import OptionParser # added path of DeeplabforRS sys.path.insert(0, os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS'))", "the change detection results') (options, args) = parser.parse_args() if len(sys.argv)", "help=\"the parameters file\") parser.add_option('-o', '--output', action=\"store\", dest = 'output', help='the", "os.path.expanduser('~/codes/PycharmProjects/DeeplabforRS')) import basic_src.io_function as io_function import basic_src.basic as basic import", "save the change detection results') (options, args) = parser.parse_args() if", "from optparse import OptionParser # added path of DeeplabforRS sys.path.insert(0,", "= \"usage: %prog [options] old_shape_file new_shape_file \" parser = OptionParser(usage=usage,", "python # Filename: polygons_cd \"\"\" introduction: compare two polygons in", "parameters files # if options.para_file is None: # print('error, no", "two polygons in to shape file authors: <NAME> email:<EMAIL> add", "is None: # print('error, no parameters file') # parser.print_help() #", "if options.para_file is None: # print('error, no parameters file') #", "= 'shrink_' + main_shp_name polygons_cd.polygons_change_detection(old_shp_path, new_shp_path, output_path_expand,output_path_shrink) if __name__ ==", "two groups of polygons ' parser.add_option(\"-p\", \"--para\", action=\"store\", dest=\"para_file\", help=\"the", "detection if options.output is not None: main_shp_name = options.output #" ]
[ "car_type=\"saloon\"): num_of_wheels = 4 num_of_doors = 4 if car_type ==", "== \"trailer\": num_of_wheels = 8 if name == \"Porshe\" or", "vehicle \"\"\" def __init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels = 4", "4 num_of_doors = 4 if car_type == \"trailer\": num_of_wheels =", "if self.type == \"trailer\": self.speed = gear * 77 /", "= gear * 77 / 7 elif self.type == \"saloon\":", "or name == \"Koenigsegg\": num_of_doors = 2 self.name = name", "\"trailer\": self.speed = gear * 77 / 7 elif self.type", "and name of the vehicle \"\"\" def __init__(self, name=\"General\", model=\"GM\",", "1000 / 3 return self def is_saloon(self): return self.type ==", "= gear * 1000 / 3 return self def is_saloon(self):", "= 2 self.name = name self.model = model self.type =", "* 77 / 7 elif self.type == \"saloon\": self.speed =", "self.speed = gear * 1000 / 3 return self def", "self.num_of_doors = num_of_doors self.num_of_wheels = num_of_wheels self.speed = 0 def", "model, and name of the vehicle \"\"\" def __init__(self, name=\"General\",", "type, model, and name of the vehicle \"\"\" def __init__(self,", "num_of_doors self.num_of_wheels = num_of_wheels self.speed = 0 def drive(self, gear):", "def __init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels = 4 num_of_doors =", "num_of_doors = 2 self.name = name self.model = model self.type", "self.model = model self.type = car_type self.num_of_doors = num_of_doors self.num_of_wheels", "self.speed = 0 def drive(self, gear): if self.type == \"trailer\":", "= 4 num_of_doors = 4 if car_type == \"trailer\": num_of_wheels", "vehicles. It takes in arguments that depict the type, model,", "depict the type, model, and name of the vehicle \"\"\"", "= num_of_wheels self.speed = 0 def drive(self, gear): if self.type", "77 / 7 elif self.type == \"saloon\": self.speed = gear", "self.speed = gear * 77 / 7 elif self.type ==", "/ 3 return self def is_saloon(self): return self.type == 'saloon'", "def drive(self, gear): if self.type == \"trailer\": self.speed = gear", "gear * 1000 / 3 return self def is_saloon(self): return", "in arguments that depict the type, model, and name of", "that depict the type, model, and name of the vehicle", "8 if name == \"Porshe\" or name == \"Koenigsegg\": num_of_doors", "4 if car_type == \"trailer\": num_of_wheels = 8 if name", "that can be used to instantiate various vehicles. It takes", "Car class that can be used to instantiate various vehicles.", "various vehicles. It takes in arguments that depict the type,", "class Car(object): \"\"\" Car class that can be used to", "self.name = name self.model = model self.type = car_type self.num_of_doors", "the vehicle \"\"\" def __init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels =", "\"saloon\": self.speed = gear * 1000 / 3 return self", "0 def drive(self, gear): if self.type == \"trailer\": self.speed =", "__init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels = 4 num_of_doors = 4", "gear): if self.type == \"trailer\": self.speed = gear * 77", "drive(self, gear): if self.type == \"trailer\": self.speed = gear *", "name of the vehicle \"\"\" def __init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"):", "\"\"\" Car class that can be used to instantiate various", "used to instantiate various vehicles. It takes in arguments that", "2 self.name = name self.model = model self.type = car_type", "of the vehicle \"\"\" def __init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels", "7 elif self.type == \"saloon\": self.speed = gear * 1000", "It takes in arguments that depict the type, model, and", "if name == \"Porshe\" or name == \"Koenigsegg\": num_of_doors =", "== \"trailer\": self.speed = gear * 77 / 7 elif", "gear * 77 / 7 elif self.type == \"saloon\": self.speed", "== \"saloon\": self.speed = gear * 1000 / 3 return", "model=\"GM\", car_type=\"saloon\"): num_of_wheels = 4 num_of_doors = 4 if car_type", "= car_type self.num_of_doors = num_of_doors self.num_of_wheels = num_of_wheels self.speed =", "name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels = 4 num_of_doors = 4 if", "if car_type == \"trailer\": num_of_wheels = 8 if name ==", "self.type == \"saloon\": self.speed = gear * 1000 / 3", "name == \"Koenigsegg\": num_of_doors = 2 self.name = name self.model", "* 1000 / 3 return self def is_saloon(self): return self.type", "= num_of_doors self.num_of_wheels = num_of_wheels self.speed = 0 def drive(self,", "= model self.type = car_type self.num_of_doors = num_of_doors self.num_of_wheels =", "== \"Porshe\" or name == \"Koenigsegg\": num_of_doors = 2 self.name", "\"Koenigsegg\": num_of_doors = 2 self.name = name self.model = model", "can be used to instantiate various vehicles. It takes in", "the type, model, and name of the vehicle \"\"\" def", "num_of_doors = 4 if car_type == \"trailer\": num_of_wheels = 8", "= 4 if car_type == \"trailer\": num_of_wheels = 8 if", "\"\"\" def __init__(self, name=\"General\", model=\"GM\", car_type=\"saloon\"): num_of_wheels = 4 num_of_doors", "self.type == \"trailer\": self.speed = gear * 77 / 7", "/ 7 elif self.type == \"saloon\": self.speed = gear *", "name self.model = model self.type = car_type self.num_of_doors = num_of_doors", "\"Porshe\" or name == \"Koenigsegg\": num_of_doors = 2 self.name =", "be used to instantiate various vehicles. It takes in arguments", "car_type self.num_of_doors = num_of_doors self.num_of_wheels = num_of_wheels self.speed = 0", "\"trailer\": num_of_wheels = 8 if name == \"Porshe\" or name", "self.type = car_type self.num_of_doors = num_of_doors self.num_of_wheels = num_of_wheels self.speed", "arguments that depict the type, model, and name of the", "model self.type = car_type self.num_of_doors = num_of_doors self.num_of_wheels = num_of_wheels", "= 8 if name == \"Porshe\" or name == \"Koenigsegg\":", "name == \"Porshe\" or name == \"Koenigsegg\": num_of_doors = 2", "= name self.model = model self.type = car_type self.num_of_doors =", "class that can be used to instantiate various vehicles. It", "takes in arguments that depict the type, model, and name", "Car(object): \"\"\" Car class that can be used to instantiate", "= 0 def drive(self, gear): if self.type == \"trailer\": self.speed", "to instantiate various vehicles. It takes in arguments that depict", "self.num_of_wheels = num_of_wheels self.speed = 0 def drive(self, gear): if", "instantiate various vehicles. It takes in arguments that depict the", "car_type == \"trailer\": num_of_wheels = 8 if name == \"Porshe\"", "elif self.type == \"saloon\": self.speed = gear * 1000 /", "num_of_wheels = 8 if name == \"Porshe\" or name ==", "num_of_wheels self.speed = 0 def drive(self, gear): if self.type ==", "== \"Koenigsegg\": num_of_doors = 2 self.name = name self.model =", "num_of_wheels = 4 num_of_doors = 4 if car_type == \"trailer\":", "<reponame>brotich/andela_bootcamp_X class Car(object): \"\"\" Car class that can be used" ]
[ "Model/Model - JupyterNotebook/mrcnn/tfliteconverter.py import tensorflow as tf # Convert the", "JupyterNotebook/mrcnn/tfliteconverter.py import tensorflow as tf # Convert the model. converter", "tensorflow as tf # Convert the model. converter = tf.lite.TFLiteConverter.from_saved_model('model.py')", "as tf # Convert the model. converter = tf.lite.TFLiteConverter.from_saved_model('model.py') tflite_model", "tf # Convert the model. converter = tf.lite.TFLiteConverter.from_saved_model('model.py') tflite_model =", "# Convert the model. converter = tf.lite.TFLiteConverter.from_saved_model('model.py') tflite_model = converter.convert()", "- JupyterNotebook/mrcnn/tfliteconverter.py import tensorflow as tf # Convert the model.", "the model. converter = tf.lite.TFLiteConverter.from_saved_model('model.py') tflite_model = converter.convert() open(\"trash_ai.tflite\", \"wb\").write(tflite_model)", "<filename>CV Model/Model - JupyterNotebook/mrcnn/tfliteconverter.py import tensorflow as tf # Convert", "Convert the model. converter = tf.lite.TFLiteConverter.from_saved_model('model.py') tflite_model = converter.convert() open(\"trash_ai.tflite\",", "import tensorflow as tf # Convert the model. converter =" ]
[ "obj.last_hit if delta.days > 2: print('link is older than 2", "a unique code def do(self): current_time = timezone.now() links =", "if delta.days > 2: print('link is older than 2 days,", "than 2 days, DELETING!') obj.delete() else: print('link was recently hit,", "timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every 2 hours", "2 days, DELETING!') obj.delete() else: print('link was recently hit, Wont", "from django_cron import CronJobBase, Schedule from .models import Link from", "django_cron import CronJobBase, Schedule from .models import Link from django.utils", "for: \", obj.shortenURL) delta = current_time - obj.last_hit if delta.days", "MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every 2 hours schedule =", "RUN_EVERY_MINS = 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS)", "Link.objects.all() for obj in links: print(\"Checking last hit date for:", "= timezone.now() links = Link.objects.all() for obj in links: print(\"Checking", "print(\"Checking last hit date for: \", obj.shortenURL) delta = current_time", "obj in links: print(\"Checking last hit date for: \", obj.shortenURL)", "= Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron' # a unique code def", "days, DELETING!') obj.delete() else: print('link was recently hit, Wont Delete.')", "import Link from django.utils import timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS =", "2: print('link is older than 2 days, DELETING!') obj.delete() else:", "links = Link.objects.all() for obj in links: print(\"Checking last hit", "hit date for: \", obj.shortenURL) delta = current_time - obj.last_hit", "django.utils import timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every", "code = 'basicapp.cron' # a unique code def do(self): current_time", "delta = current_time - obj.last_hit if delta.days > 2: print('link", "1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code =", "2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron' # a", "> 2: print('link is older than 2 days, DELETING!') obj.delete()", "do(self): current_time = timezone.now() links = Link.objects.all() for obj in", "import CronJobBase, Schedule from .models import Link from django.utils import", "obj.shortenURL) delta = current_time - obj.last_hit if delta.days > 2:", "Link from django.utils import timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1", "schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron' # a unique code", "current_time = timezone.now() links = Link.objects.all() for obj in links:", "# a unique code def do(self): current_time = timezone.now() links", "from .models import Link from django.utils import timezone class MyCronJob(CronJobBase):", "\", obj.shortenURL) delta = current_time - obj.last_hit if delta.days >", "is older than 2 days, DELETING!') obj.delete() else: print('link was", "def do(self): current_time = timezone.now() links = Link.objects.all() for obj", "from django.utils import timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 #", "date for: \", obj.shortenURL) delta = current_time - obj.last_hit if", "in links: print(\"Checking last hit date for: \", obj.shortenURL) delta", "# every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron'", "= 'basicapp.cron' # a unique code def do(self): current_time =", "= 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code", "unique code def do(self): current_time = timezone.now() links = Link.objects.all()", "code def do(self): current_time = timezone.now() links = Link.objects.all() for", "links: print(\"Checking last hit date for: \", obj.shortenURL) delta =", "for obj in links: print(\"Checking last hit date for: \",", "timezone.now() links = Link.objects.all() for obj in links: print(\"Checking last", "every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron' #", "= current_time - obj.last_hit if delta.days > 2: print('link is", "CronJobBase, Schedule from .models import Link from django.utils import timezone", "Schedule from .models import Link from django.utils import timezone class", "older than 2 days, DELETING!') obj.delete() else: print('link was recently", "import timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every 2", "class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 # every 2 hours schedule", "hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron' # a unique", "- obj.last_hit if delta.days > 2: print('link is older than", "Schedule(run_every_mins=RUN_EVERY_MINS) code = 'basicapp.cron' # a unique code def do(self):", "current_time - obj.last_hit if delta.days > 2: print('link is older", "print('link is older than 2 days, DELETING!') obj.delete() else: print('link", "delta.days > 2: print('link is older than 2 days, DELETING!')", "= Link.objects.all() for obj in links: print(\"Checking last hit date", ".models import Link from django.utils import timezone class MyCronJob(CronJobBase): RUN_EVERY_MINS", "'basicapp.cron' # a unique code def do(self): current_time = timezone.now()", "last hit date for: \", obj.shortenURL) delta = current_time -" ]
[ "Copyright 2011-2012 <NAME> and contributors, see AUTHORS. :license: BSD, see", "= StackingContext.from_box(html, page) # The image is *not* in this", "import StackingContext from .test_boxes import serialize from .test_layout import parse", "[])]) page, = parse('''\\ <div style=\"position: relative\"> <p style=\"position: relative\"></p>", "id=lorem></p> <div style=\"position: relative\"> <p id=lipsum></p> </p> ''') assert to_lists(page)", "to_lists(page) == ( 'html 1', ['body 1'], [('div 1', [],", "..stacking import StackingContext from .test_boxes import serialize from .test_layout import", "def serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b) for b in context.blocks_and_cells],", "text: <img style=\"position: relative\" src=pattern.png>''') html, = page.children context =", "def test_image_contexts(): page, = parse(''' <body>Some text: <img style=\"position: relative\"", "# ... but in a sub-context: assert serialize(c.box for c", "'Line', [ ('body', 'Text', 'Some text: ')])])])] # ... but", "see LICENSE for details. \"\"\" from __future__ import division, unicode_literals", "context = StackingContext.from_box(html, page) # The image is *not* in", "weasyprint.tests.stacking ------------------------- :copyright: Copyright 2011-2012 <NAME> and contributors, see AUTHORS.", "serialize from .test_layout import parse from .testing_utils import assert_no_logs def", ":copyright: Copyright 2011-2012 <NAME> and contributors, see AUTHORS. :license: BSD,", ".test_boxes import serialize from .test_layout import parse from .testing_utils import", "AUTHORS. :license: BSD, see LICENSE for details. \"\"\" from __future__", "serialize([context.box]) == [ ('html', 'Block', [ ('body', 'Block', [ ('body',", "serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return '%s %s' % (box.element_tag, box.sourceline)", "style=\"position: relative\"> <p id=lipsum></p> </p> ''') assert to_lists(page) == (", "assert serialize([context.box]) == [ ('html', 'Block', [ ('body', 'Block', [", "text: ')])])])] # ... but in a sub-context: assert serialize(c.box", "def test_nested(): page, = parse('''\\ <p id=lorem></p> <div style=\"position: relative\">", "''') assert to_lists(page) == ( 'html 1', ['body 1', 'p", "return ( serialize_box(context.box), [serialize_box(b) for b in context.blocks_and_cells], [serialize_stacking(c) for", "parse(''' <body>Some text: <img style=\"position: relative\" src=pattern.png>''') html, = page.children", "[ ('body', 'Line', [ ('body', 'Text', 'Some text: ')])])])] #", "assert serialize(c.box for c in context.zero_z_contexts) == [ ('img', 'InlineReplaced',", "[]), # In this order ('p 2', [], [])]) @assert_no_logs", "sub-context: assert serialize(c.box for c in context.zero_z_contexts) == [ ('img',", "( serialize_box(context.box), [serialize_box(b) for b in context.blocks_and_cells], [serialize_stacking(c) for c", "html, = page.children return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return '%s", "src=pattern.png>''') html, = page.children context = StackingContext.from_box(html, page) # The", "serialize_box(box): return '%s %s' % (box.element_tag, box.sourceline) def serialize_stacking(context): return", "coding: utf8 \"\"\" weasyprint.tests.stacking ------------------------- :copyright: Copyright 2011-2012 <NAME> and", ":license: BSD, see LICENSE for details. \"\"\" from __future__ import", "[], []), # In this order ('p 2', [], [])])", "<img style=\"position: relative\" src=pattern.png>''') html, = page.children context = StackingContext.from_box(html,", "*not* in this context: assert serialize([context.box]) == [ ('html', 'Block',", "... but in a sub-context: assert serialize(c.box for c in", "image is *not* in this context: assert serialize([context.box]) == [", "= parse(''' <body>Some text: <img style=\"position: relative\" src=pattern.png>''') html, =", "('p 2', [], [])]) @assert_no_logs def test_image_contexts(): page, = parse('''", "from .test_boxes import serialize from .test_layout import parse from .testing_utils", "# The image is *not* in this context: assert serialize([context.box])", "from .test_layout import parse from .testing_utils import assert_no_logs def to_lists(page):", "a sub-context: assert serialize(c.box for c in context.zero_z_contexts) == [", "[])]) @assert_no_logs def test_image_contexts(): page, = parse(''' <body>Some text: <img", "In this order ('p 2', [], [])]) @assert_no_logs def test_image_contexts():", "context.zero_z_contexts], ) @assert_no_logs def test_nested(): page, = parse('''\\ <p id=lorem></p>", "'Text', 'Some text: ')])])])] # ... but in a sub-context:", "relative\"> <p style=\"position: relative\"></p> </div> ''') assert to_lists(page) == (", "import division, unicode_literals from ..stacking import StackingContext from .test_boxes import", "test_nested(): page, = parse('''\\ <p id=lorem></p> <div style=\"position: relative\"> <p", "to_lists(page) == ( 'html 1', ['body 1', 'p 1'], [(", "<body>Some text: <img style=\"position: relative\" src=pattern.png>''') html, = page.children context", "'Block', [ ('body', 'Block', [ ('body', 'Line', [ ('body', 'Text',", "1'], [('div 1', [], []), # In this order ('p", "( 'html 1', ['body 1', 'p 1'], [( 'div 2',", "'%s %s' % (box.element_tag, box.sourceline) def serialize_stacking(context): return ( serialize_box(context.box),", "style=\"position: relative\"></p> </div> ''') assert to_lists(page) == ( 'html 1',", "('body', 'Line', [ ('body', 'Text', 'Some text: ')])])])] # ...", "<p style=\"position: relative\"></p> </div> ''') assert to_lists(page) == ( 'html", "assert to_lists(page) == ( 'html 1', ['body 1'], [('div 1',", "from __future__ import division, unicode_literals from ..stacking import StackingContext from", "</p> ''') assert to_lists(page) == ( 'html 1', ['body 1',", "== ( 'html 1', ['body 1', 'p 1'], [( 'div", "page.children context = StackingContext.from_box(html, page) # The image is *not*", ".test_layout import parse from .testing_utils import assert_no_logs def to_lists(page): html,", "2011-2012 <NAME> and contributors, see AUTHORS. :license: BSD, see LICENSE", "html, = page.children context = StackingContext.from_box(html, page) # The image", "c in context.zero_z_contexts], ) @assert_no_logs def test_nested(): page, = parse('''\\", "['body 1'], [('div 1', [], []), # In this order", "page.children return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return '%s %s' %", "page, = parse('''\\ <p id=lorem></p> <div style=\"position: relative\"> <p id=lipsum></p>", "('body', 'Block', [ ('body', 'Line', [ ('body', 'Text', 'Some text:", "page, = parse(''' <body>Some text: <img style=\"position: relative\" src=pattern.png>''') html,", "# coding: utf8 \"\"\" weasyprint.tests.stacking ------------------------- :copyright: Copyright 2011-2012 <NAME>", "<p id=lipsum></p> </p> ''') assert to_lists(page) == ( 'html 1',", "this context: assert serialize([context.box]) == [ ('html', 'Block', [ ('body',", "('body', 'Text', 'Some text: ')])])])] # ... but in a", "assert to_lists(page) == ( 'html 1', ['body 1', 'p 1'],", "from ..stacking import StackingContext from .test_boxes import serialize from .test_layout", "# In this order ('p 2', [], [])]) @assert_no_logs def", "\"\"\" weasyprint.tests.stacking ------------------------- :copyright: Copyright 2011-2012 <NAME> and contributors, see", "page)) def serialize_box(box): return '%s %s' % (box.element_tag, box.sourceline) def", "[serialize_box(b) for b in context.blocks_and_cells], [serialize_stacking(c) for c in context.zero_z_contexts],", "LICENSE for details. \"\"\" from __future__ import division, unicode_literals from", "2', [], [])]) @assert_no_logs def test_image_contexts(): page, = parse(''' <body>Some", "StackingContext from .test_boxes import serialize from .test_layout import parse from", "unicode_literals from ..stacking import StackingContext from .test_boxes import serialize from", "in context.zero_z_contexts], ) @assert_no_logs def test_nested(): page, = parse('''\\ <p", "utf8 \"\"\" weasyprint.tests.stacking ------------------------- :copyright: Copyright 2011-2012 <NAME> and contributors,", "to_lists(page): html, = page.children return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return", "serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b) for b in context.blocks_and_cells], [serialize_stacking(c)", "for c in context.zero_z_contexts], ) @assert_no_logs def test_nested(): page, =", "1'], [( 'div 2', ['p 3'], [])]) page, = parse('''\\", "'div 2', ['p 3'], [])]) page, = parse('''\\ <div style=\"position:", "StackingContext.from_box(html, page) # The image is *not* in this context:", "= parse('''\\ <p id=lorem></p> <div style=\"position: relative\"> <p id=lipsum></p> </p>", "and contributors, see AUTHORS. :license: BSD, see LICENSE for details.", "page) # The image is *not* in this context: assert", "= parse('''\\ <div style=\"position: relative\"> <p style=\"position: relative\"></p> </div> ''')", "[('div 1', [], []), # In this order ('p 2',", "test_image_contexts(): page, = parse(''' <body>Some text: <img style=\"position: relative\" src=pattern.png>''')", "<NAME> and contributors, see AUTHORS. :license: BSD, see LICENSE for", "for b in context.blocks_and_cells], [serialize_stacking(c) for c in context.zero_z_contexts], )", "in context.blocks_and_cells], [serialize_stacking(c) for c in context.zero_z_contexts], ) @assert_no_logs def", "'html 1', ['body 1', 'p 1'], [( 'div 2', ['p", "def serialize_box(box): return '%s %s' % (box.element_tag, box.sourceline) def serialize_stacking(context):", "['p 3'], [])]) page, = parse('''\\ <div style=\"position: relative\"> <p", "relative\" src=pattern.png>''') html, = page.children context = StackingContext.from_box(html, page) #", "')])])])] # ... but in a sub-context: assert serialize(c.box for", "[( 'div 2', ['p 3'], [])]) page, = parse('''\\ <div", "parse from .testing_utils import assert_no_logs def to_lists(page): html, = page.children", "@assert_no_logs def test_image_contexts(): page, = parse(''' <body>Some text: <img style=\"position:", "[serialize_stacking(c) for c in context.zero_z_contexts], ) @assert_no_logs def test_nested(): page,", "box.sourceline) def serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b) for b in", "style=\"position: relative\" src=pattern.png>''') html, = page.children context = StackingContext.from_box(html, page)", "page, = parse('''\\ <div style=\"position: relative\"> <p style=\"position: relative\"></p> </div>", "<p id=lorem></p> <div style=\"position: relative\"> <p id=lipsum></p> </p> ''') assert", "context.blocks_and_cells], [serialize_stacking(c) for c in context.zero_z_contexts], ) @assert_no_logs def test_nested():", "see AUTHORS. :license: BSD, see LICENSE for details. \"\"\" from", "assert_no_logs def to_lists(page): html, = page.children return serialize_stacking(StackingContext.from_box(html, page)) def", "1', [], []), # In this order ('p 2', [],", "return '%s %s' % (box.element_tag, box.sourceline) def serialize_stacking(context): return (", "parse('''\\ <p id=lorem></p> <div style=\"position: relative\"> <p id=lipsum></p> </p> ''')", "BSD, see LICENSE for details. \"\"\" from __future__ import division,", "style=\"position: relative\"> <p style=\"position: relative\"></p> </div> ''') assert to_lists(page) ==", "The image is *not* in this context: assert serialize([context.box]) ==", "% (box.element_tag, box.sourceline) def serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b) for", "%s' % (box.element_tag, box.sourceline) def serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b)", "this order ('p 2', [], [])]) @assert_no_logs def test_image_contexts(): page,", "[], [])]) @assert_no_logs def test_image_contexts(): page, = parse(''' <body>Some text:", "def to_lists(page): html, = page.children return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box):", "['body 1', 'p 1'], [( 'div 2', ['p 3'], [])])", "'Some text: ')])])])] # ... but in a sub-context: assert", "1', 'p 1'], [( 'div 2', ['p 3'], [])]) page,", "1', ['body 1', 'p 1'], [( 'div 2', ['p 3'],", "b in context.blocks_and_cells], [serialize_stacking(c) for c in context.zero_z_contexts], ) @assert_no_logs", "<div style=\"position: relative\"> <p id=lipsum></p> </p> ''') assert to_lists(page) ==", "contributors, see AUTHORS. :license: BSD, see LICENSE for details. \"\"\"", "from .testing_utils import assert_no_logs def to_lists(page): html, = page.children return", "( 'html 1', ['body 1'], [('div 1', [], []), #", "context: assert serialize([context.box]) == [ ('html', 'Block', [ ('body', 'Block',", "import parse from .testing_utils import assert_no_logs def to_lists(page): html, =", "= page.children return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return '%s %s'", "= page.children context = StackingContext.from_box(html, page) # The image is", "== [ ('html', 'Block', [ ('body', 'Block', [ ('body', 'Line',", "return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return '%s %s' % (box.element_tag,", "[ ('html', 'Block', [ ('body', 'Block', [ ('body', 'Line', [", "in this context: assert serialize([context.box]) == [ ('html', 'Block', [", "division, unicode_literals from ..stacking import StackingContext from .test_boxes import serialize", "\"\"\" from __future__ import division, unicode_literals from ..stacking import StackingContext", "1', ['body 1'], [('div 1', [], []), # In this", "[ ('body', 'Block', [ ('body', 'Line', [ ('body', 'Text', 'Some", "id=lipsum></p> </p> ''') assert to_lists(page) == ( 'html 1', ['body", "3'], [])]) page, = parse('''\\ <div style=\"position: relative\"> <p style=\"position:", "'p 1'], [( 'div 2', ['p 3'], [])]) page, =", "__future__ import division, unicode_literals from ..stacking import StackingContext from .test_boxes", "'html 1', ['body 1'], [('div 1', [], []), # In", "(box.element_tag, box.sourceline) def serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b) for b", "relative\"> <p id=lipsum></p> </p> ''') assert to_lists(page) == ( 'html", "parse('''\\ <div style=\"position: relative\"> <p style=\"position: relative\"></p> </div> ''') assert", "'Block', [ ('body', 'Line', [ ('body', 'Text', 'Some text: ')])])])]", "serialize_box(context.box), [serialize_box(b) for b in context.blocks_and_cells], [serialize_stacking(c) for c in", "@assert_no_logs def test_nested(): page, = parse('''\\ <p id=lorem></p> <div style=\"position:", "details. \"\"\" from __future__ import division, unicode_literals from ..stacking import", "relative\"></p> </div> ''') assert to_lists(page) == ( 'html 1', ['body", "''') assert to_lists(page) == ( 'html 1', ['body 1'], [('div", "in a sub-context: assert serialize(c.box for c in context.zero_z_contexts) ==", "but in a sub-context: assert serialize(c.box for c in context.zero_z_contexts)", "serialize(c.box for c in context.zero_z_contexts) == [ ('img', 'InlineReplaced', '<replaced>')]", "for details. \"\"\" from __future__ import division, unicode_literals from ..stacking", "import serialize from .test_layout import parse from .testing_utils import assert_no_logs", "import assert_no_logs def to_lists(page): html, = page.children return serialize_stacking(StackingContext.from_box(html, page))", "------------------------- :copyright: Copyright 2011-2012 <NAME> and contributors, see AUTHORS. :license:", ".testing_utils import assert_no_logs def to_lists(page): html, = page.children return serialize_stacking(StackingContext.from_box(html,", "2', ['p 3'], [])]) page, = parse('''\\ <div style=\"position: relative\">", "('html', 'Block', [ ('body', 'Block', [ ('body', 'Line', [ ('body',", "== ( 'html 1', ['body 1'], [('div 1', [], []),", "[ ('body', 'Text', 'Some text: ')])])])] # ... but in", "is *not* in this context: assert serialize([context.box]) == [ ('html',", "<div style=\"position: relative\"> <p style=\"position: relative\"></p> </div> ''') assert to_lists(page)", "</div> ''') assert to_lists(page) == ( 'html 1', ['body 1'],", ") @assert_no_logs def test_nested(): page, = parse('''\\ <p id=lorem></p> <div", "order ('p 2', [], [])]) @assert_no_logs def test_image_contexts(): page, =" ]
[ "from django.contrib.auth.decorators import login_required from sesame import utils from django.core.mail", "link.\"}) return render(request, \"login.html\") @login_required def customers_home_page(request): return render(request, \"customers/index.html\")", "login_token = utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\" <p>Hi", "django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.decorators import", "request.POST.get(\"emailId\") user = User.objects.get(email=email) login_token = utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token)", "Admin</p> \"\"\".format(login_link) send_mail( 'Django Magic Link', html_message, '<EMAIL>', [email], fail_silently=False,", "login_required from sesame import utils from django.core.mail import send_mail def", "for magic link.\"}) return render(request, \"login.html\") @login_required def customers_home_page(request): return", "send_mail( 'Django Magic Link', html_message, '<EMAIL>', [email], fail_silently=False, html_message =", "magic link.\"}) return render(request, \"login.html\") @login_required def customers_home_page(request): return render(request,", "User from django.contrib.auth.decorators import login_required from sesame import utils from", "if request.method == \"POST\": email = request.POST.get(\"emailId\") user = User.objects.get(email=email)", "= \"\"\" <p>Hi there,</p> <p>Here is your <a href=\"{}\">magic link</a>", "import send_mail def login_page(request): if request.method == \"POST\": email =", "\"login.html\", context={\"message\":\"Please check your email for magic link.\"}) return render(request,", "import utils from django.core.mail import send_mail def login_page(request): if request.method", "from django.core.mail import send_mail def login_page(request): if request.method == \"POST\":", "href=\"{}\">magic link</a> </p> <p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link) send_mail( 'Django Magic", "html_message = html_message ) return render(request, \"login.html\", context={\"message\":\"Please check your", "= User.objects.get(email=email) login_token = utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message =", "<p>Hi there,</p> <p>Here is your <a href=\"{}\">magic link</a> </p> <p>Thanks,</p>", "sesame import utils from django.core.mail import send_mail def login_page(request): if", "from sesame import utils from django.core.mail import send_mail def login_page(request):", "\"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\" <p>Hi there,</p> <p>Here is your <a", "link</a> </p> <p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link) send_mail( 'Django Magic Link',", "fail_silently=False, html_message = html_message ) return render(request, \"login.html\", context={\"message\":\"Please check", "login_page(request): if request.method == \"POST\": email = request.POST.get(\"emailId\") user =", "User.objects.get(email=email) login_token = utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\"", "html_message = \"\"\" <p>Hi there,</p> <p>Here is your <a href=\"{}\">magic", "== \"POST\": email = request.POST.get(\"emailId\") user = User.objects.get(email=email) login_token =", "utils from django.core.mail import send_mail def login_page(request): if request.method ==", "= \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\" <p>Hi there,</p> <p>Here is your", "</p> <p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link) send_mail( 'Django Magic Link', html_message,", ") return render(request, \"login.html\", context={\"message\":\"Please check your email for magic", "= utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\" <p>Hi there,</p>", "render(request, \"login.html\", context={\"message\":\"Please check your email for magic link.\"}) return", "is your <a href=\"{}\">magic link</a> </p> <p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link)", "your <a href=\"{}\">magic link</a> </p> <p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link) send_mail(", "html_message, '<EMAIL>', [email], fail_silently=False, html_message = html_message ) return render(request,", "\"\"\" <p>Hi there,</p> <p>Here is your <a href=\"{}\">magic link</a> </p>", "[email], fail_silently=False, html_message = html_message ) return render(request, \"login.html\", context={\"message\":\"Please", "html_message ) return render(request, \"login.html\", context={\"message\":\"Please check your email for", "return render(request, \"login.html\", context={\"message\":\"Please check your email for magic link.\"})", "utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\" <p>Hi there,</p> <p>Here", "context={\"message\":\"Please check your email for magic link.\"}) return render(request, \"login.html\")", "= request.POST.get(\"emailId\") user = User.objects.get(email=email) login_token = utils.get_query_string(user) login_link =", "from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from sesame", "there,</p> <p>Here is your <a href=\"{}\">magic link</a> </p> <p>Thanks,</p> <p>Django", "<p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link) send_mail( 'Django Magic Link', html_message, '<EMAIL>',", "Magic Link', html_message, '<EMAIL>', [email], fail_silently=False, html_message = html_message )", "check your email for magic link.\"}) return render(request, \"login.html\") @login_required", "django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from sesame import", "<a href=\"{}\">magic link</a> </p> <p>Thanks,</p> <p>Django Admin</p> \"\"\".format(login_link) send_mail( 'Django", "\"POST\": email = request.POST.get(\"emailId\") user = User.objects.get(email=email) login_token = utils.get_query_string(user)", "\"\"\".format(login_link) send_mail( 'Django Magic Link', html_message, '<EMAIL>', [email], fail_silently=False, html_message", "django.contrib.auth.decorators import login_required from sesame import utils from django.core.mail import", "= html_message ) return render(request, \"login.html\", context={\"message\":\"Please check your email", "send_mail def login_page(request): if request.method == \"POST\": email = request.POST.get(\"emailId\")", "'Django Magic Link', html_message, '<EMAIL>', [email], fail_silently=False, html_message = html_message", "import User from django.contrib.auth.decorators import login_required from sesame import utils", "def login_page(request): if request.method == \"POST\": email = request.POST.get(\"emailId\") user", "user = User.objects.get(email=email) login_token = utils.get_query_string(user) login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message", "'<EMAIL>', [email], fail_silently=False, html_message = html_message ) return render(request, \"login.html\",", "<p>Django Admin</p> \"\"\".format(login_link) send_mail( 'Django Magic Link', html_message, '<EMAIL>', [email],", "your email for magic link.\"}) return render(request, \"login.html\") @login_required def", "render from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from", "django.core.mail import send_mail def login_page(request): if request.method == \"POST\": email", "request.method == \"POST\": email = request.POST.get(\"emailId\") user = User.objects.get(email=email) login_token", "email = request.POST.get(\"emailId\") user = User.objects.get(email=email) login_token = utils.get_query_string(user) login_link", "import render from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required", "import login_required from sesame import utils from django.core.mail import send_mail", "from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.decorators", "login_link = \"http://127.0.0.1:8000/customers/{}\".format(login_token) html_message = \"\"\" <p>Hi there,</p> <p>Here is", "<p>Here is your <a href=\"{}\">magic link</a> </p> <p>Thanks,</p> <p>Django Admin</p>", "Link', html_message, '<EMAIL>', [email], fail_silently=False, html_message = html_message ) return", "email for magic link.\"}) return render(request, \"login.html\") @login_required def customers_home_page(request):" ]
[ "{}.\".format(self.name)) def __repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value) def __str__(self): return", "optional): Checks to run on provided value required(bool, optional): Whether", "required(bool, optional): Whether the value can be None \"\"\" if", "success message\"\"\" self.print_success_message() def print_success_message(self): \"\"\"Formats the succee message\"\"\" logger.info(\"All", "checks have been successfully done for {}.\".format(self.name)) def __repr__(self): return", "checks are successful. Prints a success message\"\"\" self.print_success_message() def print_success_message(self):", "Whether the value can be None \"\"\" if checks is", "done for {}.\".format(self.name)) def __repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value) def", "be None \"\"\" if checks is None: checks = []", "backend for custom forms. Attributes: name(str): Name of the parameter", "if errors: self.handle_failure(errors) self.handle_success() def handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is called", "this parameter\"\"\" errors = [] for check in self.checks: try:", "the parameter checks(list[dict], optional): Checks to run on provided value", "errors: self.handle_failure(errors) self.handle_success() def handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is called when", "Errors met when running checks Returns: str: Formatted error message", "succee message\"\"\" logger.info(\"All checks have been successfully done for {}.\".format(self.name))", "in errors]) ) def handle_success(self): \"\"\"Called if all checks are", "at least one test fails. It will raise an Exception", "typing import Any, List import logging logger = logging.getLogger(__name__) class", "pass class DSSParameter: \"\"\"Object related to one parameter. It is", "errors: List[CustomCheckError]): \"\"\"Is called when at least one test fails.", "called when at least one test fails. It will raise", "CustomCheck, CustomCheckError from typing import Any, List import logging logger", "= None, required: bool = False ): \"\"\"Initialization method for", "raise an Exception with understandable text Args: errors(list[CustomCheckError]: Errors met", "Errors met when running checks Raises: DSSParameterError: Raises if at", "check fails \"\"\" raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError]) ->", "parameter \\\"{name}\\\" : {errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for e", "handle_success(self): \"\"\"Called if all checks are successful. Prints a success", "): \"\"\"Initialization method for the DSSParameter class Args: name(str): Name", "\"\"\"Called if all checks are successful. Prints a success message\"\"\"", "for parameter \\\"{name}\\\" : {errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for", "text Args: errors(list[CustomCheckError]: Errors met when running checks Returns: str:", "for this parameter\"\"\" errors = [] for check in self.checks:", "self.checks: try: check.run(self.value) except CustomCheckError as err: errors.append(err) if errors:", "DSSParameter class Args: name(str): Name of the parameter value(Any): Value", "one test fails. It will raise an Exception with understandable", "check.run(self.value) except CustomCheckError as err: errors.append(err) if errors: self.handle_failure(errors) self.handle_success()", "checks: List[dict] = None, required: bool = False ): \"\"\"Initialization", "checks provided for this parameter\"\"\" errors = [] for check", "\"\"\"Initialization method for the DSSParameter class Args: name(str): Name of", "DSSParameterError(Exception): \"\"\"Exception raised when at least one CustomCheck fails.\"\"\" pass", "when at least one CustomCheck fails.\"\"\" pass class DSSParameter: \"\"\"Object", "self.run_checks() def run_checks(self): \"\"\"Runs all checks provided for this parameter\"\"\"", "CustomCheckError from typing import Any, List import logging logger =", "= [] for check in self.checks: try: check.run(self.value) except CustomCheckError", "List import logging logger = logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception raised", ".custom_check import CustomCheck, CustomCheckError from typing import Any, List import", "\"\"\" Error for parameter \\\"{name}\\\" : {errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t", "to run in backend for custom forms. Attributes: name(str): Name", "err: errors.append(err) if errors: self.handle_failure(errors) self.handle_success() def handle_failure(self, errors: List[CustomCheckError]):", "to one parameter. It is mainly used for checks to", "errors: List[CustomCheckError]) -> str: \"\"\"Format failure text Args: errors(list[CustomCheckError]: Errors", "can be None \"\"\" def __init__( self, name: str, value:", "value: Any, checks: List[dict] = None, required: bool = False", "the parameter value(Any): Value of the parameter checks(list[dict], optional): Checks", "successful. Prints a success message\"\"\" self.print_success_message() def print_success_message(self): \"\"\"Formats the", "None: checks = [] self.name = name self.value = value", "message\"\"\" logger.info(\"All checks have been successfully done for {}.\".format(self.name)) def", "It is mainly used for checks to run in backend", "one CustomCheck fails.\"\"\" pass class DSSParameter: \"\"\"Object related to one", "return \"DSSParameter(name={}, value={})\".format(self.name, self.value) def __str__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value)", ": {errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for e in errors])", "when running checks Raises: DSSParameterError: Raises if at least on", "all checks provided for this parameter\"\"\" errors = [] for", "errors(list[CustomCheckError]: Errors met when running checks Returns: str: Formatted error", "Attributes: name(str): Name of the parameter value(Any): Value of the", "except CustomCheckError as err: errors.append(err) if errors: self.handle_failure(errors) self.handle_success() def", "a success message\"\"\" self.print_success_message() def print_success_message(self): \"\"\"Formats the succee message\"\"\"", "[] self.name = name self.value = value self.checks = [CustomCheck(**check)", "Checks to run on provided value required(bool, optional): Whether the", "name(str): Name of the parameter value(Any): Value of the parameter", "required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self): \"\"\"Runs all checks provided for", "def __init__( self, name: str, value: Any, checks: List[dict] =", "parameter. It is mainly used for checks to run in", "of the parameter value(Any): Value of the parameter checks(list[dict], optional):", "Any, List import logging logger = logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception", "= logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception raised when at least one", "handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is called when at least one test", "\"\"\"Object related to one parameter. It is mainly used for", "test fails. It will raise an Exception with understandable text", "format_failure_message(self, errors: List[CustomCheckError]) -> str: \"\"\"Format failure text Args: errors(list[CustomCheckError]:", "for the DSSParameter class Args: name(str): Name of the parameter", "least on check fails \"\"\" raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors:", "Whether the value can be None \"\"\" def __init__( self,", "required: bool = False ): \"\"\"Initialization method for the DSSParameter", "for {}.\".format(self.name)) def __repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value) def __str__(self):", "is mainly used for checks to run in backend for", "Prints a success message\"\"\" self.print_success_message() def print_success_message(self): \"\"\"Formats the succee", "= False ): \"\"\"Initialization method for the DSSParameter class Args:", "str: Formatted error message \"\"\" return \"\"\" Error for parameter", "[] for check in self.checks: try: check.run(self.value) except CustomCheckError as", "Value of the parameter checks(list[dict], optional): Checks to run on", "def __repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value) def __str__(self): return \"DSSParameter(name={},", "Args: errors(list[CustomCheckError]: Errors met when running checks Returns: str: Formatted", "provided for this parameter\"\"\" errors = [] for check in", "value can be None \"\"\" if checks is None: checks", "checks(list[dict], optional): Checks to run on provided value required(bool, optional):", "value required(bool, optional): Whether the value can be None \"\"\"", "running checks Returns: str: Formatted error message \"\"\" return \"\"\"", "checks Returns: str: Formatted error message \"\"\" return \"\"\" Error", "check in checks] if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self): \"\"\"Runs", "required(bool, optional): Whether the value can be None \"\"\" def", "def print_success_message(self): \"\"\"Formats the succee message\"\"\" logger.info(\"All checks have been", "the DSSParameter class Args: name(str): Name of the parameter value(Any):", "for custom forms. Attributes: name(str): Name of the parameter value(Any):", "fails \"\"\" raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError]) -> str:", "e in errors]) ) def handle_success(self): \"\"\"Called if all checks", "met when running checks Returns: str: Formatted error message \"\"\"", "errors]) ) def handle_success(self): \"\"\"Called if all checks are successful.", "Formatted error message \"\"\" return \"\"\" Error for parameter \\\"{name}\\\"", "= value self.checks = [CustomCheck(**check) for check in checks] if", "def run_checks(self): \"\"\"Runs all checks provided for this parameter\"\"\" errors", "name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for e in errors]) ) def handle_success(self):", "[CustomCheck(**check) for check in checks] if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def", "str, value: Any, checks: List[dict] = None, required: bool =", "met when running checks Raises: DSSParameterError: Raises if at least", "used for checks to run in backend for custom forms.", "It will raise an Exception with understandable text Args: errors(list[CustomCheckError]:", "Raises: DSSParameterError: Raises if at least on check fails \"\"\"", "logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception raised when at least one CustomCheck", "text Args: errors(list[CustomCheckError]: Errors met when running checks Raises: DSSParameterError:", "self.handle_success() def handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is called when at least", "return \"\"\" Error for parameter \\\"{name}\\\" : {errors} \"\"\".format( name=self.name,", "from .custom_check import CustomCheck, CustomCheckError from typing import Any, List", "DSSParameterError: Raises if at least on check fails \"\"\" raise", "\"\"\"Formats the succee message\"\"\" logger.info(\"All checks have been successfully done", "\"\"\"Exception raised when at least one CustomCheck fails.\"\"\" pass class", "self.print_success_message() def print_success_message(self): \"\"\"Formats the succee message\"\"\" logger.info(\"All checks have", "when at least one test fails. It will raise an", "DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError]) -> str: \"\"\"Format failure text", "DSSParameter: \"\"\"Object related to one parameter. It is mainly used", "class DSSParameter: \"\"\"Object related to one parameter. It is mainly", "custom forms. Attributes: name(str): Name of the parameter value(Any): Value", "in self.checks: try: check.run(self.value) except CustomCheckError as err: errors.append(err) if", "def handle_success(self): \"\"\"Called if all checks are successful. Prints a", "Any, checks: List[dict] = None, required: bool = False ):", "try: check.run(self.value) except CustomCheckError as err: errors.append(err) if errors: self.handle_failure(errors)", "value self.checks = [CustomCheck(**check) for check in checks] if required:", "understandable text Args: errors(list[CustomCheckError]: Errors met when running checks Raises:", "logging logger = logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception raised when at", "method for the DSSParameter class Args: name(str): Name of the", "running checks Raises: DSSParameterError: Raises if at least on check", "= [CustomCheck(**check) for check in checks] if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks()", "List[CustomCheckError]): \"\"\"Is called when at least one test fails. It", "class Args: name(str): Name of the parameter value(Any): Value of", "optional): Whether the value can be None \"\"\" def __init__(", "raised when at least one CustomCheck fails.\"\"\" pass class DSSParameter:", "to run on provided value required(bool, optional): Whether the value", "check in self.checks: try: check.run(self.value) except CustomCheckError as err: errors.append(err)", "errors = [] for check in self.checks: try: check.run(self.value) except", "be None \"\"\" def __init__( self, name: str, value: Any,", "CustomCheckError as err: errors.append(err) if errors: self.handle_failure(errors) self.handle_success() def handle_failure(self,", "import CustomCheck, CustomCheckError from typing import Any, List import logging", "\\\"{name}\\\" : {errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for e in", "\"\"\"Is called when at least one test fails. It will", "checks is None: checks = [] self.name = name self.value", "an Exception with understandable text Args: errors(list[CustomCheckError]: Errors met when", "def handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is called when at least one", "if checks is None: checks = [] self.name = name", "forms. Attributes: name(str): Name of the parameter value(Any): Value of", "= [] self.name = name self.value = value self.checks =", "parameter value(Any): Value of the parameter checks(list[dict], optional): Checks to", "raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError]) -> str: \"\"\"Format failure", "message \"\"\" return \"\"\" Error for parameter \\\"{name}\\\" : {errors}", "been successfully done for {}.\".format(self.name)) def __repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name,", "in backend for custom forms. Attributes: name(str): Name of the", "None \"\"\" def __init__( self, name: str, value: Any, checks:", "on check fails \"\"\" raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError])", "provided value required(bool, optional): Whether the value can be None", "checks = [] self.name = name self.value = value self.checks", "errors(list[CustomCheckError]: Errors met when running checks Raises: DSSParameterError: Raises if", "message\"\"\" self.print_success_message() def print_success_message(self): \"\"\"Formats the succee message\"\"\" logger.info(\"All checks", "self.name = name self.value = value self.checks = [CustomCheck(**check) for", "self, name: str, value: Any, checks: List[dict] = None, required:", "on provided value required(bool, optional): Whether the value can be", "__init__( self, name: str, value: Any, checks: List[dict] = None,", "self.handle_failure(errors) self.handle_success() def handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is called when at", "if at least on check fails \"\"\" raise DSSParameterError(self.format_failure_message(errors)) def", "run on provided value required(bool, optional): Whether the value can", "\"\"\" def __init__( self, name: str, value: Any, checks: List[dict]", "name self.value = value self.checks = [CustomCheck(**check) for check in", "\"\"\" raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError]) -> str: \"\"\"Format", "str: \"\"\"Format failure text Args: errors(list[CustomCheckError]: Errors met when running", "run_checks(self): \"\"\"Runs all checks provided for this parameter\"\"\" errors =", "{errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for e in errors]) )", "checks to run in backend for custom forms. Attributes: name(str):", "for e in errors]) ) def handle_success(self): \"\"\"Called if all", "all checks are successful. Prints a success message\"\"\" self.print_success_message() def", "None, required: bool = False ): \"\"\"Initialization method for the", "optional): Whether the value can be None \"\"\" if checks", "Name of the parameter value(Any): Value of the parameter checks(list[dict],", "fails.\"\"\" pass class DSSParameter: \"\"\"Object related to one parameter. It", "can be None \"\"\" if checks is None: checks =", "Error for parameter \\\"{name}\\\" : {errors} \"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e)", "have been successfully done for {}.\".format(self.name)) def __repr__(self): return \"DSSParameter(name={},", "class DSSParameterError(Exception): \"\"\"Exception raised when at least one CustomCheck fails.\"\"\"", "least one test fails. It will raise an Exception with", "False ): \"\"\"Initialization method for the DSSParameter class Args: name(str):", "\"\"\"Runs all checks provided for this parameter\"\"\" errors = []", "errors.append(err) if errors: self.handle_failure(errors) self.handle_success() def handle_failure(self, errors: List[CustomCheckError]): \"\"\"Is", "with understandable text Args: errors(list[CustomCheckError]: Errors met when running checks", "-> str: \"\"\"Format failure text Args: errors(list[CustomCheckError]: Errors met when", "import Any, List import logging logger = logging.getLogger(__name__) class DSSParameterError(Exception):", "related to one parameter. It is mainly used for checks", "Args: name(str): Name of the parameter value(Any): Value of the", "at least on check fails \"\"\" raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self,", "as err: errors.append(err) if errors: self.handle_failure(errors) self.handle_success() def handle_failure(self, errors:", "run in backend for custom forms. Attributes: name(str): Name of", "List[CustomCheckError]) -> str: \"\"\"Format failure text Args: errors(list[CustomCheckError]: Errors met", "Returns: str: Formatted error message \"\"\" return \"\"\" Error for", "logger.info(\"All checks have been successfully done for {}.\".format(self.name)) def __repr__(self):", "checks] if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self): \"\"\"Runs all checks", "print_success_message(self): \"\"\"Formats the succee message\"\"\" logger.info(\"All checks have been successfully", "for check in checks] if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self):", "import logging logger = logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception raised when", "the value can be None \"\"\" if checks is None:", "self.checks = [CustomCheck(**check) for check in checks] if required: self.checks.append(CustomCheck(type=\"exists\"))", "error message \"\"\" return \"\"\" Error for parameter \\\"{name}\\\" :", "for checks to run in backend for custom forms. Attributes:", "def format_failure_message(self, errors: List[CustomCheckError]) -> str: \"\"\"Format failure text Args:", "checks Raises: DSSParameterError: Raises if at least on check fails", "value(Any): Value of the parameter checks(list[dict], optional): Checks to run", "bool = False ): \"\"\"Initialization method for the DSSParameter class", "\"\"\".format( name=self.name, errors=\"\\n\".join([\"\\t {}\".format(e) for e in errors]) ) def", "if all checks are successful. Prints a success message\"\"\" self.print_success_message()", "is None: checks = [] self.name = name self.value =", "in checks] if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self): \"\"\"Runs all", "self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self): \"\"\"Runs all checks provided for this", "will raise an Exception with understandable text Args: errors(list[CustomCheckError]: Errors", "= name self.value = value self.checks = [CustomCheck(**check) for check", "List[dict] = None, required: bool = False ): \"\"\"Initialization method", "\"\"\" if checks is None: checks = [] self.name =", "mainly used for checks to run in backend for custom", "CustomCheck fails.\"\"\" pass class DSSParameter: \"\"\"Object related to one parameter.", "logger = logging.getLogger(__name__) class DSSParameterError(Exception): \"\"\"Exception raised when at least", "the value can be None \"\"\" def __init__( self, name:", "None \"\"\" if checks is None: checks = [] self.name", "Raises if at least on check fails \"\"\" raise DSSParameterError(self.format_failure_message(errors))", "the succee message\"\"\" logger.info(\"All checks have been successfully done for", "__repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value) def __str__(self): return \"DSSParameter(name={}, value={})\".format(self.name,", "parameter checks(list[dict], optional): Checks to run on provided value required(bool,", "parameter\"\"\" errors = [] for check in self.checks: try: check.run(self.value)", ") def handle_success(self): \"\"\"Called if all checks are successful. Prints", "Exception with understandable text Args: errors(list[CustomCheckError]: Errors met when running", "failure text Args: errors(list[CustomCheckError]: Errors met when running checks Returns:", "when running checks Returns: str: Formatted error message \"\"\" return", "are successful. Prints a success message\"\"\" self.print_success_message() def print_success_message(self): \"\"\"Formats", "value can be None \"\"\" def __init__( self, name: str,", "self.value = value self.checks = [CustomCheck(**check) for check in checks]", "errors=\"\\n\".join([\"\\t {}\".format(e) for e in errors]) ) def handle_success(self): \"\"\"Called", "fails. It will raise an Exception with understandable text Args:", "at least one CustomCheck fails.\"\"\" pass class DSSParameter: \"\"\"Object related", "from typing import Any, List import logging logger = logging.getLogger(__name__)", "Args: errors(list[CustomCheckError]: Errors met when running checks Raises: DSSParameterError: Raises", "one parameter. It is mainly used for checks to run", "successfully done for {}.\".format(self.name)) def __repr__(self): return \"DSSParameter(name={}, value={})\".format(self.name, self.value)", "\"\"\"Format failure text Args: errors(list[CustomCheckError]: Errors met when running checks", "\"\"\" return \"\"\" Error for parameter \\\"{name}\\\" : {errors} \"\"\".format(", "for check in self.checks: try: check.run(self.value) except CustomCheckError as err:", "{}\".format(e) for e in errors]) ) def handle_success(self): \"\"\"Called if", "of the parameter checks(list[dict], optional): Checks to run on provided", "least one CustomCheck fails.\"\"\" pass class DSSParameter: \"\"\"Object related to", "name: str, value: Any, checks: List[dict] = None, required: bool", "if required: self.checks.append(CustomCheck(type=\"exists\")) self.run_checks() def run_checks(self): \"\"\"Runs all checks provided" ]
[ "don't. Instead, there are only two options without arguments: #", "from __future__ import print_function # This was written before transitfeed.py", "2.0 (the \"License\"); # you may not use this file", "xb = (y - 200000.0) / 1e6; lam = 2.6779094", "self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for date in service: out.write('%s,%d,1\\n' %", "elif code == 'E': self.drop_off_type[key] = '1' # '1' =", "* xb \\ + 0.1306 * yb * xb *", "{} # This is ugly as hell, I know. I", "out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,'", "Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli':", "month ( 8 * 4bits = 32, no month has", "hell, I know. I briefly explain what I do: #", "Swiss national grid system to WGS-84.\" yb = (x -", "for names = name.split(\", \", 1) if len(names) == 2:", "disgusting) and mark that date... for i in range(MonthNr(end_date) -", "{20060713:1, 20060714:1, ...} schedules = {} # {'j06':1, 'p27':1} for", "stations.sort() for id, s in stations: write_row(out, [id, s.uic_code, s.name,", "__future__ import print_function # This was written before transitfeed.py and", "import urllib import zipfile # Zurich tram lines TRAM_LINES =", "\\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id] = station for station_id,", "for schedule, id, bitmask, start_date, end_date in \\ read_csv(restrictions_file, ['FPL_KUERZEL',", "print_function # This was written before transitfeed.py and we haven't", "% ( id, name, name, route.type, route.color, route.color_text)) def write_stations(self,", "# --nodrop_unadvertised_lines do not drop # --drop_unadvertised_lines drop opt_parser =", "city) def import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath, mode=\"r\") read =", "WGS-84.\" yb = (x - 600000.0) / 1e6; xb =", "pass class Pattern: pass class Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM", "direction, \\ stoptime_id, schedule_id, daytype_id, restriction_id, \\ dest_station_id, dest_stop_id, trip_type", "where our heuristcs doesn't work. # Example:\"Triemli\" --> (\"Triemli\", \"Zurich\").", "line, strli, direction, seq, station_id in \\ read_csv(s, ['LI_NR', 'STR_LI_VAR',", "West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>':", "BEDVERB_CODE=%s' % (trip_id, code)) def import_services(self, daytype_file, days_file): daytypes =", "stoptime_id, drive_secs, wait_secs in \\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',", "or '\"' in k: return '\"%s\"' % k.replace('\"', '\"\"') else:", "seq # fails if seq not in order stoptimes.append((drive_secs, wait_secs))", "advertised lines file references \" \\ \"unknown station, id \"", "in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id in self.stations: # Line", "--drop_unadvertised_lines, so we # don't. Instead, there are only two", "u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli',", "\\ + 0.1306 * yb * xb * xb \\", "class Pattern: pass class Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM =", "License for the specific language governing permissions and # limitations", "was written before transitfeed.py and we haven't yet found the", "trip_id, seq, code in \\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key", "import_stop_times(self, stoptimes_file): \"imports the lid_fahrzeitart.mdv file.\" for line, strli, direction,", "TRAM_LINES[name][1] else: route.type = TYPE_BUS if route.name[0:1] == \"N\": route.color", "+ int(x[4:6]) for schedule, id, bitmask, start_date, end_date in \\", "= {'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation': 1, 'Station': 1, u'Zentrum':", "station.advertised_lines: write_row(out, [trip.id, str(seq + 1), station.id, self.format_time(time), self.format_time(time +", "# motivation to port it. Please see the examples directory", "schedules = schedules.keys() service_days = {} # 'Cj06.H9' --> {20060713:1,", "haven't yet found the # motivation to port it. Please", "no pick-up elif code == 'E': self.drop_off_type[key] = '1' #", "stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq) - 1 drive_secs", "= lambda name, prefix=\"\": (prefix + inzip.read(name)).splitlines() # The advertised", "lambda name, prefix=\"\": (prefix + inzip.read(name)).splitlines() # The advertised lines", "'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)] stoptimes =", "\\ + 4.728982 * yb \\ + 0.791484 * yb", "( id, name, name, route.type, route.color, route.color_text)) def write_stations(self, out):", "range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq] time += drive_time station =", "= schedules.keys() service_days = {} # 'Cj06.H9' --> {20060713:1, 20060714:1,", "['000000', 'FFFFFF'], '8': ['99CC00', '000000'], '9': ['333399', 'FFFFFF'], '10': ['FF6699',", "str(s.position[1]), s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id, service", "direction) pattern = self.patterns.get(pattern_id, None) if not pattern: pattern =", "1): mask = int(bitmask[i * 8:i * 8 + 8],", "stations: write_row(out, [id, s.uic_code, s.name, s.city, s.country, str(s.position[0]), str(s.position[1]), s.url])", "1) % 12) + 1 day = d + 1", "= u\"VB%s.%s\" % (schedule, id) bitmask = bitmask.strip() dates =", "in \\ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL',", "- 0.002582 * xb * xb \\ - 0.0447 *", "assert len(trip.stoptimes) == len(trip.pattern.stops) time = trip.starttime for seq in", "\", 1) if len(names) == 2: if names[1] in POI_TERMS:", "mask = int(bitmask[i * 8:i * 8 + 8], 16)", "self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq", "route.type, route.color, route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations =", "bedverb.mdv file.\" for trip_id, seq, code in \\ read_csv(drop_off_file, ['FRT_FID',", "['FFFFFF', '000000'], '13': ['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'], '15': ['FF3300',", "= [(t.id, t) for t in self.trips.itervalues()] trips.sort() for (trip_id,", "#!/usr/bin/python2.4 # Copyright (C) 2008 Google Inc. # # Licensed", "'FFFFFF'], '4': ['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'],", "for line, strli, direction, seq, station_id in \\ read_csv(s, ['LI_NR',", "= self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id = u'VB%s.%s'", "to have the driver # stop. We don't encode this", "self.coord_converter = coord_converter self.stations = {} # id --> Station", "schedule bubbles. Use # --nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true',", "# The advertised lines file has no column headers. self.import_stations(read('rec_ort.mdv'),", "station = Station() station.id = id station.position = self.coord_converter(float(x), float(y))", "self.goodTrips: continue assert len(trip.stoptimes) == len(trip.pattern.stops) time = trip.starttime for", "value to the --out_file flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file)", "'LINIEN_BEZ_DRUCK']): route = Route() route.id = line_id route.name = name", "['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'], '8': ['99CC00', '000000'], '9': ['333399',", "} def read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader = csv.reader(s,", "daytype_id, restriction_id, \\ dest_station_id, dest_stop_id, trip_type in \\ read_csv(trips_file, ['FRT_FID',", "dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file): \"imports the lid_fahrzeitart.mdv file.\" for", "them by trip.id # we should make trip.id unique, by", "\"Zurich\"). if name in SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand abbreviations.", "def write(self, outpath): \"writes a .zip file in Google Transit", "= names[1] city = names[0] else: # \"Zurich Enge\": First", "dates = {} # This is ugly as hell, I", "OF ANY KIND, either express or implied. # See the", "See the License for the specific language governing permissions and", "+ 1): mask = int(bitmask[i * 8:i * 8 +", "for i in range(MonthNr(end_date) - MonthNr(start_date) + 1): mask =", "date in daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1", "pickup self.drop_off_type = {} # (trip_id, stop_seq) --> '0'/'1', '1'=no", "to in writing, software # distributed under the License is", "month and actual day I am in # (very disgusting)", "\", [trip.id]) continue self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out,", "the bitmask). # If so I calculate back what year", "equal a month ( 8 * 4bits = 32, no", "Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt',", "CSV.\" k = x.encode('utf-8') if ',' in k or '\"'", "\"imports the lid_verlauf.mdv file.\" for line, strli, direction, seq, station_id", "= d + 1 cur_date = str(year) + (\"0\" +", "or agreed to in writing, software # distributed under the", "replicate the old behavior of --drop_unadvertised_lines, so we # don't.", "date in \\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip()", "ids in this file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else:", "vbz data, as of Dec 2009 # to prevent overwritingimported", "self.routes[route.id] = route def import_patterns(self, s): \"imports the lid_verlauf.mdv file.\"", "import print_function # This was written before transitfeed.py and we", "write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips = [(t.id, t) for t", "options.out_file is None: raise SystemExit('Please provide a value to the", "row in reader: result = [None] * len(cols) for i", "nam = names[1] city = names[0] else: # \"Zurich Enge\":", "pattern.stops.extend([None] * (seq - len(pattern.stops) + 1)) pattern.stops[seq] = station_id", "line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id in self.stations: #", "print(\"skipping Trip \", trip_id, line, direction, \\ dest_station_id, trip_type) continue", "import StringIO as cStringIO except ImportError: import cStringIO import csv", "for t in self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips:", "# The trip_id (FRT_FID) field is not unique in the", "compliance with the License. # You may obtain a copy", "does not include area. Fortunately, it seems # that line", "# https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS = 3 class Divaimporter:", "@staticmethod def demangle_name(name): \"Applies some simple heuristics to split names", "id, route in k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % (", "values to stream.\" stream.write(','.join([encode_for_csv(val) for val in values])) stream.write('\\n') class", "wait_time def main(argv): # It's hard to replicate the old", "len(uic_code) == 7 and uic_code[:2] == '85': station.uic_code = uic_code", "special cases where our heuristcs doesn't work. # Example:\"Triemli\" -->", "pattern.id = pattern_id pattern.stops = [] pattern.stoptimes = {} self.patterns[pattern_id]", "(prefix + inzip.read(name)).splitlines() # The advertised lines file has no", "in daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1 for", "POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation': 1, 'Station': 1,", "pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) pattern = self.patterns.get(pattern_id,", "references \" \\ \"unknown station, id \" + station_id) def", "['FF3300', 'FFFFFF']} # Terms that indicate points of interest. Used", "not use this file except in compliance with the License.", "urllib import zipfile # Zurich tram lines TRAM_LINES = {'2':", "self.write_stations), ('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close()", "in TRAM_LINES: route.type = TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text =", "outpath): \"writes a .zip file in Google Transit format.\" out", "\\ - 0.002582 * xb * xb \\ - 0.0447", "you may not use this file except in compliance with", "out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for", "in trips: if (not len(trip.pattern.stops)) or (None in trip.pattern.stops): print(\"***", "strli, direction) pattern = self.patterns.get(pattern_id, None) if not pattern: pattern", "- MonthNr(start_date) + 1): mask = int(bitmask[i * 8:i *", "and we haven't yet found the # motivation to port", "= {} self.patterns[pattern_id] = pattern seq = int(seq) - 1", "strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq) -", "val in values])) stream.write('\\n') class Station: pass class Route: pass", "'12': ['FFFFFF', '000000'], '13': ['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'], '15':", "export format to Google Transit format.\"\"\" from __future__ import print_function", "not self._drop_unadvertised_lines or \\ trip.route.id in station.advertised_lines: write_row(out, [trip.id, str(seq", "8 characters in the bitmask equal a month ( 8", "Station: pass class Route: pass class Pattern: pass class Trip:", "etc, to not confuse the data in schedule bubbles. Use", "# that line ids are unique across all areas, so", "route.id = line_id route.name = name route.color = \"FFFFFF\" route.color_text", "time. SPECIAL_CITIES = { 'Affoltern a. A.': 'Affoltern am Albis',", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "= uic_code station.name, station.city = self.demangle_name(name) station.country = 'CH' station.url", "(\"0\" + str(month))[-2:] + (\"0\" + str(day))[-2:] dates[int(cur_date)] = 1", "strli, direction, \\ stoptime_id, schedule_id, daytype_id, restriction_id, \\ dest_station_id, dest_stop_id,", "name, name, route.type, route.color, route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n')", "def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter self.stations = {}", "= next(reader) col_index = [-1] * len(cols) for i in", "\\ dest_station_id, trip_type) continue # 1=normal, 2=empty, 3=from depot, 4=to", "'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'], '8': ['99CC00', '000000'],", "+ (\"0\" + str(day))[-2:] dates[int(cur_date)] = 1 self.services[id] = dates.keys()", "encode this for now. pass else: raise ValueError('Unexpected code in", "s = cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod def write_agency(out):", "Station() station.id = id station.position = self.coord_converter(float(x), float(y)) station.uic_code =", "in trip.pattern.stops): print(\"*** Skipping bad trip: \", [trip.id]) continue self.goodTrips[trip_id]", "else: return k def write_row(stream, values): \"writes one row of", "7 and uic_code[:2] == '85': station.uic_code = uic_code station.name, station.city", "xb * xb return phi * 100.0 / 36.0, lam", "of comma-separated values to stream.\" stream.write(','.join([encode_for_csv(val) for val in values]))", "in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self, out):", "in range(MonthNr(end_date) - MonthNr(start_date) + 1): mask = int(bitmask[i *", "pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS = 3 class", "stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file): \"imports the rec_frt.mdv file.\" for", "1e6; lam = 2.6779094 \\ + 4.728982 * yb \\", "\"Converts coordinates from the 1903 Swiss national grid system to", "'Zentrum/Bahnhof': 1, 'Dorf': 1} # Maps station names to (name,", "= 1 schedules = schedules.keys() service_days = {} # 'Cj06.H9'", "Used as exception list where our # simple heuristcs doesn't", "/ 3600, (t % 3600) / 60, t % 60)", "daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1 for k in service_days.iterkeys(): self.services[k]", "yb * yb phi = 16.9023892 \\ + 3.238372 *", "= { 'Freienbach SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West':", "the # table of advertised lines does not include area.", "['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']} # Terms that indicate points", "so we can just throw it away. for line_id, name", "raise SystemExit('Please provide a value to the --in_file flag.') if", "& mask: year = int(start_date[0:4]) + ((int(start_date[4:6]) + i -", "than 31 days, so it's ok). # Then I check", "Only export the departures of lines that # are advertised", "TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else: route.type = TYPE_BUS if route.name[0:1]", "trip def write(self, outpath): \"writes a .zip file in Google", "Route self.patterns = {} # id --> Pattern self.services =", "the driver # stop. We don't encode this for now.", "the data in schedule bubbles. Use # --nodrop_unadvertised_lines to disable", "= trip def write(self, outpath): \"writes a .zip file in", "'FFFFFF'], '3': ['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'],", "self.demangle_name(name) station.country = 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1'))", "route.name[0:1] == \"N\": route.color = \"000000\" route.color_text = \"FFFF00\" self.routes[route.id]", "month has # more than 31 days, so it's ok).", "len(stoptimes) == seq # fails if seq not in order", "'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev) if suffix_pos > 0:", "- 0.0447 * yb * yb * xb \\ -", "--> Pattern self.services = {} # id --> [date, date,", "\"Reads the vb_regio.mdv file.\" ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]),", "== 'B': # 'B' just means that rider needs to", "= {} # 'j06' --> {20060713:1, 20060714:1, ...} schedules =", "s in stations: write_row(out, [id, s.uic_code, s.name, s.city, s.country, str(s.position[0]),", "if names[1] in POI_TERMS: nam = u'%s %s' % (names[0],", "* len(cols) for i in range(len(cols)): if cols[i] in header:", "if ci >= 0: result[i] = row[ci].decode('iso-8859-1').strip() yield result def", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "yb \\ - 0.002582 * xb * xb \\ -", "by trip.id # we should make trip.id unique, by combining", "'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type", "filename, func in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt',", "def import_routes(self, s): \"imports the rec_lin_ber.mdv file.\" # the line", "= route def import_patterns(self, s): \"imports the lid_verlauf.mdv file.\" for", "service = 'C%s.%s' % (schedule, service_id) for date in daytypes['%s.%s'", "s.uic_code, s.name, s.city, s.country, str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self, out):", "['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq) - 1) if", "options without arguments: # nothing drop # --nodrop_unadvertised_lines do not", "# shifting the bit by x days and comparing it", "self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n')", "\\ + 0.791484 * yb * xb \\ + 0.1306", "= 'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id] =", "uic_code in \\ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station", "__init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter self.stations = {} #", "seq, station_id in \\ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']):", "dest_station_id, trip_type) continue # 1=normal, 2=empty, 3=from depot, 4=to depot,", "for (trip_id, trip) in trips: if (not len(trip.pattern.stops)) or (None", "header: col_index[i] = header.index(cols[i]) for row in reader: result =", "in \\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s'", "actual day I am in # (very disgusting) and mark", "(schedule, id) bitmask = bitmask.strip() dates = {} # This", "# {'j06':1, 'p27':1} for schedule, daytype, date in \\ read_csv(days_file,", "it seems # that line ids are unique across all", "out = zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename, func in [('agency.txt',", "'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital", "xb return phi * 100.0 / 36.0, lam * 100.0", "'1'=no drop-off self.trips = {} # id --> Trip self.goodTrips", "col_index[i] if ci >= 0: result[i] = row[ci].decode('iso-8859-1').strip() yield result", "file except in compliance with the License. # You may", "what I do: # 8 characters in the bitmask equal", "can just throw it away. for line_id, name in \\", "60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips = [(t.id, t)", "= int(seq) - 1 if len(pattern.stops) <= seq: pattern.stops.extend([None] *", "in trips: if trip_id not in self.goodTrips: continue assert len(trip.stoptimes)", "def import_patterns(self, s): \"imports the lid_verlauf.mdv file.\" for line, strli,", "if options.in_file is None: raise SystemExit('Please provide a value to", "schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)] = 1 schedules[schedule] =", "'000000'], '14': ['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']} # Terms that", "= TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else: route.type = TYPE_BUS if", "name.split(\", \", 1) if len(names) == 2: if names[1] in", "if name in TRAM_LINES: route.type = TYPE_TRAM route.color = TRAM_LINES[name][0]", "id, s in stations: write_row(out, [id, s.uic_code, s.name, s.city, s.country,", "for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \\", "doesn't work. SPECIAL_NAMES = { 'Freienbach SOB, Bahnhof': ('Freienbach SOB',", "mark that date... for i in range(MonthNr(end_date) - MonthNr(start_date) +", "* 100.0 / 36.0, lam * 100.0 / 36.0 def", "of advertised lines does not include area. Fortunately, it seems", "whose names we want to prettify/correct at import time. SPECIAL_CITIES", "= u'Pat.%s.%s.%s' % (line, strli, direction) pattern = self.patterns.get(pattern_id, None)", "back what year month and actual day I am in", "expanded in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev) if", "trip_id (FRT_FID) field is not unique in the vbz data,", "seq not in order stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file): \"imports", "values): \"writes one row of comma-separated values to stream.\" stream.write(','.join([encode_for_csv(val)", "3 class Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter", "/ 60, t % 60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n')", "inzip = zipfile.ZipFile(inpath, mode=\"r\") read = lambda name, prefix=\"\": (prefix", "have the driver # stop. We don't encode this for", "col_index[i] = header.index(cols[i]) for row in reader: result = [None]", "dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store',", "# Example:\"Triemli\" --> (\"Triemli\", \"Zurich\"). if name in SPECIAL_NAMES: return", "str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id,", "qualified with an area_id (BEREICH_NR), but the # table of", "trip.route = self.routes[line] dest_station = self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' %", "under the License. \"\"\"imports Zurich timetables, converting them from DIVA", "(schedule, daytype), {})[int(date)] = 1 schedules[schedule] = 1 schedules =", "KIND, either express or implied. # See the License for", "if suffix_pos > 0: name = name[:suffix_pos] + expanded #", "('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev) if suffix_pos > 0: name", "direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id", "[(r.id, r) for r in self.routes.itervalues()] k.sort() for id, route", "data, as of Dec 2009 # to prevent overwritingimported trips", "in \\ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station =", "for station_id, line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id in", "lines does not include area. Fortunately, it seems # that", "Google Inc. # # Licensed under the Apache License, Version", "data in schedule bubbles. Use # --nodrop_unadvertised_lines to disable that.", "self.write_stop_times)]: s = cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod def", "trip.route.id, trip.service_id, headsign]) @staticmethod def format_time(t): return \"%02d:%02d:%02d\" % (t", "read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id = u\"VB%s.%s\" %", "Transit format.\" out = zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename, func", "(the \"License\"); # you may not use this file except", "result def convert_c_h1903(x, y): \"Converts coordinates from the 1903 Swiss", "+ (\"0\" + str(month))[-2:] + (\"0\" + str(day))[-2:] dates[int(cur_date)] =", "self.routes.itervalues()] k.sort() for id, route in k: name = encode_for_csv(route.name)", "as hell, I know. I briefly explain what I do:", "...] (sorted) self.pickup_type = {} # (trip_id, stop_seq) --> '0'=normal/'1'=no", "'7': ['000000', 'FFFFFF'], '8': ['99CC00', '000000'], '9': ['333399', 'FFFFFF'], '10':", "if station_id in self.stations: # Line ids in this file", "t) for t in self.trips.itervalues()] trips.sort() for (trip_id, trip) in", "= pattern seq = int(seq) - 1 if len(pattern.stops) <=", "= u'Pat.%s.%s.%s' % (line, strli, direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes", "importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to', options.out_file)", "# # Unless required by applicable law or agreed to", "% (names[0], names[1]) else: nam = names[1] city = names[0]", "self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO()", "if uic_code and len(uic_code) == 7 and uic_code[:2] == '85':", "raise ValueError('Unexpected code in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id,", "The advertised lines file has no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv',", "main(argv): # It's hard to replicate the old behavior of", "yb * yb * xb \\ - 0.0140 * xb", "'stop_lat,stop_lon,stop_url\\n') stations = [(s.id, s) for s in self.stations.itervalues()] stations.sort()", "implied. # See the License for the specific language governing", "stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type = {} # (trip_id, stop_seq)", "# 'B' just means that rider needs to push a", "t in self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if", "timetables, converting them from DIVA export format to Google Transit", "('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO() func(s)", "names to (name, city). Used as exception list where our", "% (schedule_id, restriction_id) else: service_id = u'C%s.%s' % (schedule_id, daytype_id)", "len(pattern.stops) <= seq: pattern.stops.extend([None] * (seq - len(pattern.stops) + 1))", "lid_fahrzeitart.mdv file.\" for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs", "self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq), '0')]) time", "in stations: write_row(out, [id, s.uic_code, s.name, s.city, s.country, str(s.position[0]), str(s.position[1]),", "in \\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']):", "route.type = TYPE_BUS if route.name[0:1] == \"N\": route.color = \"000000\"", "from DIVA export format to Google Transit format.\"\"\" from __future__", "int(seq) - 1) if code == 'A': self.pickup_type[key] = '1'", "check if the current day of the month is in", "dest_stop_id, trip_type in \\ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR',", "= Route() route.id = line_id route.name = name route.color =", "to Google Transit format.\"\"\" from __future__ import print_function # This", "seq = int(seq) - 1 drive_secs = int(drive_secs) wait_secs =", "Zurich timetables, converting them from DIVA export format to Google", "= col_index[i] if ci >= 0: result[i] = row[ci].decode('iso-8859-1').strip() yield", "are advertised at the station in question. This is used", "for s in self.stations.itervalues()] stations.sort() for id, s in stations:", "of the month is in the bitmask (by # shifting", "the city nam = names[0] city = nam.split(' ')[0] return", "def write_row(stream, values): \"writes one row of comma-separated values to", "# (trip_id, stop_seq) --> '0'/'1', '1'=no drop-off self.trips = {}", "...} for daytype, service_id in \\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for", "city = nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city, city) def import_feeds(self,", "write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k = [(r.id, r) for r", "= lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr = lambda x:", "for (trip_id, trip) in trips: if trip_id not in self.goodTrips:", "as cStringIO except ImportError: import cStringIO import csv import datetime", "where our # simple heuristcs doesn't work. SPECIAL_NAMES = {", "at import time. SPECIAL_CITIES = { 'Affoltern a. A.': 'Affoltern", "A.': 'Affoltern am Albis', 'Wangen b. D.': 'Wangen' } def", "schedules.keys() service_days = {} # 'Cj06.H9' --> {20060713:1, 20060714:1, ...}", "xb * xb * xb return phi * 100.0 /", "1 cur_date = str(year) + (\"0\" + str(month))[-2:] + (\"0\"", "# Cities whose names we want to prettify/correct at import", "( 8 * 4bits = 32, no month has #", "Unless required by applicable law or agreed to in writing,", "str(day))[-2:] dates[int(cur_date)] = 1 self.services[id] = dates.keys() self.services[id].sort() def import_stop_times(self,", "self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq), '0')]) time += wait_time def", "to prettify/correct at import time. SPECIAL_CITIES = { 'Affoltern a.", "read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id in self.stations: # Line ids", "# Copyright (C) 2008 Google Inc. # # Licensed under", "station_id) def import_routes(self, s): \"imports the rec_lin_ber.mdv file.\" # the", "% (line, strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq =", "lines file has no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv'))", "and uic_code[:2] == '85': station.uic_code = uic_code station.name, station.city =", "the specific language governing permissions and # limitations under the", "drop-off elif code == 'B': # 'B' just means that", "trips.sort() for (trip_id, trip) in trips: if (not len(trip.pattern.stops)) or", "if options.out_file is None: raise SystemExit('Please provide a value to", "when we key them by trip.id # we should make", "('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'), } # Cities", "class Route: pass class Pattern: pass class Trip: pass #", "= names[0] else: # \"Zurich Enge\": First word of station", "class Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter self.stations", "name[:suffix_pos] + expanded # end for names = name.split(\", \",", "= 3 class Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter =", "line) trip.starttime = int(trip_starttime) trip.route = self.routes[line] dest_station = self.stations[dest_station_id]", "+ 0.1306 * yb * xb * xb \\ -", "['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station() station.id =", "# \"Zurich Enge\": First word of station name designates the", "'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) def import_services(self, daytype_file, days_file): daytypes", "in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt',", "\", trip_id, line, direction, \\ dest_station_id, trip_type) continue # 1=normal,", "= trip.starttime for seq in range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq]", "route.type = TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else:", "\"N\": route.color = \"000000\" route.color_text = \"FFFF00\" self.routes[route.id] = route", "drive_time station = self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or \\ trip.route.id", "(schedule_id, restriction_id) else: service_id = u'C%s.%s' % (schedule_id, daytype_id) trip.service_id", "'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id = u\"VB%s.%s\" % (schedule, id)", "the bitmask (by # shifting the bit by x days", "out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k = [(r.id, r) for r in", "\"%02d:%02d:%02d\" % (t / 3600, (t % 3600) / 60,", "('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum", "overwritingimported trips when we key them by trip.id # we", "\\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id = u\"VB%s.%s\"", "str(month))[-2:] + (\"0\" + str(day))[-2:] dates[int(cur_date)] = 1 self.services[id] =", "in \\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq)", "\\ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station()", "port it. Please see the examples directory for better #", "datetime import optparse import sys import urllib import zipfile #", "trips = [(t.id, t) for t in self.trips.itervalues()] trips.sort() for", "@staticmethod def format_time(t): return \"%02d:%02d:%02d\" % (t / 3600, (t", "West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'),", "bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) def import_services(self, daytype_file,", "u\"VB%s.%s\" % (schedule, id) bitmask = bitmask.strip() dates = {}", "out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id, t) for t in self.trips.itervalues()] trips.sort()", "the lid_fahrzeitart.mdv file.\" for line, strli, direction, seq, stoptime_id, drive_secs,", "to port it. Please see the examples directory for better", "{'j06':1, 'p27':1} for schedule, daytype, date in \\ read_csv(days_file, ['FPL_KUERZEL',", "[('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev) if suffix_pos >", "return k def write_row(stream, values): \"writes one row of comma-separated", "= {} # id --> Trip self.goodTrips = {} self._drop_unadvertised_lines", "['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'], '5': ['996600',", "names[1]) else: nam = names[1] city = names[0] else: #", "k: return '\"%s\"' % k.replace('\"', '\"\"') else: return k def", "\"imports the rec_lin_ber.mdv file.\" # the line id is really", "int(bitmask[i * 8:i * 8 + 8], 16) for d", "direction, seq, stoptime_id, drive_secs, wait_secs in \\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR',", "bad trip: \", [trip.id]) continue self.goodTrips[trip_id] = True headsign =", "== \"N\": route.color = \"000000\" route.color_text = \"FFFF00\" self.routes[route.id] =", "2008 Google Inc. # # Licensed under the Apache License,", "36.0, lam * 100.0 / 36.0 def encode_for_csv(x): \"Encodes one", "= station for station_id, line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if", "has # more than 31 days, so it's ok). #", "prettify/correct at import time. SPECIAL_CITIES = { 'Affoltern a. A.':", "rider needs to push a button to have the driver", "header = next(reader) col_index = [-1] * len(cols) for i", "heuristcs doesn't work. SPECIAL_NAMES = { 'Freienbach SOB, Bahnhof': ('Freienbach", "sys import urllib import zipfile # Zurich tram lines TRAM_LINES", "for service_id, service in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for date", "8 * 4bits = 32, no month has # more", "simple heuristics to split names into (city, name).\" # Handle", "(line, strli, direction) pattern = self.patterns.get(pattern_id, None) if not pattern:", "{} # 'j06' --> {20060713:1, 20060714:1, ...} schedules = {}", "yb * yb * yb phi = 16.9023892 \\ +", "% 3600) / 60, t % 60) def write_stop_times(self, out):", "SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand abbreviations. for abbrev, expanded in", "# This is ugly as hell, I know. I briefly", "uic_code and len(uic_code) == 7 and uic_code[:2] == '85': station.uic_code", "trip.service_id, headsign]) @staticmethod def format_time(t): return \"%02d:%02d:%02d\" % (t /", "import_boarding(self, drop_off_file): \"Reads the bedverb.mdv file.\" for trip_id, seq, code", "x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr = lambda x: int(x[:4]) *", "self.patterns.get(pattern_id, None) if not pattern: pattern = Pattern() pattern.id =", "# (very disgusting) and mark that date... for i in", "the 1903 Swiss national grid system to WGS-84.\" yb =", "# Maps station names to (name, city). Used as exception", "rec_lin_ber.mdv file.\" # the line id is really qualified with", "= Station() station.id = id station.position = self.coord_converter(float(x), float(y)) station.uic_code", "\\ + 3.238372 * xb \\ - 0.270978 * yb", "coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter self.stations = {} # id", "type='string') opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file", "else: print(\"Warning, advertised lines file references \" \\ \"unknown station,", "drive_secs, wait_secs in \\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR',", "yb = (x - 600000.0) / 1e6; xb = (y", "ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr = lambda", "You may obtain a copy of the License at #", "encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % ( id, name, name, route.type, route.color, route.color_text))", "['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS',", "(\"0\" + str(day))[-2:] dates[int(cur_date)] = 1 self.services[id] = dates.keys() self.services[id].sort()", "into (city, name).\" # Handle special cases where our heuristcs", "print(\"*** Skipping bad trip: \", [trip.id]) continue self.goodTrips[trip_id] = True", "MonthNr(start_date) + 1): mask = int(bitmask[i * 8:i * 8", "* xb \\ - 0.0436 * yb * yb *", "see the examples directory for better # examples. try: from", "opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string')", "u'%s %s' % (names[0], names[1]) else: nam = names[1] city", "'1': print(\"skipping Trip \", trip_id, line, direction, \\ dest_station_id, trip_type)", "date, ...] (sorted) self.pickup_type = {} # (trip_id, stop_seq) -->", "urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id] = station for station_id, line_id", "is used to remove # depot trips etc, to not", "if len(pattern.stops) <= seq: pattern.stops.extend([None] * (seq - len(pattern.stops) +", "code == 'B': # 'B' just means that rider needs", "xb \\ - 0.0140 * xb * xb * xb", "'Freienbach SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West',", "bubbles. Use # --nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines',", "shifting the bit by x days and comparing it to", "Maps station names to (name, city). Used as exception list", "inzip.read(name)).splitlines() # The advertised lines file has no column headers.", "in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) def import_services(self,", "id = u\"VB%s.%s\" % (schedule, id) bitmask = bitmask.strip() dates", "('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'),", "1, 'Dorf': 1} # Maps station names to (name, city).", "the --in_file flag.') if options.out_file is None: raise SystemExit('Please provide", "to split station names # to (name, city). POI_TERMS =", "in values])) stream.write('\\n') class Station: pass class Route: pass class", "names into (city, name).\" # Handle special cases where our", "name in \\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route() route.id", "= row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x, y): \"Converts coordinates from", "= id station.position = self.coord_converter(float(x), float(y)) station.uic_code = '' if", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "row of comma-separated values to stream.\" stream.write(','.join([encode_for_csv(val) for val in", "== 7 and uic_code[:2] == '85': station.uic_code = uic_code station.name,", "for d in range(32): if 1 << d & mask:", "from io import StringIO as cStringIO except ImportError: import cStringIO", "write_row(stream, values): \"writes one row of comma-separated values to stream.\"", "1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf': 1} # Maps station", "yb * xb \\ + 0.1306 * yb * xb", "['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'], '13': ['FFCC33', '000000'], '14': ['3399CC',", "\"FFFF00\" self.routes[route.id] = route def import_patterns(self, s): \"imports the lid_verlauf.mdv", "% 60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips = [(t.id,", "unique in the vbz data, as of Dec 2009 #", "'14': ['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']} # Terms that indicate", "SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath, mode=\"r\") read", "- 1) if code == 'A': self.pickup_type[key] = '1' #", "pass class Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS", "{} self.patterns[pattern_id] = pattern seq = int(seq) - 1 if", "u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf': 1} # Maps", "(name, city). POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation': 1,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "* xb * xb \\ - 0.0447 * yb *", "= int(seq) - 1 drive_secs = int(drive_secs) wait_secs = int(wait_secs)", "License. # You may obtain a copy of the License", "= [(s.id, s) for s in self.stations.itervalues()] stations.sort() for id,", "\\ - 0.270978 * yb * yb \\ - 0.002582", "names[1] city = names[0] else: # \"Zurich Enge\": First word", "Used to split station names # to (name, city). POI_TERMS", "am Albis', 'Wangen b. D.': 'Wangen' } def read_csv(s, cols):", "departures of lines that # are advertised at the station", "self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s", "zipfile # Zurich tram lines TRAM_LINES = {'2': ['FF3300', 'FFFFFF'],", "limitations under the License. \"\"\"imports Zurich timetables, converting them from", "read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file): \"imports", "reader = csv.reader(s, csv_dialect) header = next(reader) col_index = [-1]", "csv_dialect) header = next(reader) col_index = [-1] * len(cols) for", "national grid system to WGS-84.\" yb = (x - 600000.0)", "= line_id route.name = name route.color = \"FFFFFF\" route.color_text =", "file.\" for id, name, x, y, uic_code in \\ read_csv(station_file,", "service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self,", "to remove # depot trips etc, to not confuse the", "Albis', 'Wangen b. D.': 'Wangen' } def read_csv(s, cols): csv_dialect", "cols[i] in header: col_index[i] = header.index(cols[i]) for row in reader:", "old behavior of --drop_unadvertised_lines, so we # don't. Instead, there", "before transitfeed.py and we haven't yet found the # motivation", "trips when we key them by trip.id # we should", "to split names into (city, name).\" # Handle special cases", "tram lines TRAM_LINES = {'2': ['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'],", "# --drop_unadvertised_lines drop opt_parser = optparse.OptionParser() # drop_unadvertised_lines: Only export", "self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) trip.pattern =", "format.\"\"\" from __future__ import print_function # This was written before", "4=to depot, 5=other trip = Trip() # The trip_id (FRT_FID)", "Enge\": First word of station name designates the city nam", "action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments", "i - 1)) / 12 month = ((int(start_date[4:6]) + i", "'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch',", "points of interest. Used to split station names # to", "'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1': print(\"skipping", "= [-1] * len(cols) for i in range(len(cols)): if cols[i]", "* xb \\ - 0.0140 * xb * xb *", "values])) stream.write('\\n') class Station: pass class Route: pass class Pattern:", "['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route() route.id = line_id route.name =", "service_id in \\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in schedules:", "self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq), '0')])", "not in self.goodTrips: continue assert len(trip.stoptimes) == len(trip.pattern.stops) time =", "trips: if trip_id not in self.goodTrips: continue assert len(trip.stoptimes) ==", "'\"\"') else: return k def write_row(stream, values): \"writes one row", "\"Zurich Enge\": First word of station name designates the city", "areas, so we can just throw it away. for line_id,", "read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB',", "direction, seq, station_id in \\ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',", "'\"' in k: return '\"%s\"' % k.replace('\"', '\"\"') else: return", "= 'C%s.%s' % (schedule, service_id) for date in daytypes['%s.%s' %", "current day of the month is in the bitmask (by", "trip.starttime = int(trip_starttime) trip.route = self.routes[line] dest_station = self.stations[dest_station_id] pattern_id", "service_id = u'VB%s.%s' % (schedule_id, restriction_id) else: service_id = u'C%s.%s'", "id, name, x, y, uic_code in \\ read_csv(station_file, ['ORT_NR', 'ORT_NAME',", "that indicate points of interest. Used to split station names", "% k.replace('\"', '\"\"') else: return k def write_row(stream, values): \"writes", "\" + station_id) def import_routes(self, s): \"imports the rec_lin_ber.mdv file.\"", "line, strli, direction, \\ stoptime_id, schedule_id, daytype_id, restriction_id, \\ dest_station_id,", "not unique in the vbz data, as of Dec 2009", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "i in range(len(cols)): if cols[i] in header: col_index[i] = header.index(cols[i])", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "+ 1)) pattern.stops[seq] = station_id def import_boarding(self, drop_off_file): \"Reads the", "station.advertised_lines = set() self.stations[id] = station for station_id, line_id in", "<filename>misc/import_ch_zurich.py #!/usr/bin/python2.4 # Copyright (C) 2008 Google Inc. # #", "order stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file): \"imports the rec_frt.mdv file.\"", "the rec_frt.mdv file.\" for trip_id, trip_starttime, line, strli, direction, \\", "suffix_pos = name.rfind(abbrev) if suffix_pos > 0: name = name[:suffix_pos]", "else: # \"Zurich Enge\": First word of station name designates", "required by applicable law or agreed to in writing, software", "id --> Route self.patterns = {} # id --> Pattern", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "0 TYPE_BUS = 3 class Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines):", "simple heuristcs doesn't work. SPECIAL_NAMES = { 'Freienbach SOB, Bahnhof':", "= TYPE_BUS if route.name[0:1] == \"N\": route.color = \"000000\" route.color_text", "TRAM_LINES = {'2': ['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'], '4': ['333399',", "just throw it away. for line_id, name in \\ read_csv(s,", "agreed to in writing, software # distributed under the License", "that rider needs to push a button to have the", "unique, by combining trip_id and line trip.id = (\"%s_%s\") %", "of interest. Used to split station names # to (name,", ">= 0: result[i] = row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x, y):", "file.\" for line, strli, direction, seq, station_id in \\ read_csv(s,", "distributed under the License is distributed on an \"AS IS\"", "in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for date in service: out.write('%s,%d,1\\n'", "= \"000000\" route.color_text = \"FFFF00\" self.routes[route.id] = route def import_patterns(self,", "for id, name, x, y, uic_code in \\ read_csv(station_file, ['ORT_NR',", "headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv'))", "'1' = no drop-off elif code == 'B': # 'B'", "is ugly as hell, I know. I briefly explain what", "drop # --nodrop_unadvertised_lines do not drop # --drop_unadvertised_lines drop opt_parser", "file.\" # the line id is really qualified with an", "lam = 2.6779094 \\ + 4.728982 * yb \\ +", "for trip_id, seq, code in \\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']):", "trip.route.id in station.advertised_lines: write_row(out, [trip.id, str(seq + 1), station.id, self.format_time(time),", "int(trip_starttime) trip.route = self.routes[line] dest_station = self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s'", "'3': ['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'], '6':", "the departures of lines that # are advertised at the", "1 self.services[id] = dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file): \"imports the", "by combining trip_id and line trip.id = (\"%s_%s\") % (trip_id,", "'FFFFFF'], '8': ['99CC00', '000000'], '9': ['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'],", "- 1 drive_secs = int(drive_secs) wait_secs = int(wait_secs) assert len(stoptimes)", "table of advertised lines does not include area. Fortunately, it", "restrictions_file): \"Reads the vb_regio.mdv file.\" ParseDate = lambda x: datetime.date(int(x[:4]),", "--> Route self.patterns = {} # id --> Pattern self.services", "'Neue Forch': ('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg':", "'E': self.drop_off_type[key] = '1' # '1' = no drop-off elif", "trip.id = (\"%s_%s\") % (trip_id, line) trip.starttime = int(trip_starttime) trip.route", "for schedule, daytype, date in \\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']):", "def import_traffic_restrictions(self, restrictions_file): \"Reads the vb_regio.mdv file.\" ParseDate = lambda", "Trip() # The trip_id (FRT_FID) field is not unique in", "Forch': ('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg': ('Spital',", "schedule in schedules: service = 'C%s.%s' % (schedule, service_id) for", "leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised lines file references", "Pattern() pattern.id = pattern_id pattern.stops = [] pattern.stoptimes = {}", "--out_file flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output", "time += drive_time station = self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or", "reader: result = [None] * len(cols) for i in range(len(cols)):", "t % 60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips =", "a. A.': 'Affoltern am Albis', 'Wangen b. D.': 'Wangen' }", "# don't. Instead, there are only two options without arguments:", "# 8 characters in the bitmask equal a month (", "3=from depot, 4=to depot, 5=other trip = Trip() # The", "d in range(32): if 1 << d & mask: year", "(BEREICH_NR), but the # table of advertised lines does not", "if trip_type != '1': print(\"skipping Trip \", trip_id, line, direction,", "id --> Trip self.goodTrips = {} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod", "{} # id --> [date, date, ...] (sorted) self.pickup_type =", "permissions and # limitations under the License. \"\"\"imports Zurich timetables,", "by x days and comparing it to the bitmask). #", "route = Route() route.id = line_id route.name = name route.color", "hard to replicate the old behavior of --drop_unadvertised_lines, so we", "OR CONDITIONS OF ANY KIND, either express or implied. #", "found the # motivation to port it. Please see the", "'Schiffstation': 1, 'Station': 1, u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1,", "# (trip_id, stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type = {} #", "the License is distributed on an \"AS IS\" BASIS, #", "out.write('%s,%s,%s,%s,%s,%s\\n' % ( id, name, name, route.type, route.color, route.color_text)) def", "the License. \"\"\"imports Zurich timetables, converting them from DIVA export", "return \"%02d:%02d:%02d\" % (t / 3600, (t % 3600) /", "'FFFFFF'], '5': ['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'],", "func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def", "(C) 2008 Google Inc. # # Licensed under the Apache", "[]) seq = int(seq) - 1 drive_secs = int(drive_secs) wait_secs", "This is ugly as hell, I know. I briefly explain", "schedule_id, daytype_id, restriction_id, \\ dest_station_id, dest_stop_id, trip_type in \\ read_csv(trips_file,", "trip.stoptimes[seq] time += drive_time station = self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines", "law or agreed to in writing, software # distributed under", "1, u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf': 1} #", "and mark that date... for i in range(MonthNr(end_date) - MonthNr(start_date)", "'C%s.%s' % (schedule, service_id) for date in daytypes['%s.%s' % (schedule,", "csv.reader(s, csv_dialect) header = next(reader) col_index = [-1] * len(cols)", "the vbz data, as of Dec 2009 # to prevent", "import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath, mode=\"r\") read = lambda name,", "'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1': print(\"skipping Trip \",", "= encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % ( id, name, name, route.type, route.color,", "1 schedules = schedules.keys() service_days = {} # 'Cj06.H9' -->", "def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for service_id, service in self.services.iteritems(): encoded_service_id", "self.services[id].sort() def import_stop_times(self, stoptimes_file): \"imports the lid_fahrzeitart.mdv file.\" for line,", "self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod def format_time(t): return", "= name[:suffix_pos] + expanded # end for names = name.split(\",", "route.color_text = \"FFFF00\" self.routes[route.id] = route def import_patterns(self, s): \"imports", "wait_time = trip.stoptimes[seq] time += drive_time station = self.stations[trip.pattern.stops[seq]] if", "zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename, func in [('agency.txt', self.write_agency), ('calendar.txt',", "if the current day of the month is in the", "Fortunately, it seems # that line ids are unique across", "Instead, there are only two options without arguments: # nothing", "there are only two options without arguments: # nothing drop", "import_trips(self, trips_file): \"imports the rec_frt.mdv file.\" for trip_id, trip_starttime, line,", "may obtain a copy of the License at # #", "License. \"\"\"imports Zurich timetables, converting them from DIVA export format", "\\ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s'", "ci >= 0: result[i] = row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x,", "[trip.id]) continue self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id,", "0: result[i] = row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x, y): \"Converts", "('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'),", "optparse.OptionParser() # drop_unadvertised_lines: Only export the departures of lines that", "import_patterns(self, s): \"imports the lid_verlauf.mdv file.\" for line, strli, direction,", "that # are advertised at the station in question. This", "Cities whose names we want to prettify/correct at import time.", "SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue", "+ inzip.read(name)).splitlines() # The advertised lines file has no column", "may not use this file except in compliance with the", "'11': ['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'], '13': ['FFCC33', '000000'], '14':", "Glatt', 'Wallisellen'), } # Cities whose names we want to", "strli, direction, seq, station_id in \\ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR',", "write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k =", "some simple heuristics to split names into (city, name).\" #", "('Zentrum Glatt', 'Wallisellen'), } # Cities whose names we want", "'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)] stoptimes", "this file except in compliance with the License. # You", "to stream.\" stream.write(','.join([encode_for_csv(val) for val in values])) stream.write('\\n') class Station:", "'TAGESMERKMAL_NR']): for schedule in schedules: service = 'C%s.%s' % (schedule,", "'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq) - 1) if code", "We don't encode this for now. pass else: raise ValueError('Unexpected", "'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station() station.id = id", "{} # {'j06':1, 'p27':1} for schedule, daytype, date in \\", "self.drop_off_type[key] = '1' # '1' = no drop-off elif code", "def convert_c_h1903(x, y): \"Converts coordinates from the 1903 Swiss national", "file in Google Transit format.\" out = zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED)", "self.drop_off_type.get((trip.id, seq), '0')]) time += wait_time def main(argv): # It's", "datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr = lambda x: int(x[:4]) * 12", "<< d & mask: year = int(start_date[0:4]) + ((int(start_date[4:6]) +", "# # Licensed under the Apache License, Version 2.0 (the", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "len(self.services[service_id]) > 0 assert not trip.id in self.trips self.trips[trip.id] =", "so I calculate back what year month and actual day", "strli, direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id:", "self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised lines file references \" \\ \"unknown", "write_row(out, [trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod def format_time(t): return \"%02d:%02d:%02d\"", "self.pickup_type = {} # (trip_id, stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type", "else: nam = names[1] city = names[0] else: # \"Zurich", "= (\"%s_%s\") % (trip_id, line) trip.starttime = int(trip_starttime) trip.route =", "self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file): \"imports the", "suffix_pos > 0: name = name[:suffix_pos] + expanded # end", "in service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): \"Reads", "'Wangen' } def read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader =", "Station self.routes = {} # id --> Route self.patterns =", "MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6]) for", "'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' % (line,", "self.drop_off_type = {} # (trip_id, stop_seq) --> '0'/'1', '1'=no drop-off", "trip) in trips: if trip_id not in self.goodTrips: continue assert", "is None: raise SystemExit('Please provide a value to the --out_file", "so it's ok). # Then I check if the current", "not confuse the data in schedule bubbles. Use # --nodrop_unadvertised_lines", "range(MonthNr(end_date) - MonthNr(start_date) + 1): mask = int(bitmask[i * 8:i", "Trip self.goodTrips = {} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def demangle_name(name):", "x days and comparing it to the bitmask). # If", "if name in SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand abbreviations. for", "(names[0], names[1]) else: nam = names[1] city = names[0] else:", "daytype, date in \\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule =", "36.0 def encode_for_csv(x): \"Encodes one value for CSV.\" k =", "days, so it's ok). # Then I check if the", "designates the city nam = names[0] city = nam.split(' ')[0]", "for date in service: out.write('%s,%d,1\\n' % (encoded_service_id, date)) def write_trips(self,", "12 + int(x[4:6]) for schedule, id, bitmask, start_date, end_date in", "station_id in self.stations: # Line ids in this file have", "wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq), '0')]) time += wait_time", "% 12) + 1 day = d + 1 cur_date", "pass class Route: pass class Pattern: pass class Trip: pass", "or implied. # See the License for the specific language", "line trip.id = (\"%s_%s\") % (trip_id, line) trip.starttime = int(trip_starttime)", "k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % ( id, name, name,", "name designates the city nam = names[0] city = nam.split('", "* 8 + 8], 16) for d in range(32): if", "headsign]) @staticmethod def format_time(t): return \"%02d:%02d:%02d\" % (t / 3600,", "None) if not pattern: pattern = Pattern() pattern.id = pattern_id", "('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch', u'Z\\u00fcrich'), 'O<NAME>': ('O<NAME>',", "DIVA export format to Google Transit format.\"\"\" from __future__ import", "if len(names) == 2: if names[1] in POI_TERMS: nam =", "action='store', type='string') options, unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file is None:", "means that rider needs to push a button to have", "'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1': print(\"skipping Trip", "(encoded_service_id, date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id, t)", "code == 'E': self.drop_off_type[key] = '1' # '1' = no", "# '1' = no drop-off elif code == 'B': #", "[id, s.uic_code, s.name, s.city, s.country, str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self,", "['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7': ['000000',", "depot trips etc, to not confuse the data in schedule", "import_stations(self, station_file, adv_file): \"imports the rec_ort.mdv file.\" for id, name,", "8:i * 8 + 8], 16) for d in range(32):", "names = name.split(\", \", 1) if len(names) == 2: if", "we haven't yet found the # motivation to port it.", "trip_id, trip_starttime, line, strli, direction, \\ stoptime_id, schedule_id, daytype_id, restriction_id,", "POI_TERMS: nam = u'%s %s' % (names[0], names[1]) else: nam", "\\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern", "encode_for_csv(x): \"Encodes one value for CSV.\" k = x.encode('utf-8') if", "# id --> Pattern self.services = {} # id -->", "file.\" for trip_id, trip_starttime, line, strli, direction, \\ stoptime_id, schedule_id,", "= u'VB%s.%s' % (schedule_id, restriction_id) else: service_id = u'C%s.%s' %", "\"FFFFFF\" route.color_text = \"000000\" if name in TRAM_LINES: route.type =", "True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod", "self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if (not len(trip.pattern.stops))", "options, unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file is None: raise SystemExit('Please", "if ',' in k or '\"' in k: return '\"%s\"'", "'Affoltern am Albis', 'Wangen b. D.': 'Wangen' } def read_csv(s,", "'10': ['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'], '13':", "(schedule_id, daytype_id) trip.service_id = service_id assert len(self.services[service_id]) > 0 assert", "trip_type != '1': print(\"skipping Trip \", trip_id, line, direction, \\", "= {} # {'j06':1, 'p27':1} for schedule, daytype, date in", "{'2': ['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'], '5':", "--drop_unadvertised_lines drop opt_parser = optparse.OptionParser() # drop_unadvertised_lines: Only export the", "{} # 'Cj06.H9' --> {20060713:1, 20060714:1, ...} for daytype, service_id", "we should make trip.id unique, by combining trip_id and line", "\" \\ \"unknown station, id \" + station_id) def import_routes(self,", "'O<NAME>': ('O<NAME>', 'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'),", "cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n')", "out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k = [(r.id, r)", "prevent overwritingimported trips when we key them by trip.id #", "{} # id --> Route self.patterns = {} # id", "name).\" # Handle special cases where our heuristcs doesn't work.", "read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s' % (schedule,", "(None in trip.pattern.stops): print(\"*** Skipping bad trip: \", [trip.id]) continue", "trips.sort() for (trip_id, trip) in trips: if trip_id not in", "better # examples. try: from io import StringIO as cStringIO", "line_id route.name = name route.color = \"FFFFFF\" route.color_text = \"000000\"", "'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum", "1) if len(names) == 2: if names[1] in POI_TERMS: nam", "code in \\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id,", "{} # id --> Station self.routes = {} # id", "* yb * yb phi = 16.9023892 \\ + 3.238372", "self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self,", "id is really qualified with an area_id (BEREICH_NR), but the", "schedule, daytype, date in \\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule", "out.write('%s,%d,1\\n' % (encoded_service_id, date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips =", "for row in reader: result = [None] * len(cols) for", "for abbrev, expanded in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos =", "names # to (name, city). POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum':", "trip = Trip() # The trip_id (FRT_FID) field is not", "unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file is None: raise SystemExit('Please provide", "the line id is really qualified with an area_id (BEREICH_NR),", "nam = names[0] city = nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city,", "one value for CSV.\" k = x.encode('utf-8') if ',' in", "write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations = [(s.id, s) for s", "self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file,", "drop_unadvertised_lines @staticmethod def demangle_name(name): \"Applies some simple heuristics to split", "file has no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv'))", "<= seq: pattern.stops.extend([None] * (seq - len(pattern.stops) + 1)) pattern.stops[seq]", "\"Applies some simple heuristics to split names into (city, name).\"", "if code == 'A': self.pickup_type[key] = '1' # '1' =", "self.trips = {} # id --> Trip self.goodTrips = {}", "+ expanded # end for names = name.split(\", \", 1)", "(trip_id, stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type = {} # (trip_id,", "read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station() station.id", "to (name, city). Used as exception list where our #", "% (line, strli, direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id]", "code)) def import_services(self, daytype_file, days_file): daytypes = {} # 'j06'", "seq), '0'), self.drop_off_type.get((trip.id, seq), '0')]) time += wait_time def main(argv):", "k = [(r.id, r) for r in self.routes.itervalues()] k.sort() for", "convert_c_h1903(x, y): \"Converts coordinates from the 1903 Swiss national grid", "(t / 3600, (t % 3600) / 60, t %", "1), station.id, self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id,", "is really qualified with an area_id (BEREICH_NR), but the #", "service_id assert len(self.services[service_id]) > 0 assert not trip.id in self.trips", "start_date, end_date in \\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']):", "examples directory for better # examples. try: from io import", "s.name, s.city, s.country, str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,'", "--nodrop_unadvertised_lines do not drop # --drop_unadvertised_lines drop opt_parser = optparse.OptionParser()", "name in TRAM_LINES: route.type = TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text", "in k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % ( id, name,", "date... for i in range(MonthNr(end_date) - MonthNr(start_date) + 1): mask", "in order stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file): \"imports the rec_frt.mdv", "return '\"%s\"' % k.replace('\"', '\"\"') else: return k def write_row(stream,", "name route.color = \"FFFFFF\" route.color_text = \"000000\" if name in", "file.\" for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in", "mask: year = int(start_date[0:4]) + ((int(start_date[4:6]) + i - 1))", "make trip.id unique, by combining trip_id and line trip.id =", "in writing, software # distributed under the License is distributed", "['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'], '6': ['CC9933',", "# more than 31 days, so it's ok). # Then", "'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set()", "# If so I calculate back what year month and", "/ 1e6; xb = (y - 200000.0) / 1e6; lam", "key = (trip_id, int(seq) - 1) if code == 'A':", "for val in values])) stream.write('\\n') class Station: pass class Route:", "/ 36.0, lam * 100.0 / 36.0 def encode_for_csv(x): \"Encodes", "has no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'),", "s.city, s.country, str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n')", "mode=\"r\") read = lambda name, prefix=\"\": (prefix + inzip.read(name)).splitlines() #", "the vb_regio.mdv file.\" ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8]))", "nothing drop # --nodrop_unadvertised_lines do not drop # --drop_unadvertised_lines drop", "bitmask = bitmask.strip() dates = {} # This is ugly", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "route.color_text = \"000000\" if name in TRAM_LINES: route.type = TYPE_TRAM", "License, Version 2.0 (the \"License\"); # you may not use", "x.encode('utf-8') if ',' in k or '\"' in k: return", "trip.starttime for seq in range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq] time", "station.uic_code = '' if uic_code and len(uic_code) == 7 and", "else: raise ValueError('Unexpected code in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' %", "Handle special cases where our heuristcs doesn't work. # Example:\"Triemli\"", "self.stations[id] = station for station_id, line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']):", "\"000000\" if name in TRAM_LINES: route.type = TYPE_TRAM route.color =", "- 600000.0) / 1e6; xb = (y - 200000.0) /", "--> {20060713:1, 20060714:1, ...} for daytype, service_id in \\ read_csv(daytype_file,", "TYPE_BUS if route.name[0:1] == \"N\": route.color = \"000000\" route.color_text =", "= int(start_date[0:4]) + ((int(start_date[4:6]) + i - 1)) / 12", "station names # to (name, city). POI_TERMS = {'Bahnhof': 1,", "id, bitmask, start_date, end_date in \\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM',", "for schedule in schedules: service = 'C%s.%s' % (schedule, service_id)", "fails if seq not in order stoptimes.append((drive_secs, wait_secs)) def import_trips(self,", "drop # --drop_unadvertised_lines drop opt_parser = optparse.OptionParser() # drop_unadvertised_lines: Only", "= trip.stoptimes[seq] time += drive_time station = self.stations[trip.pattern.stops[seq]] if not", "'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' % (line, strli,", "Route() route.id = line_id route.name = name route.color = \"FFFFFF\"", "- 1)) / 12 month = ((int(start_date[4:6]) + i -", "stream.write(','.join([encode_for_csv(val) for val in values])) stream.write('\\n') class Station: pass class", "the License for the specific language governing permissions and #", "= \"FFFF00\" self.routes[route.id] = route def import_patterns(self, s): \"imports the", "import optparse import sys import urllib import zipfile # Zurich", "is None: raise SystemExit('Please provide a value to the --in_file", "read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in schedules: service = 'C%s.%s'", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "1 drive_secs = int(drive_secs) wait_secs = int(wait_secs) assert len(stoptimes) ==", "k in service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file):", "['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' % (line,", "self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if trip_id not", "self.services[id] = dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file): \"imports the lid_fahrzeitart.mdv", "i in range(len(cols)): ci = col_index[i] if ci >= 0:", "= {} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def demangle_name(name): \"Applies some", "for id, s in stations: write_row(out, [id, s.uic_code, s.name, s.city,", "= self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or \\ trip.route.id in station.advertised_lines:", "yield result def convert_c_h1903(x, y): \"Converts coordinates from the 1903", "stoptime_id, schedule_id, daytype_id, restriction_id, \\ dest_station_id, dest_stop_id, trip_type in \\", "if (not len(trip.pattern.stops)) or (None in trip.pattern.stops): print(\"*** Skipping bad", "work. # Example:\"Triemli\" --> (\"Triemli\", \"Zurich\"). if name in SPECIAL_NAMES:", "'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station() station.id = id station.position", "[-1] * len(cols) for i in range(len(cols)): if cols[i] in", "schedule, id, bitmask, start_date, end_date in \\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB',", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "= 16.9023892 \\ + 3.238372 * xb \\ - 0.270978", "in the vbz data, as of Dec 2009 # to", "bitmask equal a month ( 8 * 4bits = 32,", "len(trip.stoptimes) == len(trip.pattern.stops) time = trip.starttime for seq in range(len(trip.stoptimes)):", "print(\"Warning, advertised lines file references \" \\ \"unknown station, id", "pattern seq = int(seq) - 1 if len(pattern.stops) <= seq:", "id --> Station self.routes = {} # id --> Route", "pattern = Pattern() pattern.id = pattern_id pattern.stops = [] pattern.stoptimes", "# to (name, city). POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum': 1,", "0.002582 * xb * xb \\ - 0.0447 * yb", "\"000000\" route.color_text = \"FFFF00\" self.routes[route.id] = route def import_patterns(self, s):", "'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']):", "Google Transit format.\"\"\" from __future__ import print_function # This was", "20060714:1, ...} schedules = {} # {'j06':1, 'p27':1} for schedule,", "y): \"Converts coordinates from the 1903 Swiss national grid system", "('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue())", "x, y, uic_code in \\ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y',", "it to the bitmask). # If so I calculate back", "a value to the --out_file flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines)", "in Google Transit format.\" out = zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for", "used to remove # depot trips etc, to not confuse", "* 100.0 / 36.0 def encode_for_csv(x): \"Encodes one value for", "'FFFFFF'], '12': ['FFFFFF', '000000'], '13': ['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'],", "# distributed under the License is distributed on an \"AS", "s.country, str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for", "what year month and actual day I am in #", "# Unless required by applicable law or agreed to in", "trip) in trips: if (not len(trip.pattern.stops)) or (None in trip.pattern.stops):", "trip_id and line trip.id = (\"%s_%s\") % (trip_id, line) trip.starttime", "city = names[0] else: # \"Zurich Enge\": First word of", "= self.demangle_name(name) station.country = 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' + \\", "Terms that indicate points of interest. Used to split station", "} # Cities whose names we want to prettify/correct at", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "station names to (name, city). Used as exception list where", "wait_secs = int(wait_secs) assert len(stoptimes) == seq # fails if", "split station names # to (name, city). POI_TERMS = {'Bahnhof':", "= header.index(cols[i]) for row in reader: result = [None] *", "((int(start_date[4:6]) + i - 1)) / 12 month = ((int(start_date[4:6])", "def import_stations(self, station_file, adv_file): \"imports the rec_ort.mdv file.\" for id,", "\\ dest_station_id, dest_stop_id, trip_type in \\ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR',", "class Station: pass class Route: pass class Pattern: pass class", "100.0 / 36.0, lam * 100.0 / 36.0 def encode_for_csv(x):", "int(drive_secs) wait_secs = int(wait_secs) assert len(stoptimes) == seq # fails", "restriction_id, \\ dest_station_id, dest_stop_id, trip_type in \\ read_csv(trips_file, ['FRT_FID', 'FRT_START',", "'friday,saturday,sunday,start_date,end_date\\n') for service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0],", "the Apache License, Version 2.0 (the \"License\"); # you may", "'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)", "vb_regio.mdv file.\" ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr", "trip.service_id = service_id assert len(self.services[service_id]) > 0 assert not trip.id", "--> Trip self.goodTrips = {} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def", "import_services(self, daytype_file, days_file): daytypes = {} # 'j06' --> {20060713:1,", "set() self.stations[id] = station for station_id, line_id in read_csv(adv_file, ['ORT_NR',", "self.trips[trip.id] = trip def write(self, outpath): \"writes a .zip file", "(trip_id, trip) in trips: if trip_id not in self.goodTrips: continue", "('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch':", "code in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) def", "briefly explain what I do: # 8 characters in the", "for trip_id, trip_starttime, line, strli, direction, \\ stoptime_id, schedule_id, daytype_id,", "'Schiffstation')]: suffix_pos = name.rfind(abbrev) if suffix_pos > 0: name =", "bitmask, start_date, end_date in \\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON',", "% (trip_id, line) trip.starttime = int(trip_starttime) trip.route = self.routes[line] dest_station", "'0')]) time += wait_time def main(argv): # It's hard to", "# 'j06' --> {20060713:1, 20060714:1, ...} schedules = {} #", "with an area_id (BEREICH_NR), but the # table of advertised", "# 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other trip =", "--> '0'=normal/'1'=no pickup self.drop_off_type = {} # (trip_id, stop_seq) -->", "= ((int(start_date[4:6]) + i - 1) % 12) + 1", "'1' # '1' = no pick-up elif code == 'E':", "+ 1 day = d + 1 cur_date = str(year)", "dates[int(cur_date)] = 1 self.services[id] = dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file):", "prefix=\"\": (prefix + inzip.read(name)).splitlines() # The advertised lines file has", "cases where our heuristcs doesn't work. # Example:\"Triemli\" --> (\"Triemli\",", "== len(trip.pattern.stops) time = trip.starttime for seq in range(len(trip.stoptimes)): drive_time,", "\\ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR',", "= int(trip_starttime) trip.route = self.routes[line] dest_station = self.stations[dest_station_id] pattern_id =", "header.index(cols[i]) for row in reader: result = [None] * len(cols)", "[] pattern.stoptimes = {} self.patterns[pattern_id] = pattern seq = int(seq)", "should make trip.id unique, by combining trip_id and line trip.id", "- 1 if len(pattern.stops) <= seq: pattern.stops.extend([None] * (seq -", "+ wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq), '0')]) time +=", "language governing permissions and # limitations under the License. \"\"\"imports", "if cols[i] in header: col_index[i] = header.index(cols[i]) for row in", "= [] pattern.stoptimes = {} self.patterns[pattern_id] = pattern seq =", "--> {20060713:1, 20060714:1, ...} schedules = {} # {'j06':1, 'p27':1}", "{})[int(date)] = 1 schedules[schedule] = 1 schedules = schedules.keys() service_days", "name in SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand abbreviations. for abbrev,", "= zipfile.ZipFile(inpath, mode=\"r\") read = lambda name, prefix=\"\": (prefix +", "depot, 4=to depot, 5=other trip = Trip() # The trip_id", "def import_trips(self, trips_file): \"imports the rec_frt.mdv file.\" for trip_id, trip_starttime,", "trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id = u'VB%s.%s' % (schedule_id,", "200000.0) / 1e6; lam = 2.6779094 \\ + 4.728982 *", "lid_verlauf.mdv file.\" for line, strli, direction, seq, station_id in \\", "+ str(day))[-2:] dates[int(cur_date)] = 1 self.services[id] = dates.keys() self.services[id].sort() def", "the bitmask equal a month ( 8 * 4bits =", "names[0] city = nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city, city) def", "to not confuse the data in schedule bubbles. Use #", "{'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation': 1, 'Station': 1, u'Zentrum': 1,", "dest_station = self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)", "of station name designates the city nam = names[0] city", "# id --> Trip self.goodTrips = {} self._drop_unadvertised_lines = drop_unadvertised_lines", "under the License is distributed on an \"AS IS\" BASIS,", "If so I calculate back what year month and actual", "in this file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning,", "3600, (t % 3600) / 60, t % 60) def", "# 'Cj06.H9' --> {20060713:1, 20060714:1, ...} for daytype, service_id in", "restriction_id) else: service_id = u'C%s.%s' % (schedule_id, daytype_id) trip.service_id =", "= 1 schedules[schedule] = 1 schedules = schedules.keys() service_days =", "def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips = [(t.id, t) for", "as exception list where our # simple heuristcs doesn't work.", "'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt':", "'B' just means that rider needs to push a button", "2=empty, 3=from depot, 4=to depot, 5=other trip = Trip() #", "for CSV.\" k = x.encode('utf-8') if ',' in k or", "(\"Triemli\", \"Zurich\"). if name in SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand", "direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq) - 1", "len(pattern.stops) + 1)) pattern.stops[seq] = station_id def import_boarding(self, drop_off_file): \"Reads", "Expand abbreviations. for abbrev, expanded in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]:", "all areas, so we can just throw it away. for", "station.url = 'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id]", "(FRT_FID) field is not unique in the vbz data, as", "we can just throw it away. for line_id, name in", "'B': # 'B' just means that rider needs to push", "+ 8], 16) for d in range(32): if 1 <<", "abbreviations. for abbrev, expanded in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos", "')[0] return nam, SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath): inzip =", "know. I briefly explain what I do: # 8 characters", "out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips = [(t.id, t) for t in self.trips.itervalues()]", "def demangle_name(name): \"Applies some simple heuristics to split names into", "['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'], '12': ['FFFFFF',", "not drop # --drop_unadvertised_lines drop opt_parser = optparse.OptionParser() # drop_unadvertised_lines:", "(line, strli, direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if", "self.patterns[pattern_id] = pattern seq = int(seq) - 1 if len(pattern.stops)", "s in self.stations.itervalues()] stations.sort() for id, s in stations: write_row(out,", "/ 12 month = ((int(start_date[4:6]) + i - 1) %", "self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file):", "d + 1 cur_date = str(year) + (\"0\" + str(month))[-2:]", "in range(len(cols)): ci = col_index[i] if ci >= 0: result[i]", "str(seq + 1), station.id, self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq),", "trip.pattern.stops): print(\"*** Skipping bad trip: \", [trip.id]) continue self.goodTrips[trip_id] =", "self.stations.itervalues()] stations.sort() for id, s in stations: write_row(out, [id, s.uic_code,", "out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id, t) for t in self.trips.itervalues()]", "line_id, name in \\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route()", "Dec 2009 # to prevent overwritingimported trips when we key", "def import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath, mode=\"r\") read = lambda", "3600) / 60, t % 60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,'", "1, 'Dorfzentrum': 1, 'Schiffstation': 1, 'Station': 1, u'Zentrum': 1, 'Dorfplatz':", "wait_secs)) def import_trips(self, trips_file): \"imports the rec_frt.mdv file.\" for trip_id,", "= 1 for k in service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort()", "raise SystemExit('Please provide a value to the --out_file flag.') importer", "'0'), self.drop_off_type.get((trip.id, seq), '0')]) time += wait_time def main(argv): #", "csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect) header = next(reader) col_index =", "do not drop # --drop_unadvertised_lines drop opt_parser = optparse.OptionParser() #", "in service: out.write('%s,%d,1\\n' % (encoded_service_id, date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n')", "write(self, outpath): \"writes a .zip file in Google Transit format.\"", "zipfile.ZipFile(inpath, mode=\"r\") read = lambda name, prefix=\"\": (prefix + inzip.read(name)).splitlines()", "0.0140 * xb * xb * xb return phi *", "import zipfile # Zurich tram lines TRAM_LINES = {'2': ['FF3300',", "[(t.id, t) for t in self.trips.itervalues()] trips.sort() for (trip_id, trip)", "area_id (BEREICH_NR), but the # table of advertised lines does", "Pattern self.services = {} # id --> [date, date, ...]", "== 2: if names[1] in POI_TERMS: nam = u'%s %s'", "in the bitmask equal a month ( 8 * 4bits", "in the bitmask (by # shifting the bit by x", "drop_unadvertised_lines: Only export the departures of lines that # are", "8 + 8], 16) for d in range(32): if 1", "= x.encode('utf-8') if ',' in k or '\"' in k:", "ANY KIND, either express or implied. # See the License", "self.patterns = {} # id --> Pattern self.services = {}", "0 assert not trip.id in self.trips self.trips[trip.id] = trip def", "s.getvalue()) out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out):", "the License. # You may obtain a copy of the", "def encode_for_csv(x): \"Encodes one value for CSV.\" k = x.encode('utf-8')", "= True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id, headsign])", "comparing it to the bitmask). # If so I calculate", "station_id def import_boarding(self, drop_off_file): \"Reads the bedverb.mdv file.\" for trip_id,", "# See the License for the specific language governing permissions", "12 month = ((int(start_date[4:6]) + i - 1) % 12)", "= station_id def import_boarding(self, drop_off_file): \"Reads the bedverb.mdv file.\" for", "import datetime import optparse import sys import urllib import zipfile", "not include area. Fortunately, it seems # that line ids", "0.1306 * yb * xb * xb \\ - 0.0436", "in schedule bubbles. Use # --nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines',", "['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id = u\"VB%s.%s\" % (schedule,", "k.replace('\"', '\"\"') else: return k def write_row(stream, values): \"writes one", "out): out.write('service_id,date,exception_type\\n') for service_id, service in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id)", "list where our # simple heuristcs doesn't work. SPECIAL_NAMES =", "trips_file): \"imports the rec_frt.mdv file.\" for trip_id, trip_starttime, line, strli,", "int(start_date[0:4]) + ((int(start_date[4:6]) + i - 1)) / 12 month", "1e6; xb = (y - 200000.0) / 1e6; lam =", "grid system to WGS-84.\" yb = (x - 600000.0) /", "one row of comma-separated values to stream.\" stream.write(','.join([encode_for_csv(val) for val", "cStringIO import csv import datetime import optparse import sys import", "to push a button to have the driver # stop.", "int(x[4:6]), int(x[6:8])) MonthNr = lambda x: int(x[:4]) * 12 +", "((int(start_date[4:6]) + i - 1) % 12) + 1 day", "bitmask (by # shifting the bit by x days and", "Route: pass class Pattern: pass class Trip: pass # https://developers.google.com/transit/gtfs/", "year month and actual day I am in # (very", "flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to',", "= encode_for_csv(service_id) for date in service: out.write('%s,%d,1\\n' % (encoded_service_id, date))", "pick-up elif code == 'E': self.drop_off_type[key] = '1' # '1'", "\"unknown station, id \" + station_id) def import_routes(self, s): \"imports", "Trip \", trip_id, line, direction, \\ dest_station_id, trip_type) continue #", "I do: # 8 characters in the bitmask equal a", "= { 'Affoltern a. A.': 'Affoltern am Albis', 'Wangen b.", "for date in daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] =", "x: int(x[:4]) * 12 + int(x[4:6]) for schedule, id, bitmask,", "advertised lines does not include area. Fortunately, it seems #", "'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station() station.id = id station.position =", "[('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips),", "% (encoded_service_id, date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id,", "+ station_id) def import_routes(self, s): \"imports the rec_lin_ber.mdv file.\" #", "* yb * yb \\ - 0.002582 * xb *", "self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv'))", "word of station name designates the city nam = names[0]", "schedules = {} # {'j06':1, 'p27':1} for schedule, daytype, date", "= {} # id --> Station self.routes = {} #", "SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'),", "route def import_patterns(self, s): \"imports the lid_verlauf.mdv file.\" for line,", "rec_frt.mdv file.\" for trip_id, trip_starttime, line, strli, direction, \\ stoptime_id,", "# Zurich tram lines TRAM_LINES = {'2': ['FF3300', 'FFFFFF'], '3':", "file.\" ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr =", "out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k = [(r.id,", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "\\ \"unknown station, id \" + station_id) def import_routes(self, s):", "result = [None] * len(cols) for i in range(len(cols)): ci", "+ 0.791484 * yb * xb \\ + 0.1306 *", "'FFFFFF']} # Terms that indicate points of interest. Used to", "station in question. This is used to remove # depot", "writing, software # distributed under the License is distributed on", "def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id, t) for t", "yb * xb * xb \\ - 0.0436 * yb", "'FGR_NR', 'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)]", "service_days.setdefault(service, {})[date] = 1 for k in service_days.iterkeys(): self.services[k] =", "ValueError('Unexpected code in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code))", "pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) trip.pattern = self.patterns[pattern_id]", "4.728982 * yb \\ + 0.791484 * yb * xb", "and line trip.id = (\"%s_%s\") % (trip_id, line) trip.starttime =", "city). Used as exception list where our # simple heuristcs", "'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf': 1} # Maps station names", "= '1' # '1' = no pick-up elif code ==", "characters in the bitmask equal a month ( 8 *", "8], 16) for d in range(32): if 1 << d", "= name route.color = \"FFFFFF\" route.color_text = \"000000\" if name", "r in self.routes.itervalues()] k.sort() for id, route in k: name", "that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store',", "16) for d in range(32): if 1 << d &", "int(seq) - 1 drive_secs = int(drive_secs) wait_secs = int(wait_secs) assert", "i in range(MonthNr(end_date) - MonthNr(start_date) + 1): mask = int(bitmask[i", "trip_id, line, direction, \\ dest_station_id, trip_type) continue # 1=normal, 2=empty,", "name = name[:suffix_pos] + expanded # end for names =", "Example:\"Triemli\" --> (\"Triemli\", \"Zurich\"). if name in SPECIAL_NAMES: return SPECIAL_NAMES[name]", "id --> Pattern self.services = {} # id --> [date,", "\"writes a .zip file in Google Transit format.\" out =", "for better # examples. try: from io import StringIO as", "self.coord_converter(float(x), float(y)) station.uic_code = '' if uic_code and len(uic_code) ==", "provide a value to the --out_file flag.') importer = Divaimporter(convert_c_h1903,", "doesn't work. # Example:\"Triemli\" --> (\"Triemli\", \"Zurich\"). if name in", "away. for line_id, name in \\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route", "'pickup_type,drop_off_type\\n') trips = [(t.id, t) for t in self.trips.itervalues()] trips.sort()", "'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1': print(\"skipping Trip \", trip_id,", "out.writestr(filename, s.getvalue()) out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self,", "in station.advertised_lines: write_row(out, [trip.id, str(seq + 1), station.id, self.format_time(time), self.format_time(time", "* 8:i * 8 + 8], 16) for d in", "write_row(out, [trip.id, str(seq + 1), station.id, self.format_time(time), self.format_time(time + wait_time),", "of lines that # are advertised at the station in", "(x - 600000.0) / 1e6; xb = (y - 200000.0)", "route.color = TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else: route.type = TYPE_BUS", "seq, code in \\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key =", "trip_type in \\ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR',", "y, uic_code in \\ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']):", "k.sort() for id, route in k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n'", "* yb * yb * yb phi = 16.9023892 \\", "@staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n')", "\\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq) -", "2.6779094 \\ + 4.728982 * yb \\ + 0.791484 *", "assert not trip.id in self.trips self.trips[trip.id] = trip def write(self,", "1} # Maps station names to (name, city). Used as", "Glatt': ('Zentrum Glatt', 'Wallisellen'), } # Cities whose names we", "write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id, t) for t in", "= {} # (trip_id, stop_seq) --> '0'/'1', '1'=no drop-off self.trips", "of Dec 2009 # to prevent overwritingimported trips when we", "'' if uic_code and len(uic_code) == 7 and uic_code[:2] ==", "# stop. We don't encode this for now. pass else:", "only two options without arguments: # nothing drop # --nodrop_unadvertised_lines", "key them by trip.id # we should make trip.id unique,", "station_id in \\ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id", "pattern.stops = [] pattern.stoptimes = {} self.patterns[pattern_id] = pattern seq", "ok). # Then I check if the current day of", "'15': ['FF3300', 'FFFFFF']} # Terms that indicate points of interest.", "== 'A': self.pickup_type[key] = '1' # '1' = no pick-up", "schedule = schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)] = 1", "seq = int(seq) - 1 if len(pattern.stops) <= seq: pattern.stops.extend([None]", "'4': ['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7':", "= (x - 600000.0) / 1e6; xb = (y -", "[trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod def format_time(t): return \"%02d:%02d:%02d\" %", "importer.write(options.out_file) print('Wrote output to', options.out_file) if __name__ == '__main__': main(sys.argv)", "month is in the bitmask (by # shifting the bit", "def read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect)", "route.name = name route.color = \"FFFFFF\" route.color_text = \"000000\" if", "expanded # end for names = name.split(\", \", 1) if", "or \\ trip.route.id in station.advertised_lines: write_row(out, [trip.id, str(seq + 1),", "= dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file): \"imports the lid_fahrzeitart.mdv file.\"", "u'Pat.%s.%s.%s' % (line, strli, direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes =", "SPECIAL_NAMES = { 'Freienbach SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf", "no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv'))", "['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s'", "else: route.type = TYPE_BUS if route.name[0:1] == \"N\": route.color =", "in self.routes.itervalues()] k.sort() for id, route in k: name =", "--in_file flag.') if options.out_file is None: raise SystemExit('Please provide a", "at the station in question. This is used to remove", "the month is in the bitmask (by # shifting the", "# the line id is really qualified with an area_id", "1)) pattern.stops[seq] = station_id def import_boarding(self, drop_off_file): \"Reads the bedverb.mdv", "+ ((int(start_date[4:6]) + i - 1)) / 12 month =", "out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id),", "Inc. # # Licensed under the Apache License, Version 2.0", "1) if code == 'A': self.pickup_type[key] = '1' # '1'", "k = x.encode('utf-8') if ',' in k or '\"' in", "= pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq) - 1 drive_secs =", "len(trip.pattern.stops) time = trip.starttime for seq in range(len(trip.stoptimes)): drive_time, wait_time", "daytype, service_id in \\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "'0'/'1', '1'=no drop-off self.trips = {} # id --> Trip", "--> '0'/'1', '1'=no drop-off self.trips = {} # id -->", "\"Reads the bedverb.mdv file.\" for trip_id, seq, code in \\", "column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv'))", "60, t % 60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips", "if restriction_id: service_id = u'VB%s.%s' % (schedule_id, restriction_id) else: service_id", "station, id \" + station_id) def import_routes(self, s): \"imports the", "route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations = [(s.id, s)", "= 32, no month has # more than 31 days,", "now. pass else: raise ValueError('Unexpected code in bedverb.mdv; ' 'FRT_FID=%s", "service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): \"Reads the", "int(seq) - 1 if len(pattern.stops) <= seq: pattern.stops.extend([None] * (seq", "drop-off self.trips = {} # id --> Trip self.goodTrips =", "is not unique in the vbz data, as of Dec", "It's hard to replicate the old behavior of --drop_unadvertised_lines, so", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= {} # 'Cj06.H9' --> {20060713:1, 20060714:1, ...} for daytype,", "result[i] = row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x, y): \"Converts coordinates", "'BEDVERB_CODE']): key = (trip_id, int(seq) - 1) if code ==", "(sorted) self.pickup_type = {} # (trip_id, stop_seq) --> '0'=normal/'1'=no pickup", "'9': ['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'], '12':", "'13': ['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']} #", "SystemExit('Please provide a value to the --in_file flag.') if options.out_file", "names we want to prettify/correct at import time. SPECIAL_CITIES =", "to the --in_file flag.') if options.out_file is None: raise SystemExit('Please", "trip: \", [trip.id]) continue self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "'Affoltern a. A.': 'Affoltern am Albis', 'Wangen b. D.': 'Wangen'", "yb * yb \\ - 0.002582 * xb * xb", "pattern.stoptimes = {} self.patterns[pattern_id] = pattern seq = int(seq) -", "{} # id --> Trip self.goodTrips = {} self._drop_unadvertised_lines =", "+ 1 cur_date = str(year) + (\"0\" + str(month))[-2:] +", "io import StringIO as cStringIO except ImportError: import cStringIO import", "2009 # to prevent overwritingimported trips when we key them", "encode_for_csv(service_id) for date in service: out.write('%s,%d,1\\n' % (encoded_service_id, date)) def", "Copyright (C) 2008 Google Inc. # # Licensed under the", "inpath): inzip = zipfile.ZipFile(inpath, mode=\"r\") read = lambda name, prefix=\"\":", "this for now. pass else: raise ValueError('Unexpected code in bedverb.mdv;", "as of Dec 2009 # to prevent overwritingimported trips when", "a value to the --in_file flag.') if options.out_file is None:", "= bitmask.strip() dates = {} # This is ugly as", "lines that # are advertised at the station in question.", "'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'],", "it away. for line_id, name in \\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']):", "\\ - 0.0447 * yb * yb * xb \\", "('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "def import_stop_times(self, stoptimes_file): \"imports the lid_fahrzeitart.mdv file.\" for line, strli,", "push a button to have the driver # stop. We", "if 1 << d & mask: year = int(start_date[0:4]) +", "pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq) - 1 drive_secs = int(drive_secs)", "write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n'", "the bedverb.mdv file.\" for trip_id, seq, code in \\ read_csv(drop_off_file,", "I calculate back what year month and actual day I", "are only two options without arguments: # nothing drop #", "service: out.write('%s,%d,1\\n' % (encoded_service_id, date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips", "name, x, y, uic_code in \\ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X',", "= zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename, func in [('agency.txt', self.write_agency),", "specific language governing permissions and # limitations under the License.", "station.country = 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines", "Pattern: pass class Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0", "for now. pass else: raise ValueError('Unexpected code in bedverb.mdv; '", "throw it away. for line_id, name in \\ read_csv(s, ['LI_NR',", "bit by x days and comparing it to the bitmask).", "= u'%s %s' % (names[0], names[1]) else: nam = names[1]", "route.color = \"FFFFFF\" route.color_text = \"000000\" if name in TRAM_LINES:", "!= '1': print(\"skipping Trip \", trip_id, line, direction, \\ dest_station_id,", "for service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0], service[-1]))", "day I am in # (very disgusting) and mark that", "governing permissions and # limitations under the License. \"\"\"imports Zurich", "cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect) header =", "options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to', options.out_file) if __name__ ==", "in range(len(cols)): if cols[i] in header: col_index[i] = header.index(cols[i]) for", "= coord_converter self.stations = {} # id --> Station self.routes", "two options without arguments: # nothing drop # --nodrop_unadvertised_lines do", "u'VB%s.%s' % (schedule_id, restriction_id) else: service_id = u'C%s.%s' % (schedule_id,", "in reader: result = [None] * len(cols) for i in", "% (encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for service_id,", "time = trip.starttime for seq in range(len(trip.stoptimes)): drive_time, wait_time =", "# you may not use this file except in compliance", "('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]:", "# It's hard to replicate the old behavior of --drop_unadvertised_lines,", "optparse import sys import urllib import zipfile # Zurich tram", "* xb * xb return phi * 100.0 / 36.0,", "route in k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % ( id,", "continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other trip", "stations = [(s.id, s) for s in self.stations.itervalues()] stations.sort() for", "service_id, service in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for date in", "'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) pattern =", "action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments = opt_parser.parse_args(argv[1:]) if", "station for station_id, line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id", "# nothing drop # --nodrop_unadvertised_lines do not drop # --drop_unadvertised_lines", "(y - 200000.0) / 1e6; lam = 2.6779094 \\ +", "explain what I do: # 8 characters in the bitmask", "1)) / 12 month = ((int(start_date[4:6]) + i - 1)", "= service_id assert len(self.services[service_id]) > 0 assert not trip.id in", "in self.trips self.trips[trip.id] = trip def write(self, outpath): \"writes a", "'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1':", "1 for k in service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort() def", "= {} # This is ugly as hell, I know.", "xb \\ + 0.1306 * yb * xb * xb", "daytype_id) trip.service_id = service_id assert len(self.services[service_id]) > 0 assert not", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "= csv.reader(s, csv_dialect) header = next(reader) col_index = [-1] *", "self.goodTrips = {} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def demangle_name(name): \"Applies", "= self.patterns.get(pattern_id, None) if not pattern: pattern = Pattern() pattern.id", "format_time(t): return \"%02d:%02d:%02d\" % (t / 3600, (t % 3600)", "> 0 assert not trip.id in self.trips self.trips[trip.id] = trip", "\"imports the rec_ort.mdv file.\" for id, name, x, y, uic_code", "in self.stations: # Line ids in this file have leading", "('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations),", "{20060713:1, 20060714:1, ...} for daytype, service_id in \\ read_csv(daytype_file, ['TAGESART_NR',", "the current day of the month is in the bitmask", "to WGS-84.\" yb = (x - 600000.0) / 1e6; xb", "1, 'Schiffstation': 1, 'Station': 1, u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof':", "of --drop_unadvertised_lines, so we # don't. Instead, there are only", "'Wallisellen'), } # Cities whose names we want to prettify/correct", "days_file): daytypes = {} # 'j06' --> {20060713:1, 20060714:1, ...}", "under the Apache License, Version 2.0 (the \"License\"); # you", "\\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in schedules: service =", "'000000'], '13': ['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']}", "daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)] = 1 schedules[schedule] = 1", "that line ids are unique across all areas, so we", "to prevent overwritingimported trips when we key them by trip.id", "# This was written before transitfeed.py and we haven't yet", "opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file is", "b. D.': 'Wangen' } def read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0])", "This is used to remove # depot trips etc, to", "'route_color,route_text_color\\n') k = [(r.id, r) for r in self.routes.itervalues()] k.sort()", "provide a value to the --in_file flag.') if options.out_file is", "in self.stations.itervalues()] stations.sort() for id, s in stations: write_row(out, [id,", "100.0 / 36.0 def encode_for_csv(x): \"Encodes one value for CSV.\"", "pattern = self.patterns.get(pattern_id, None) if not pattern: pattern = Pattern()", "nam, SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath, mode=\"r\")", "= {} # id --> Pattern self.services = {} #", "* len(cols) for i in range(len(cols)): ci = col_index[i] if", "0.791484 * yb * xb \\ + 0.1306 * yb", "needs to push a button to have the driver #", "* yb * xb \\ - 0.0140 * xb *", "= no drop-off elif code == 'B': # 'B' just", "stop_seq) --> '0'/'1', '1'=no drop-off self.trips = {} # id", "so we # don't. Instead, there are only two options", "# simple heuristcs doesn't work. SPECIAL_NAMES = { 'Freienbach SOB,", "def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations = [(s.id, s) for", "% (trip_id, code)) def import_services(self, daytype_file, days_file): daytypes = {}", "no month has # more than 31 days, so it's", "'Station': 1, u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf': 1}", "schedules: service = 'C%s.%s' % (schedule, service_id) for date in", "\\ trip.route.id in station.advertised_lines: write_row(out, [trip.id, str(seq + 1), station.id,", "value to the --in_file flag.') if options.out_file is None: raise", "for id, route in k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' %", "(encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for service_id, service", "pattern: pattern = Pattern() pattern.id = pattern_id pattern.stops = []", "in SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand abbreviations. for abbrev, expanded", "% (line, strli, direction) pattern = self.patterns.get(pattern_id, None) if not", "= name.rfind(abbrev) if suffix_pos > 0: name = name[:suffix_pos] +", "'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'), } #", "# Then I check if the current day of the", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file): \"imports the rec_ort.mdv file.\"", "self.trips self.trips[trip.id] = trip def write(self, outpath): \"writes a .zip", "the bit by x days and comparing it to the", "/ 1e6; lam = 2.6779094 \\ + 4.728982 * yb", "heuristics to split names into (city, name).\" # Handle special", "4bits = 32, no month has # more than 31", "for i in range(len(cols)): ci = col_index[i] if ci >=", "yet found the # motivation to port it. Please see", "heuristcs doesn't work. # Example:\"Triemli\" --> (\"Triemli\", \"Zurich\"). if name", "+ \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id] = station for", "yb \\ + 0.791484 * yb * xb \\ +", "ci = col_index[i] if ci >= 0: result[i] = row[ci].decode('iso-8859-1').strip()", "u'Pat.%s.%s.%s' % (line, strli, direction) pattern = self.patterns.get(pattern_id, None) if", "import_traffic_restrictions(self, restrictions_file): \"Reads the vb_regio.mdv file.\" ParseDate = lambda x:", "self.routes = {} # id --> Route self.patterns = {}", "route.color = \"000000\" route.color_text = \"FFFF00\" self.routes[route.id] = route def", "class Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS =", "int(x[:4]) * 12 + int(x[4:6]) for schedule, id, bitmask, start_date,", "out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' %", "cur_date = str(year) + (\"0\" + str(month))[-2:] + (\"0\" +", "['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in schedules: service = 'C%s.%s' %", "'j06' --> {20060713:1, 20060714:1, ...} schedules = {} # {'j06':1,", "driver # stop. We don't encode this for now. pass", "opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments = opt_parser.parse_args(argv[1:])", "import csv import datetime import optparse import sys import urllib", "to the bitmask). # If so I calculate back what", "default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string')", "seq in range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq] time += drive_time", "read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern =", "TYPE_TRAM = 0 TYPE_BUS = 3 class Divaimporter: def __init__(self,", "\"imports the rec_frt.mdv file.\" for trip_id, trip_starttime, line, strli, direction,", "% (schedule_id, daytype_id) trip.service_id = service_id assert len(self.services[service_id]) > 0", "* yb * yb * xb \\ - 0.0140 *", "examples. try: from io import StringIO as cStringIO except ImportError:", "mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename, func in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar),", "service_id) for date in daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date]", "to replicate the old behavior of --drop_unadvertised_lines, so we #", "= self.coord_converter(float(x), float(y)) station.uic_code = '' if uic_code and len(uic_code)", "Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue", "service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for service_id, service in self.services.iteritems():", "Google Transit format.\" out = zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename,", "1, 'Station': 1, u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf':", "the rec_ort.mdv file.\" for id, name, x, y, uic_code in", "names[1] in POI_TERMS: nam = u'%s %s' % (names[0], names[1])", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "The trip_id (FRT_FID) field is not unique in the vbz", "'p27':1} for schedule, daytype, date in \\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR',", "if seq not in order stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file):", "an area_id (BEREICH_NR), but the # table of advertised lines", "= TRAM_LINES[name][1] else: route.type = TYPE_BUS if route.name[0:1] == \"N\":", "ids are unique across all areas, so we can just", "* xb \\ - 0.270978 * yb * yb \\", "xb \\ - 0.270978 * yb * yb \\ -", "for k in service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self,", "% (schedule, service_id) for date in daytypes['%s.%s' % (schedule, daytype)].iterkeys():", "u'C%s.%s' % (schedule_id, daytype_id) trip.service_id = service_id assert len(self.services[service_id]) >", "I check if the current day of the month is", "format to Google Transit format.\"\"\" from __future__ import print_function #", "cStringIO except ImportError: import cStringIO import csv import datetime import", "# Terms that indicate points of interest. Used to split", "without arguments: # nothing drop # --nodrop_unadvertised_lines do not drop", "Apache License, Version 2.0 (the \"License\"); # you may not", "= int(drive_secs) wait_secs = int(wait_secs) assert len(stoptimes) == seq #", "either express or implied. # See the License for the", "> 0: name = name[:suffix_pos] + expanded # end for", "1903 Swiss national grid system to WGS-84.\" yb = (x", "daytype), {})[int(date)] = 1 schedules[schedule] = 1 schedules = schedules.keys()", "trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id = u'VB%s.%s' % (schedule_id, restriction_id) else:", "not pattern: pattern = Pattern() pattern.id = pattern_id pattern.stops =", "+ 3.238372 * xb \\ - 0.270978 * yb *", "\"writes one row of comma-separated values to stream.\" stream.write(','.join([encode_for_csv(val) for", "date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\\n') trips = [(t.id, t) for", "5=other trip = Trip() # The trip_id (FRT_FID) field is", "import sys import urllib import zipfile # Zurich tram lines", "(by # shifting the bit by x days and comparing", "service in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for date in service:", "next(reader) col_index = [-1] * len(cols) for i in range(len(cols)):", "\"Encodes one value for CSV.\" k = x.encode('utf-8') if ','", "disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file',", "--> [date, date, ...] (sorted) self.pickup_type = {} # (trip_id,", "'85': station.uic_code = uic_code station.name, station.city = self.demangle_name(name) station.country =", "'ORT_NR_NATIONAL']): station = Station() station.id = id station.position = self.coord_converter(float(x),", "in POI_TERMS: nam = u'%s %s' % (names[0], names[1]) else:", "encoded_service_id = encode_for_csv(service_id) for date in service: out.write('%s,%d,1\\n' % (encoded_service_id,", "'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id] = station", "am in # (very disgusting) and mark that date... for", "demangle_name(name): \"Applies some simple heuristics to split names into (city,", "and len(uic_code) == 7 and uic_code[:2] == '85': station.uic_code =", "for filename, func in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates),", "= {} # id --> [date, date, ...] (sorted) self.pickup_type", "'6': ['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'], '8': ['99CC00', '000000'], '9':", "s) for s in self.stations.itervalues()] stations.sort() for id, s in", "advertised lines file has no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\"))", "1 day = d + 1 cur_date = str(year) +", "\\ - 0.0436 * yb * yb * yb phi", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'), } # Cities whose names", "in range(32): if 1 << d & mask: year =", "'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL',", "strli, direction, seq, stoptime_id, drive_secs, wait_secs in \\ read_csv(stoptimes_file, ['LI_NR',", "lam * 100.0 / 36.0 def encode_for_csv(x): \"Encodes one value", "['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'], '8': ['99CC00',", "want to prettify/correct at import time. SPECIAL_CITIES = { 'Affoltern", "SPECIAL_CITIES = { 'Affoltern a. A.': 'Affoltern am Albis', 'Wangen", "\\ - 0.0140 * xb * xb * xb return", "calculate back what year month and actual day I am", "'Cj06.H9' --> {20060713:1, 20060714:1, ...} for daytype, service_id in \\", "# end for names = name.split(\", \", 1) if len(names)", "self._drop_unadvertised_lines or \\ trip.route.id in station.advertised_lines: write_row(out, [trip.id, str(seq +", "have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised lines file", "self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or \\ trip.route.id in station.advertised_lines: write_row(out,", "id) bitmask = bitmask.strip() dates = {} # This is", "in self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if (not", "def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id, service in self.services.iteritems():", "+ 4.728982 * yb \\ + 0.791484 * yb *", "flag.') if options.out_file is None: raise SystemExit('Please provide a value", "opt_parser = optparse.OptionParser() # drop_unadvertised_lines: Only export the departures of", "[date, date, ...] (sorted) self.pickup_type = {} # (trip_id, stop_seq)", "station_file, adv_file): \"imports the rec_ort.mdv file.\" for id, name, x,", "Then I check if the current day of the month", "month = ((int(start_date[4:6]) + i - 1) % 12) +", "{})[date] = 1 for k in service_days.iterkeys(): self.services[k] = service_days[k].keys()", "'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id = u\"VB%s.%s\" % (schedule, id) bitmask", "= nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath):", "or (None in trip.pattern.stops): print(\"*** Skipping bad trip: \", [trip.id])", "lines file references \" \\ \"unknown station, id \" +", "\\ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s' %", "lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr = lambda x: int(x[:4])", "int(x[6:8])) MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6])", "route.color_text = TRAM_LINES[name][1] else: route.type = TYPE_BUS if route.name[0:1] ==", "comma-separated values to stream.\" stream.write(','.join([encode_for_csv(val) for val in values])) stream.write('\\n')", "in self.goodTrips: continue assert len(trip.stoptimes) == len(trip.pattern.stops) time = trip.starttime", "= Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to', options.out_file) if", "out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\\n') trips = [(t.id, t) for t in", "daytypes = {} # 'j06' --> {20060713:1, 20060714:1, ...} schedules", "motivation to port it. Please see the examples directory for", "% (schedule, daytype), {})[int(date)] = 1 schedules[schedule] = 1 schedules", "our heuristcs doesn't work. # Example:\"Triemli\" --> (\"Triemli\", \"Zurich\"). if", "seq: pattern.stops.extend([None] * (seq - len(pattern.stops) + 1)) pattern.stops[seq] =", "= optparse.OptionParser() # drop_unadvertised_lines: Only export the departures of lines", "id --> [date, date, ...] (sorted) self.pickup_type = {} #", "days and comparing it to the bitmask). # If so", "= 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' + \\ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines =", "def import_boarding(self, drop_off_file): \"Reads the bedverb.mdv file.\" for trip_id, seq,", "= \"FFFFFF\" route.color_text = \"000000\" if name in TRAM_LINES: route.type", "write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for service_id, service in self.services.iteritems(): encoded_service_id =", "# id --> [date, date, ...] (sorted) self.pickup_type = {}", "None: raise SystemExit('Please provide a value to the --in_file flag.')", "just means that rider needs to push a button to", "import time. SPECIAL_CITIES = { 'Affoltern a. A.': 'Affoltern am", "out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k = [(r.id, r) for r in self.routes.itervalues()]", "str(year) + (\"0\" + str(month))[-2:] + (\"0\" + str(day))[-2:] dates[int(cur_date)]", "'Zollikerberg'), 'Triemli': ('Triemli', u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'), }", "Use # --nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True)", "use this file except in compliance with the License. #", "(seq - len(pattern.stops) + 1)) pattern.stops[seq] = station_id def import_boarding(self,", "field is not unique in the vbz data, as of", "'000000'], '9': ['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'],", "'Dorfzentrum': 1, 'Schiffstation': 1, 'Station': 1, u'Zentrum': 1, 'Dorfplatz': 1,", "--> Station self.routes = {} # id --> Route self.patterns", "service_id = u'C%s.%s' % (schedule_id, daytype_id) trip.service_id = service_id assert", "ugly as hell, I know. I briefly explain what I", "== 'E': self.drop_off_type[key] = '1' # '1' = no drop-off", "wait_secs in \\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL',", "range(32): if 1 << d & mask: year = int(start_date[0:4])", "1 if len(pattern.stops) <= seq: pattern.stops.extend([None] * (seq - len(pattern.stops)", "a button to have the driver # stop. We don't", "= u'C%s.%s' % (schedule_id, daytype_id) trip.service_id = service_id assert len(self.services[service_id])", "- 1) % 12) + 1 day = d +", "remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised lines file references \" \\", "across all areas, so we can just throw it away.", "= Trip() # The trip_id (FRT_FID) field is not unique", "= 0 TYPE_BUS = 3 class Divaimporter: def __init__(self, coord_converter,", "stream.write('\\n') class Station: pass class Route: pass class Pattern: pass", "# are advertised at the station in question. This is", "(trip_id, stop_seq) --> '0'/'1', '1'=no drop-off self.trips = {} #", "self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file): \"imports the rec_ort.mdv file.\" for", "(t % 3600) / 60, t % 60) def write_stop_times(self,", "read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' %", "= int(wait_secs) assert len(stoptimes) == seq # fails if seq", "Please see the examples directory for better # examples. try:", "(trip_id, line) trip.starttime = int(trip_starttime) trip.route = self.routes[line] dest_station =", "service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\\n' % (encode_for_csv(service_id), service[0], service[-1])) def", "self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt',", "(trip_id, int(seq) - 1) if code == 'A': self.pickup_type[key] =", "for line_id, name in \\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route =", "service_days = {} # 'Cj06.H9' --> {20060713:1, 20060714:1, ...} for", "https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS = 3 class Divaimporter: def", "trip_type) continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other", "= str(year) + (\"0\" + str(month))[-2:] + (\"0\" + str(day))[-2:]", "station.city = self.demangle_name(name) station.country = 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' +", "in compliance with the License. # You may obtain a", "k or '\"' in k: return '\"%s\"' % k.replace('\"', '\"\"')", "software # distributed under the License is distributed on an", "'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if", "in range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq] time += drive_time station", "= (trip_id, int(seq) - 1) if code == 'A': self.pickup_type[key]", "...} schedules = {} # {'j06':1, 'p27':1} for schedule, daytype,", "in schedules: service = 'C%s.%s' % (schedule, service_id) for date", "out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations = [(s.id, s) for s in", "zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised lines file references \"", "the station in question. This is used to remove #", "# --nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines',", "trip.id # we should make trip.id unique, by combining trip_id", "end for names = name.split(\", \", 1) if len(names) ==", "len(cols) for i in range(len(cols)): if cols[i] in header: col_index[i]", "32, no month has # more than 31 days, so", "'FFFFFF'], '7': ['000000', 'FFFFFF'], '8': ['99CC00', '000000'], '9': ['333399', 'FFFFFF'],", "city nam = names[0] city = nam.split(' ')[0] return nam,", "# fails if seq not in order stoptimes.append((drive_secs, wait_secs)) def", "s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\\n') for service_id, service in", "'LI_NR']): if station_id in self.stations: # Line ids in this", "\"\"\"imports Zurich timetables, converting them from DIVA export format to", "remove # depot trips etc, to not confuse the data", "read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq) - 1)", "+ i - 1) % 12) + 1 day =", "= opt_parser.parse_args(argv[1:]) if options.in_file is None: raise SystemExit('Please provide a", "in \\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route() route.id =", "names[0] else: # \"Zurich Enge\": First word of station name", "drop_unadvertised_lines): self.coord_converter = coord_converter self.stations = {} # id -->", "SystemExit('Please provide a value to the --out_file flag.') importer =", "line id is really qualified with an area_id (BEREICH_NR), but", "out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations = [(s.id, s) for s in self.stations.itervalues()]", "k def write_row(stream, values): \"writes one row of comma-separated values", "= no pick-up elif code == 'E': self.drop_off_type[key] = '1'", "600000.0) / 1e6; xb = (y - 200000.0) / 1e6;", "{ 'Freienbach SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof", "lambda x: int(x[:4]) * 12 + int(x[4:6]) for schedule, id,", "self.services = {} # id --> [date, date, ...] (sorted)", "+ 1), station.id, self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq), '0'),", "self.stations: # Line ids in this file have leading zeroes,", "'5': ['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'], '8':", "# table of advertised lines does not include area. Fortunately,", "station.id = id station.position = self.coord_converter(float(x), float(y)) station.uic_code = ''", "yb phi = 16.9023892 \\ + 3.238372 * xb \\", "service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): \"Reads the vb_regio.mdv file.\" ParseDate", "(name, city). Used as exception list where our # simple", "the --out_file flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote", "trip.id unique, by combining trip_id and line trip.id = (\"%s_%s\")", "== seq # fails if seq not in order stoptimes.append((drive_secs,", "in question. This is used to remove # depot trips", "don't encode this for now. pass else: raise ValueError('Unexpected code", "lines TRAM_LINES = {'2': ['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'], '4':", "csv import datetime import optparse import sys import urllib import", "with the License. # You may obtain a copy of", "converting them from DIVA export format to Google Transit format.\"\"\"", "(\"%s_%s\") % (trip_id, line) trip.starttime = int(trip_starttime) trip.route = self.routes[line]", "route.color, route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations = [(s.id,", "'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' %", "= name.split(\", \", 1) if len(names) == 2: if names[1]", "'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)] =", "a .zip file in Google Transit format.\" out = zipfile.ZipFile(outpath,", "except ImportError: import cStringIO import csv import datetime import optparse", "in header: col_index[i] = header.index(cols[i]) for row in reader: result", "in \\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id =", "+= drive_time station = self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or \\", "I briefly explain what I do: # 8 characters in", "export the departures of lines that # are advertised at", "time += wait_time def main(argv): # It's hard to replicate", "coordinates from the 1903 Swiss national grid system to WGS-84.\"", "station name designates the city nam = names[0] city =", "station.position = self.coord_converter(float(x), float(y)) station.uic_code = '' if uic_code and", "= {} # id --> Route self.patterns = {} #", "daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1 for k", "express or implied. # See the License for the specific", "that date... for i in range(MonthNr(end_date) - MonthNr(start_date) + 1):", "1=normal, 2=empty, 3=from depot, 4=to depot, 5=other trip = Trip()", "compression=zipfile.ZIP_DEFLATED) for filename, func in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt',", "except in compliance with the License. # You may obtain", "self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def demangle_name(name): \"Applies some simple heuristics", "= cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n')", "abbrev, expanded in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev)", "None: raise SystemExit('Please provide a value to the --out_file flag.')", "no drop-off elif code == 'B': # 'B' just means", "'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)]", "system to WGS-84.\" yb = (x - 600000.0) / 1e6;", "self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt',", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "= csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect) header = next(reader) col_index", "* xb return phi * 100.0 / 36.0, lam *", "'DATUM_VON', 'DATUM_BIS']): id = u\"VB%s.%s\" % (schedule, id) bitmask =", "and # limitations under the License. \"\"\"imports Zurich timetables, converting", "name.rfind(abbrev) if suffix_pos > 0: name = name[:suffix_pos] + expanded", "CONDITIONS OF ANY KIND, either express or implied. # See", "col_index = [-1] * len(cols) for i in range(len(cols)): if", "# Expand abbreviations. for abbrev, expanded in [('str.', 'strasse'), ('Schiffst.',", "Skipping bad trip: \", [trip.id]) continue self.goodTrips[trip_id] = True headsign", "* 12 + int(x[4:6]) for schedule, id, bitmask, start_date, end_date", "format.\" out = zipfile.ZipFile(outpath, mode=\"w\", compression=zipfile.ZIP_DEFLATED) for filename, func in", "stoptimes_file): \"imports the lid_fahrzeitart.mdv file.\" for line, strli, direction, seq,", "for daytype, service_id in \\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule", "0.0436 * yb * yb * yb phi = 16.9023892", "[trip.id, str(seq + 1), station.id, self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id,", "if not self._drop_unadvertised_lines or \\ trip.route.id in station.advertised_lines: write_row(out, [trip.id,", "read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route() route.id = line_id route.name", "advertised at the station in question. This is used to", "[None] * len(cols) for i in range(len(cols)): ci = col_index[i]", "s): \"imports the rec_lin_ber.mdv file.\" # the line id is", "% (t / 3600, (t % 3600) / 60, t", "* yb \\ + 0.791484 * yb * xb \\", "len(trip.pattern.stops)) or (None in trip.pattern.stops): print(\"*** Skipping bad trip: \",", "len(cols) for i in range(len(cols)): ci = col_index[i] if ci", "def main(argv): # It's hard to replicate the old behavior", "== '85': station.uic_code = uic_code station.name, station.city = self.demangle_name(name) station.country", "s): \"imports the lid_verlauf.mdv file.\" for line, strli, direction, seq,", "stream.\" stream.write(','.join([encode_for_csv(val) for val in values])) stream.write('\\n') class Station: pass", "\"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def", "if route.name[0:1] == \"N\": route.color = \"000000\" route.color_text = \"FFFF00\"", "restriction_id: service_id = u'VB%s.%s' % (schedule_id, restriction_id) else: service_id =", "(schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1 for k in service_days.iterkeys():", "seems # that line ids are unique across all areas,", "combining trip_id and line trip.id = (\"%s_%s\") % (trip_id, line)", "service[0], service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\\n') for service_id, service in", "read = lambda name, prefix=\"\": (prefix + inzip.read(name)).splitlines() # The", "id station.position = self.coord_converter(float(x), float(y)) station.uic_code = '' if uic_code", "int(x[4:6]) for schedule, id, bitmask, start_date, end_date in \\ read_csv(restrictions_file,", "and comparing it to the bitmask). # If so I", "city). POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation': 1, 'Station':", "unique across all areas, so we can just throw it", "value for CSV.\" k = x.encode('utf-8') if ',' in k", "('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s =", "'FFFFFF'], '11': ['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'], '13': ['FFCC33', '000000'],", "date in service: out.write('%s,%d,1\\n' % (encoded_service_id, date)) def write_trips(self, out):", "20060714:1, ...} for daytype, service_id in \\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']):", "the lid_verlauf.mdv file.\" for line, strli, direction, seq, station_id in", "StringIO as cStringIO except ImportError: import cStringIO import csv import", "file references \" \\ \"unknown station, id \" + station_id)", "trip.id in self.trips self.trips[trip.id] = trip def write(self, outpath): \"writes", "= set() self.stations[id] = station for station_id, line_id in read_csv(adv_file,", "self.services[k] = service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): \"Reads the vb_regio.mdv", "in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev) if suffix_pos", "drop_off_file): \"Reads the bedverb.mdv file.\" for trip_id, seq, code in", "line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \\ read_csv(stoptimes_file,", "* yb phi = 16.9023892 \\ + 3.238372 * xb", "confuse the data in schedule bubbles. Use # --nodrop_unadvertised_lines to", "xb \\ - 0.0447 * yb * yb * xb", "0.0447 * yb * yb * xb \\ - 0.0140", "float(y)) station.uic_code = '' if uic_code and len(uic_code) == 7", "self.pickup_type[key] = '1' # '1' = no pick-up elif code", "trip_starttime, line, strli, direction, \\ stoptime_id, schedule_id, daytype_id, restriction_id, \\", "dest_station_id, dest_stop_id, trip_type in \\ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR',", "if not pattern: pattern = Pattern() pattern.id = pattern_id pattern.stops", "First word of station name designates the city nam =", "pass else: raise ValueError('Unexpected code in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s'", "for seq in range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq] time +=", "pattern.stops[seq] = station_id def import_boarding(self, drop_off_file): \"Reads the bedverb.mdv file.\"", "it's ok). # Then I check if the current day", "(line, strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq)", "area. Fortunately, it seems # that line ids are unique", "yb * xb \\ - 0.0140 * xb * xb", "importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to', options.out_file) if __name__ == '__main__':", "= names[0] city = nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city, city)", "= Pattern() pattern.id = pattern_id pattern.stops = [] pattern.stoptimes =", "+ str(month))[-2:] + (\"0\" + str(day))[-2:] dates[int(cur_date)] = 1 self.services[id]", "transitfeed.py and we haven't yet found the # motivation to", "# id --> Station self.routes = {} # id -->", "Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS = 3", "arguments: # nothing drop # --nodrop_unadvertised_lines do not drop #", "in \\ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in schedules: service", ".zip file in Google Transit format.\" out = zipfile.ZipFile(outpath, mode=\"w\",", "= 2.6779094 \\ + 4.728982 * yb \\ + 0.791484", "we key them by trip.id # we should make trip.id", "{} # id --> Pattern self.services = {} # id", "* xb * xb * xb return phi * 100.0", "SPECIAL_NAMES[name] # Expand abbreviations. for abbrev, expanded in [('str.', 'strasse'),", "day of the month is in the bitmask (by #", "[(s.id, s) for s in self.stations.itervalues()] stations.sort() for id, s", "seq), '0')]) time += wait_time def main(argv): # It's hard", "+ i - 1)) / 12 month = ((int(start_date[4:6]) +", "# to prevent overwritingimported trips when we key them by", "in k or '\"' in k: return '\"%s\"' % k.replace('\"',", "func in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes),", "= [(r.id, r) for r in self.routes.itervalues()] k.sort() for id,", "uic_code station.name, station.city = self.demangle_name(name) station.country = 'CH' station.url =", "'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch', u'Z\\u00fcrich'),", "import cStringIO import csv import datetime import optparse import sys", "it. Please see the examples directory for better # examples.", "nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath): inzip", "coord_converter self.stations = {} # id --> Station self.routes =", "self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id = u'VB%s.%s' %", "phi = 16.9023892 \\ + 3.238372 * xb \\ -", "= int(bitmask[i * 8:i * 8 + 8], 16) for", "in self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if trip_id", "This was written before transitfeed.py and we haven't yet found", "self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file): \"imports the rec_ort.mdv", "* (seq - len(pattern.stops) + 1)) pattern.stops[seq] = station_id def", "- len(pattern.stops) + 1)) pattern.stops[seq] = station_id def import_boarding(self, drop_off_file):", "%s' % (names[0], names[1]) else: nam = names[1] city =", "trip.pattern = self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id =", "= 1 self.services[id] = dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file): \"imports", "assert len(stoptimes) == seq # fails if seq not in", "id \" + station_id) def import_routes(self, s): \"imports the rec_lin_ber.mdv", "for r in self.routes.itervalues()] k.sort() for id, route in k:", "question. This is used to remove # depot trips etc,", "line, direction, \\ dest_station_id, trip_type) continue # 1=normal, 2=empty, 3=from", "int(wait_secs) assert len(stoptimes) == seq # fails if seq not", "'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli,", "# Line ids in this file have leading zeroes, remove.", "12) + 1 day = d + 1 cur_date =", "not trip.id in self.trips self.trips[trip.id] = trip def write(self, outpath):", "self.stations = {} # id --> Station self.routes = {}", "= '' if uic_code and len(uic_code) == 7 and uic_code[:2]", "(not len(trip.pattern.stops)) or (None in trip.pattern.stops): print(\"*** Skipping bad trip:", "try: from io import StringIO as cStringIO except ImportError: import", "= schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)] = 1 schedules[schedule]", "# drop_unadvertised_lines: Only export the departures of lines that #", "else: service_id = u'C%s.%s' % (schedule_id, daytype_id) trip.service_id = service_id", "return nam, SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath,", "include area. Fortunately, it seems # that line ids are", "rec_ort.mdv file.\" for id, name, x, y, uic_code in \\", "ImportError: import cStringIO import csv import datetime import optparse import", "['ORT_NR', 'LI_NR']): if station_id in self.stations: # Line ids in", "'8': ['99CC00', '000000'], '9': ['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11':", "'Wangen b. D.': 'Wangen' } def read_csv(s, cols): csv_dialect =", "- 200000.0) / 1e6; lam = 2.6779094 \\ + 4.728982", "opt_parser.parse_args(argv[1:]) if options.in_file is None: raise SystemExit('Please provide a value", "= (y - 200000.0) / 1e6; lam = 2.6779094 \\", "'1' = no pick-up elif code == 'E': self.drop_off_type[key] =", "\\ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route() route.id = line_id", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else: route.type", "split names into (city, name).\" # Handle special cases where", "the rec_lin_ber.mdv file.\" # the line id is really qualified", "# '1' = no pick-up elif code == 'E': self.drop_off_type[key]", "TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else: route.type =", "elif code == 'B': # 'B' just means that rider", "Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to', options.out_file) if __name__", "len(names) == 2: if names[1] in POI_TERMS: nam = u'%s", "adv_file): \"imports the rec_ort.mdv file.\" for id, name, x, y,", "in k: return '\"%s\"' % k.replace('\"', '\"\"') else: return k", "end_date in \\ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id", "behavior of --drop_unadvertised_lines, so we # don't. Instead, there are", "range(len(cols)): ci = col_index[i] if ci >= 0: result[i] =", "return phi * 100.0 / 36.0, lam * 100.0 /", "year = int(start_date[0:4]) + ((int(start_date[4:6]) + i - 1)) /", "to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines')", "I am in # (very disgusting) and mark that date...", "['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'], '13': ['FFCC33',", "our # simple heuristcs doesn't work. SPECIAL_NAMES = { 'Freienbach", "station_id, line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id in self.stations:", "' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) def import_services(self, daytype_file, days_file):", "def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k = [(r.id, r) for", "csv_dialect = csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect) header = next(reader)", "2: if names[1] in POI_TERMS: nam = u'%s %s' %", "31 days, so it's ok). # Then I check if", "id, name, name, route.type, route.color, route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,'", "button to have the driver # stop. We don't encode", "'FAHRTART_NR']): if trip_type != '1': print(\"skipping Trip \", trip_id, line,", "',' in k or '\"' in k: return '\"%s\"' %", "# examples. try: from io import StringIO as cStringIO except", "'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) pattern", "in # (very disgusting) and mark that date... for i", "work. SPECIAL_NAMES = { 'Freienbach SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'),", "bitmask.strip() dates = {} # This is ugly as hell,", "\\ stoptime_id, schedule_id, daytype_id, restriction_id, \\ dest_station_id, dest_stop_id, trip_type in", "Version 2.0 (the \"License\"); # you may not use this", "daytype_file, days_file): daytypes = {} # 'j06' --> {20060713:1, 20060714:1,", "write_row(out, [id, s.uic_code, s.name, s.city, s.country, str(s.position[0]), str(s.position[1]), s.url]) def", "interest. Used to split station names # to (name, city).", "= {} # (trip_id, stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type =", "+= wait_time def main(argv): # It's hard to replicate the", "Zurich tram lines TRAM_LINES = {'2': ['FF3300', 'FFFFFF'], '3': ['009933',", "really qualified with an area_id (BEREICH_NR), but the # table", "bitmask). # If so I calculate back what year month", "range(len(cols)): if cols[i] in header: col_index[i] = header.index(cols[i]) for row", "station.name, station.city = self.demangle_name(name) station.country = 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0='", "trips etc, to not confuse the data in schedule bubbles.", "line ids are unique across all areas, so we can", "= [None] * len(cols) for i in range(len(cols)): ci =", "out.write('service_id,date,exception_type\\n') for service_id, service in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for", "self.routes[line] dest_station = self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' % (line, strli,", "continue assert len(trip.stoptimes) == len(trip.pattern.stops) time = trip.starttime for seq", "'1' # '1' = no drop-off elif code == 'B':", "1, 'Zentrum/Bahnhof': 1, 'Dorf': 1} # Maps station names to", "r) for r in self.routes.itervalues()] k.sort() for id, route in", "* xb \\ - 0.0447 * yb * yb *", "I know. I briefly explain what I do: # 8", "by applicable law or agreed to in writing, software #", "Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter self.stations =", "directory for better # examples. try: from io import StringIO", "options.in_file is None: raise SystemExit('Please provide a value to the", "assert len(self.services[service_id]) > 0 assert not trip.id in self.trips self.trips[trip.id]", "1 schedules[schedule] = 1 schedules = schedules.keys() service_days = {}", "'0'=normal/'1'=no pickup self.drop_off_type = {} # (trip_id, stop_seq) --> '0'/'1',", "import_routes(self, s): \"imports the rec_lin_ber.mdv file.\" # the line id", "file.\" for trip_id, seq, code in \\ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR',", "self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO() func(s) out.writestr(filename,", "- 0.270978 * yb * yb \\ - 0.002582 *", "- 0.0140 * xb * xb * xb return phi", "seq, stoptime_id, drive_secs, wait_secs in \\ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR',", "def format_time(t): return \"%02d:%02d:%02d\" % (t / 3600, (t %", "'DATUM_BIS']): id = u\"VB%s.%s\" % (schedule, id) bitmask = bitmask.strip()", "xb * xb \\ - 0.0436 * yb * yb", "day = d + 1 cur_date = str(year) + (\"0\"", "# we should make trip.id unique, by combining trip_id and", "file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised lines", "TYPE_BUS = 3 class Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter", "them from DIVA export format to Google Transit format.\"\"\" from", "not in order stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file): \"imports the", "the # motivation to port it. Please see the examples", "d & mask: year = int(start_date[0:4]) + ((int(start_date[4:6]) + i", "* xb * xb \\ - 0.0436 * yb *", "--nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false',", "- 0.0436 * yb * yb * yb phi =", "is in the bitmask (by # shifting the bit by", "we # don't. Instead, there are only two options without", "= service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): \"Reads the vb_regio.mdv file.\"", "0.270978 * yb * yb \\ - 0.002582 * xb", "read('bedienendeLinien_google.csv', \"ORT_NR;LI_NR;;;;\")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv'))", "applicable law or agreed to in writing, software # distributed", "= '1' # '1' = no drop-off elif code ==", "\"imports the lid_fahrzeitart.mdv file.\" for line, strli, direction, seq, stoptime_id,", "D.': 'Wangen' } def read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader", "{} # (trip_id, stop_seq) --> '0'/'1', '1'=no drop-off self.trips =", "{} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def demangle_name(name): \"Applies some simple", "{} # (trip_id, stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type = {}", "station.uic_code = uic_code station.name, station.city = self.demangle_name(name) station.country = 'CH'", "we want to prettify/correct at import time. SPECIAL_CITIES = {", "% (schedule, id) bitmask = bitmask.strip() dates = {} #", "row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x, y): \"Converts coordinates from the", "xb \\ - 0.0436 * yb * yb * yb", "u'Z\\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'), } # Cities whose", "nam = u'%s %s' % (names[0], names[1]) else: nam =", "xb * xb \\ - 0.0447 * yb * yb", "'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type !=", "from the 1903 Swiss national grid system to WGS-84.\" yb", "a month ( 8 * 4bits = 32, no month", "= self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) trip.pattern", "pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id,", "direction, \\ dest_station_id, trip_type) continue # 1=normal, 2=empty, 3=from depot,", "self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id,", "drop opt_parser = optparse.OptionParser() # drop_unadvertised_lines: Only export the departures", "opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string') options,", "(very disgusting) and mark that date... for i in range(MonthNr(end_date)", "# You may obtain a copy of the License at", "* 4bits = 32, no month has # more than", "'\"%s\"' % k.replace('\"', '\"\"') else: return k def write_row(stream, values):", "3.238372 * xb \\ - 0.270978 * yb * yb", "type='string') options, unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file is None: raise", "'A': self.pickup_type[key] = '1' # '1' = no pick-up elif", "# limitations under the License. \"\"\"imports Zurich timetables, converting them", "def import_services(self, daytype_file, days_file): daytypes = {} # 'j06' -->", "# Handle special cases where our heuristcs doesn't work. #", "Transit format.\"\"\" from __future__ import print_function # This was written", "trips: if (not len(trip.pattern.stops)) or (None in trip.pattern.stops): print(\"*** Skipping", "exception list where our # simple heuristcs doesn't work. SPECIAL_NAMES", "(trip_id, code)) def import_services(self, daytype_file, days_file): daytypes = {} #", "written before transitfeed.py and we haven't yet found the #", "['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype),", "to the --out_file flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file)", "trip_id not in self.goodTrips: continue assert len(trip.stoptimes) == len(trip.pattern.stops) time", "# id --> Route self.patterns = {} # id -->", "= pattern_id pattern.stops = [] pattern.stoptimes = {} self.patterns[pattern_id] =", "name, route.type, route.color, route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\\n') stations", "= {'2': ['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'],", "indicate points of interest. Used to split station names #", "Line ids in this file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\"))", "TRAM_LINES: route.type = TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1]", "['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']} # Terms", "to (name, city). POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation':", "continue self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id,", "= lambda x: int(x[:4]) * 12 + int(x[4:6]) for schedule,", "stop. We don't encode this for now. pass else: raise", "in \\ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id =", "= self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod def format_time(t):", "the examples directory for better # examples. try: from io", "* yb * xb * xb \\ - 0.0436 *", "more than 31 days, so it's ok). # Then I", "the old behavior of --drop_unadvertised_lines, so we # don't. Instead,", "for i in range(len(cols)): if cols[i] in header: col_index[i] =", "return SPECIAL_NAMES[name] # Expand abbreviations. for abbrev, expanded in [('str.',", "1 << d & mask: year = int(start_date[0:4]) + ((int(start_date[4:6])", "= \"000000\" if name in TRAM_LINES: route.type = TYPE_TRAM route.color", "read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect) header", "station.id, self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq),", "drive_secs = int(drive_secs) wait_secs = int(wait_secs) assert len(stoptimes) == seq", "name, prefix=\"\": (prefix + inzip.read(name)).splitlines() # The advertised lines file", "['99CC00', '000000'], '9': ['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11': ['009933',", "--> (\"Triemli\", \"Zurich\"). if name in SPECIAL_NAMES: return SPECIAL_NAMES[name] #", "(schedule, service_id) for date in daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service,", "16.9023892 \\ + 3.238372 * xb \\ - 0.270978 *", "station = self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or \\ trip.route.id in", "name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\\n' % ( id, name, name, route.type,", "* yb * xb \\ + 0.1306 * yb *", "but the # table of advertised lines does not include", "'Dorf': 1} # Maps station names to (name, city). Used", "\"License\"); # you may not use this file except in", "headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod def", "0: name = name[:suffix_pos] + expanded # end for names", "this file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip(\"0\")) else: print(\"Warning, advertised", "schedules[schedule] = 1 schedules = schedules.keys() service_days = {} #", "if trip_id not in self.goodTrips: continue assert len(trip.stoptimes) == len(trip.pattern.stops)", "(trip_id, trip) in trips: if (not len(trip.pattern.stops)) or (None in", "/ 36.0 def encode_for_csv(x): \"Encodes one value for CSV.\" k", "= self.routes[line] dest_station = self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' % (line,", "code == 'A': self.pickup_type[key] = '1' # '1' = no", "def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\\n') k", "dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments =", "self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): \"Reads the vb_regio.mdv file.\" ParseDate =", "depot, 5=other trip = Trip() # The trip_id (FRT_FID) field", "are unique across all areas, so we can just throw", "= trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id = u'VB%s.%s' % (schedule_id, restriction_id)", "= self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, [])", "= drop_unadvertised_lines @staticmethod def demangle_name(name): \"Applies some simple heuristics to", "uic_code[:2] == '85': station.uic_code = uic_code station.name, station.city = self.demangle_name(name)", "do: # 8 characters in the bitmask equal a month", "and actual day I am in # (very disgusting) and", "# depot trips etc, to not confuse the data in", "action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file',", "{ 'Affoltern a. A.': 'Affoltern am Albis', 'Wangen b. D.':", "pattern_id pattern.stops = [] pattern.stoptimes = {} self.patterns[pattern_id] = pattern", "(city, name).\" # Handle special cases where our heuristcs doesn't", "% (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1 for k in", "i - 1) % 12) + 1 day = d", "drive_time, wait_time = trip.stoptimes[seq] time += drive_time station = self.stations[trip.pattern.stops[seq]]", "* yb \\ - 0.002582 * xb * xb \\", "phi * 100.0 / 36.0, lam * 100.0 / 36.0", "'FFFFFF'], '15': ['FF3300', 'FFFFFF']} # Terms that indicate points of" ]
[ "of documents, using `extractor` \"\"\" self._documents = [] page_types_and_dates =", "print \"This module is only intended to be called from", "\"AND\": hit = True for rule in rule_val: hit =", "-------- if rule_key == \"AND\": hit = True for rule", "rule_val = tuple_[1] header = header.upper() # --------- Logical separators", "try: pos = make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos = -1 return", "hit # -------------- Rules ---------------- elif rule_key == \"HEADER_CONTAINS\": try:", "rule_key = tuple_[0].upper() rule_val = tuple_[1] header = header.upper() #", "constructed from more than one file. This is a limitation,", "page): \"\"\"Append content from a page to this document. \"\"\"", "= page.get_date() or extractor.get_date() def append_page(self, page): \"\"\"Append content from", "from a page to this document. \"\"\" pass def append_text(self,", "page_types_and_dates = [] \"\"\"Keep track of documents by type and", "\"\"\"Merge this document with another one\"\"\" try: self.text += document.text", "(type_, date)) if type_ in disallow_infixes and last_match > i:", "i += num_docs_to_merge else: doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge) i +=", "\"\"\"len is the length of the total plaintext\"\"\" return len(self.text)", "from more than one file. This is a limitation, obvious", "split up in a large number of files. \"\"\" import", "is a limitation, obvious in cases like Gotlands kommun, where", "def parse_rules(self, tuple_, header): \"\"\"Parse document rules. See settings.py for", "rules in settings.py A file can contain one or more", "`settings.document_type_settings` \"\"\" # Loop through pages, and add pages of", "page, extractor): \"\"\"Create a document stub from a page. Use", "separators -------- if rule_key == \"AND\": hit = True for", "(type_, date) = page_types_and_dates[i] last_match = last_index(page_types_and_dates, (type_, date)) if", "\"\"\"Append content to this document. \"\"\" self.text += text def", "disallow_infixes == True doc_settings = settings.document_type_settings disallow_infixes = [d for", "DocumentList(object): \"\"\"Contains a list of documents, extracted from a file.", "not be constructed from more than one file. This is", "\"\"\" import settings from modules.utils import make_unicode, last_index from modules.extractors.documentBase", "page in extractor.get_next_page(): temp_doc = Document(page, extractor) if (len(documents) >", "return pos > -1 if __name__ == \"__main__\": print \"This", "disallow holes\"\"\" num_docs = len(page_types_and_dates) i = 0 while i", "in rule_val: hit = hit or self.parse_rules(rule, header) return hit", "num_docs: (type_, date) = page_types_and_dates[i] last_match = last_index(page_types_and_dates, (type_, date))", "a limitation, obvious in cases like Gotlands kommun, where meeting", "\"\"\"Create a list of documents, using `extractor` \"\"\" self._documents =", "page.get_date() or extractor.get_date() self.type_ = self.get_document_type() self.date = page.get_date() or", "a document can not be constructed from more than one", "self.parse_rules(rule_val, header) return hit # -------------- Rules ---------------- elif rule_key", "\"attachment\", \"Cache-Control\": \"public\" } class DocumentList(object): \"\"\"Contains a list of", "header = header.upper() # --------- Logical separators -------- if rule_key", "try: for page in extractor.get_next_page(): temp_doc = Document(page, extractor) if", "return len(self._documents) class Document(object): \"\"\"Represents a single document \"\"\" text", "page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type = temp_doc.type_ last_page_date = temp_doc.date except ExtractionNotAllowed:", "documents.pop(0) for j in range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i +=", "\"\"\"Document types that disallow holes\"\"\" num_docs = len(page_types_and_dates) i =", "page_types_and_dates[i] last_match = last_index(page_types_and_dates, (type_, date)) if type_ in disallow_infixes", "document can not be constructed from more than one file.", "this document. \"\"\" self.text = page.get_text() self.header = page.get_header() or", "using `extractor` \"\"\" self._documents = [] page_types_and_dates = [] \"\"\"Keep", "\"\" header = \"\" date = None type_ = None", "like Gotlands kommun, where meeting minutes are split up in", "disallow_infixes and last_match > i: num_docs_to_merge = last_match - i", "disallow_infixes = [d for d in doc_settings if doc_settings[d][\"disallow_infixes\"] is", "text = \"\" header = \"\" date = None type_", "rule_val: hit = hit or self.parse_rules(rule, header) return hit elif", "self.parse_rules(rule, header) return hit elif rule_key == \"NOT\": hit =", "= hit and self.parse_rules(rule, header) return hit elif rule_key ==", "= last_match - i + 1 new_doc = documents.pop(0) for", "document.text except UnicodeDecodeError: self.text = make_unicode(self.text) + make_unicode(document.text) def __len__(self):", "to this document. \"\"\" self.text += text def merge_with(self, document):", "header) return hit elif rule_key == \"OR\": hit = False", "rule_key == \"AND\": hit = True for rule in rule_val:", "\"\"\"Create a document stub from a page. Use add_page to", "self.parse_rules(document_type[1], self.header): return document_type[0] return None def parse_rules(self, tuple_, header):", "pos = -1 return pos > -1 if __name__ ==", "last_match = last_index(page_types_and_dates, (type_, date)) if type_ in disallow_infixes and", "\"public\" } class DocumentList(object): \"\"\"Contains a list of documents, extracted", "\"\"\" pass def append_text(self, text): \"\"\"Append content to this document.", "extractor): \"\"\"Create a document stub from a page. Use add_page", "== \"AND\": hit = True for rule in rule_val: hit", "def get_next_document(self): for document in self._documents: yield document def __len__(self):", "\"\"\"Contains a list of documents, extracted from a file. \"\"\"", "the length of the total plaintext\"\"\" return len(self.text) def get_document_type(self):", "self.text += document.text except UnicodeDecodeError: self.text = make_unicode(self.text) + make_unicode(document.text)", "= None type_ = None def __init__(self, page, extractor): \"\"\"Create", "doc_settings = settings.document_type_settings disallow_infixes = [d for d in doc_settings", "length of the total plaintext\"\"\" return len(self.text) def get_document_type(self): \"\"\"", "# merge documents, if disallow_infixes == True doc_settings = settings.document_type_settings", "the number of documents\"\"\" return len(self._documents) class Document(object): \"\"\"Represents a", "document \"\"\" text = \"\" header = \"\" date =", "this document with another one\"\"\" try: self.text += document.text except", "def __len__(self): \"\"\"len is the length of the total plaintext\"\"\"", "defined by the document rules in settings.py A file can", "page to this document. \"\"\" pass def append_text(self, text): \"\"\"Append", "[] \"\"\"Keep track of documents by type and date, to", "\"\"\"Append content from a page to this document. \"\"\" pass", "i < num_docs: (type_, date) = page_types_and_dates[i] last_match = last_index(page_types_and_dates,", "hit elif rule_key == \"OR\": hit = False for rule", "UnicodeDecodeError: self.text = make_unicode(self.text) + make_unicode(document.text) def __len__(self): \"\"\"len is", "Loop through pages, and add pages of the same type", "through pages, and add pages of the same type and", "extractor.get_header() self.date = page.get_date() or extractor.get_date() self.type_ = self.get_document_type() self.date", "+= 1 def get_next_document(self): for document in self._documents: yield document", "True for rule in rule_val: hit = hit and self.parse_rules(rule,", "if (len(documents) > 0 and temp_doc.type_ == last_page_type and temp_doc.date", "= page.get_text() self.header = page.get_header() or extractor.get_header() self.date = page.get_date()", "class DocumentList(object): \"\"\"Contains a list of documents, extracted from a", "d in doc_settings if doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document types that", "len(page_types_and_dates) i = 0 while i < num_docs: (type_, date)", "same type and date together last_page_type = None last_page_date =", "= [] \"\"\"Keep track of documents by type and date,", "extractor): \"\"\"Create a list of documents, using `extractor` \"\"\" self._documents", "extractor.get_next_page(): temp_doc = Document(page, extractor) if (len(documents) > 0 and", "page.get_text() self.header = page.get_header() or extractor.get_header() self.date = page.get_date() or", "= documents.pop(0) self._documents.append(doc_to_merge) i += 1 def get_next_document(self): for document", "not self.parse_rules(rule_val, header) return hit # -------------- Rules ---------------- elif", "last_page_type = temp_doc.type_ last_page_date = temp_doc.date except ExtractionNotAllowed: raise ExtractionNotAllowed", "self._documents.append(new_doc) i += num_docs_to_merge else: doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge) i", "keep extending this document. \"\"\" self.text = page.get_text() self.header =", "self.header = page.get_header() or extractor.get_header() self.date = page.get_date() or extractor.get_date()", "document stub from a page. Use add_page to keep extending", "document_type[0] return None def parse_rules(self, tuple_, header): \"\"\"Parse document rules.", "one or more document. However, a document can not be", "pos = make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos = -1 return pos", "by type and date, to be able to merge documents", "in disallow_infixes and last_match > i: num_docs_to_merge = last_match -", "+= document.text except UnicodeDecodeError: self.text = make_unicode(self.text) + make_unicode(document.text) def", "rule_key == \"NOT\": hit = not self.parse_rules(rule_val, header) return hit", "this document. \"\"\" pass def append_text(self, text): \"\"\"Append content to", "header) return hit # -------------- Rules ---------------- elif rule_key ==", "rule_key == \"HEADER_CONTAINS\": try: pos = make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos", "extractor) if (len(documents) > 0 and temp_doc.type_ == last_page_type and", "in settings.py A file can contain one or more document.", "last_page_date = temp_doc.date except ExtractionNotAllowed: raise ExtractionNotAllowed # merge documents,", "the first matching document type, based on this header text.", "stub from a page. Use add_page to keep extending this", "= page.get_date() or extractor.get_date() self.type_ = self.get_document_type() self.date = page.get_date()", "that disallow holes\"\"\" num_docs = len(page_types_and_dates) i = 0 while", "def get_document_type(self): \"\"\" Return the first matching document type, based", "in settings.document_rules: if self.parse_rules(document_type[1], self.header): return document_type[0] return None def", "documents depending on `settings.document_type_settings` \"\"\" # Loop through pages, and", "hit or self.parse_rules(rule, header) return hit elif rule_key == \"NOT\":", "None last_page_date = None documents = [] try: for page", "of the same type and date together last_page_type = None", "== True doc_settings = settings.document_type_settings disallow_infixes = [d for d", "= make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos = -1 return pos >", "last_match > i: num_docs_to_merge = last_match - i + 1", "if rule_key == \"AND\": hit = True for rule in", "for rule in rule_val: hit = hit and self.parse_rules(rule, header)", "only intended to be called from other scripts.\" import sys", "or self.parse_rules(rule, header) return hit elif rule_key == \"NOT\": hit", "document rules. See settings.py for syntax\"\"\" rule_key = tuple_[0].upper() rule_val", "== last_page_type and temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_,", "settings.py for syntax\"\"\" rule_key = tuple_[0].upper() rule_val = tuple_[1] header", "doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document types that disallow holes\"\"\" num_docs =", "--------- Logical separators -------- if rule_key == \"AND\": hit =", "can contain one or more document. However, a document can", "None documents = [] try: for page in extractor.get_next_page(): temp_doc", "module is only intended to be called from other scripts.\"", "if type_ in disallow_infixes and last_match > i: num_docs_to_merge =", "return None def parse_rules(self, tuple_, header): \"\"\"Parse document rules. See", "hit and self.parse_rules(rule, header) return hit elif rule_key == \"OR\":", "hit elif rule_key == \"NOT\": hit = not self.parse_rules(rule_val, header)", "= \"\" header = \"\" date = None type_ =", "for j in range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i += num_docs_to_merge", "\"__main__\": print \"This module is only intended to be called", "more document. However, a document can not be constructed from", "on `settings.document_type_settings` \"\"\" # Loop through pages, and add pages", "\"OR\": hit = False for rule in rule_val: hit =", "+ 1 new_doc = documents.pop(0) for j in range(i, last_match):", "try: self.text += document.text except UnicodeDecodeError: self.text = make_unicode(self.text) +", "the document rules in settings.py A file can contain one", "last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i += num_docs_to_merge else: doc_to_merge = documents.pop(0)", "__init__(self, page, extractor): \"\"\"Create a document stub from a page.", "tuple_, header): \"\"\"Parse document rules. See settings.py for syntax\"\"\" rule_key", "new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i += num_docs_to_merge else: doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge)", "extending this document. \"\"\" self.text = page.get_text() self.header = page.get_header()", "page.get_date() or extractor.get_date() def append_page(self, page): \"\"\"Append content from a", "append_page(self, page): \"\"\"Append content from a page to this document.", "rule_key == \"OR\": hit = False for rule in rule_val:", "type and date together last_page_type = None last_page_date = None", "merge_with(self, document): \"\"\"Merge this document with another one\"\"\" try: self.text", "document with another one\"\"\" try: self.text += document.text except UnicodeDecodeError:", "len(self._documents) class Document(object): \"\"\"Represents a single document \"\"\" text =", "Document(page, extractor) if (len(documents) > 0 and temp_doc.type_ == last_page_type", "be constructed from more than one file. This is a", "\"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\" } class DocumentList(object): \"\"\"Contains", "one file. This is a limitation, obvious in cases like", "to merge documents depending on `settings.document_type_settings` \"\"\" # Loop through", "> 0 and temp_doc.type_ == last_page_type and temp_doc.date == last_page_date):", "elif rule_key == \"OR\": hit = False for rule in", "documents\"\"\" return len(self._documents) class Document(object): \"\"\"Represents a single document \"\"\"", "based on this header text. \"\"\" for document_type in settings.document_rules:", "a document stub from a page. Use add_page to keep", "document. \"\"\" self.text = page.get_text() self.header = page.get_header() or extractor.get_header()", "or extractor.get_header() self.date = page.get_date() or extractor.get_date() self.type_ = self.get_document_type()", "import settings from modules.utils import make_unicode, last_index from modules.extractors.documentBase import", "\"\"\" text = \"\" header = \"\" date = None", "document rules in settings.py A file can contain one or", "for rule in rule_val: hit = hit or self.parse_rules(rule, header)", "file. \"\"\" def __init__(self, extractor): \"\"\"Create a list of documents,", "settings.py A file can contain one or more document. However,", "i + 1 new_doc = documents.pop(0) for j in range(i,", "to this document. \"\"\" pass def append_text(self, text): \"\"\"Append content", "\"\"\"This module contains classes for documents, and lists of documents.", "---------------- elif rule_key == \"HEADER_CONTAINS\": try: pos = make_unicode(header).find(rule_val.upper()) except", "while i < num_docs: (type_, date) = page_types_and_dates[i] last_match =", "extracted from a file. \"\"\" def __init__(self, extractor): \"\"\"Create a", "self.date = page.get_date() or extractor.get_date() self.type_ = self.get_document_type() self.date =", "None def __init__(self, page, extractor): \"\"\"Create a document stub from", "\"\"\" def __init__(self, extractor): \"\"\"Create a list of documents, using", "{ \"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\" } class DocumentList(object):", "are split up in a large number of files. \"\"\"", "in doc_settings if doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document types that disallow", "See settings.py for syntax\"\"\" rule_key = tuple_[0].upper() rule_val = tuple_[1]", "contain one or more document. However, a document can not", "except UnicodeDecodeError: self.text = make_unicode(self.text) + make_unicode(document.text) def __len__(self): \"\"\"len", "last_index(page_types_and_dates, (type_, date)) if type_ in disallow_infixes and last_match >", "= [] page_types_and_dates = [] \"\"\"Keep track of documents by", "one\"\"\" try: self.text += document.text except UnicodeDecodeError: self.text = make_unicode(self.text)", "self.date = page.get_date() or extractor.get_date() def append_page(self, page): \"\"\"Append content", "== \"OR\": hit = False for rule in rule_val: hit", "Use add_page to keep extending this document. \"\"\" self.text =", "class Document(object): \"\"\"Represents a single document \"\"\" text = \"\"", "on this header text. \"\"\" for document_type in settings.document_rules: if", "Gotlands kommun, where meeting minutes are split up in a", "make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos = -1 return pos > -1", "or extractor.get_date() self.type_ = self.get_document_type() self.date = page.get_date() or extractor.get_date()", "True doc_settings = settings.document_type_settings disallow_infixes = [d for d in", "documents. Documents are defined by the document rules in settings.py", "cases like Gotlands kommun, where meeting minutes are split up", "temp_doc = Document(page, extractor) if (len(documents) > 0 and temp_doc.type_", "ExtractionNotAllowed # merge documents, if disallow_infixes == True doc_settings =", "else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type = temp_doc.type_ last_page_date = temp_doc.date", "doc_settings if doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document types that disallow holes\"\"\"", "text): \"\"\"Append content to this document. \"\"\" self.text += text", "[] page_types_and_dates = [] \"\"\"Keep track of documents by type", "header): \"\"\"Parse document rules. See settings.py for syntax\"\"\" rule_key =", "document_headers = { \"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\" }", "a file. \"\"\" def __init__(self, extractor): \"\"\"Create a list of", "of documents. Documents are defined by the document rules in", "able to merge documents depending on `settings.document_type_settings` \"\"\" # Loop", "from a file. \"\"\" def __init__(self, extractor): \"\"\"Create a list", "type_ = None def __init__(self, page, extractor): \"\"\"Create a document", "a single document \"\"\" text = \"\" header = \"\"", "track of documents by type and date, to be able", "= hit or self.parse_rules(rule, header) return hit elif rule_key ==", "\"\"\" self.text += text def merge_with(self, document): \"\"\"Merge this document", "contains classes for documents, and lists of documents. Documents are", "of files. \"\"\" import settings from modules.utils import make_unicode, last_index", "in cases like Gotlands kommun, where meeting minutes are split", "True] \"\"\"Document types that disallow holes\"\"\" num_docs = len(page_types_and_dates) i", "holes\"\"\" num_docs = len(page_types_and_dates) i = 0 while i <", "= header.upper() # --------- Logical separators -------- if rule_key ==", "documents.pop(0) self._documents.append(doc_to_merge) i += 1 def get_next_document(self): for document in", "in a large number of files. \"\"\" import settings from", "== \"__main__\": print \"This module is only intended to be", "pass def append_text(self, text): \"\"\"Append content to this document. \"\"\"", "Return the first matching document type, based on this header", "settings.document_rules: if self.parse_rules(document_type[1], self.header): return document_type[0] return None def parse_rules(self,", "return hit # -------------- Rules ---------------- elif rule_key == \"HEADER_CONTAINS\":", "the same type and date together last_page_type = None last_page_date", "new_doc = documents.pop(0) for j in range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc)", "= None def __init__(self, page, extractor): \"\"\"Create a document stub", "self.text += text def merge_with(self, document): \"\"\"Merge this document with", "i = 0 while i < num_docs: (type_, date) =", "header text. \"\"\" for document_type in settings.document_rules: if self.parse_rules(document_type[1], self.header):", "for page in extractor.get_next_page(): temp_doc = Document(page, extractor) if (len(documents)", "if __name__ == \"__main__\": print \"This module is only intended", "this header text. \"\"\" for document_type in settings.document_rules: if self.parse_rules(document_type[1],", "def merge_with(self, document): \"\"\"Merge this document with another one\"\"\" try:", "\"\"\"Parse document rules. See settings.py for syntax\"\"\" rule_key = tuple_[0].upper()", "modules.extractors.documentBase import ExtractionNotAllowed document_headers = { \"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\",", "last_page_date = None documents = [] try: for page in", "file can contain one or more document. However, a document", "a list of documents, using `extractor` \"\"\" self._documents = []", "def __init__(self, extractor): \"\"\"Create a list of documents, using `extractor`", "`extractor` \"\"\" self._documents = [] page_types_and_dates = [] \"\"\"Keep track", "pos > -1 if __name__ == \"__main__\": print \"This module", "= \"\" date = None type_ = None def __init__(self,", "for document in self._documents: yield document def __len__(self): \"\"\"len is", "meeting minutes are split up in a large number of", "\"\"\"Represents a single document \"\"\" text = \"\" header =", "or extractor.get_date() def append_page(self, page): \"\"\"Append content from a page", "= make_unicode(self.text) + make_unicode(document.text) def __len__(self): \"\"\"len is the length", "of documents\"\"\" return len(self._documents) class Document(object): \"\"\"Represents a single document", "elif rule_key == \"HEADER_CONTAINS\": try: pos = make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError:", "limitation, obvious in cases like Gotlands kommun, where meeting minutes", "documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type = temp_doc.type_ last_page_date = temp_doc.date except", "last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type = temp_doc.type_ last_page_date", "\"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\" } class DocumentList(object): \"\"\"Contains a list", "documents, using `extractor` \"\"\" self._documents = [] page_types_and_dates = []", "for document_type in settings.document_rules: if self.parse_rules(document_type[1], self.header): return document_type[0] return", "= page.get_header() or extractor.get_header() self.date = page.get_date() or extractor.get_date() self.type_", "This is a limitation, obvious in cases like Gotlands kommun,", "if self.parse_rules(document_type[1], self.header): return document_type[0] return None def parse_rules(self, tuple_,", "\"\"\" self._documents = [] page_types_and_dates = [] \"\"\"Keep track of", "= [] try: for page in extractor.get_next_page(): temp_doc = Document(page,", "self.text = page.get_text() self.header = page.get_header() or extractor.get_header() self.date =", "last_index from modules.extractors.documentBase import ExtractionNotAllowed document_headers = { \"Content-Type\": \"text/plain\",", "is True] \"\"\"Document types that disallow holes\"\"\" num_docs = len(page_types_and_dates)", "= tuple_[0].upper() rule_val = tuple_[1] header = header.upper() # ---------", "UnicodeDecodeError: pos = -1 return pos > -1 if __name__", "documents, and lists of documents. Documents are defined by the", "more than one file. This is a limitation, obvious in", "self.parse_rules(rule, header) return hit elif rule_key == \"OR\": hit =", "is the number of documents\"\"\" return len(self._documents) class Document(object): \"\"\"Represents", "if doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document types that disallow holes\"\"\" num_docs", "to be able to merge documents depending on `settings.document_type_settings` \"\"\"", "date)) if type_ in disallow_infixes and last_match > i: num_docs_to_merge", "and temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type", "get_document_type(self): \"\"\" Return the first matching document type, based on", "document. \"\"\" self.text += text def merge_with(self, document): \"\"\"Merge this", "document type, based on this header text. \"\"\" for document_type", "range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i += num_docs_to_merge else: doc_to_merge =", "hit = not self.parse_rules(rule_val, header) return hit # -------------- Rules", "= documents.pop(0) for j in range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i", "Rules ---------------- elif rule_key == \"HEADER_CONTAINS\": try: pos = make_unicode(header).find(rule_val.upper())", "in rule_val: hit = hit and self.parse_rules(rule, header) return hit", "\"\"\" self.text = page.get_text() self.header = page.get_header() or extractor.get_header() self.date", "temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type =", "-*- \"\"\"This module contains classes for documents, and lists of", "yield document def __len__(self): \"\"\"len is the number of documents\"\"\"", "a page. Use add_page to keep extending this document. \"\"\"", "of documents, extracted from a file. \"\"\" def __init__(self, extractor):", "date, to be able to merge documents depending on `settings.document_type_settings`", "return len(self.text) def get_document_type(self): \"\"\" Return the first matching document", "= Document(page, extractor) if (len(documents) > 0 and temp_doc.type_ ==", "__len__(self): \"\"\"len is the number of documents\"\"\" return len(self._documents) class", "make_unicode(document.text) def __len__(self): \"\"\"len is the length of the total", "i += 1 def get_next_document(self): for document in self._documents: yield", "modules.utils import make_unicode, last_index from modules.extractors.documentBase import ExtractionNotAllowed document_headers =", "lists of documents. Documents are defined by the document rules", "temp_doc.type_ == last_page_type and temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc)", "< num_docs: (type_, date) = page_types_and_dates[i] last_match = last_index(page_types_and_dates, (type_,", "doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge) i += 1 def get_next_document(self): for", "\"\" date = None type_ = None def __init__(self, page,", "add_page to keep extending this document. \"\"\" self.text = page.get_text()", "+ make_unicode(document.text) def __len__(self): \"\"\"len is the length of the", "= 0 while i < num_docs: (type_, date) = page_types_and_dates[i]", "= page_types_and_dates[i] last_match = last_index(page_types_and_dates, (type_, date)) if type_ in", "= None last_page_date = None documents = [] try: for", "header = \"\" date = None type_ = None def", "def __init__(self, page, extractor): \"\"\"Create a document stub from a", "self._documents: yield document def __len__(self): \"\"\"len is the number of", "# -*- coding: utf-8 -*- \"\"\"This module contains classes for", "last_match - i + 1 new_doc = documents.pop(0) for j", "for syntax\"\"\" rule_key = tuple_[0].upper() rule_val = tuple_[1] header =", "date together last_page_type = None last_page_date = None documents =", "list of documents, extracted from a file. \"\"\" def __init__(self,", "is only intended to be called from other scripts.\" import", "pages, and add pages of the same type and date", "1 new_doc = documents.pop(0) for j in range(i, last_match): new_doc.merge_with(documents.pop(0))", "documents by type and date, to be able to merge", "date = None type_ = None def __init__(self, page, extractor):", "import ExtractionNotAllowed document_headers = { \"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\":", "coding: utf-8 -*- \"\"\"This module contains classes for documents, and", "documents, extracted from a file. \"\"\" def __init__(self, extractor): \"\"\"Create", "> i: num_docs_to_merge = last_match - i + 1 new_doc", "else: doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge) i += 1 def get_next_document(self):", "\"\"\"len is the number of documents\"\"\" return len(self._documents) class Document(object):", "settings.document_type_settings disallow_infixes = [d for d in doc_settings if doc_settings[d][\"disallow_infixes\"]", "= self.get_document_type() self.date = page.get_date() or extractor.get_date() def append_page(self, page):", "pages of the same type and date together last_page_type =", "rule_val: hit = hit and self.parse_rules(rule, header) return hit elif", "def __len__(self): \"\"\"len is the number of documents\"\"\" return len(self._documents)", "document in self._documents: yield document def __len__(self): \"\"\"len is the", "from modules.extractors.documentBase import ExtractionNotAllowed document_headers = { \"Content-Type\": \"text/plain\", \"Content-Disposition\":", "temp_doc.date except ExtractionNotAllowed: raise ExtractionNotAllowed # merge documents, if disallow_infixes", "syntax\"\"\" rule_key = tuple_[0].upper() rule_val = tuple_[1] header = header.upper()", "append_text(self, text): \"\"\"Append content to this document. \"\"\" self.text +=", "__len__(self): \"\"\"len is the length of the total plaintext\"\"\" return", "document_type in settings.document_rules: if self.parse_rules(document_type[1], self.header): return document_type[0] return None", "= False for rule in rule_val: hit = hit or", "document): \"\"\"Merge this document with another one\"\"\" try: self.text +=", "files. \"\"\" import settings from modules.utils import make_unicode, last_index from", "= -1 return pos > -1 if __name__ == \"__main__\":", "\"NOT\": hit = not self.parse_rules(rule_val, header) return hit # --------------", "where meeting minutes are split up in a large number", "header.upper() # --------- Logical separators -------- if rule_key == \"AND\":", "than one file. This is a limitation, obvious in cases", "except ExtractionNotAllowed: raise ExtractionNotAllowed # merge documents, if disallow_infixes ==", "from a page. Use add_page to keep extending this document.", "= tuple_[1] header = header.upper() # --------- Logical separators --------", "= not self.parse_rules(rule_val, header) return hit # -------------- Rules ----------------", "num_docs_to_merge else: doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge) i += 1 def", "i: num_docs_to_merge = last_match - i + 1 new_doc =", "except UnicodeDecodeError: pos = -1 return pos > -1 if", "-*- coding: utf-8 -*- \"\"\"This module contains classes for documents,", "self.get_document_type() self.date = page.get_date() or extractor.get_date() def append_page(self, page): \"\"\"Append", "types that disallow holes\"\"\" num_docs = len(page_types_and_dates) i = 0", "depending on `settings.document_type_settings` \"\"\" # Loop through pages, and add", "obvious in cases like Gotlands kommun, where meeting minutes are", "(len(documents) > 0 and temp_doc.type_ == last_page_type and temp_doc.date ==", "0 while i < num_docs: (type_, date) = page_types_and_dates[i] last_match", "0 and temp_doc.type_ == last_page_type and temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc)", "extractor.get_date() def append_page(self, page): \"\"\"Append content from a page to", "temp_doc.type_ last_page_date = temp_doc.date except ExtractionNotAllowed: raise ExtractionNotAllowed # merge", "-1 return pos > -1 if __name__ == \"__main__\": print", "= settings.document_type_settings disallow_infixes = [d for d in doc_settings if", "# -------------- Rules ---------------- elif rule_key == \"HEADER_CONTAINS\": try: pos", "tuple_[1] header = header.upper() # --------- Logical separators -------- if", "self._documents.append(doc_to_merge) i += 1 def get_next_document(self): for document in self._documents:", "A file can contain one or more document. However, a", "__init__(self, extractor): \"\"\"Create a list of documents, using `extractor` \"\"\"", "settings from modules.utils import make_unicode, last_index from modules.extractors.documentBase import ExtractionNotAllowed", "rule in rule_val: hit = hit and self.parse_rules(rule, header) return", "and self.parse_rules(rule, header) return hit elif rule_key == \"OR\": hit", "and lists of documents. Documents are defined by the document", "= temp_doc.type_ last_page_date = temp_doc.date except ExtractionNotAllowed: raise ExtractionNotAllowed #", "or more document. However, a document can not be constructed", "- i + 1 new_doc = documents.pop(0) for j in", "\"\"\" # Loop through pages, and add pages of the", "return hit elif rule_key == \"OR\": hit = False for", "large number of files. \"\"\" import settings from modules.utils import", "last_page_type and temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date))", "matching document type, based on this header text. \"\"\" for", "list of documents, using `extractor` \"\"\" self._documents = [] page_types_and_dates", "= { \"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\" } class", "first matching document type, based on this header text. \"\"\"", "+= text def merge_with(self, document): \"\"\"Merge this document with another", "content to this document. \"\"\" self.text += text def merge_with(self,", "and date, to be able to merge documents depending on", "type and date, to be able to merge documents depending", "a page to this document. \"\"\" pass def append_text(self, text):", "hit = False for rule in rule_val: hit = hit", "num_docs_to_merge = last_match - i + 1 new_doc = documents.pop(0)", "make_unicode(self.text) + make_unicode(document.text) def __len__(self): \"\"\"len is the length of", "get_next_document(self): for document in self._documents: yield document def __len__(self): \"\"\"len", "text def merge_with(self, document): \"\"\"Merge this document with another one\"\"\"", "type_ in disallow_infixes and last_match > i: num_docs_to_merge = last_match", "extractor.get_date() self.type_ = self.get_document_type() self.date = page.get_date() or extractor.get_date() def", "hit = hit or self.parse_rules(rule, header) return hit elif rule_key", "total plaintext\"\"\" return len(self.text) def get_document_type(self): \"\"\" Return the first", "= len(page_types_and_dates) i = 0 while i < num_docs: (type_,", "documents = [] try: for page in extractor.get_next_page(): temp_doc =", "for documents, and lists of documents. Documents are defined by", "Document(object): \"\"\"Represents a single document \"\"\" text = \"\" header", "elif rule_key == \"NOT\": hit = not self.parse_rules(rule_val, header) return", "raise ExtractionNotAllowed # merge documents, if disallow_infixes == True doc_settings", "1 def get_next_document(self): for document in self._documents: yield document def", "= True for rule in rule_val: hit = hit and", "import make_unicode, last_index from modules.extractors.documentBase import ExtractionNotAllowed document_headers = {", "and date together last_page_type = None last_page_date = None documents", "\"HEADER_CONTAINS\": try: pos = make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos = -1", "[] try: for page in extractor.get_next_page(): temp_doc = Document(page, extractor)", "} class DocumentList(object): \"\"\"Contains a list of documents, extracted from", "-------------- Rules ---------------- elif rule_key == \"HEADER_CONTAINS\": try: pos =", "\"\"\"Keep track of documents by type and date, to be", "document. However, a document can not be constructed from more", "in extractor.get_next_page(): temp_doc = Document(page, extractor) if (len(documents) > 0", "num_docs = len(page_types_and_dates) i = 0 while i < num_docs:", "== \"HEADER_CONTAINS\": try: pos = make_unicode(header).find(rule_val.upper()) except UnicodeDecodeError: pos =", "[d for d in doc_settings if doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document", "However, a document can not be constructed from more than", "document. \"\"\" pass def append_text(self, text): \"\"\"Append content to this", "= [d for d in doc_settings if doc_settings[d][\"disallow_infixes\"] is True]", "module contains classes for documents, and lists of documents. Documents", "temp_doc.date)) last_page_type = temp_doc.type_ last_page_date = temp_doc.date except ExtractionNotAllowed: raise", "number of documents\"\"\" return len(self._documents) class Document(object): \"\"\"Represents a single", "\"\"\" for document_type in settings.document_rules: if self.parse_rules(document_type[1], self.header): return document_type[0]", "documents, if disallow_infixes == True doc_settings = settings.document_type_settings disallow_infixes =", "of documents by type and date, to be able to", "ExtractionNotAllowed: raise ExtractionNotAllowed # merge documents, if disallow_infixes == True", "make_unicode, last_index from modules.extractors.documentBase import ExtractionNotAllowed document_headers = { \"Content-Type\":", "in range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i += num_docs_to_merge else: doc_to_merge", "the total plaintext\"\"\" return len(self.text) def get_document_type(self): \"\"\" Return the", "j in range(i, last_match): new_doc.merge_with(documents.pop(0)) self._documents.append(new_doc) i += num_docs_to_merge else:", "ExtractionNotAllowed document_headers = { \"Content-Type\": \"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\"", "with another one\"\"\" try: self.text += document.text except UnicodeDecodeError: self.text", "self._documents = [] page_types_and_dates = [] \"\"\"Keep track of documents", "return hit elif rule_key == \"NOT\": hit = not self.parse_rules(rule_val,", "type, based on this header text. \"\"\" for document_type in", "tuple_[0].upper() rule_val = tuple_[1] header = header.upper() # --------- Logical", "kommun, where meeting minutes are split up in a large", "# Loop through pages, and add pages of the same", "+= num_docs_to_merge else: doc_to_merge = documents.pop(0) self._documents.append(doc_to_merge) i += 1", "of the total plaintext\"\"\" return len(self.text) def get_document_type(self): \"\"\" Return", "Documents are defined by the document rules in settings.py A", "intended to be called from other scripts.\" import sys sys.exit()", "plaintext\"\"\" return len(self.text) def get_document_type(self): \"\"\" Return the first matching", "together last_page_type = None last_page_date = None documents = []", "False for rule in rule_val: hit = hit or self.parse_rules(rule,", "number of files. \"\"\" import settings from modules.utils import make_unicode,", "== \"NOT\": hit = not self.parse_rules(rule_val, header) return hit #", "merge documents depending on `settings.document_type_settings` \"\"\" # Loop through pages,", "page. Use add_page to keep extending this document. \"\"\" self.text", "= temp_doc.date except ExtractionNotAllowed: raise ExtractionNotAllowed # merge documents, if", "# --------- Logical separators -------- if rule_key == \"AND\": hit", "def append_text(self, text): \"\"\"Append content to this document. \"\"\" self.text", "file. This is a limitation, obvious in cases like Gotlands", "to keep extending this document. \"\"\" self.text = page.get_text() self.header", "= None documents = [] try: for page in extractor.get_next_page():", "page.get_header() or extractor.get_header() self.date = page.get_date() or extractor.get_date() self.type_ =", "utf-8 -*- \"\"\"This module contains classes for documents, and lists", "last_page_type = None last_page_date = None documents = [] try:", "and add pages of the same type and date together", "hit = True for rule in rule_val: hit = hit", "documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type = temp_doc.type_ last_page_date =", "from modules.utils import make_unicode, last_index from modules.extractors.documentBase import ExtractionNotAllowed document_headers", "by the document rules in settings.py A file can contain", "up in a large number of files. \"\"\" import settings", "def append_page(self, page): \"\"\"Append content from a page to this", "a large number of files. \"\"\" import settings from modules.utils", "merge documents, if disallow_infixes == True doc_settings = settings.document_type_settings disallow_infixes", "= last_index(page_types_and_dates, (type_, date)) if type_ in disallow_infixes and last_match", "is the length of the total plaintext\"\"\" return len(self.text) def", "single document \"\"\" text = \"\" header = \"\" date", "another one\"\"\" try: self.text += document.text except UnicodeDecodeError: self.text =", "-1 if __name__ == \"__main__\": print \"This module is only", "None def parse_rules(self, tuple_, header): \"\"\"Parse document rules. See settings.py", "this document. \"\"\" self.text += text def merge_with(self, document): \"\"\"Merge", "self.type_ = self.get_document_type() self.date = page.get_date() or extractor.get_date() def append_page(self,", "rules. See settings.py for syntax\"\"\" rule_key = tuple_[0].upper() rule_val =", "classes for documents, and lists of documents. Documents are defined", "rule in rule_val: hit = hit or self.parse_rules(rule, header) return", "and temp_doc.type_ == last_page_type and temp_doc.date == last_page_date): documents[-1].merge_with(temp_doc) else:", "hit = hit and self.parse_rules(rule, header) return hit elif rule_key", "self.text = make_unicode(self.text) + make_unicode(document.text) def __len__(self): \"\"\"len is the", "Logical separators -------- if rule_key == \"AND\": hit = True", "content from a page to this document. \"\"\" pass def", "are defined by the document rules in settings.py A file", "a list of documents, extracted from a file. \"\"\" def", "return document_type[0] return None def parse_rules(self, tuple_, header): \"\"\"Parse document", "None type_ = None def __init__(self, page, extractor): \"\"\"Create a", "minutes are split up in a large number of files.", "for d in doc_settings if doc_settings[d][\"disallow_infixes\"] is True] \"\"\"Document types", "parse_rules(self, tuple_, header): \"\"\"Parse document rules. See settings.py for syntax\"\"\"", "be able to merge documents depending on `settings.document_type_settings` \"\"\" #", "self.header): return document_type[0] return None def parse_rules(self, tuple_, header): \"\"\"Parse", "__name__ == \"__main__\": print \"This module is only intended to", "\"\"\" Return the first matching document type, based on this", "header) return hit elif rule_key == \"NOT\": hit = not", "and last_match > i: num_docs_to_merge = last_match - i +", "add pages of the same type and date together last_page_type", "len(self.text) def get_document_type(self): \"\"\" Return the first matching document type,", "text. \"\"\" for document_type in settings.document_rules: if self.parse_rules(document_type[1], self.header): return", "can not be constructed from more than one file. This", "== last_page_date): documents[-1].merge_with(temp_doc) else: documents.append(temp_doc) page_types_and_dates.append((temp_doc.type_, temp_doc.date)) last_page_type = temp_doc.type_", "> -1 if __name__ == \"__main__\": print \"This module is", "date) = page_types_and_dates[i] last_match = last_index(page_types_and_dates, (type_, date)) if type_", "document def __len__(self): \"\"\"len is the number of documents\"\"\" return", "\"This module is only intended to be called from other", "\"text/plain\", \"Content-Disposition\": \"attachment\", \"Cache-Control\": \"public\" } class DocumentList(object): \"\"\"Contains a", "if disallow_infixes == True doc_settings = settings.document_type_settings disallow_infixes = [d", "in self._documents: yield document def __len__(self): \"\"\"len is the number", "\"Cache-Control\": \"public\" } class DocumentList(object): \"\"\"Contains a list of documents," ]
[ "import sys import tempfile import uuid import mgm_utils def main():", "import shutil import subprocess import sys import tempfile import uuid", "import tempfile import uuid import mgm_utils def main(): (root_dir, input_file,", "import subprocess import sys import tempfile import uuid import mgm_utils", "sif = mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r = subprocess.run([\"singularity\", \"run\", sif,", "json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file) exit(r.returncode) if __name__", "shutil import subprocess import sys import tempfile import uuid import", "= subprocess.run([\"singularity\", \"run\", sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file):", "\"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif", "= f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif = mgm_utils.get_sif_dir(root_dir)", "\"/ina_segmentation.sif\" r = subprocess.run([\"singularity\", \"run\", sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file)", "f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif = mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r =", "subprocess import sys import tempfile import uuid import mgm_utils def", "uuid import mgm_utils def main(): (root_dir, input_file, json_file) = sys.argv[1:4]", "temp_output_file]) shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file) exit(r.returncode)", "= \"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file)", "r = subprocess.run([\"singularity\", \"run\", sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file) if", "sys.argv[1:4] tmpName = str(uuid.uuid4()) tmpdir = \"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\"", "f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif = mgm_utils.get_sif_dir(root_dir) +", "shutil.copy(input_file, temp_input_file) sif = mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r = subprocess.run([\"singularity\",", "os import os.path import shutil import subprocess import sys import", "tempfile import uuid import mgm_utils def main(): (root_dir, input_file, json_file)", "os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file) exit(r.returncode) if __name__ == \"__main__\":", "os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file) exit(r.returncode) if __name__ == \"__main__\": main()", "sys import tempfile import uuid import mgm_utils def main(): (root_dir,", "import uuid import mgm_utils def main(): (root_dir, input_file, json_file) =", "import os import os.path import shutil import subprocess import sys", "= f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif = mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r", "temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif = mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\"", "= mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r = subprocess.run([\"singularity\", \"run\", sif, temp_input_file,", "subprocess.run([\"singularity\", \"run\", sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file)", "temp_input_file) sif = mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r = subprocess.run([\"singularity\", \"run\",", "sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file):", "shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file) exit(r.returncode) if", "(root_dir, input_file, json_file) = sys.argv[1:4] tmpName = str(uuid.uuid4()) tmpdir =", "str(uuid.uuid4()) tmpdir = \"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\"", "input_file, json_file) = sys.argv[1:4] tmpName = str(uuid.uuid4()) tmpdir = \"/tmp\"", "= str(uuid.uuid4()) tmpdir = \"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file =", "tmpName = str(uuid.uuid4()) tmpdir = \"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file", "mgm_utils def main(): (root_dir, input_file, json_file) = sys.argv[1:4] tmpName =", "tmpdir = \"/tmp\" temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file,", "+ \"/ina_segmentation.sif\" r = subprocess.run([\"singularity\", \"run\", sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file,", "python3 import os import os.path import shutil import subprocess import", "main(): (root_dir, input_file, json_file) = sys.argv[1:4] tmpName = str(uuid.uuid4()) tmpdir", "import mgm_utils def main(): (root_dir, input_file, json_file) = sys.argv[1:4] tmpName", "if os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file) exit(r.returncode) if __name__ ==", "json_file) = sys.argv[1:4] tmpName = str(uuid.uuid4()) tmpdir = \"/tmp\" temp_input_file", "def main(): (root_dir, input_file, json_file) = sys.argv[1:4] tmpName = str(uuid.uuid4())", "temp_input_file = f\"{tmpdir}/{tmpName}.dat\" temp_output_file = f\"{tmpdir}/{tmpName}.json\" shutil.copy(input_file, temp_input_file) sif =", "os.path import shutil import subprocess import sys import tempfile import", "= sys.argv[1:4] tmpName = str(uuid.uuid4()) tmpdir = \"/tmp\" temp_input_file =", "import os.path import shutil import subprocess import sys import tempfile", "\"run\", sif, temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file) if", "#!/usr/bin/env python3 import os import os.path import shutil import subprocess", "mgm_utils.get_sif_dir(root_dir) + \"/ina_segmentation.sif\" r = subprocess.run([\"singularity\", \"run\", sif, temp_input_file, temp_output_file])", "temp_input_file, temp_output_file]) shutil.copy(temp_output_file, json_file) if os.path.exists(temp_input_file): os.remove(temp_input_file) if os.path.exists(temp_output_file): os.remove(temp_output_file)" ]
[ "django import forms from django.db import models class XMLFileField(models.FileField): def", "super(XMLFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(XMLFileField,", "forms from django.db import models class XMLFileField(models.FileField): def __init__(self, *args,", "**kwargs) def clean(self, *args, **kwargs): data = super(XMLFileField, self).clean(*args, **kwargs)", "doc = etree.parse(fh) with open(self.schema) as fh: schema = etree.XMLSchema(etree.parse(fh))", "not schema.validate(doc): raise forms.ValidationError('The XML file failed to validate '", "data as fh: doc = etree.parse(fh) with open(self.schema) as fh:", "etree.parse(fh) with open(self.schema) as fh: schema = etree.XMLSchema(etree.parse(fh)) if not", "<filename>csat/django/fields.py<gh_stars>0 from lxml import etree from django import forms from", "with open(self.schema) as fh: schema = etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc):", "raise forms.ValidationError('The XML file failed to validate ' 'against the", "= etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise forms.ValidationError('The XML file failed", "def clean(self, *args, **kwargs): data = super(XMLFileField, self).clean(*args, **kwargs) with", "*args, **kwargs): self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def clean(self,", "XML file failed to validate ' 'against the supplied schema.')", "XMLFileField(models.FileField): def __init__(self, *args, **kwargs): self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args,", "as fh: doc = etree.parse(fh) with open(self.schema) as fh: schema", "__init__(self, *args, **kwargs): self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def", "self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(XMLFileField, self).clean(*args,", "**kwargs): data = super(XMLFileField, self).clean(*args, **kwargs) with data as fh:", "*args, **kwargs): data = super(XMLFileField, self).clean(*args, **kwargs) with data as", "with data as fh: doc = etree.parse(fh) with open(self.schema) as", "class XMLFileField(models.FileField): def __init__(self, *args, **kwargs): self.schema = kwargs.pop('schema') super(XMLFileField,", "clean(self, *args, **kwargs): data = super(XMLFileField, self).clean(*args, **kwargs) with data", "schema = etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise forms.ValidationError('The XML file", "def __init__(self, *args, **kwargs): self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs)", "fh: doc = etree.parse(fh) with open(self.schema) as fh: schema =", "open(self.schema) as fh: schema = etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise", "= etree.parse(fh) with open(self.schema) as fh: schema = etree.XMLSchema(etree.parse(fh)) if", "fh: schema = etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise forms.ValidationError('The XML", "**kwargs) with data as fh: doc = etree.parse(fh) with open(self.schema)", "schema.validate(doc): raise forms.ValidationError('The XML file failed to validate ' 'against", "from lxml import etree from django import forms from django.db", "from django import forms from django.db import models class XMLFileField(models.FileField):", "from django.db import models class XMLFileField(models.FileField): def __init__(self, *args, **kwargs):", "= kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data", "data = super(XMLFileField, self).clean(*args, **kwargs) with data as fh: doc", "failed to validate ' 'against the supplied schema.') return data", "self).clean(*args, **kwargs) with data as fh: doc = etree.parse(fh) with", "etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise forms.ValidationError('The XML file failed to", "import etree from django import forms from django.db import models", "forms.ValidationError('The XML file failed to validate ' 'against the supplied", "= super(XMLFileField, self).clean(*args, **kwargs) with data as fh: doc =", "super(XMLFileField, self).clean(*args, **kwargs) with data as fh: doc = etree.parse(fh)", "if not schema.validate(doc): raise forms.ValidationError('The XML file failed to validate", "file failed to validate ' 'against the supplied schema.') return", "**kwargs): self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def clean(self, *args,", "import forms from django.db import models class XMLFileField(models.FileField): def __init__(self,", "kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data =", "as fh: schema = etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise forms.ValidationError('The", "lxml import etree from django import forms from django.db import", "models class XMLFileField(models.FileField): def __init__(self, *args, **kwargs): self.schema = kwargs.pop('schema')", "django.db import models class XMLFileField(models.FileField): def __init__(self, *args, **kwargs): self.schema", "etree from django import forms from django.db import models class", "import models class XMLFileField(models.FileField): def __init__(self, *args, **kwargs): self.schema =", "self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs):" ]
[ "upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> upsample_merge inputs: {[ii.shape", "= conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"short_\") deep =", "- 1] # -> [3, 5] anchor_scale = (1 if", "for ii in out_features] model = keras.models.Model(inputs, nn, name=model_name) return", "width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80,", "p3: [64, 64, 256], p4: [32, 32, 512], p5: [16,", "odd input_shape inputs = tf.pad(inputs, [[0, 0], [0, 1], [0,", "use_depthwise_conv, activation=activation, name=name + \"down_\") nn = tf.concat(inputs, axis=-1) nn", "in features]) / 256` for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\",", "**kwargs) def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\",", "[0, 1], [0, 0]]) patch_top_left = inputs[:, :-1:2, :-1:2] patch_top_right", "use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn = inputs if use_depthwise_conv: nn =", "name=name + \"object_out_\") obj_out = keras.layers.Reshape([-1, 1], name=name + \"object_out_reshape\")(obj_out)", "= features # p3: [64, 64, 256], p4: [32, 32,", "1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5,", "features = [nn] \"\"\" dark blocks \"\"\" depthes = [base_depth,", "backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\" means 1 if use_anchor_free_mode", "def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> upsample_merge inputs:", "+ 1) nn = conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation,", "for ii in pool_sizes] nn = tf.concat([nn, *pp], axis=-1) nn", "\"2_\") if use_shortcut: nn = keras.layers.Add()([inputs, nn]) return nn def", "name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels * expansion),", "activation=activation, name=\"stem_\") features = [nn] \"\"\" dark blocks \"\"\" depthes", "= CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\") features =", "3, 2, use_depthwise_conv, activation=activation, name=name + \"down_\") nn = tf.concat(inputs,", "+ \"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "+ 1) deep = csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name)", "[features[id] for id in features_pick] print(\">>>> features:\", {ii.name: ii.output_shape for", "= backbone.outputs else: if isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name) for", "p5 ─> fpn_out0 ───────────> pan_out0 # ↓ ↑ # p4", "num_anchors=\"auto\", # \"auto\" means 1 if use_anchor_free_mode else 9 use_object_scores=\"auto\",", "= inputs[:, :-1:2, :-1:2] patch_top_right = inputs[:, :-1:2, 1::2] patch_bottom_left", "p3 ───────────> pan_out2 ──────┘ csp_depth = max(round(depth_mul * 3), 1)", "\"reg_2_\") reg_out = keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name + \"regression_out\")(reg_nn)", "upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p3_\") # pan_out1:", "f_out0 ─> fpn_out1 ─> pan_out1 # ↓ ↑ # p3", "means: `min([ii.shape[-1] for ii in features]) / 256` for custom", "target_channel = inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name +", "activation=activation, name=block_name) out = tf.concat([deep, short], axis=-1) out = conv_dw_pw_block(out,", "= activation_by_name(cls_out, \"sigmoid\", name=name + \"class_out_\") cls_out = keras.layers.Reshape([-1, num_classes],", "fpn_out0: [16, 16, 512], f_out0: [32, 32, 512] fpn_out0, f_out0", "axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"):", "= depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation,", "**kwargs) def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\",", "conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"2_\") if", "out_channels, kernel_size=1, activation=activation, name=name + \"output_\") return out def spatial_pyramid_pooling(inputs,", "conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp: nn", "8, base_channels * 16] use_spps = [False, False, False, True]", "kernel_size, strides = 1, 1 nn = conv2d_no_bias(nn, filters, kernel_size,", "= keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained) # AA", "if use_object_scores == \"auto\" else use_object_scores num_anchors = (1 if", "use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels = inputs.shape[-1] if out_channels == -1", "num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\") outputs = keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs)", "{\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\":", "↑ # p4 ─> f_out0 ─> fpn_out1 ─> pan_out1 #", "interpolation=\"nearest\", name=name + \"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn", "YOLOXHead \"\"\" def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\",", "**kwargs) def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\",", "padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return", "inputs[:, :-1:2, :-1:2] patch_top_right = inputs[:, :-1:2, 1::2] patch_bottom_left =", "patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides,", "False] for id, (channel, depth, use_spp, use_shortcut) in enumerate(zip(channels, depthes,", "name=name + \"class_out_\") cls_out = keras.layers.Reshape([-1, num_classes], name=name + \"class_out_reshape\")(cls_out)", "patch_top_right, patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation,", "inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right =", "4 rescale_mode=\"raw\", # For decode predictions, raw means input value", "\"same\": # Handling odd input_shape inputs = tf.pad(inputs, [[0, 0],", "pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model def", "(channel, depth, use_spp, use_shortcut) in enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name", "return fpn_out, nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): #", "width_mul) if freeze_backbone: backbone.trainable = False else: backbone.trainable = True", "width_mul) outputs = [] for id, input in enumerate(inputs): cur_name", "inputs[:, fc00:db20:35b:7399::5, 1::2] else: patch_top_left = inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right", "fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n3_\") # pan_out0: [16,", "fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name + \"fpn_\") # inputs[0]", "nn = keras.layers.Add()([inputs, nn]) return nn def csp_stack(inputs, depth, out_channels=-1,", "name=name + \"regression_out_reshape\")(reg_out) # obj_preds if use_object_scores: obj_out = keras.layers.Conv2D(1", "= inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation, name=name", "= max(round(depth_mul * 3), 1) p3, p4, p5 = features", "1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5,", "activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models import model_surgery", "backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"),", "ii.output_shape for ii in features}) features = [ii.output for ii", "prediction. \"auto\" means 1 if use_anchor_free_mode else 4 rescale_mode=\"raw\", #", "use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): out_channel = int(256 * width_mul) outputs", "───────────> pan_out0 # ↓ ↑ # p4 ─> f_out0 ─>", "use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01) /", "anchors for model prediction. anchor_scale=\"auto\", # Init anchors for model", "max(round(depth_mul * 3), 1) p3, p4, p5 = features #", "activation=\"swish\", model_name=\"\"): base_channels, base_depth = int(width_mul * 64), max(round(depth_mul *", "pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def", "[0, 0]]) patch_top_left = inputs[:, :-1:2, :-1:2] patch_top_right = inputs[:,", "return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416,", "\"\"\" YOLOX models \"\"\" def YOLOX( backbone=None, features_pick=[-3, -2, -1],", "depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False,", "\"block{}_\".format(id + 1) deep = csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation,", "16, 512], f_out0: [32, 32, 512] fpn_out0, f_out0 = upsample_merge([p5,", "model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None,", "target_channel, activation=activation, name=name + \"fpn_\") # inputs[0] = keras.layers.UpSampling2D(size=(2, 2),", "= }\") target_channel = inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation,", "name=name + \"1_\") nn = conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv,", "+ \"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for ii in", "# cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation,", "p4: [32, 32, 512], p5: [16, 16, 1024] # fpn_out0:", "9 use_object_scores=\"auto\", # \"auto\" means same with use_anchor_free_mode input_shape=(640, 640,", "activation=activation, name=\"pafpn_\") outputs = yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores,", "> 0 else 1 backbone = CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv,", "features] width_mul = width_mul if width_mul > 0 else min([ii.shape[-1]", ") from keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights from", "{\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\"", "\"\"\" YOLOXHead \"\"\" def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True,", "nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn,", "3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.67,", "inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] nn =", "use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels", "else 1 backbone = CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation,", "fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs = yolox_head(fpn_features,", "# stem stem = conv_dw_pw_block(inputs, out_channels, activation=activation, name=name + \"stem_\")", "\"regression_out_reshape\")(reg_out) # obj_preds if use_object_scores: obj_out = keras.layers.Conv2D(1 * num_anchors,", "num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.33, width_mul=1.25, model_name=kwargs.pop(\"model_name\",", "yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): out_channel =", "256], p4: [32, 32, 512], p5: [16, 16, 1024] #", "+ \"deep_\") for id in range(depth): block_name = name +", "# fpn_out0: [16, 16, 512], f_out0: [32, 32, 512] fpn_out0,", "/ 256` for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\"", "fpn_out0 ───────────> pan_out0 # ↓ ↑ # p4 ─> f_out0", "activation=\"swish\", name=\"\"): # print(f\">>>> upsample_merge inputs: {[ii.shape for ii in", "== -1 else out_channels hidden_channels = int(out_channels * expansion) short", "backbone.trainable = False else: backbone.trainable = True inputs = backbone.inputs[0]", "\"\"\" def YOLOX( backbone=None, features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1, #", "width_mul:\", width_mul) if freeze_backbone: backbone.trainable = False else: backbone.trainable =", "use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\") outputs = keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model", "1024] pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "= inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] nn", "# obj_preds if use_object_scores: obj_out = keras.layers.Conv2D(1 * num_anchors, kernel_size=1,", "activation=\"swish\", name=\"\"): out_channels = inputs.shape[-1] if out_channels == -1 else", "width_mul = width_mul if width_mul > 0 else 1 backbone", "+ \"{}_\".format(id + 1) out = yolox_head_single(input, out_channel, num_classes, num_anchors,", "13), activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels", "ii in pool_sizes] nn = tf.concat([nn, *pp], axis=-1) nn =", "features_pick] print(\">>>> features:\", {ii.name: ii.output_shape for ii in features}) features", "out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation=\"swish\", name=\"\"): input_channels =", "keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from", "= csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out = tf.concat([deep,", "from tensorflow import keras from keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation,", "activation=activation, name=name + \"cls_2_\") cls_out = keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1,", "-1], use_depthwise_conv=False, input_shape=(512, 512, 3), activation=\"swish\", model_name=\"\"): base_channels, base_depth =", "3), activation=\"swish\", model_name=\"\"): base_channels, base_depth = int(width_mul * 64), max(round(depth_mul", "= inputs[:, fc00:db20:35b:7399::5, 1::2] nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right],", "for layer_name in features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone) features =", "pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs)", "= name + \"{}_\".format(id + 1) out = yolox_head_single(input, out_channel,", "rescale_mode=rescale_mode, post_process=post_process) return model def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80,", "if width_mul > 0 else 1 backbone = CSPDarknet(width_mul, depth_mul,", "= upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p4_\") #", "activation=\"swish\", name=\"\"): if padding.lower() == \"same\": # Handling odd input_shape", "= [base_channels * 2, base_channels * 4, base_channels * 8,", "= keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name + \"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out,", "kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM,", "out_channel = int(256 * width_mul) outputs = [] for id,", "use_object_scores=True, activation=\"swish\", name=\"\"): out_channel = int(256 * width_mul) outputs =", "= True inputs = backbone.inputs[0] use_object_scores = use_anchor_free_mode if use_object_scores", "tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv,", "in pool_sizes] nn = tf.concat([nn, *pp], axis=-1) nn = conv_dw_pw_block(nn,", "= conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp:", "padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name +", "name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\")", "def focus_stem(inputs, filters, kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\", name=\"\"): if padding.lower()", "if isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name) for layer_name in features_pick]", "───────────> pan_out2 ──────┘ csp_depth = max(round(depth_mul * 3), 1) p3,", "(1 if use_anchor_free_mode else 4) if anchor_scale == \"auto\" else", "\"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\",", "= backbone.inputs[0] use_object_scores = use_anchor_free_mode if use_object_scores == \"auto\" else", "\"output_\") return out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation=\"swish\", name=\"\"):", "16] use_spps = [False, False, False, True] use_shortcuts = [True,", "activation=activation, name=name + \"c3n4_\") return [pan_out2, pan_out1, pan_out0] \"\"\" YOLOXHead", "= tf.concat([deep, short], axis=-1) out = conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation,", "num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): out_channel = int(256 *", "↓ ↑ # p3 ───────────> pan_out2 ──────┘ csp_depth = max(round(depth_mul", "512], p5: [16, 16, 1024] # fpn_out0: [16, 16, 512],", "- 0.01) / 0.01).numpy()) # stem stem = conv_dw_pw_block(inputs, out_channels,", "outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in outputs], axis=1) outputs", "parameter ): if backbone is None: width_mul = width_mul if", "DecodePredictions PRETRAINED_DICT = { \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"},", "features = model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for id in features_pick]", "base_channels * 8, base_channels * 16] use_spps = [False, False,", "= use_anchor_free_mode if use_object_scores == \"auto\" else use_object_scores num_anchors =", "obj_out], axis=-1) else: return tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0,", "csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation, name=name) return nn", "{\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet backbone \"\"\"", "= model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for id in features_pick] print(\">>>>", "\"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn = tf.concat(inputs, axis=-1)", "\"\"\" def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> upsample_merge", "64, 256], p4: [32, 32, 512], p5: [16, 16, 1024]", "return nn def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels", "width_mul = width_mul if width_mul > 0 else min([ii.shape[-1] for", "else min([ii.shape[-1] for ii in features]) / 256 print(\">>>> width_mul:\",", "= csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn =", "nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, nn.shape[-1], 0.5,", "pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, # Init anchors for model prediction. anchor_scale=\"auto\",", "num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): out_channel = int(256 * width_mul)", "True inputs = backbone.inputs[0] use_object_scores = use_anchor_free_mode if use_object_scores ==", "pan_out2 ──────┘ csp_depth = max(round(depth_mul * 3), 1) p3, p4,", "features # p3: [64, 64, 256], p4: [32, 32, 512],", "def YOLOX( backbone=None, features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1, # -1", "ii in features]) / 256 print(\">>>> width_mul:\", width_mul) if freeze_backbone:", "nn = conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1, activation=activation, name=name +", "= tf.pad(inputs, [[0, 0], [0, 1], [0, 1], [0, 0]])", "# ↓ ↑ # p4 ─> f_out0 ─> fpn_out1 ─>", "use_spps, use_shortcuts)): stack_name = \"stack{}_\".format(id + 1) nn = conv_dw_pw_block(nn,", "0]]) patch_top_left = inputs[:, :-1:2, :-1:2] patch_top_right = inputs[:, :-1:2,", "activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels //", "ii in features] width_mul = width_mul if width_mul > 0", "in features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for", "reg_preds reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "return model \"\"\" path aggregation fpn \"\"\" def upsample_merge(inputs, csp_depth,", "p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p4_\") # fpn_out1: [32,", "csp_stack(nn, csp_depth, target_channel, 0.5, False, use_depthwise_conv, activation=activation, name=name) return fpn_out,", "kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"2_\") if use_shortcut: nn", "input_channels // 2, kernel_size=1, activation=activation, name=name + \"1_\") pp =", "base_depth * 3, base_depth * 3, base_depth] channels = [base_channels", "activation_by_name(obj_out, \"sigmoid\", name=name + \"object_out_\") obj_out = keras.layers.Reshape([-1, 1], name=name", "{[ii.shape for ii in inputs] = }\") inputs[0] = conv_dw_pw_block(inputs[0],", "* expansion) short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name +", "keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"object_out\")(reg_nn) obj_out =", "# p3: [64, 64, 256], p4: [32, 32, 512], p5:", "models \"\"\" def YOLOX( backbone=None, features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1,", "num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1 -", "for ii in features]) / 256 print(\">>>> width_mul:\", width_mul) if", "nn def focus_stem(inputs, filters, kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\", name=\"\"): if", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out = tf.concat([deep, short], axis=-1) out =", "+ \"dw_\") kernel_size, strides = 1, 1 nn = conv2d_no_bias(nn,", "stem = conv_dw_pw_block(inputs, out_channels, activation=activation, name=name + \"stem_\") # cls_convs,", "= conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_2_\") reg_out", "num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\") outputs = keras.layers.Activation(\"linear\", dtype=\"float32\",", "{ \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"},", "nn = conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False,", "1::2] else: patch_top_left = inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right = inputs[:,", "activation=activation, name=name + \"down_\") nn = tf.concat(inputs, axis=-1) nn =", "\"sigmoid\", name=name + \"class_out_\") cls_out = keras.layers.Reshape([-1, num_classes], name=name +", "anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode,", "nn = inputs if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size, strides,", "activation_by_name(cls_out, \"sigmoid\", name=name + \"class_out_\") cls_out = keras.layers.Reshape([-1, num_classes], name=name", "model prediction. \"auto\" means 1 if use_anchor_free_mode else 4 rescale_mode=\"raw\",", "name=name + \"reg_2_\") reg_out = keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name", "\"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\",", "= inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] else:", "name=\"\"): # print(f\">>>> downsample_merge inputs: {[ii.shape for ii in inputs]", "depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # p5 ─> fpn_out0 ───────────> pan_out0", "freeze_backbone: backbone.trainable = False else: backbone.trainable = True inputs =", "YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640, 640, 3),", "use_shortcut) in enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name = \"stack{}_\".format(id +", "from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT =", "use_anchor_free_mode else 9) if num_anchors == \"auto\" else num_anchors fpn_features", "* 64), max(round(depth_mul * 3), 1) inputs = keras.layers.Input(input_shape) \"\"\"", "for ii in features]) / 256` for custom backbones. use_depthwise_conv=False,", "width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80,", "1::2] nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn =", "1 nn = conv2d_no_bias(nn, filters, kernel_size, strides, padding=\"SAME\", name=name) nn", "\"yolox\", pretrained) # AA = {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\":", "* expansion), activation=activation, name=name + \"1_\") nn = conv_dw_pw_block(nn, input_channels,", "return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640, 640,", "↓ ↑ # p4 ─> f_out0 ─> fpn_out1 ─> pan_out1", "path aggregation fpn \"\"\" def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"):", "f_out0: [32, 32, 512] fpn_out0, f_out0 = upsample_merge([p5, p4], csp_depth,", "name=\"pafpn_\") outputs = yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation,", "num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, # Init anchors for", "[32, 32, 512] pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation,", "None: width_mul = width_mul if width_mul > 0 else 1", "depth_mul=1, width_mul=-1, # -1 means: `min([ii.shape[-1] for ii in features])", "dark blocks \"\"\" depthes = [base_depth, base_depth * 3, base_depth", "[16, 16, 1024] pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation,", "\"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"},", "1 backbone = CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\")", "= tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in outputs], axis=1) outputs =", "= int(out_channels * expansion) short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation,", "DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model", "use_object_scores == \"auto\" else use_object_scores num_anchors = (1 if use_anchor_free_mode", "kernel_size=1, bias_initializer=bias_init, name=name + \"object_out\")(reg_nn) obj_out = activation_by_name(obj_out, \"sigmoid\", name=name", "name + \"{}_\".format(id + 1) out = yolox_head_single(input, out_channel, num_classes,", "\"object_out\")(reg_nn) obj_out = activation_by_name(obj_out, \"sigmoid\", name=name + \"object_out_\") obj_out =", "= tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, target_channel, 0.5, False,", "1) p3, p4, p5 = features # p3: [64, 64,", "p4, p5 = features # p3: [64, 64, 256], p4:", "# pan_out0: [16, 16, 1024] pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth,", "BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1,", "**kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640,", "fdf8:f53e:61e4::18, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right = inputs[:,", "ii.shape[-1]])(ii) for ii in outputs], axis=1) outputs = tf.concat(outputs, axis=1)", "3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33,", "anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model def YOLOXNano(input_shape=(416,", "= csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation, name=name) return", "tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True,", "depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels = inputs.shape[-1]", "16, 1024] pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "# nn = SPPBottleneck(base_channels * 16, base_channels * 16, activation=act)", "outputs = keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs, outputs, name=model_name)", "from keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func", "conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name) return nn def CSPDarknet(width_mul=1,", "for id, input in enumerate(inputs): cur_name = name + \"{}_\".format(id", "obj_out = keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"object_out\")(reg_nn)", "short], axis=-1) out = conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name +", "1024] # fpn_out0: [16, 16, 512], f_out0: [32, 32, 512]", "for id in features_pick] print(\">>>> features:\", {ii.name: ii.output_shape for ii", "1, 1 nn = conv2d_no_bias(nn, filters, kernel_size, strides, padding=\"SAME\", name=name)", "use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80,", "= keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model,", "SPPBottleneck(base_channels * 16, base_channels * 16, activation=act) nn = csp_stack(nn,", "return out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation=\"swish\", name=\"\"): input_channels", "\"1_\") nn = conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.0,", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n3_\") # pan_out0: [16, 16, 1024]", "AA = {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start}", "activation=\"swish\", name=\"\"): out_channel = int(256 * width_mul) outputs = []", "== \"auto\" else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode,", "+ \"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1, 4], name=name + \"regression_out_reshape\")(reg_out) #", "+ \"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "Init anchors for model prediction. \"auto\" means 1 if use_anchor_free_mode", "+ \"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out, obj_out], axis=-1) else: return tf.concat([reg_out,", "256], pan_out2: [64, 64, 256] fpn_out1, pan_out2 = upsample_merge([f_out0, p3],", "conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_2_\") reg_out =", "\"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\":", "import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models", "\"2_\") return nn def focus_stem(inputs, filters, kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\",", "inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn = tf.concat(inputs, axis=-1) nn", "features_pick, use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\") features = backbone.outputs else: if", "/ 256 print(\">>>> width_mul:\", width_mul) if freeze_backbone: backbone.trainable = False", "activation=activation, name=name) return fpn_out, nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\",", "\"auto\" means 1 if use_anchor_free_mode else 4 rescale_mode=\"raw\", # For", "conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"short_\") deep = conv_dw_pw_block(inputs,", "[32, 32, 512] fpn_out0, f_out0 = upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv,", "512] pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "depth, use_spp, use_shortcut) in enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name =", "width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\") outputs = keras.layers.Activation(\"linear\",", "= conv2d_no_bias(nn, filters, kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn,", "return [pan_out2, pan_out1, pan_out0] \"\"\" YOLOXHead \"\"\" def yolox_head_single(inputs, out_channels,", "16, activation=act) nn = csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name)", "using, recieving parameter ): if backbone is None: width_mul =", "inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name + \"fpn_\") #", "+ \"object_out_\") obj_out = keras.layers.Reshape([-1, 1], name=name + \"object_out_reshape\")(obj_out) return", "ii in inputs] = }\") target_channel = inputs[-1].shape[-1] fpn_out =", "16, 1024] # fpn_out0: [16, 16, 512], f_out0: [32, 32,", "Not using, recieving parameter ): if backbone is None: width_mul", "import model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions", "─> fpn_out1 ─> pan_out1 # ↓ ↑ # p3 ───────────>", "= conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation, name=name + \"down_\")", "activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn def csp_block(inputs, expansion=0.5, use_shortcut=True,", "= [nn] \"\"\" dark blocks \"\"\" depthes = [base_depth, base_depth", "use_anchor_free_mode if use_object_scores == \"auto\" else use_object_scores num_anchors = (1", "in features}) features = [ii.output for ii in features] width_mul", "def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> downsample_merge inputs:", "/ 0.01).numpy()) # stem stem = conv_dw_pw_block(inputs, out_channels, activation=activation, name=name", "kernel_size=kernel_size, strides=strides, activation=activation, name=name) return nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3,", "YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return", "depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON,", "csp_depth = max(round(depth_mul * 3), 1) p3, p4, p5 =", "nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\") kernel_size,", "1 if use_anchor_free_mode else 9 use_object_scores=\"auto\", # \"auto\" means same", "else num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs", "* 8, base_channels * 16] use_spps = [False, False, False,", "keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name + \"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1,", "name=name + \"class_out\")(cls_nn) cls_out = activation_by_name(cls_out, \"sigmoid\", name=name + \"class_out_\")", "out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out) # outputs", "input_shape=(640, 640, 3), num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, #", "cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_1_\")", "else use_object_scores num_anchors = (1 if use_anchor_free_mode else 9) if", "= [pyramid_levels_min, pyramid_levels_min + len(features_pick) - 1] # -> [3,", "name=name + \"fpn_\") # inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name", "PRETRAINED_DICT, \"yolox\", pretrained) # AA = {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales,", "YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return", "fc00:db20:35b:7399::5, 1::2] else: patch_top_left = inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right =", "\"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON =", "cls_out = keras.layers.Reshape([-1, num_classes], name=name + \"class_out_reshape\")(cls_out) # reg_convs, reg_preds", "model \"\"\" path aggregation fpn \"\"\" def upsample_merge(inputs, csp_depth, use_depthwise_conv=False,", "+ \"class_out_reshape\")(cls_out) # reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3,", "[3, 5] anchor_scale = (1 if use_anchor_free_mode else 4) if", "= keras.layers.Add()([inputs, nn]) return nn def csp_stack(inputs, depth, out_channels=-1, expansion=0.5,", "[keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for ii in pool_sizes] nn = tf.concat([nn,", "\"auto\" means 1 if use_anchor_free_mode else 9 use_object_scores=\"auto\", # \"auto\"", "\"grid_zero_start\": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min + len(features_pick) - 1]", "def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): out_channel", "def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs):", "activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs)", "name=name) return nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): #", "nn = depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn,", "# print(f\">>>> downsample_merge inputs: {[ii.shape for ii in inputs] =", "depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs = yolox_head(fpn_features, width_mul, num_classes, num_anchors,", "strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn = inputs if use_depthwise_conv: nn", "backbone is None: width_mul = width_mul if width_mul > 0", "+ \"output_\") return out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation=\"swish\",", "`min([ii.shape[-1] for ii in features]) / 256` for custom backbones.", "else out_channels hidden_channels = int(out_channels * expansion) short = conv_dw_pw_block(inputs,", "True] use_shortcuts = [True, True, True, False] for id, (channel,", "backbone \"\"\" BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs,", "activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs)", ":-1:2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] else: patch_top_left = inputs[:,", "path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs = yolox_head(fpn_features, width_mul, num_classes,", "return tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False,", "if out_channels == -1 else out_channels hidden_channels = int(out_channels *", "strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"2_\") if use_shortcut: nn =", "outputs = [] for id, input in enumerate(inputs): cur_name =", "outputs = tf.concat(outputs, axis=1) return outputs \"\"\" YOLOX models \"\"\"", "def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs):", "in inputs] = }\") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2,", "name=name + \"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation,", "freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.33, width_mul=1.25,", "model = keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained) #", "patch_top_right = inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, ::2]", "# ↓ ↑ # p3 ───────────> pan_out2 ──────┘ csp_depth =", "\"\"\" def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"):", "fpn_out1, pan_out2 = upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "name=name + \"dw_\") kernel_size, strides = 1, 1 nn =", "p5: [16, 16, 1024] # fpn_out0: [16, 16, 512], f_out0:", "::2] patch_top_right = inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5,", "patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] else: patch_top_left = inputs[:, fdf8:f53e:61e4::18,", "nn = conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name + \"2_\") return", "input_channels, kernel_size=1, activation=activation, name=name + \"2_\") return nn def focus_stem(inputs,", "= batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn def csp_block(inputs,", "base_channels, base_depth = int(width_mul * 64), max(round(depth_mul * 3), 1)", "use_object_scores num_anchors = (1 if use_anchor_free_mode else 9) if num_anchors", "= downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n3_\") #", "out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_2_\") reg_out = keras.layers.Conv2D(4", "kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn, out_channels,", "[64, 64, 256], p4: [32, 32, 512], p5: [16, 16,", "tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn,", "nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation, name=name) return nn def path_aggregation_fpn(features,", "backbone.inputs[0] use_object_scores = use_anchor_free_mode if use_object_scores == \"auto\" else use_object_scores", "kernel_size=1, activation=activation, name=name + \"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn)", "print(f\">>>> downsample_merge inputs: {[ii.shape for ii in inputs] = }\")", "strides=1, padding=\"SAME\")(nn) for ii in pool_sizes] nn = tf.concat([nn, *pp],", "False, use_depthwise_conv, activation=activation, name=name) return nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False,", "if use_object_scores: obj_out = keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name", "= [] for id, input in enumerate(inputs): cur_name = name", "csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation, name=name) return nn def", "axis=1) return outputs \"\"\" YOLOX models \"\"\" def YOLOX( backbone=None,", "reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_1_\")", "[pyramid_levels_min, pyramid_levels_min + len(features_pick) - 1] # -> [3, 5]", "with use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\",", "use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\" means 1 if use_anchor_free_mode else", "outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in outputs],", "1 if use_anchor_free_mode else 4 rescale_mode=\"raw\", # For decode predictions,", "activation=\"swish\", name=\"\"): # p5 ─> fpn_out0 ───────────> pan_out0 # ↓", "= yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out)", "use_depthwise_conv=False, input_shape=(512, 512, 3), activation=\"swish\", model_name=\"\"): base_channels, base_depth = int(width_mul", "= [features[ii] for ii in out_features] model = keras.models.Model(inputs, nn,", "stem stem = conv_dw_pw_block(inputs, out_channels, activation=activation, name=name + \"stem_\") #", "─> pan_out1 # ↓ ↑ # p3 ───────────> pan_out2 ──────┘", "use_object_scores, activation=activation, name=cur_name) outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for", "num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\",", "momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\") kernel_size, strides = 1, 1 nn", "\"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet", "input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"2_\") if use_shortcut:", "pan_out2: [64, 64, 256] fpn_out1, pan_out2 = upsample_merge([f_out0, p3], csp_depth,", "patch_top_right = inputs[:, :-1:2, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, :-1:2]", "inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1, activation=activation, name=name", "name=name) return nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False,", "activation=activation, name=stack_name + \"spp_\") # nn = SPPBottleneck(base_channels * 16,", "+ \"regression_out_reshape\")(reg_out) # obj_preds if use_object_scores: obj_out = keras.layers.Conv2D(1 *", "name=cur_name) outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in", "pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def", "+ \"block{}_\".format(id + 1) deep = csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv,", "4, base_channels * 8, base_channels * 16] use_spps = [False,", "activation=activation, name=name + \"reg_2_\") reg_out = keras.layers.Conv2D(4 * num_anchors, kernel_size=1,", "name=name + \"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1, 4], name=name + \"regression_out_reshape\")(reg_out)", "activation=activation, name=cur_name) outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii", "freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5,", "focus_stem(inputs, base_channels, activation=activation, name=\"stem_\") features = [nn] \"\"\" dark blocks", "name=name + \"c3n3_\") # pan_out0: [16, 16, 1024] pan_out0 =", "expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn =", "{[ii.shape for ii in inputs] = }\") target_channel = inputs[-1].shape[-1]", "if use_anchor_free_mode else 9 use_object_scores=\"auto\", # \"auto\" means same with", "anchor_scale == \"auto\" else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale,", "= path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs = yolox_head(fpn_features, width_mul,", "use_object_scores = use_anchor_free_mode if use_object_scores == \"auto\" else use_object_scores num_anchors", "== \"auto\" else num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation,", "fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n4_\") return [pan_out2, pan_out1,", "use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> downsample_merge inputs: {[ii.shape for ii", "backbone.outputs else: if isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name) for layer_name", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3,", "= conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"deep_\") for id", "from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT = { \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"},", "kernel_size=1, activation=activation, name=name + \"output_\") return out def spatial_pyramid_pooling(inputs, pool_sizes=(5,", "if anchor_scale == \"auto\" else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels,", "kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_2_\") cls_out = keras.layers.Conv2D(num_classes *", "def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1]", "model_name=\"yolox\", pyramid_levels_min=3, # Init anchors for model prediction. anchor_scale=\"auto\", #", "name=name + \"cls_2_\") cls_out = keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init,", "conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation, name=name + \"down_\") nn", "tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in outputs], axis=1) outputs = tf.concat(outputs,", "conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_1_\") cls_nn =", "kernel_size=1, bias_initializer=bias_init, name=name + \"class_out\")(cls_nn) cls_out = activation_by_name(cls_out, \"sigmoid\", name=name", "yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out) #", "= tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn, filters,", "::2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] nn = tf.concat([patch_top_left, patch_bottom_left,", "* 3), 1) inputs = keras.layers.Input(input_shape) \"\"\" Stem \"\"\" nn", "backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\",", "anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min + len(features_pick) -", "[nn] \"\"\" dark blocks \"\"\" depthes = [base_depth, base_depth *", "+ \"2_\") return nn def focus_stem(inputs, filters, kernel_size=3, strides=1, padding=\"valid\",", "outputs], axis=1) outputs = tf.concat(outputs, axis=1) return outputs \"\"\" YOLOX", "num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"class_out\")(cls_nn) cls_out = activation_by_name(cls_out, \"sigmoid\",", "fpn_out1 ─> pan_out1 # ↓ ↑ # p3 ───────────> pan_out2", "in inputs] = }\") target_channel = inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0],", "pan_out1 # ↓ ↑ # p3 ───────────> pan_out2 ──────┘ csp_depth", "custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\" means 1 if", "channels = [base_channels * 2, base_channels * 4, base_channels *", "name=name) return fpn_out, nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"):", "csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p4_\") # fpn_out1: [32, 32,", "outputs = yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\")", "print(\">>>> width_mul:\", width_mul) if freeze_backbone: backbone.trainable = False else: backbone.trainable", "\"\"\" Stem \"\"\" nn = focus_stem(inputs, base_channels, activation=activation, name=\"stem_\") features", "enumerate(inputs): cur_name = name + \"{}_\".format(id + 1) out =", "nn = conv2d_no_bias(nn, filters, kernel_size, strides, padding=\"SAME\", name=name) nn =", "= inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name + \"fpn_\")", "width_mul > 0 else 1 backbone = CSPDarknet(width_mul, depth_mul, features_pick,", "2, use_depthwise_conv, activation=activation, name=name + \"down_\") nn = tf.concat(inputs, axis=-1)", "axis=1) outputs = tf.concat(outputs, axis=1) return outputs \"\"\" YOLOX models", "= \"stack{}_\".format(id + 1) nn = conv_dw_pw_block(nn, channel, kernel_size=3, strides=2,", "use_anchor_free_mode else 4) if anchor_scale == \"auto\" else anchor_scale post_process", "= width_mul if width_mul > 0 else min([ii.shape[-1] for ii", "max(round(depth_mul * 3), 1) inputs = keras.layers.Input(input_shape) \"\"\" Stem \"\"\"", "cls_out = activation_by_name(cls_out, \"sigmoid\", name=name + \"class_out_\") cls_out = keras.layers.Reshape([-1,", "Init anchors for model prediction. anchor_scale=\"auto\", # Init anchors for", "pyramid_levels = [pyramid_levels_min, pyramid_levels_min + len(features_pick) - 1] # ->", "def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs):", "num_anchors, kernel_size=1, name=name + \"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1, 4], name=name", "return outputs \"\"\" YOLOX models \"\"\" def YOLOX( backbone=None, features_pick=[-3,", "width_mul if width_mul > 0 else min([ii.shape[-1] for ii in", "kwargs=None, # Not using, recieving parameter ): if backbone is", "activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.33, width_mul=1.25, model_name=kwargs.pop(\"model_name\", \"yolox_x\"), **kwargs)", "pan_out0] \"\"\" YOLOXHead \"\"\" def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False,", "upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p4_\") # fpn_out1:", "name=\"\"): out_channels = inputs.shape[-1] if out_channels == -1 else out_channels", "\"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1, 4], name=name + \"regression_out_reshape\")(reg_out) # obj_preds", "use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels = inputs.shape[-1] if out_channels ==", "─> f_out0 ─> fpn_out1 ─> pan_out1 # ↓ ↑ #", "ii in out_features] model = keras.models.Model(inputs, nn, name=model_name) return model", "num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\",", "patch_top_left = inputs[:, :-1:2, :-1:2] patch_top_right = inputs[:, :-1:2, 1::2]", "nn = tf.concat([nn, *pp], axis=-1) nn = conv_dw_pw_block(nn, input_channels, kernel_size=1,", "reg_out = keras.layers.Reshape([-1, 4], name=name + \"regression_out_reshape\")(reg_out) # obj_preds if", "activation=activation, name=stack_name) features.append(nn) nn = [features[ii] for ii in out_features]", "512], f_out0: [32, 32, 512] fpn_out0, f_out0 = upsample_merge([p5, p4],", "False, False, True] use_shortcuts = [True, True, True, False] for", "activation=activation, name=name + \"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv,", "anchor_scale = (1 if use_anchor_free_mode else 4) if anchor_scale ==", "def csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels", "# p3 ───────────> pan_out2 ──────┘ csp_depth = max(round(depth_mul * 3),", "def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs):", "model prediction. anchor_scale=\"auto\", # Init anchors for model prediction. \"auto\"", "= inputs if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\",", "= tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy()) # stem stem =", "padding.lower() == \"same\": # Handling odd input_shape inputs = tf.pad(inputs,", "strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp: nn = spatial_pyramid_pooling(nn, activation=activation,", "reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained) # AA = {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\":", "name=\"stem_\") features = [nn] \"\"\" dark blocks \"\"\" depthes =", "3), 1) p3, p4, p5 = features # p3: [64,", "use_shortcut: nn = keras.layers.Add()([inputs, nn]) return nn def csp_stack(inputs, depth,", "tensorflow import keras from keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias,", "name=name + \"deep_\") for id in range(depth): block_name = name", "= inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right", "0.5, False, use_depthwise_conv, activation=activation, name=name) return fpn_out, nn def downsample_merge(inputs,", "activation=activation, name=name + \"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for", "means 1 if use_anchor_free_mode else 9 use_object_scores=\"auto\", # \"auto\" means", "bias_initializer=bias_init, name=name + \"object_out\")(reg_nn) obj_out = activation_by_name(obj_out, \"sigmoid\", name=name +", "deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"deep_\") for", "16, base_channels * 16, activation=act) nn = csp_stack(nn, depth, use_shortcut=use_shortcut,", "model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None,", "# fpn_out1: [32, 32, 256], pan_out2: [64, 64, 256] fpn_out1,", "= inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right = inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left", "True, True, False] for id, (channel, depth, use_spp, use_shortcut) in", "depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn = [features[ii] for", "= conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name) return nn def", "= keras.models.Model(inputs, nn, name=model_name) return model \"\"\" path aggregation fpn", "num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\",", "activation=activation, name=name + \"2_\") if use_shortcut: nn = keras.layers.Add()([inputs, nn])", "backbone=None, features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1, # -1 means: `min([ii.shape[-1]", "\"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min", "width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80,", "strides=1, padding=\"valid\", activation=\"swish\", name=\"\"): if padding.lower() == \"same\": # Handling", "* num_anchors, kernel_size=1, name=name + \"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1, 4],", "fpn_out1: [32, 32, 256], pan_out2: [64, 64, 256] fpn_out1, pan_out2", "\"\"\" BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs, filters,", "keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained) # AA =", "\"dw_\") kernel_size, strides = 1, 1 nn = conv2d_no_bias(nn, filters,", "filters, kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON,", "[base_depth, base_depth * 3, base_depth * 3, base_depth] channels =", "model_name=\"\"): base_channels, base_depth = int(width_mul * 64), max(round(depth_mul * 3),", "else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model,", "model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None,", "anchors for model prediction. \"auto\" means 1 if use_anchor_free_mode else", "model_name=\"darknet\") features = backbone.outputs else: if isinstance(features_pick[0], str): features =", "inputs = keras.layers.Input(input_shape) \"\"\" Stem \"\"\" nn = focus_stem(inputs, base_channels,", "# AA = {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\":", "\"class_out\")(cls_nn) cls_out = activation_by_name(cls_out, \"sigmoid\", name=name + \"class_out_\") cls_out =", "backbone.trainable = True inputs = backbone.inputs[0] use_object_scores = use_anchor_free_mode if", "inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation, name=name +", "use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii)", "\"{}_\".format(id + 1) out = yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv,", "return nn def csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\",", "YOLOX( backbone=None, features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1, # -1 means:", "inputs[:, fc00:db20:35b:7399::5, 1::2] nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1)", "+ \"2_\") if use_shortcut: nn = keras.layers.Add()([inputs, nn]) return nn", "[64, 64, 256] fpn_out1, pan_out2 = upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv,", "freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75,", "use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model def YOLOXNano(input_shape=(416, 416, 3),", "use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model def YOLOXNano(input_shape=(416, 416,", "= tf.concat(outputs, axis=1) return outputs \"\"\" YOLOX models \"\"\" def", "width_mul > 0 else min([ii.shape[-1] for ii in features]) /", "for ii in features}) features = [ii.output for ii in", "* 3), 1) p3, p4, p5 = features # p3:", "conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_1_\") reg_nn =", "csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn = [features[ii]", "use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\" means 1 if use_anchor_free_mode else 9", "1) deep = csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out", "csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n3_\") # pan_out0: [16, 16,", "axis=-1) else: return tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80,", "conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name + \"output_\") return out def", "1e-3 BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False,", "nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> downsample_merge", "nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name + \"spp_\") # nn =", "fdf8:f53e:61e4::18, ::2] patch_top_right = inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left = inputs[:,", "= width_mul if width_mul > 0 else 1 backbone =", "= tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False,", "name + \"block{}_\".format(id + 1) deep = csp_block(deep, 1, use_shortcut=use_shortcut,", "= keras.layers.Reshape([-1, 1], name=name + \"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out, obj_out],", "int(256 * width_mul) outputs = [] for id, input in", "[0, 255]. kwargs=None, # Not using, recieving parameter ): if", "pan_out2 = upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p3_\")", "model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None,", "return tf.concat([reg_out, cls_out, obj_out], axis=-1) else: return tf.concat([reg_out, cls_out], axis=-1)", "+ \"stem_\") # cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3,", "len(features_pick) - 1] # -> [3, 5] anchor_scale = (1", "num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs =", "input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1,", "num_classes], name=name + \"class_out_reshape\")(cls_out) # reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem,", "+ \"down_\") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth,", "raw means input value in range [0, 255]. kwargs=None, #", "for model prediction. anchor_scale=\"auto\", # Init anchors for model prediction.", "0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn", "yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): bias_init =", "keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT = { \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\":", "1], [0, 0]]) patch_top_left = inputs[:, :-1:2, :-1:2] patch_top_right =", "conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"deep_\") for id in", "= (1 if use_anchor_free_mode else 4) if anchor_scale == \"auto\"", "num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True,", "downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> downsample_merge inputs: {[ii.shape", "activation=activation, name=name + \"stem_\") # cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem,", "for ii in inputs] = }\") target_channel = inputs[-1].shape[-1] fpn_out", "pan_out1: [32, 32, 512] pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv,", "csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> upsample_merge inputs: {[ii.shape for", "+ \"c3n3_\") # pan_out0: [16, 16, 1024] pan_out0 = downsample_merge([pan_out1,", "kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\", name=\"\"): if padding.lower() == \"same\": #", "* num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"class_out\")(cls_nn) cls_out = activation_by_name(cls_out,", "5] anchor_scale = (1 if use_anchor_free_mode else 4) if anchor_scale", "\"c3n4_\") return [pan_out2, pan_out1, pan_out0] \"\"\" YOLOXHead \"\"\" def yolox_head_single(inputs,", "= conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name + \"2_\") return nn", "nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512, 512,", "──────┘ csp_depth = max(round(depth_mul * 3), 1) p3, p4, p5", "= tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn = tf.concat(inputs, axis=-1) nn =", "[base_channels * 2, base_channels * 4, base_channels * 8, base_channels", "\"object_out_\") obj_out = keras.layers.Reshape([-1, 1], name=name + \"object_out_reshape\")(obj_out) return tf.concat([reg_out,", "means 1 if use_anchor_free_mode else 4 rescale_mode=\"raw\", # For decode", "-1], depth_mul=1, width_mul=-1, # -1 means: `min([ii.shape[-1] for ii in", "3, base_depth] channels = [base_channels * 2, base_channels * 4,", "): if backbone is None: width_mul = width_mul if width_mul", "activation=activation, name=name + \"2_\") return nn def focus_stem(inputs, filters, kernel_size=3,", "name=name + \"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn =", "255]. kwargs=None, # Not using, recieving parameter ): if backbone", "def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn =", "input in enumerate(inputs): cur_name = name + \"{}_\".format(id + 1)", "if use_anchor_free_mode else 4) if anchor_scale == \"auto\" else anchor_scale", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\") outputs = yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv,", "inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation, name=name +", "name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained)", "if num_anchors == \"auto\" else num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul,", "\"auto\" else use_object_scores num_anchors = (1 if use_anchor_free_mode else 9)", "\"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\":", "use_depthwise_conv, activation=activation, name=name) return fpn_out, nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False,", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_2_\") cls_out = keras.layers.Conv2D(num_classes * num_anchors,", "= conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation, name=name + \"1_\") nn", "cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_2_\")", "anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min + len(features_pick) - 1] #", "+ \"class_out\")(cls_nn) cls_out = activation_by_name(cls_out, \"sigmoid\", name=name + \"class_out_\") cls_out", "name=\"head_\") outputs = keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs, outputs,", "-1 means: `min([ii.shape[-1] for ii in features]) / 256` for", "# \"auto\" means 1 if use_anchor_free_mode else 9 use_object_scores=\"auto\", #", "[16, 16, 512], f_out0: [32, 32, 512] fpn_out0, f_out0 =", "+ \"cls_2_\") cls_out = keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name", "name=name + \"c3p4_\") # fpn_out1: [32, 32, 256], pan_out2: [64,", "out_channels = inputs.shape[-1] if out_channels == -1 else out_channels hidden_channels", "features = backbone.outputs else: if isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name)", "use_object_scores, activation=activation, name=\"head_\") outputs = keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model =", "cur_name = name + \"{}_\".format(id + 1) out = yolox_head_single(input,", "\"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\",", "depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False,", "dtype=\"float32\", name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\",", "str): features = [backbone.get_layer(layer_name) for layer_name in features_pick] else: features", "nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # p5 ─>", "use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs,", "conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load", "csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> downsample_merge inputs: {[ii.shape for", "axis=-1) out = conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name + \"output_\")", "use_shortcuts = [True, True, True, False] for id, (channel, depth,", "= [False, False, False, True] use_shortcuts = [True, True, True,", "256` for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\" means", "= keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"object_out\")(reg_nn) obj_out", "ii in features}) features = [ii.output for ii in features]", "+ \"c3p3_\") # pan_out1: [32, 32, 512] pan_out1 = downsample_merge([pan_out2,", "= spatial_pyramid_pooling(nn, activation=activation, name=stack_name + \"spp_\") # nn = SPPBottleneck(base_channels", "256 print(\">>>> width_mul:\", width_mul) if freeze_backbone: backbone.trainable = False else:", "[features[ii] for ii in out_features] model = keras.models.Model(inputs, nn, name=model_name)", "activation=\"swish\", name=\"\"): nn = inputs if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn,", "keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"class_out\")(cls_nn) cls_out =", "fpn_out0, f_out0 = upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "name=name + \"2_\") return nn def focus_stem(inputs, filters, kernel_size=3, strides=1,", "YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return", "blocks \"\"\" depthes = [base_depth, base_depth * 3, base_depth *", "input_shape=(512, 512, 3), activation=\"swish\", model_name=\"\"): base_channels, base_depth = int(width_mul *", "2, base_channels * 4, base_channels * 8, base_channels * 16]", "**kwargs) def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\",", "features:\", {ii.name: ii.output_shape for ii in features}) features = [ii.output", "[16, 16, 1024] # fpn_out0: [16, 16, 512], f_out0: [32,", "range(depth): block_name = name + \"block{}_\".format(id + 1) deep =", "base_channels, activation=activation, name=\"stem_\") features = [nn] \"\"\" dark blocks \"\"\"", "use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\") features = backbone.outputs else: if isinstance(features_pick[0],", "range [0, 255]. kwargs=None, # Not using, recieving parameter ):", "nn = csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn", "conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn = inputs", "\"c3p3_\") # pan_out1: [32, 32, 512] pan_out1 = downsample_merge([pan_out2, fpn_out1],", "+ \"c3p4_\") # fpn_out1: [32, 32, 256], pan_out2: [64, 64,", "1) nn = conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name)", "conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation, name=name + \"1_\") nn =", "block_name = name + \"block{}_\".format(id + 1) deep = csp_block(deep,", "for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", # \"auto\" means 1", "= conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_2_\") cls_out", "focus_stem(inputs, filters, kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\", name=\"\"): if padding.lower() ==", "name=block_name) out = tf.concat([deep, short], axis=-1) out = conv_dw_pw_block(out, out_channels,", "\"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON", "depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False,", "\"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "\"fpn_\") # inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name + \"up\")(fpn_out)", "out_features] model = keras.models.Model(inputs, nn, name=model_name) return model \"\"\" path", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p3_\") # pan_out1: [32, 32, 512]", "reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT = { \"yolox_nano\": {\"coco\":", "name=model_name) return model \"\"\" path aggregation fpn \"\"\" def upsample_merge(inputs,", "\"\"\" path aggregation fpn \"\"\" def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\",", "freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0,", "activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs)", "= inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1, activation=activation,", "activation=activation, name=stack_name) if use_spp: nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name +", "keras from keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process,", "= tf.concat([nn, *pp], axis=-1) nn = conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation,", "name=name + \"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for ii", "nn, name=model_name) return model \"\"\" path aggregation fpn \"\"\" def", "activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs)", "* 16, activation=act) nn = csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation,", "[pan_out2, pan_out1, pan_out0] \"\"\" YOLOXHead \"\"\" def yolox_head_single(inputs, out_channels, num_classes=80,", "# -1 means: `min([ii.shape[-1] for ii in features]) / 256`", "keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name + \"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1],", "inputs] = }\") target_channel = inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel,", "backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"),", "nn def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels =", "False else: backbone.trainable = True inputs = backbone.inputs[0] use_object_scores =", "[32, 32, 256], pan_out2: [64, 64, 256] fpn_out1, pan_out2 =", "name=\"\"): out_channel = int(256 * width_mul) outputs = [] for", "nn = conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation, name=name + \"1_\")", "+ \"c3n4_\") return [pan_out2, pan_out1, pan_out0] \"\"\" YOLOXHead \"\"\" def", "* 3, base_depth] channels = [base_channels * 2, base_channels *", "pan_out1, pan_out0] \"\"\" YOLOXHead \"\"\" def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1,", "strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name)", "cls_preds cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min +", "YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416, 416,", "= { \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\":", "*pp], axis=-1) nn = conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name +", "nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name) return nn", "kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_2_\") reg_out = keras.layers.Conv2D(4 *", "out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1", "features]) / 256 print(\">>>> width_mul:\", width_mul) if freeze_backbone: backbone.trainable =", "obj_preds if use_object_scores: obj_out = keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init,", "= conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name + \"fpn_\") # inputs[0] =", "tf from tensorflow import keras from keras_cv_attention_models.attention_layers import ( activation_by_name,", "[False, False, False, True] use_shortcuts = [True, True, True, False]", "isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name) for layer_name in features_pick] else:", "num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out) # outputs =", "{\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\":", "inputs = tf.pad(inputs, [[0, 0], [0, 1], [0, 1], [0,", "activation=activation, name=name + \"short_\") deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation,", "if use_anchor_free_mode else 4 rescale_mode=\"raw\", # For decode predictions, raw", "inputs[:, :-1:2, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right =", "YOLOX models \"\"\" def YOLOX( backbone=None, features_pick=[-3, -2, -1], depth_mul=1,", "\"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min + len(features_pick)", "1], name=name + \"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out, obj_out], axis=-1) else:", "YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640, 640, 3),", "= keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"class_out\")(cls_nn) cls_out", "\"sigmoid\", name=name + \"object_out_\") obj_out = keras.layers.Reshape([-1, 1], name=name +", "YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640, 640, 3),", "patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2]", "def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): bias_init", "aggregation fpn \"\"\" def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): #", "tf.concat([nn, *pp], axis=-1) nn = conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name", "+ len(features_pick) - 1] # -> [3, 5] anchor_scale =", "use_spps = [False, False, False, True] use_shortcuts = [True, True,", "use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn = [features[ii] for ii", "YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return", "= DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return", "YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return", "out = conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name + \"output_\") return", "name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn", "out = yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name)", "name=name + \"2_\") if use_shortcut: nn = keras.layers.Add()([inputs, nn]) return", "{\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels =", "else: if isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name) for layer_name in", "activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, # Init anchors for model", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp: nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name", "num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1,", "method=\"nearest\") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, target_channel,", "nn = SPPBottleneck(base_channels * 16, base_channels * 16, activation=act) nn", "+ \"reg_2_\") reg_out = keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name +", "conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name + \"2_\") return nn def", "padding=\"valid\", activation=\"swish\", name=\"\"): if padding.lower() == \"same\": # Handling odd", "spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn", "inputs: {[ii.shape for ii in inputs] = }\") target_channel =", "\"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM", "**kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640,", "base_channels * 16, activation=act) nn = csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv,", "pan_out0: [16, 16, 1024] pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv,", "= int(256 * width_mul) outputs = [] for id, input", "Stem \"\"\" nn = focus_stem(inputs, base_channels, activation=activation, name=\"stem_\") features =", "activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\") kernel_size, strides = 1,", "p5 = features # p3: [64, 64, 256], p4: [32,", "csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels =", "features}) features = [ii.output for ii in features] width_mul =", "inputs = backbone.inputs[0] use_object_scores = use_anchor_free_mode if use_object_scores == \"auto\"", "p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p3_\") # pan_out1: [32,", "\"\"\" dark blocks \"\"\" depthes = [base_depth, base_depth * 3,", "freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, # Init anchors for model prediction.", "print(\">>>> features:\", {ii.name: ii.output_shape for ii in features}) features =", "\"c3n3_\") # pan_out0: [16, 16, 1024] pan_out0 = downsample_merge([pan_out1, fpn_out0],", "num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01)", "depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False,", "0.5, False, use_depthwise_conv, activation=activation, name=name) return nn def path_aggregation_fpn(features, depth_mul=1,", "name=name + \"c3n4_\") return [pan_out2, pan_out1, pan_out0] \"\"\" YOLOXHead \"\"\"", "if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\", name=name) nn", "pan_out0 # ↓ ↑ # p4 ─> f_out0 ─> fpn_out1", "freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375,", "else: features = model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for id in", "= False else: backbone.trainable = True inputs = backbone.inputs[0] use_object_scores", "import DecodePredictions PRETRAINED_DICT = { \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\":", "+ \"class_out_\") cls_out = keras.layers.Reshape([-1, num_classes], name=name + \"class_out_reshape\")(cls_out) #", "import reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT = { \"yolox_nano\":", "cls_out, obj_out], axis=-1) else: return tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs,", "+ \"short_\") deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name +", "backbone = CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\") features", "tensorflow as tf from tensorflow import keras from keras_cv_attention_models.attention_layers import", "**kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def", "* width_mul) outputs = [] for id, input in enumerate(inputs):", "use_spp: nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name + \"spp_\") # nn", "\"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out, obj_out], axis=-1) else: return tf.concat([reg_out, cls_out],", "inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation, name=name + \"down_\") nn =", "add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False,", "keras.layers.Input(input_shape) \"\"\" Stem \"\"\" nn = focus_stem(inputs, base_channels, activation=activation, name=\"stem_\")", "else 4) if anchor_scale == \"auto\" else anchor_scale post_process =", "= [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for ii in pool_sizes] nn =", "0 else min([ii.shape[-1] for ii in features]) / 256 print(\">>>>", "strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name", "{ii.name: ii.output_shape for ii in features}) features = [ii.output for", "32, 512], p5: [16, 16, 1024] # fpn_out0: [16, 16,", "activation=act) nn = csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn)", "return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640, 640,", "name=name + \"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation,", "= keras.layers.Reshape([-1, 4], name=name + \"regression_out_reshape\")(reg_out) # obj_preds if use_object_scores:", "path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # p5 ─> fpn_out0 ───────────>", "conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1, activation=activation, name=name + \"1_\") pp", "name=name + \"object_out\")(reg_nn) obj_out = activation_by_name(obj_out, \"sigmoid\", name=name + \"object_out_\")", "9) if num_anchors == \"auto\" else num_anchors fpn_features = path_aggregation_fpn(features,", "= [features[id] for id in features_pick] print(\">>>> features:\", {ii.name: ii.output_shape", "deep = csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out =", "model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for id in features_pick] print(\">>>> features:\",", "features = [backbone.get_layer(layer_name) for layer_name in features_pick] else: features =", "out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512, 512, 3), activation=\"swish\", model_name=\"\"): base_channels,", "batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn def csp_block(inputs, expansion=0.5,", "if use_shortcut: nn = keras.layers.Add()([inputs, nn]) return nn def csp_stack(inputs,", "↑ # p3 ───────────> pan_out2 ──────┘ csp_depth = max(round(depth_mul *", "depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\") features = backbone.outputs else:", "0.01).numpy()) # stem stem = conv_dw_pw_block(inputs, out_channels, activation=activation, name=name +", "value in range [0, 255]. kwargs=None, # Not using, recieving", "downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n4_\") return [pan_out2,", "activation=activation, name=name + \"output_\") return out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9,", "for id, (channel, depth, use_spp, use_shortcut) in enumerate(zip(channels, depthes, use_spps,", "activation=activation, name=name) return nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1],", "if padding.lower() == \"same\": # Handling odd input_shape inputs =", "\"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\",", "640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(),", "input value in range [0, 255]. kwargs=None, # Not using,", "416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(),", "else 4 rescale_mode=\"raw\", # For decode predictions, raw means input", "-2, -1], depth_mul=1, width_mul=-1, # -1 means: `min([ii.shape[-1] for ii", "csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out = tf.concat([deep, short],", "else 9 use_object_scores=\"auto\", # \"auto\" means same with use_anchor_free_mode input_shape=(640,", "0], [0, 1], [0, 1], [0, 0]]) patch_top_left = inputs[:,", "4) if anchor_scale == \"auto\" else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:],", "width_mul if width_mul > 0 else 1 backbone = CSPDarknet(width_mul,", "= csp_stack(nn, csp_depth, target_channel, 0.5, False, use_depthwise_conv, activation=activation, name=name) return", "channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp: nn =", "num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"object_out\")(reg_nn) obj_out = activation_by_name(obj_out, \"sigmoid\",", "BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\",", "\"spp_\") # nn = SPPBottleneck(base_channels * 16, base_channels * 16,", "32, 512] fpn_out0, f_out0 = upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation,", "in enumerate(inputs): cur_name = name + \"{}_\".format(id + 1) out", "anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min,", "= (1 if use_anchor_free_mode else 9) if num_anchors == \"auto\"", "def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs):", "out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_2_\") cls_out = keras.layers.Conv2D(num_classes", "backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"),", "in enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name = \"stack{}_\".format(id + 1)", "== \"same\": # Handling odd input_shape inputs = tf.pad(inputs, [[0,", "id in range(depth): block_name = name + \"block{}_\".format(id + 1)", "512] fpn_out0, f_out0 = upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained) # AA = {\"aspect_ratios\":", "CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation, model_name=\"darknet\") features = backbone.outputs", "use_depthwise_conv=False, activation=\"swish\", name=\"\"): # p5 ─> fpn_out0 ───────────> pan_out0 #", "in range [0, 255]. kwargs=None, # Not using, recieving parameter", "out_channels == -1 else out_channels hidden_channels = int(out_channels * expansion)", "print(f\">>>> upsample_merge inputs: {[ii.shape for ii in inputs] = }\")", "= downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n4_\") return", "use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>> upsample_merge inputs: {[ii.shape for ii", "activation=\"swish\", name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy()) #", "activation=activation, name=name + \"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv,", "inputs if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\", name=name)", "out = tf.concat([deep, short], axis=-1) out = conv_dw_pw_block(out, out_channels, kernel_size=1,", "num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\",", "[[0, 0], [0, 1], [0, 1], [0, 0]]) patch_top_left =", "short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"short_\") deep", "activation=activation, name=name + \"c3p4_\") # fpn_out1: [32, 32, 256], pan_out2:", "batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models import model_surgery from", "name=name + \"stem_\") # cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem, out_channels,", "= [True, True, True, False] for id, (channel, depth, use_spp,", "64, 256] fpn_out1, pan_out2 = upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation,", "freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25,", "expansion), activation=activation, name=name + \"1_\") nn = conv_dw_pw_block(nn, input_channels, kernel_size=3,", "keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT = {", "kernel_size=1, name=name + \"regression_out\")(reg_nn) reg_out = keras.layers.Reshape([-1, 4], name=name +", "id, input in enumerate(inputs): cur_name = name + \"{}_\".format(id +", "4], name=name + \"regression_out_reshape\")(reg_out) # obj_preds if use_object_scores: obj_out =", "> 0 else min([ii.shape[-1] for ii in features]) / 256", "post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process)", "input_shape inputs = tf.pad(inputs, [[0, 0], [0, 1], [0, 1],", "keras.layers.Reshape([-1, num_classes], name=name + \"class_out_reshape\")(cls_out) # reg_convs, reg_preds reg_nn =", "reg_out = keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name + \"regression_out\")(reg_nn) reg_out", "== \"auto\" else use_object_scores num_anchors = (1 if use_anchor_free_mode else", "def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512, 512, 3),", "1] # -> [3, 5] anchor_scale = (1 if use_anchor_free_mode", "= [backbone.get_layer(layer_name) for layer_name in features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone)", "\"\"\" nn = focus_stem(inputs, base_channels, activation=activation, name=\"stem_\") features = [nn]", "1) inputs = keras.layers.Input(input_shape) \"\"\" Stem \"\"\" nn = focus_stem(inputs,", "3, base_depth * 3, base_depth] channels = [base_channels * 2,", "upsample_merge inputs: {[ii.shape for ii in inputs] = }\") target_channel", "axis=-1) nn = csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation,", "expansion) short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"short_\")", "[ii.output for ii in features] width_mul = width_mul if width_mul", "id in features_pick] print(\">>>> features:\", {ii.name: ii.output_shape for ii in", "fc00:db20:35b:7399::5, 1::2] nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn", "\"down_\") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, nn.shape[-1],", "= focus_stem(inputs, base_channels, activation=activation, name=\"stem_\") features = [nn] \"\"\" dark", "for model prediction. \"auto\" means 1 if use_anchor_free_mode else 4", "= 0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"):", "= keras.layers.Input(input_shape) \"\"\" Stem \"\"\" nn = focus_stem(inputs, base_channels, activation=activation,", "32, 512] pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "use_object_scores=True, activation=\"swish\", name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy())", "\"stack{}_\".format(id + 1) nn = conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv,", "out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn,", "3), 1) inputs = keras.layers.Input(input_shape) \"\"\" Stem \"\"\" nn =", "tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy()) # stem stem = conv_dw_pw_block(inputs,", "stack_name = \"stack{}_\".format(id + 1) nn = conv_dw_pw_block(nn, channel, kernel_size=3,", "num_anchors == \"auto\" else num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv,", "activation=activation, name=name + \"c3p3_\") # pan_out1: [32, 32, 512] pan_out1", "tf.concat([reg_out, cls_out, obj_out], axis=-1) else: return tf.concat([reg_out, cls_out], axis=-1) def", "}\") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation, name=name", "use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size, strides, padding=\"SAME\", name=name) nn =", "use_object_scores: obj_out = keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name +", "tf.concat([deep, short], axis=-1) out = conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name", "+ \"spp_\") # nn = SPPBottleneck(base_channels * 16, base_channels *", "= name + \"block{}_\".format(id + 1) deep = csp_block(deep, 1,", "post_process=post_process) return model def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None,", "CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM = 0.03 def", "\"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name +", "return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640, 640,", "anchor_scale=\"auto\", # Init anchors for model prediction. \"auto\" means 1", "YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def YOLOXL(input_shape=(640, 640, 3),", "\"class_out_reshape\")(cls_out) # reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv,", "0.01) / 0.01).numpy()) # stem stem = conv_dw_pw_block(inputs, out_channels, activation=activation,", "ii in outputs], axis=1) outputs = tf.concat(outputs, axis=1) return outputs", "\"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\":", "\"stem_\") # cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv,", "\"\"\" depthes = [base_depth, base_depth * 3, base_depth * 3,", "min([ii.shape[-1] for ii in features]) / 256 print(\">>>> width_mul:\", width_mul)", "= upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p3_\") #", "name=model_name) reload_model_weights(model, PRETRAINED_DICT, \"yolox\", pretrained) # AA = {\"aspect_ratios\": anchor_aspect_ratios,", "**kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640,", "pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n3_\")", "p3, p4, p5 = features # p3: [64, 64, 256],", "**kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop(\"model_name\", \"yolox_s\"), **kwargs) def YOLOXM(input_shape=(640,", "─> fpn_out0 ───────────> pan_out0 # ↓ ↑ # p4 ─>", "backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.33, width_mul=1.25, model_name=kwargs.pop(\"model_name\", \"yolox_x\"),", "activation=activation, name=name + \"deep_\") for id in range(depth): block_name =", "obj_out = activation_by_name(obj_out, \"sigmoid\", name=name + \"object_out_\") obj_out = keras.layers.Reshape([-1,", "base_depth * 3, base_depth] channels = [base_channels * 2, base_channels", "strides=strides, activation=activation, name=name) return nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2,", "activation=activation, name=\"head_\") outputs = keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs,", "}\") target_channel = inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name", "for ii in inputs] = }\") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1],", "id, (channel, depth, use_spp, use_shortcut) in enumerate(zip(channels, depthes, use_spps, use_shortcuts)):", ":-1:2, :-1:2] patch_top_right = inputs[:, :-1:2, 1::2] patch_bottom_left = inputs[:,", "= SPPBottleneck(base_channels * 16, base_channels * 16, activation=act) nn =", "\"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\",", "depthes, use_spps, use_shortcuts)): stack_name = \"stack{}_\".format(id + 1) nn =", "activation=\"swish\", name=\"\"): # print(f\">>>> downsample_merge inputs: {[ii.shape for ii in", "yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\") outputs =", "in out_features] model = keras.models.Model(inputs, nn, name=model_name) return model \"\"\"", "# Handling odd input_shape inputs = tf.pad(inputs, [[0, 0], [0,", "depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load import", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_2_\") reg_out = keras.layers.Conv2D(4 * num_anchors,", "fc00:db20:35b:7399::5, :-1:2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] else: patch_top_left =", "decode predictions, raw means input value in range [0, 255].", "kernel_size=1, activation=activation, name=name + \"deep_\") for id in range(depth): block_name", "= int(width_mul * 64), max(round(depth_mul * 3), 1) inputs =", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p4_\") # fpn_out1: [32, 32, 256],", "return nn def focus_stem(inputs, filters, kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\", name=\"\"):", "patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name)", "filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name) return nn def CSPDarknet(width_mul=1, depth_mul=1,", "# p4 ─> f_out0 ─> fpn_out1 ─> pan_out1 # ↓", "bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy()) # stem stem", "\"\"\" CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM = 0.03", "nn = csp_stack(nn, csp_depth, target_channel, 0.5, False, use_depthwise_conv, activation=activation, name=name)", "# reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation,", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn = [features[ii] for ii in", "int(width_mul * 64), max(round(depth_mul * 3), 1) inputs = keras.layers.Input(input_shape)", "# Init anchors for model prediction. \"auto\" means 1 if", "(1 if use_anchor_free_mode else 9) if num_anchors == \"auto\" else", "3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.33,", "\"short_\") deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + \"deep_\")", "* 2, base_channels * 4, base_channels * 8, base_channels *", "else 9) if num_anchors == \"auto\" else num_anchors fpn_features =", "= inputs[:, fc00:db20:35b:7399::5, 1::2] else: patch_top_left = inputs[:, fdf8:f53e:61e4::18, ::2]", "= keras.layers.Reshape([-1, num_classes], name=name + \"class_out_reshape\")(cls_out) # reg_convs, reg_preds reg_nn", "patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right,", "pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n4_\")", "= conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_1_\") reg_nn", "width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"), **kwargs) def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80,", "-2, -1], use_depthwise_conv=False, input_shape=(512, 512, 3), activation=\"swish\", model_name=\"\"): base_channels, base_depth", "activation=activation, model_name=\"darknet\") features = backbone.outputs else: if isinstance(features_pick[0], str): features", "2), interpolation=\"nearest\", name=name + \"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\")", "pyramid_levels_min=3, # Init anchors for model prediction. anchor_scale=\"auto\", # Init", "+ 1) out = yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores,", "width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\", name=\"\"): out_channel = int(256", "640, 3), num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, # Init", "name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels // 2,", "keras.layers.Add()([inputs, nn]) return nn def csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True,", "momentum=BATCH_NORM_MOMENTUM, name=name) return nn def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\",", "False, use_depthwise_conv, activation=activation, name=name) return fpn_out, nn def downsample_merge(inputs, csp_depth,", "# inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name + \"up\")(fpn_out) inputs[0]", "* 4, base_channels * 8, base_channels * 16] use_spps =", "conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_2_\") cls_out =", "nn = [features[ii] for ii in out_features] model = keras.models.Model(inputs,", "use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out = tf.concat([deep, short], axis=-1) out", "layer_name in features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone) features = [features[id]", "[backbone.get_layer(layer_name) for layer_name in features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone) features", "is None: width_mul = width_mul if width_mul > 0 else", "\"auto\" else num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name=\"pafpn_\")", "0 else 1 backbone = CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape,", "pyramid_levels_min + len(features_pick) - 1] # -> [3, 5] anchor_scale", "nn = conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if", "backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop(\"model_name\", \"yolox_tiny\"),", "+ \"up\")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn = tf.concat(inputs,", "tf.concat(outputs, axis=1) return outputs \"\"\" YOLOX models \"\"\" def YOLOX(", "features = [ii.output for ii in features] width_mul = width_mul", "= batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\") kernel_size, strides", "= {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale, \"grid_zero_start\": anchor_grid_zero_start} pyramid_levels", "# Not using, recieving parameter ): if backbone is None:", "rescale_mode=\"raw\", # For decode predictions, raw means input value in", "name=name + \"class_out_reshape\")(cls_out) # reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem, out_channels,", "name=\"\"): nn = inputs if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size,", "# Init anchors for model prediction. anchor_scale=\"auto\", # Init anchors", "* 3, base_depth * 3, base_depth] channels = [base_channels *", "for ii in features] width_mul = width_mul if width_mul >", "pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for ii in pool_sizes] nn", "# \"auto\" means same with use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80,", "axis=-1) nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name) return", "def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1]", "conv2d_no_bias(nn, filters, kernel_size, strides, padding=\"SAME\", name=name) nn = batchnorm_with_activation(nn, activation=activation,", "kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp: nn = spatial_pyramid_pooling(nn,", "cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "For decode predictions, raw means input value in range [0,", "activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels *", "# p5 ─> fpn_out0 ───────────> pan_out0 # ↓ ↑ #", "9, 13), activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs,", "csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p3_\") # pan_out1: [32, 32,", "means input value in range [0, 255]. kwargs=None, # Not", "nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, target_channel, 0.5,", "= conv_dw_pw_block(inputs, out_channels, activation=activation, name=name + \"stem_\") # cls_convs, cls_preds", "// 2, kernel_size=1, activation=activation, name=name + \"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii,", "out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_1_\") cls_nn = conv_dw_pw_block(cls_nn,", "if use_spp: nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name + \"spp_\") #", "} \"\"\" CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM =", "* 16, base_channels * 16, activation=act) nn = csp_stack(nn, depth,", "= 1, 1 nn = conv2d_no_bias(nn, filters, kernel_size, strides, padding=\"SAME\",", "in outputs], axis=1) outputs = tf.concat(outputs, axis=1) return outputs \"\"\"", "in features]) / 256 print(\">>>> width_mul:\", width_mul) if freeze_backbone: backbone.trainable", "downsample_merge inputs: {[ii.shape for ii in inputs] = }\") inputs[0]", "from keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, )", "width_mul=-1, # -1 means: `min([ii.shape[-1] for ii in features]) /", "name=stack_name + \"spp_\") # nn = SPPBottleneck(base_channels * 16, base_channels", "in features] width_mul = width_mul if width_mul > 0 else", "= }\") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation,", "kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn, out_channels,", "inputs.shape[-1] if out_channels == -1 else out_channels hidden_channels = int(out_channels", "64), max(round(depth_mul * 3), 1) inputs = keras.layers.Input(input_shape) \"\"\" Stem", "[True, True, True, False] for id, (channel, depth, use_spp, use_shortcut)", "reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_2_\")", "inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] else: patch_top_left", "# pan_out1: [32, 32, 512] pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth,", "csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n4_\") return [pan_out2, pan_out1, pan_out0]", "base_depth = int(width_mul * 64), max(round(depth_mul * 3), 1) inputs", "256] fpn_out1, pan_out2 = upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "filters, kernel_size=3, strides=1, padding=\"valid\", activation=\"swish\", name=\"\"): if padding.lower() == \"same\":", "features]) / 256` for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors=\"auto\", #", "int(out_channels * expansion) short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name", "depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416, 416, 3),", "features.append(nn) nn = [features[ii] for ii in out_features] model =", "name=\"\"): # p5 ─> fpn_out0 ───────────> pan_out0 # ↓ ↑", "name=stack_name) if use_spp: nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name + \"spp_\")", "base_channels * 16] use_spps = [False, False, False, True] use_shortcuts", "same with use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None,", "# -> [3, 5] anchor_scale = (1 if use_anchor_free_mode else", "\"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, }", "if freeze_backbone: backbone.trainable = False else: backbone.trainable = True inputs", "pool_sizes=(5, 9, 13), activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn =", "name=name + \"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out, obj_out], axis=-1) else: return", "hidden_channels, kernel_size=1, activation=activation, name=name + \"deep_\") for id in range(depth):", "cls_out = keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"class_out\")(cls_nn)", "pool_sizes] nn = tf.concat([nn, *pp], axis=-1) nn = conv_dw_pw_block(nn, input_channels,", "conv_dw_pw_block(inputs, out_channels, activation=activation, name=name + \"stem_\") # cls_convs, cls_preds cls_nn", "name=name + \"c3p3_\") # pan_out1: [32, 32, 512] pan_out1 =", "kernel_size=1, activation=activation, name=name + \"short_\") deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1,", "activation=\"swish\", pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"),", "batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\") kernel_size, strides =", "# print(f\">>>> upsample_merge inputs: {[ii.shape for ii in inputs] =", "p4 ─> f_out0 ─> fpn_out1 ─> pan_out1 # ↓ ↑", "nn = csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation, name=name)", "\"cls_2_\") cls_out = keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name +", "32, 256], pan_out2: [64, 64, 256] fpn_out1, pan_out2 = upsample_merge([f_out0,", "depthes = [base_depth, base_depth * 3, base_depth * 3, base_depth]", "nn def csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"):", "model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None,", "inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right = inputs[:, fdf8:f53e:61e4::18, 1::2] patch_bottom_left =", "+ \"1_\") nn = conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation,", "\"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"},", "{\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet backbone \"\"\" BATCH_NORM_EPSILON = 1e-3", "base_channels * 4, base_channels * 8, base_channels * 16] use_spps", "out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels = inputs.shape[-1] if", "= [ii.output for ii in features] width_mul = width_mul if", "downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n3_\") # pan_out0:", "[32, 32, 512], p5: [16, 16, 1024] # fpn_out0: [16,", "in range(depth): block_name = name + \"block{}_\".format(id + 1) deep", "kernel_size=1, activation=activation, name=name + \"2_\") return nn def focus_stem(inputs, filters,", "name=name + \"short_\") deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name", "fpn_out, nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>>", "prediction. anchor_scale=\"auto\", # Init anchors for model prediction. \"auto\" means", "if width_mul > 0 else min([ii.shape[-1] for ii in features])", "nn = focus_stem(inputs, base_channels, activation=activation, name=\"stem_\") features = [nn] \"\"\"", "name=\"\"): if padding.lower() == \"same\": # Handling odd input_shape inputs", "use_spp, use_shortcut) in enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name = \"stack{}_\".format(id", "\"deep_\") for id in range(depth): block_name = name + \"block{}_\".format(id", "use_shortcuts)): stack_name = \"stack{}_\".format(id + 1) nn = conv_dw_pw_block(nn, channel,", "= conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1, activation=activation, name=name + \"1_\")", "expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): out_channels = inputs.shape[-1] if out_channels", "# For decode predictions, raw means input value in range", "name=\"\"): # print(f\">>>> upsample_merge inputs: {[ii.shape for ii in inputs]", "nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn def", "pretrained) # AA = {\"aspect_ratios\": anchor_aspect_ratios, \"num_scales\": anchor_num_scales, \"anchor_scale\": anchor_scale,", "csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"): input_channels = inputs.shape[-1] nn", "name=name + \"down_\") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn,", "inputs: {[ii.shape for ii in inputs] = }\") inputs[0] =", "{\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\": {\"coco\": \"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\":", "* 16] use_spps = [False, False, False, True] use_shortcuts =", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3n4_\") return [pan_out2, pan_out1, pan_out0] \"\"\"", "return nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # p5", "num_anchors = (1 if use_anchor_free_mode else 9) if num_anchors ==", "def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # p5 ─> fpn_out0", "-1 else out_channels hidden_channels = int(out_channels * expansion) short =", "model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT", "PRETRAINED_DICT = { \"yolox_nano\": {\"coco\": \"7c97d60d4cc9d54321176f844acee627\"}, \"yolox_tiny\": {\"coco\": \"f9b51ff24290090c86a10a45f811140b\"}, \"yolox_s\":", "width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop(\"model_name\", \"yolox_nano\"), **kwargs) def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False,", "if backbone is None: width_mul = width_mul if width_mul >", "patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, ::2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2]", "kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn = inputs if use_depthwise_conv:", "inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name + \"up\")(fpn_out) inputs[0] =", "= conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"2_\")", "False, True] use_shortcuts = [True, True, True, False] for id,", ":-1:2] patch_top_right = inputs[:, :-1:2, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5,", "as tf from tensorflow import keras from keras_cv_attention_models.attention_layers import (", "use_anchor_free_mode else 4 rescale_mode=\"raw\", # For decode predictions, raw means", "\"auto\" else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores)", "+ \"object_out\")(reg_nn) obj_out = activation_by_name(obj_out, \"sigmoid\", name=name + \"object_out_\") obj_out", "keras.layers.Activation(\"linear\", dtype=\"float32\", name=\"outputs_fp32\")(outputs) model = keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT,", "= activation_by_name(obj_out, \"sigmoid\", name=name + \"object_out_\") obj_out = keras.layers.Reshape([-1, 1],", "csp_depth, target_channel, 0.5, False, use_depthwise_conv, activation=activation, name=name) return fpn_out, nn", "return model def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\",", "filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"): nn = inputs if", "add_pre_post_process, ) from keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights", "1) out = yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation,", "patch_top_left = inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right = inputs[:, fdf8:f53e:61e4::18, 1::2]", "tf.pad(inputs, [[0, 0], [0, 1], [0, 1], [0, 0]]) patch_top_left", "predictions, raw means input value in range [0, 255]. kwargs=None,", "import keras from keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias,", ":-1:2, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right = inputs[:,", "outputs \"\"\" YOLOX models \"\"\" def YOLOX( backbone=None, features_pick=[-3, -2,", "keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func import", "\"class_out_\") cls_out = keras.layers.Reshape([-1, num_classes], name=name + \"class_out_reshape\")(cls_out) # reg_convs,", "= 1e-3 BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1,", "= inputs.shape[-1] if out_channels == -1 else out_channels hidden_channels =", "strides = 1, 1 nn = conv2d_no_bias(nn, filters, kernel_size, strides,", "base_depth] channels = [base_channels * 2, base_channels * 4, base_channels", "use_object_scores=\"auto\", # \"auto\" means same with use_anchor_free_mode input_shape=(640, 640, 3),", "-> [3, 5] anchor_scale = (1 if use_anchor_free_mode else 4)", "[0, 1], [0, 1], [0, 0]]) patch_top_left = inputs[:, :-1:2,", "f_out0 = upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"c3p4_\")", "input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation,", "activation=activation, name=name) return nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\", name=\"\"):", "= keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name + \"regression_out\")(reg_nn) reg_out =", "name=\"\"): bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy()) # stem", "hidden_channels, kernel_size=1, activation=activation, name=name + \"short_\") deep = conv_dw_pw_block(inputs, hidden_channels,", "ii in features]) / 256` for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True,", "activation=activation, name=name + \"1_\") nn = conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1,", "import tensorflow as tf from tensorflow import keras from keras_cv_attention_models.attention_layers", "fc00:db20:35b:7399::5, ::2] patch_bottom_right = inputs[:, fc00:db20:35b:7399::5, 1::2] nn = tf.concat([patch_top_left,", "features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1, # -1 means: `min([ii.shape[-1] for", "**kwargs) def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\",", "use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3,", "hidden_channels = int(out_channels * expansion) short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1,", "# outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in outputs], axis=1)", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"2_\") if use_shortcut: nn = keras.layers.Add()([inputs,", "tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size,", "name=name + \"output_\") return out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13),", "\"c3p4_\") # fpn_out1: [32, 32, 256], pan_out2: [64, 64, 256]", "ii in inputs] = }\") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3,", "features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for id", "model = keras.models.Model(inputs, nn, name=model_name) return model \"\"\" path aggregation", "1], [0, 1], [0, 0]]) patch_top_left = inputs[:, :-1:2, :-1:2]", "1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out = tf.concat([deep, short], axis=-1)", "obj_out = keras.layers.Reshape([-1, 1], name=name + \"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out,", "Handling odd input_shape inputs = tf.pad(inputs, [[0, 0], [0, 1],", "target_channel, 0.5, False, use_depthwise_conv, activation=activation, name=name) return fpn_out, nn def", "spatial_pyramid_pooling(nn, activation=activation, name=stack_name + \"spp_\") # nn = SPPBottleneck(base_channels *", "epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + \"dw_\") kernel_size, strides = 1, 1", "name=name) return nn def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation=\"swish\", name=\"\"):", "use_anchor_free_mode else 9 use_object_scores=\"auto\", # \"auto\" means same with use_anchor_free_mode", "= conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"cls_1_\") cls_nn", "\"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"}, } \"\"\" CSPDarknet backbone", "activation=activation, name=name + \"fpn_\") # inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\",", "for ii in outputs], axis=1) outputs = tf.concat(outputs, axis=1) return", "else: return tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1,", "( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models import", "activation=activation, name=name + \"c3n3_\") # pan_out0: [16, 16, 1024] pan_out0", "True, False] for id, (channel, depth, use_spp, use_shortcut) in enumerate(zip(channels,", "if use_anchor_free_mode else 9) if num_anchors == \"auto\" else num_anchors", "3), num_classes=80, activation=\"swish\", freeze_backbone=False, pretrained=None, model_name=\"yolox\", pyramid_levels_min=3, # Init anchors", "else: patch_top_left = inputs[:, fdf8:f53e:61e4::18, ::2] patch_top_right = inputs[:, fdf8:f53e:61e4::18,", "keras.layers.Reshape([-1, 4], name=name + \"regression_out_reshape\")(reg_out) # obj_preds if use_object_scores: obj_out", "= [base_depth, base_depth * 3, base_depth * 3, base_depth] channels", "padding=\"SAME\")(nn) for ii in pool_sizes] nn = tf.concat([nn, *pp], axis=-1)", "= yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=\"head_\") outputs", "* num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + \"object_out\")(reg_nn) obj_out = activation_by_name(obj_out,", "\"a989f5a808ddc4a8242157a6a3e64977\"}, \"yolox_m\": {\"coco\": \"5c2333d2f12b2f48e3ec8555b29d242f\"}, \"yolox_l\": {\"coco\": \"a07c48994b7a67dba421025ef39b858b\"}, \"yolox_x\": {\"coco\": \"de9741d3f67f50c54856bcae0f07b7ef\"},", "\"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding=\"SAME\")(nn) for ii in pool_sizes]", "return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def YOLOXX(input_shape=(640, 640,", "out_channels, activation=activation, name=name + \"stem_\") # cls_convs, cls_preds cls_nn =", "out_channels hidden_channels = int(out_channels * expansion) short = conv_dw_pw_block(inputs, hidden_channels,", "512, 3), activation=\"swish\", model_name=\"\"): base_channels, base_depth = int(width_mul * 64),", "tf.shape(inputs[-1])[1:-1], method=\"nearest\") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth,", "reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name", "depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512, 512, 3), activation=\"swish\", model_name=\"\"):", "CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512, 512, 3), activation=\"swish\",", "pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop(\"model_name\", \"yolox_l\"), **kwargs) def", "cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation=\"swish\",", "input_shape, activation=activation, model_name=\"darknet\") features = backbone.outputs else: if isinstance(features_pick[0], str):", "fpn \"\"\" def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation=\"swish\", name=\"\"): # print(f\">>>>", "[] for id, input in enumerate(inputs): cur_name = name +", "\"auto\" means same with use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80, activation=\"swish\",", "enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name = \"stack{}_\".format(id + 1) nn", "use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + \"reg_1_\") reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3,", "model def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\",", "def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs):", "axis=-1) nn = csp_stack(nn, csp_depth, target_channel, 0.5, False, use_depthwise_conv, activation=activation,", "tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, target_channel, 0.5, False, use_depthwise_conv,", "for id in range(depth): block_name = name + \"block{}_\".format(id +", "keras.layers.Reshape([-1, 1], name=name + \"object_out_reshape\")(obj_out) return tf.concat([reg_out, cls_out, obj_out], axis=-1)", "recieving parameter ): if backbone is None: width_mul = width_mul", "in features_pick] print(\">>>> features:\", {ii.name: ii.output_shape for ii in features})", "name=stack_name) features.append(nn) nn = [features[ii] for ii in out_features] model", "means same with use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80, activation=\"swish\", freeze_backbone=False,", "pretrained=\"coco\", **kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop(\"model_name\", \"yolox_m\"), **kwargs) def", "features = [features[id] for id in features_pick] print(\">>>> features:\", {ii.name:", "+ \"fpn_\") # inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation=\"nearest\", name=name +", "bias_initializer=bias_init, name=name + \"class_out\")(cls_nn) cls_out = activation_by_name(cls_out, \"sigmoid\", name=name +", "axis=-1) nn = conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name + \"2_\")", "YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation=\"swish\", pretrained=\"coco\", **kwargs): return", "2, kernel_size=1, activation=activation, name=name + \"1_\") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1,", "else: backbone.trainable = True inputs = backbone.inputs[0] use_object_scores = use_anchor_free_mode", "use_depthwise_conv, activation=activation, name=name) return nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation=\"swish\",", "return nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512,", "int(input_channels * expansion), activation=activation, name=name + \"1_\") nn = conv_dw_pw_block(nn,", "conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name + \"fpn_\") # inputs[0] = keras.layers.UpSampling2D(size=(2,", "= conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name + \"output_\") return out", "= inputs[:, :-1:2, 1::2] patch_bottom_left = inputs[:, fc00:db20:35b:7399::5, :-1:2] patch_bottom_right", "inputs] = }\") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv,", "keras.models.Model(inputs, nn, name=model_name) return model \"\"\" path aggregation fpn \"\"\"", "nn]) return nn def csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False," ]
[ "[ { \"loc\": (\"data\", \"name\"), \"msg\": \"field required\", \"type\": \"value_error.missing\",", "\"field required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"quantity\"), \"msg\":", "\"id\": \"123\", }, } with raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert", "obj_to_validate = { \"data\": {\"id\": \"123\"}, \"links\": None, } my_response_object", "[ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\",", "\"price\": 1.2, \"quantity\": 10, }, { \"id\": \"3\", \"name\": \"orange\",", "\"apple\", \"quantity\": 10, \"price\": 1.20}, } my_response_obj = ItemResponse(**obj_to_validate) assert", "\"2\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, }, { \"id\":", "\"links\": None, \"data\": [ { \"id\": \"123\", \"name\": \"apple\", \"quantity\":", "None] items = [ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\",", "1.20}, } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\":", "def test_attributes_as_dict() -> None: MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate =", "with raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert e.value.errors() == [ {", "as e: ItemResponse(**obj_to_validate) assert e.value.errors() == [ { \"loc\": (\"data\",", "def test_attributes_as_item_model() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate =", "def test_response_constructed_with_resource_object() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] item =", "name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2,", "1.5, \"quantity\": 3, }, { \"id\": \"2\", \"name\": \"pear\", \"price\":", "pytest import raises from pydantic import ValidationError from robot_server.service.json_api.response import", "= ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10) data", "= { \"data\": {\"id\": \"123\"}, \"links\": None, } my_response_object =", "\"apple\", \"quantity\": 10, \"price\": 1.20, }, { \"id\": \"321\", \"name\":", "}, } def test_attributes_as_item_model() -> None: ItemResponse = ResponseModel[ItemResponseModel, None]", "\"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, } my_response_obj =", "\"price\": 1.20}, } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == {", "price=1.2, quantity=10) data = item.dict() assert ItemResponse(data=data, links=None).dict() == {", "== [ { \"loc\": (\"data\", \"name\"), \"msg\": \"field required\", \"type\":", "\"price\": 2.34}, ], } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() ==", "\"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, }, { \"id\": \"321\",", "{ \"id\": \"123\", }, } with raises(ValidationError) as e: ItemResponse(**obj_to_validate)", "-> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\":", "\"links\": None, \"data\": { \"id\": \"123\", }, } with raises(ValidationError)", "ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5), ] response", "\"name\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\",", "assert my_response_object.dict() == { \"links\": None, \"data\": { \"id\": \"123\",", "MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate = { \"data\": {\"id\": \"123\"},", "10, \"price\": 1.20}, } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() ==", "} my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\": None,", "\"quantity\": 10, \"price\": 1.20, }, { \"id\": \"321\", \"name\": \"banana\",", "None] item = ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10) data = item.dict()", "= [ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10),", "}, { \"id\": \"3\", \"name\": \"orange\", \"price\": 2.2, \"quantity\": 5,", "{ \"links\": None, \"data\": {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10,", "\"abc123\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, }, } def", "[ { \"id\": \"1\", \"name\": \"apple\", \"price\": 1.5, \"quantity\": 3,", "= ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\": {\"id\":", "required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"price\"), \"msg\": \"field", "my_response_obj.dict() == { \"links\": None, \"data\": { \"id\": \"123\", \"name\":", "} def test_list_item_model() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate", "\"field required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"price\"), \"msg\":", "\"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, }, } def test_list_item_model()", "from tests.service.helpers import ItemResponseModel def test_attributes_as_dict() -> None: MyResponse =", "<filename>robot-server/tests/service/json_api/test_response.py from pytest import raises from pydantic import ValidationError from", "1.20, }, { \"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\":", "\"loc\": (\"data\", \"quantity\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, {", "required\", \"type\": \"value_error.missing\", }, ] def test_response_constructed_with_resource_object() -> None: ItemResponse", "{ \"id\": \"2\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, },", "{ \"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34, },", "\"data\": [ { \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\":", "{ \"links\": None, \"data\": { \"id\": \"123\", }, } with", "= ResponseModel[ResponseDataModel, None] obj_to_validate = { \"data\": {\"id\": \"123\"}, \"links\":", "1.2, \"quantity\": 10, }, { \"id\": \"3\", \"name\": \"orange\", \"price\":", "20, \"price\": 2.34}, ], } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict()", "\"id\": \"1\", \"name\": \"apple\", \"price\": 1.5, \"quantity\": 3, }, {", "assert my_response_obj.dict() == { \"links\": None, \"data\": [ { \"id\":", "\"quantity\": 3, }, { \"id\": \"2\", \"name\": \"pear\", \"price\": 1.2,", "\"apple\", \"price\": 1.5, \"quantity\": 3, }, { \"id\": \"2\", \"name\":", "1.2, \"quantity\": 10, }, } def test_response_constructed_with_resource_object_list() -> None: ItemResponse", "item.dict() assert ItemResponse(data=data, links=None).dict() == { \"links\": None, \"data\": {", "None, \"data\": {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20},", "-> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] items = [ ItemResponseModel(id=\"1\",", "\"id\": \"3\", \"name\": \"orange\", \"price\": 2.2, \"quantity\": 5, }, ],", "\"price\": 1.20, }, } def test_list_item_model() -> None: ItemResponse =", "\"data\": { \"id\": \"123\", }, } with raises(ValidationError) as e:", "\"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, {\"id\": \"321\", \"name\":", "MultiResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\": [ {\"id\":", "}, } with raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert e.value.errors() ==", "ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\":", "None: MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate = { \"data\": {\"id\":", "quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5), ] response = ItemResponse(data=items, links=None)", "from robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel, MultiResponseModel, ) from tests.service.helpers", "}, { \"id\": \"2\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10,", "assert ItemResponse(data=data, links=None).dict() == { \"links\": None, \"data\": { \"id\":", "{ \"links\": None, \"data\": [ {\"id\": \"123\", \"name\": \"apple\", \"quantity\":", "\"quantity\": 10, }, } def test_response_constructed_with_resource_object_list() -> None: ItemResponse =", "\"price\": 1.5, \"quantity\": 3, }, { \"id\": \"2\", \"name\": \"pear\",", "\"links\": None, \"data\": { \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10,", "None: ItemResponse = ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2,", "{\"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34}, ], }", "ItemResponse(data=data, links=None).dict() == { \"links\": None, \"data\": { \"id\": \"abc123\",", "10, }, { \"id\": \"3\", \"name\": \"orange\", \"price\": 2.2, \"quantity\":", "\"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34, }, ], }", "\"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, }, } def", "{ \"id\": \"123\", }, } def test_attributes_as_item_model() -> None: ItemResponse", "\"field required\", \"type\": \"value_error.missing\", }, ] def test_response_constructed_with_resource_object() -> None:", "\"name\": \"banana\", \"quantity\": 20, \"price\": 2.34}, ], } my_response_obj =", "\"msg\": \"field required\", \"type\": \"value_error.missing\", }, ] def test_response_constructed_with_resource_object() ->", "ItemResponse(data=items, links=None) assert response.dict() == { \"links\": None, \"data\": [", "None, \"data\": [ { \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10,", "\"pear\", \"price\": 1.2, \"quantity\": 10, }, } def test_response_constructed_with_resource_object_list() ->", "= ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\": {", "required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"quantity\"), \"msg\": \"field", "ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5), ] response = ItemResponse(data=items, links=None) assert", "-> None: MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate = { \"data\":", "e: ItemResponse(**obj_to_validate) assert e.value.errors() == [ { \"loc\": (\"data\", \"name\"),", "} def test_response_constructed_with_resource_object_list() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] items", "None] obj_to_validate = { \"links\": None, \"data\": [ {\"id\": \"123\",", "name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5), ] response =", "\"links\": None, \"data\": [ {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10,", "None] obj_to_validate = { \"data\": {\"id\": \"123\"}, \"links\": None, }", "ItemResponse = ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10)", "\"value_error.missing\", }, ] def test_response_constructed_with_resource_object() -> None: ItemResponse = ResponseModel[ItemResponseModel,", "None, \"data\": [ {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\":", "} def test_attributes_as_item_model() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate", "ResponseDataModel, ResponseModel, MultiResponseModel, ) from tests.service.helpers import ItemResponseModel def test_attributes_as_dict()", "== { \"links\": None, \"data\": { \"id\": \"abc123\", \"name\": \"pear\",", "= ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\": None, \"data\": [", "\"data\": {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, }", "= { \"links\": None, \"data\": [ {\"id\": \"123\", \"name\": \"apple\",", "], } def test_attributes_as_item_model_empty_dict() -> None: ItemResponse = ResponseModel[ItemResponseModel, None]", "[ {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, {\"id\":", "(\"data\", \"quantity\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, { \"loc\":", "\"msg\": \"field required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"price\"),", "2.34}, ], } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == {", "None, \"data\": { \"id\": \"123\", }, } with raises(ValidationError) as", "my_response_obj.dict() == { \"links\": None, \"data\": [ { \"id\": \"123\",", "{ \"loc\": (\"data\", \"price\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", },", "\"quantity\": 10, }, { \"id\": \"3\", \"name\": \"orange\", \"price\": 2.2,", "def test_attributes_as_item_model_empty_dict() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate =", "ItemResponse = MultiResponseModel[ItemResponseModel, None] items = [ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5,", "\"id\": \"2\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, }, {", "\"type\": \"value_error.missing\", }, ] def test_response_constructed_with_resource_object() -> None: ItemResponse =", "\"banana\", \"quantity\": 20, \"price\": 2.34}, ], } my_response_obj = ItemResponse(**obj_to_validate)", "{ \"id\": \"abc123\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, },", "\"msg\": \"field required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"quantity\"),", "\"name\": \"banana\", \"quantity\": 20, \"price\": 2.34, }, ], } def", "raises from pydantic import ValidationError from robot_server.service.json_api.response import ( ResponseDataModel,", "None: ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None,", "10, }, } def test_response_constructed_with_resource_object_list() -> None: ItemResponse = MultiResponseModel[ItemResponseModel,", "\"quantity\": 20, \"price\": 2.34}, ], } my_response_obj = ItemResponse(**obj_to_validate) assert", "ResponseModel[ResponseDataModel, None] obj_to_validate = { \"data\": {\"id\": \"123\"}, \"links\": None,", "== { \"links\": None, \"data\": { \"id\": \"123\", }, }", "{ \"id\": \"1\", \"name\": \"apple\", \"price\": 1.5, \"quantity\": 3, },", "}, ], } def test_attributes_as_item_model_empty_dict() -> None: ItemResponse = ResponseModel[ItemResponseModel,", "links=None) assert response.dict() == { \"links\": None, \"data\": [ {", "{ \"links\": None, \"data\": { \"id\": \"123\", }, } def", "\"id\": \"123\", }, } def test_attributes_as_item_model() -> None: ItemResponse =", "== { \"links\": None, \"data\": [ { \"id\": \"1\", \"name\":", "None] obj_to_validate = { \"links\": None, \"data\": {\"id\": \"123\", \"name\":", "\"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, } my_response_obj = ItemResponse(**obj_to_validate)", "\"data\": [ { \"id\": \"1\", \"name\": \"apple\", \"price\": 1.5, \"quantity\":", "my_response_object.dict() == { \"links\": None, \"data\": { \"id\": \"123\", },", "\"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, {\"id\": \"321\", \"name\": \"banana\",", "( ResponseDataModel, ResponseModel, MultiResponseModel, ) from tests.service.helpers import ItemResponseModel def", "== { \"links\": None, \"data\": { \"id\": \"123\", \"name\": \"apple\",", "10, \"price\": 1.20, }, } def test_list_item_model() -> None: ItemResponse", "links=None).dict() == { \"links\": None, \"data\": { \"id\": \"abc123\", \"name\":", "quantity=10) data = item.dict() assert ItemResponse(data=data, links=None).dict() == { \"links\":", "def test_response_constructed_with_resource_object_list() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] items =", "= ItemResponse(data=items, links=None) assert response.dict() == { \"links\": None, \"data\":", "ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\": {\"id\": \"123\",", "= ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10) data = item.dict() assert ItemResponse(data=data,", "} def test_attributes_as_item_model_empty_dict() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate", "ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10) data =", "\"links\": None, \"data\": [ { \"id\": \"1\", \"name\": \"apple\", \"price\":", "2.34, }, ], } def test_attributes_as_item_model_empty_dict() -> None: ItemResponse =", "MultiResponseModel[ItemResponseModel, None] items = [ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\",", "== { \"links\": None, \"data\": [ { \"id\": \"123\", \"name\":", "\"123\"}, \"links\": None, } my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict() ==", "\"quantity\": 20, \"price\": 2.34, }, ], } def test_attributes_as_item_model_empty_dict() ->", "\"price\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, ] def test_response_constructed_with_resource_object()", "= ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\": None, \"data\": {", "name=\"pear\", price=1.2, quantity=10) data = item.dict() assert ItemResponse(data=data, links=None).dict() ==", "ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\":", "assert response.dict() == { \"links\": None, \"data\": [ { \"id\":", "{ \"data\": {\"id\": \"123\"}, \"links\": None, } my_response_object = MyResponse(**obj_to_validate)", "ResponseModel, MultiResponseModel, ) from tests.service.helpers import ItemResponseModel def test_attributes_as_dict() ->", "ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\",", "assert my_response_obj.dict() == { \"links\": None, \"data\": { \"id\": \"123\",", "ItemResponse(**obj_to_validate) assert e.value.errors() == [ { \"loc\": (\"data\", \"name\"), \"msg\":", "[ { \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20,", "quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5), ]", "ValidationError from robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel, MultiResponseModel, ) from", ") from tests.service.helpers import ItemResponseModel def test_attributes_as_dict() -> None: MyResponse", "= { \"links\": None, \"data\": {\"id\": \"123\", \"name\": \"apple\", \"quantity\":", "10, \"price\": 1.20}, {\"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\":", "}, } def test_list_item_model() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None]", "response.dict() == { \"links\": None, \"data\": [ { \"id\": \"1\",", "}, { \"loc\": (\"data\", \"quantity\"), \"msg\": \"field required\", \"type\": \"value_error.missing\",", "\"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"price\"), \"msg\": \"field required\",", "e.value.errors() == [ { \"loc\": (\"data\", \"name\"), \"msg\": \"field required\",", "import ItemResponseModel def test_attributes_as_dict() -> None: MyResponse = ResponseModel[ResponseDataModel, None]", "from pytest import raises from pydantic import ValidationError from robot_server.service.json_api.response", "\"quantity\": 10, \"price\": 1.20}, {\"id\": \"321\", \"name\": \"banana\", \"quantity\": 20,", "] response = ItemResponse(data=items, links=None) assert response.dict() == { \"links\":", "from pydantic import ValidationError from robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel,", "\"price\": 1.20}, {\"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34},", "\"value_error.missing\", }, { \"loc\": (\"data\", \"quantity\"), \"msg\": \"field required\", \"type\":", "\"1\", \"name\": \"apple\", \"price\": 1.5, \"quantity\": 3, }, { \"id\":", "\"data\": { \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20,", "\"value_error.missing\", }, { \"loc\": (\"data\", \"price\"), \"msg\": \"field required\", \"type\":", "None, \"data\": { \"id\": \"abc123\", \"name\": \"pear\", \"price\": 1.2, \"quantity\":", "None, \"data\": { \"id\": \"123\", }, } def test_attributes_as_item_model() ->", "data = item.dict() assert ItemResponse(data=data, links=None).dict() == { \"links\": None,", "{ \"links\": None, \"data\": { \"id\": \"abc123\", \"name\": \"pear\", \"price\":", "name=\"orange\", price=2.2, quantity=5), ] response = ItemResponse(data=items, links=None) assert response.dict()", "= { \"links\": None, \"data\": { \"id\": \"123\", }, }", "\"data\": { \"id\": \"123\", }, } def test_attributes_as_item_model() -> None:", "\"123\", }, } with raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert e.value.errors()", "\"quantity\": 10, \"price\": 1.20}, } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict()", "my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\": None, \"data\":", "robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel, MultiResponseModel, ) from tests.service.helpers import", "{ \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, },", "None: ItemResponse = MultiResponseModel[ItemResponseModel, None] items = [ ItemResponseModel(id=\"1\", name=\"apple\",", "-> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\":", "\"banana\", \"quantity\": 20, \"price\": 2.34, }, ], } def test_attributes_as_item_model_empty_dict()", "None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None,", "import ValidationError from robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel, MultiResponseModel, )", "\"apple\", \"quantity\": 10, \"price\": 1.20, }, } def test_list_item_model() ->", "obj_to_validate = { \"links\": None, \"data\": [ {\"id\": \"123\", \"name\":", "\"123\", }, } def test_attributes_as_item_model() -> None: ItemResponse = ResponseModel[ItemResponseModel,", "item = ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10) data = item.dict() assert", "\"type\": \"value_error.missing\", }, { \"loc\": (\"data\", \"quantity\"), \"msg\": \"field required\",", "20, \"price\": 2.34, }, ], } def test_attributes_as_item_model_empty_dict() -> None:", "\"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, }, { \"id\":", "{ \"links\": None, \"data\": [ { \"id\": \"123\", \"name\": \"apple\",", "\"quantity\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, { \"loc\": (\"data\",", "test_response_constructed_with_resource_object_list() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] items = [", "import ( ResponseDataModel, ResponseModel, MultiResponseModel, ) from tests.service.helpers import ItemResponseModel", "\"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, }, { \"id\": \"3\",", "None, } my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict() == { \"links\":", "\"price\": 1.2, \"quantity\": 10, }, } def test_response_constructed_with_resource_object_list() -> None:", "-> None: ItemResponse = ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id=\"abc123\", name=\"pear\",", "(\"data\", \"price\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, ] def", "{ \"links\": None, \"data\": [ { \"id\": \"1\", \"name\": \"apple\",", "], } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\":", "obj_to_validate = { \"links\": None, \"data\": { \"id\": \"123\", },", "{\"id\": \"123\"}, \"links\": None, } my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict()", "test_attributes_as_item_model() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = {", "obj_to_validate = { \"links\": None, \"data\": {\"id\": \"123\", \"name\": \"apple\",", "{ \"links\": None, \"data\": { \"id\": \"123\", \"name\": \"apple\", \"quantity\":", "ItemResponseModel(id=\"abc123\", name=\"pear\", price=1.2, quantity=10) data = item.dict() assert ItemResponse(data=data, links=None).dict()", "None] obj_to_validate = { \"links\": None, \"data\": { \"id\": \"123\",", "\"price\": 2.34, }, ], } def test_attributes_as_item_model_empty_dict() -> None: ItemResponse", "{\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, {\"id\": \"321\",", "= item.dict() assert ItemResponse(data=data, links=None).dict() == { \"links\": None, \"data\":", "= MultiResponseModel[ItemResponseModel, None] items = [ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3),", "MyResponse(**obj_to_validate) assert my_response_object.dict() == { \"links\": None, \"data\": { \"id\":", "price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5),", "}, { \"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34,", "\"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, }, } def test_response_constructed_with_resource_object_list()", "} my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict() == { \"links\": None,", "test_response_constructed_with_resource_object() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id=\"abc123\",", "\"data\": {\"id\": \"123\"}, \"links\": None, } my_response_object = MyResponse(**obj_to_validate) assert", "{ \"loc\": (\"data\", \"quantity\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", },", "1.20, }, } def test_list_item_model() -> None: ItemResponse = MultiResponseModel[ItemResponseModel,", "\"links\": None, \"data\": { \"id\": \"123\", }, } def test_attributes_as_item_model()", "\"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34}, ], } my_response_obj", "(\"data\", \"name\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, { \"loc\":", "{ \"id\": \"3\", \"name\": \"orange\", \"price\": 2.2, \"quantity\": 5, },", "tests.service.helpers import ItemResponseModel def test_attributes_as_dict() -> None: MyResponse = ResponseModel[ResponseDataModel,", "10, \"price\": 1.20, }, { \"id\": \"321\", \"name\": \"banana\", \"quantity\":", "\"quantity\": 10, \"price\": 1.20, }, } def test_list_item_model() -> None:", "}, ] def test_response_constructed_with_resource_object() -> None: ItemResponse = ResponseModel[ItemResponseModel, None]", "test_attributes_as_item_model_empty_dict() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = {", "assert e.value.errors() == [ { \"loc\": (\"data\", \"name\"), \"msg\": \"field", "{\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}, } my_response_obj", "raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert e.value.errors() == [ { \"loc\":", "test_list_item_model() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate = {", "None, \"data\": { \"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\":", "= MultiResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\": [", "MultiResponseModel, ) from tests.service.helpers import ItemResponseModel def test_attributes_as_dict() -> None:", "ItemResponseModel def test_attributes_as_dict() -> None: MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate", "\"loc\": (\"data\", \"name\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, {", "\"3\", \"name\": \"orange\", \"price\": 2.2, \"quantity\": 5, }, ], }", "ResponseModel[ItemResponseModel, None] obj_to_validate = { \"links\": None, \"data\": { \"id\":", "\"name\": \"apple\", \"price\": 1.5, \"quantity\": 3, }, { \"id\": \"2\",", "ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\": None, \"data\": [ {", "price=2.2, quantity=5), ] response = ItemResponse(data=items, links=None) assert response.dict() ==", "\"links\": None, } my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict() == {", "items = [ ItemResponseModel(id=\"1\", name=\"apple\", price=1.5, quantity=3), ItemResponseModel(id=\"2\", name=\"pear\", price=1.2,", "test_attributes_as_dict() -> None: MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate = {", "\"apple\", \"quantity\": 10, \"price\": 1.20}, {\"id\": \"321\", \"name\": \"banana\", \"quantity\":", "\"loc\": (\"data\", \"price\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", }, ]", "}, { \"loc\": (\"data\", \"price\"), \"msg\": \"field required\", \"type\": \"value_error.missing\",", "\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, }, {", "import raises from pydantic import ValidationError from robot_server.service.json_api.response import (", "} with raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert e.value.errors() == [", "\"links\": None, \"data\": { \"id\": \"abc123\", \"name\": \"pear\", \"price\": 1.2,", "\"id\": \"abc123\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10, }, }", "{ \"loc\": (\"data\", \"name\"), \"msg\": \"field required\", \"type\": \"value_error.missing\", },", "1.20}, {\"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34}, ],", "price=1.2, quantity=10), ItemResponseModel(id=\"3\", name=\"orange\", price=2.2, quantity=5), ] response = ItemResponse(data=items,", "\"data\": { \"id\": \"abc123\", \"name\": \"pear\", \"price\": 1.2, \"quantity\": 10,", "quantity=5), ] response = ItemResponse(data=items, links=None) assert response.dict() == {", "None, \"data\": [ { \"id\": \"1\", \"name\": \"apple\", \"price\": 1.5,", "pydantic import ValidationError from robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel, MultiResponseModel,", "}, } def test_response_constructed_with_resource_object_list() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None]", "\"id\": \"321\", \"name\": \"banana\", \"quantity\": 20, \"price\": 2.34, }, ],", "= MyResponse(**obj_to_validate) assert my_response_object.dict() == { \"links\": None, \"data\": {", "def test_list_item_model() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate =", "\"price\": 1.20, }, { \"id\": \"321\", \"name\": \"banana\", \"quantity\": 20,", "] def test_response_constructed_with_resource_object() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] item", "\"pear\", \"price\": 1.2, \"quantity\": 10, }, { \"id\": \"3\", \"name\":", "\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20, }, }", "my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict() == { \"links\": None, \"data\":", "ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { \"links\": None, \"data\": { \"id\":", "3, }, { \"id\": \"2\", \"name\": \"pear\", \"price\": 1.2, \"quantity\":", "\"links\": None, \"data\": {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\":", "response = ItemResponse(data=items, links=None) assert response.dict() == { \"links\": None,", "\"data\": [ {\"id\": \"123\", \"name\": \"apple\", \"quantity\": 10, \"price\": 1.20}," ]
[ "from game.menu_view import menu_view from game import constants import arcade", "game import constants import arcade SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT =", "arcade SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE", "GameView from game.menu_view import menu_view from game import constants import", "game.game_view import GameView from game.menu_view import menu_view from game import", "from game import constants import arcade SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT", "constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) start_view = menu_view() window.show_view(start_view)", "import menu_view from game import constants import arcade SCREEN_WIDTH =", "SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT,", "constants import arcade SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE", "game.menu_view import menu_view from game import constants import arcade SCREEN_WIDTH", "SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE window", "import constants import arcade SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT", "= constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)", "menu_view from game import constants import arcade SCREEN_WIDTH = constants.SCREEN_WIDTH", "constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH,", "from game.game_view import GameView from game.menu_view import menu_view from game", "import arcade SCREEN_WIDTH = constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE =", "= constants.SCREEN_WIDTH SCREEN_HEIGHT = constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE window =", "constants.SCREEN_HEIGHT SCREEN_TITLE = constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) start_view", "import GameView from game.menu_view import menu_view from game import constants", "= constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) start_view = menu_view()", "window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) start_view = menu_view() window.show_view(start_view) arcade.run()", "<filename>stickmanZ/__main__.py from game.game_view import GameView from game.menu_view import menu_view from", "SCREEN_TITLE = constants.SCREEN_TITLE window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) start_view =" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "Date: 2015-11-25 18:45:03.831359 \"\"\" # revision identifiers, used by Alembic.", "may obtain # a copy of the License at #", "# # Licensed under the Apache License, Version 2.0 (the", "nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) # A simple model of the", "agreed to in writing, software # distributed under the License", "fields needed for # the migration. qos_policy = sa.Table('qos_policies', sa.MetaData(),", "rbac_db_models \"\"\"rbac_qos_policy Revision ID: c6c112992c9 Revises: <PASSWORD> Create Date: 2015-11-25", "Unless required by applicable law or agreed to in writing,", "qos_policies table with only the fields needed for # the", "= 'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(),", "sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) #", "distributed under the License is distributed on an \"AS IS\"", "op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def get_values(): session = sa.orm.Session(bind=op.get_bind()) values", "\"\"\"rbac_qos_policy Revision ID: c6c112992c9 Revises: <PASSWORD> Create Date: 2015-11-25 18:45:03.831359", "depends_on = ('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36),", "oslo_utils import uuidutils import sqlalchemy as sa from neutron.db import", "sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id',", "sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies',", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "obtain # a copy of the License at # #", "applicable law or agreed to in writing, software # distributed", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "'object_id': row[0], 'tenant_id': row[1], 'target_tenant': '*', 'action': rbac_db_models.ACCESS_SHARED}) session.commit() return", "ID: c6c112992c9 Revises: <PASSWORD> Create Date: 2015-11-25 18:45:03.831359 \"\"\" #", "Version 2.0 (the \"License\"); you may # not use this", "\"\"\" # revision identifiers, used by Alembic. revision = 'c6c112992c9'", "specific language governing permissions and limitations # under the License.", "sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def", "('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id',", "sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def get_values():", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "identifiers, used by Alembic. revision = 'c6c112992c9' down_revision = 'e3278ee65050'", "permissions and limitations # under the License. # from alembic", "Revision ID: c6c112992c9 Revises: <PASSWORD> Create Date: 2015-11-25 18:45:03.831359 \"\"\"", "of the qos_policies table with only the fields needed for", "alembic import op from oslo_utils import uuidutils import sqlalchemy as", "sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) # A simple model", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "OpenStack Foundation # # Licensed under the Apache License, Version", "in writing, software # distributed under the License is distributed", "sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) # A", "session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1], 'target_tenant': '*', 'action':", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "needed for # the migration. qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id',", "uuidutils import sqlalchemy as sa from neutron.db import rbac_db_models \"\"\"rbac_qos_policy", "def get_values(): session = sa.orm.Session(bind=op.get_bind()) values = [] for row", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "sa from neutron.db import rbac_db_models \"\"\"rbac_qos_policy Revision ID: c6c112992c9 Revises:", "You may obtain # a copy of the License at", "table with only the fields needed for # the migration.", "<PASSWORD> Create Date: 2015-11-25 18:45:03.831359 \"\"\" # revision identifiers, used", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= ('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False),", "from neutron.db import rbac_db_models \"\"\"rbac_qos_policy Revision ID: c6c112992c9 Revises: <PASSWORD>", "values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1], 'target_tenant': '*', 'action': rbac_db_models.ACCESS_SHARED})", "= sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(),", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant',", "A simple model of the qos_policies table with only the", "c6c112992c9 Revises: <PASSWORD> Create Date: 2015-11-25 18:45:03.831359 \"\"\" # revision", "sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) # A simple model of", "Copyright 2015 OpenStack Foundation # # Licensed under the Apache", "either express or implied. See the # License for the", "# Copyright 2015 OpenStack Foundation # # Licensed under the", "import op from oslo_utils import uuidutils import sqlalchemy as sa", "the License. # from alembic import op from oslo_utils import", "import sqlalchemy as sa from neutron.db import rbac_db_models \"\"\"rbac_qos_policy Revision", "under the License is distributed on an \"AS IS\" BASIS,", "only the fields needed for # the migration. qos_policy =", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "= 'c6c112992c9' down_revision = 'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs =", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "op from oslo_utils import uuidutils import sqlalchemy as sa from", "'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255),", "you may # not use this file except in compliance", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "the migration. qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id',", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "[] for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id':", "# A simple model of the qos_policies table with only", "compliance with the License. You may obtain # a copy", "sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs,", "'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id',", "the fields needed for # the migration. qos_policy = sa.Table('qos_policies',", "the Apache License, Version 2.0 (the \"License\"); you may #", "in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1], 'target_tenant': '*',", "Revises: <PASSWORD> Create Date: 2015-11-25 18:45:03.831359 \"\"\" # revision identifiers,", "row[0], 'tenant_id': row[1], 'target_tenant': '*', 'action': rbac_db_models.ACCESS_SHARED}) session.commit() return values", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "values = [] for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id':", "language governing permissions and limitations # under the License. #", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "2015-11-25 18:45:03.831359 \"\"\" # revision identifiers, used by Alembic. revision", "with only the fields needed for # the migration. qos_policy", "See the # License for the specific language governing permissions", "= sa.orm.Session(bind=op.get_bind()) values = [] for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id':", "import uuidutils import sqlalchemy as sa from neutron.db import rbac_db_models", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255),", "the # License for the specific language governing permissions and", "upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def get_values(): session = sa.orm.Session(bind=op.get_bind())", "migration. qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)),", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared')", "from alembic import op from oslo_utils import uuidutils import sqlalchemy", "'shared') def get_values(): session = sa.orm.Session(bind=op.get_bind()) values = [] for", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "simple model of the qos_policies table with only the fields", "get_values(): session = sa.orm.Session(bind=op.get_bind()) values = [] for row in", "nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False))", "file except in compliance with the License. You may obtain", "used by Alembic. revision = 'c6c112992c9' down_revision = 'e3278ee65050' depends_on", "down_revision = 'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs',", "= [] for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0],", "for the specific language governing permissions and limitations # under", "sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False),", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "the qos_policies table with only the fields needed for #", "nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False),", "as sa from neutron.db import rbac_db_models \"\"\"rbac_qos_policy Revision ID: c6c112992c9", "session = sa.orm.Session(bind=op.get_bind()) values = [] for row in session.query(qos_policy).filter(qos_policy.c.shared).all():", "governing permissions and limitations # under the License. # from", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "limitations # under the License. # from alembic import op", "sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255),", "Create Date: 2015-11-25 18:45:03.831359 \"\"\" # revision identifiers, used by", "for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1],", "License. You may obtain # a copy of the License", "sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action',", "<gh_stars>1000+ # Copyright 2015 OpenStack Foundation # # Licensed under", "sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def", "get_values()) op.drop_column('qos_policies', 'shared') def get_values(): session = sa.orm.Session(bind=op.get_bind()) values =", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "import rbac_db_models \"\"\"rbac_qos_policy Revision ID: c6c112992c9 Revises: <PASSWORD> Create Date:", "18:45:03.831359 \"\"\" # revision identifiers, used by Alembic. revision =", "# Unless required by applicable law or agreed to in", "sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade():", "def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def get_values(): session =", "nullable=False)) # A simple model of the qos_policies table with", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "model of the qos_policies table with only the fields needed", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "# revision identifiers, used by Alembic. revision = 'c6c112992c9' down_revision", "revision = 'c6c112992c9' down_revision = 'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs", "revision identifiers, used by Alembic. revision = 'c6c112992c9' down_revision =", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "Alembic. revision = 'c6c112992c9' down_revision = 'e3278ee65050' depends_on = ('15e43b934f81',)", "2015 OpenStack Foundation # # Licensed under the Apache License,", "row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1], 'target_tenant':", "# the migration. qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False),", "uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1], 'target_tenant': '*', 'action': rbac_db_models.ACCESS_SHARED}) session.commit()", "or agreed to in writing, software # distributed under the", "qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared',", "nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) # A simple", "'c6c112992c9' down_revision = 'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs = sa.Table(", "sa.Column('object_id', sa.String(length=36), nullable=False)) # A simple model of the qos_policies", "required by applicable law or agreed to in writing, software", "# from alembic import op from oslo_utils import uuidutils import", "from oslo_utils import uuidutils import sqlalchemy as sa from neutron.db", "sa.String(length=36), nullable=False)) # A simple model of the qos_policies table", "nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def get_values(): session", "sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36),", "neutron.db import rbac_db_models \"\"\"rbac_qos_policy Revision ID: c6c112992c9 Revises: <PASSWORD> Create", "Foundation # # Licensed under the Apache License, Version 2.0", "and limitations # under the License. # from alembic import", "= sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True),", "nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values())", "for # the migration. qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36),", "under the License. # from alembic import op from oslo_utils", "sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False))", "sa.orm.Session(bind=op.get_bind()) values = [] for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(),", "License. # from alembic import op from oslo_utils import uuidutils", "by Alembic. revision = 'c6c112992c9' down_revision = 'e3278ee65050' depends_on =", "op.drop_column('qos_policies', 'shared') def get_values(): session = sa.orm.Session(bind=op.get_bind()) values = []", "sqlalchemy as sa from neutron.db import rbac_db_models \"\"\"rbac_qos_policy Revision ID:", "# under the License. # from alembic import op from", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "will block indefinitely, # unless an exception is encountered first.", "an exception is encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() #", "encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown.", "except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() # Block", "None: print(f\"Received {message}.\") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for", "# Wrap subscriber in a 'with' block to automatically call", "# unless an exception is encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError:", "= subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f\"Received {message}.\")", "fully qualified identifier # in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path =", "timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() # The `subscription_path` method", "subscription_id = \"test-sub\" # Number of seconds the subscriber should", "subscriber in a 'with' block to automatically call close() when", "streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() #", "call close() when done. with subscriber: try: # When `timeout`", "pubsub_v1.SubscriberClient() # The `subscription_path` method creates a fully qualified identifier", "messages on {subscription_path}..\\n\") # Wrap subscriber in a 'with' block", "qualified identifier # in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id,", "# in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id) def", "\"pubsub-testing-331300\" subscription_id = \"test-sub\" # Number of seconds the subscriber", "on {subscription_path}..\\n\") # Wrap subscriber in a 'with' block to", "callback=callback) print(f\"Listening for messages on {subscription_path}..\\n\") # Wrap subscriber in", "`timeout` is not set, result() will block indefinitely, # unless", "# Trigger the shutdown. streaming_pull_future.result() # Block until the shutdown", "# When `timeout` is not set, result() will block indefinitely,", "close() when done. with subscriber: try: # When `timeout` is", "Trigger the shutdown. streaming_pull_future.result() # Block until the shutdown is", "TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() # Block until", "{subscription_path}..\\n\") # Wrap subscriber in a 'with' block to automatically", "is not set, result() will block indefinitely, # unless an", "is encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() # Trigger the", "streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() # Block until the", "subscriber = pubsub_v1.SubscriberClient() # The `subscription_path` method creates a fully", "from google.cloud import pubsub_v1 project_id = \"pubsub-testing-331300\" subscription_id = \"test-sub\"", "def callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f\"Received {message}.\") message.ack() streaming_pull_future =", "from concurrent.futures import TimeoutError from google.cloud import pubsub_v1 project_id =", "creates a fully qualified identifier # in the form `projects/{project_id}/subscriptions/{subscription_id}`", "result() will block indefinitely, # unless an exception is encountered", "pubsub_v1 project_id = \"pubsub-testing-331300\" subscription_id = \"test-sub\" # Number of", "The `subscription_path` method creates a fully qualified identifier # in", "block to automatically call close() when done. with subscriber: try:", "-> None: print(f\"Received {message}.\") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening", "streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for messages on {subscription_path}..\\n\") #", "to automatically call close() when done. with subscriber: try: #", "import pubsub_v1 project_id = \"pubsub-testing-331300\" subscription_id = \"test-sub\" # Number", "= subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for messages on {subscription_path}..\\n\") # Wrap", "subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for messages on {subscription_path}..\\n\") # Wrap subscriber", "concurrent.futures import TimeoutError from google.cloud import pubsub_v1 project_id = \"pubsub-testing-331300\"", "set, result() will block indefinitely, # unless an exception is", "with subscriber: try: # When `timeout` is not set, result()", "= pubsub_v1.SubscriberClient() # The `subscription_path` method creates a fully qualified", "TimeoutError from google.cloud import pubsub_v1 project_id = \"pubsub-testing-331300\" subscription_id =", "pubsub_v1.subscriber.message.Message) -> None: print(f\"Received {message}.\") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)", "for messages on {subscription_path}..\\n\") # Wrap subscriber in a 'with'", "a fully qualified identifier # in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path", "Wrap subscriber in a 'with' block to automatically call close()", "of seconds the subscriber should listen for messages timeout =", "google.cloud import pubsub_v1 project_id = \"pubsub-testing-331300\" subscription_id = \"test-sub\" #", "the shutdown. streaming_pull_future.result() # Block until the shutdown is complete.", "the subscriber should listen for messages timeout = 5.0 subscriber", "subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f\"Received", "print(f\"Listening for messages on {subscription_path}..\\n\") # Wrap subscriber in a", "done. with subscriber: try: # When `timeout` is not set,", "for messages timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() # The", "Number of seconds the subscriber should listen for messages timeout", "method creates a fully qualified identifier # in the form", "'with' block to automatically call close() when done. with subscriber:", "exception is encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() # Trigger", "callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f\"Received {message}.\") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path,", "# Number of seconds the subscriber should listen for messages", "# The `subscription_path` method creates a fully qualified identifier #", "= 5.0 subscriber = pubsub_v1.SubscriberClient() # The `subscription_path` method creates", "print(f\"Received {message}.\") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for messages", "`subscription_path` method creates a fully qualified identifier # in the", "in a 'with' block to automatically call close() when done.", "messages timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() # The `subscription_path`", "listen for messages timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() #", "identifier # in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id)", "subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f\"Received {message}.\") message.ack() streaming_pull_future", "5.0 subscriber = pubsub_v1.SubscriberClient() # The `subscription_path` method creates a", "\"test-sub\" # Number of seconds the subscriber should listen for", "form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) ->", "indefinitely, # unless an exception is encountered first. streaming_pull_future.result(timeout=timeout) except", "not set, result() will block indefinitely, # unless an exception", "when done. with subscriber: try: # When `timeout` is not", "in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message:", "unless an exception is encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel()", "= \"pubsub-testing-331300\" subscription_id = \"test-sub\" # Number of seconds the", "automatically call close() when done. with subscriber: try: # When", "`projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) -> None:", "first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result()", "import TimeoutError from google.cloud import pubsub_v1 project_id = \"pubsub-testing-331300\" subscription_id", "message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for messages on {subscription_path}..\\n\")", "the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message)", "try: # When `timeout` is not set, result() will block", "a 'with' block to automatically call close() when done. with", "When `timeout` is not set, result() will block indefinitely, #", "project_id = \"pubsub-testing-331300\" subscription_id = \"test-sub\" # Number of seconds", "= \"test-sub\" # Number of seconds the subscriber should listen", "subscriber should listen for messages timeout = 5.0 subscriber =", "seconds the subscriber should listen for messages timeout = 5.0", "{message}.\") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f\"Listening for messages on", "block indefinitely, # unless an exception is encountered first. streaming_pull_future.result(timeout=timeout)", "subscriber: try: # When `timeout` is not set, result() will", "subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f\"Received {message}.\") message.ack()", "should listen for messages timeout = 5.0 subscriber = pubsub_v1.SubscriberClient()" ]
[ "Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri", "res = super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return", "Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL to generate", "URL to generate the authorization code from Google\") is_google_drive_token_generated =", "config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL to generate the", "authorization_code) if authorization_code else False ) params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self):", "False ) params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard')", "and licensing details. from odoo import api, fields, models, _", "refresh_token) def action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name':", "= params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if authorization_code != authorization_code_before: refresh_token", "refresh token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views': [(template.id, 'form')], 'target':", "refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else False )", "self.google_drive_authorization_code if authorization_code != authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code)", "import api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\"", "= self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self): params =", "self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self):", "api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\" google_drive_authorization_code", "See LICENSE file for full copyright and licensing details. from", "scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri def get_values(self):", "utf-8 -*- # Part of Odoo. See LICENSE file for", "from Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self):", "False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before", "= fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL to generate the authorization code", "up refresh token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views': [(template.id, 'form')],", ") params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return", "Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for", "authorization_code = self.google_drive_authorization_code if authorization_code != authorization_code_before: refresh_token = (", "in self: config.google_drive_uri = google_drive_uri def get_values(self): res = super(ResConfigSettings,", "def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code =", "help=\"The URL to generate the authorization code from Google\") is_google_drive_token_generated", "is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri =", "models, _ class ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization", "fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL to", "config in self: config.google_drive_uri = google_drive_uri def get_values(self): res =", "= fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL", "# Part of Odoo. See LICENSE file for full copyright", "file for full copyright and licensing details. from odoo import", "details. from odoo import api, fields, models, _ class ResConfigSettings(models.TransientModel):", "-*- coding: utf-8 -*- # Part of Odoo. See LICENSE", "from odoo import api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit", "= self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set up refresh token'), 'type':", "'name': _('Set up refresh token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views':", "class ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code')", "# -*- coding: utf-8 -*- # Part of Odoo. See", "authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if authorization_code != authorization_code_before:", "for config in self: config.google_drive_uri = google_drive_uri def get_values(self): res", "-*- # Part of Odoo. See LICENSE file for full", "authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else False", "_compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri", "_ class ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization Code',", "string='URI', help=\"The URL to generate the authorization code from Google\")", "res def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code", "= ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else False ) params.set_param('google_drive_refresh_token',", "Odoo. See LICENSE file for full copyright and licensing details.", "_inherit = \"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri =", "authorization code from Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code')", "if authorization_code != authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if", "template = self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set up refresh token'),", "google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri =", "odoo import api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit =", "to generate the authorization code from Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh", "_('Set up refresh token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views': [(template.id,", "self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else False ) params.set_param('google_drive_refresh_token', refresh_token) def", "def get_values(self): res = super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False)", "of Odoo. See LICENSE file for full copyright and licensing", "def action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set", "return res def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code')", "get_values(self): res = super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token))", "fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope())", "for full copyright and licensing details. from odoo import api,", "params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if authorization_code != authorization_code_before: refresh_token =", "= super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res", "!= authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else", "LICENSE file for full copyright and licensing details. from odoo", "return { 'name': _('Set up refresh token'), 'type': 'ir.actions.act_window', 'res_model':", "if authorization_code else False ) params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one()", "fields, models, _ class ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\" google_drive_authorization_code =", "= fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive',", "else False ) params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one() template =", "authorization_code else False ) params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one() template", "self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set up refresh token'), 'type': 'ir.actions.act_window',", "confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code", "\"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI',", "self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set up refresh", "= \"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri',", "google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help=\"The", "fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL to generate the authorization code from", "token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views': [(template.id, 'form')], 'target': 'new',", "def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self:", "Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config", "refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self): params", "self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo()", "the authorization code from Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated')", "= self.google_drive_authorization_code if authorization_code != authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive',", "= self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if authorization_code", "full copyright and licensing details. from odoo import api, fields,", "self: config.google_drive_uri = google_drive_uri def get_values(self): res = super(ResConfigSettings, self).get_values()", "generate the authorization code from Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh Token", "{ 'name': _('Set up refresh token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings',", "params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return {", "@api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in", "self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri def", "coding: utf-8 -*- # Part of Odoo. See LICENSE file", "config.google_drive_uri = google_drive_uri def get_values(self): res = super(ResConfigSettings, self).get_values() refresh_token", "params = self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if", "authorization_code != authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code", "self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if authorization_code !=", "ResConfigSettings(models.TransientModel): _inherit = \"res.config.settings\" google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri", "Part of Odoo. See LICENSE file for full copyright and", "copyright and licensing details. from odoo import api, fields, models,", "google_drive_uri def get_values(self): res = super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token',", "super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def", "licensing details. from odoo import api, fields, models, _ class", "res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before =", "= self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri", "( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else False ) params.set_param('google_drive_refresh_token', refresh_token)", "code from Google\") is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def", "'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views': [(template.id, 'form')], 'target': 'new', }", "= google_drive_uri def get_values(self): res = super(ResConfigSettings, self).get_values() refresh_token =", "action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set up", "google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help=\"The URL to generate the authorization" ]
[ "= np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M) # z=upright assumption if", "return P class MyDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode=50000,", "= np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds] xyz = data[:, 0:3]", "support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\", "= pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config if dataset_name", "support_ptclouds, support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels,", "= np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds", "self.dataset = ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown dataset %s!' %", "index, n_way_classes=None): if n_way_classes is not None: sampled_classes = np.array(n_way_classes)", "contain target class valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0] # indices", "z=upright assumption if pc_augm_config['mirror_prob'] > 0: # mirroring x&y, not", "self.num_episode def __getitem__(self, index, n_way_classes=None): if n_way_classes is not None:", "pointclouds and the corresponding labels for one class (one_way)''' ptclouds", "task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks", "def __len__(self): return len(self.block_names) def __getitem__(self, index): block_name = self.block_names[index]", "N = data.shape[0] #number of points in this scan if", "'data', '%s.npy' %scan_name)) N = data.shape[0] #number of points in", "\\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\", "class valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0] # indices of points", "% episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind += 1 def __len__(self):", "[1, 0, 0]), M) if random.random() < pc_augm_config['mirror_prob'] / 2:", "n_way_classes is not None: sampled_classes = np.array(n_way_classes) else: sampled_classes =", "Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode", "= [] query_ptclouds = [] query_labels = [] black_list =", "task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch))", "M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M) if random.random() <", "all_scannames = [x for x in all_scannames if x not", "\\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64)", "ptclouds = [] labels = [] for scan_name in scan_names:", "random.uniform(0, 2 * math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle),", "labels = [] for scan_name in scan_names: ptcloud, label =", "k_shot, num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode (%s) is unknown!' %mode)", "mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path self.classes", "<NAME>, 2020 \"\"\" import os import random import math import", "torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################", "The number remaining classes is less than %d_way' %self.n_way) valid_support_ptclouds,", "/ pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] ==", "prevent sampling one scan several times... for sampled_class in sampled_classes:", "indices of points belonging to the sampled class if N", "x&y, not z if random.random() < pc_augm_config['mirror_prob'] / 2: M", "sampled_valid_point_num = len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point)", "__len__(self): return self.num_episode def __getitem__(self, index): file_name = self.file_names[index] return", "try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise NotImplementedError('Error! The", "points belonging to the sampled class if N < num_point:", "all_scannames = self.class2scans[sampled_class].copy() if len(black_list) != 0: all_scannames = [x", "support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks, axis=0)", "episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind += 1 def __len__(self): return", "== 'train' and self.phase == 'metatrain': remain_classes = list(set(self.classes) -", "= data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels =", "random_sample=False): sampled_classes = list(sampled_classes) data = np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name))", "task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks", "= [] support_masks = [] query_ptclouds = [] query_labels =", "num_episode self.phase = phase self.mode = mode self.num_point = num_point", "= np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds =", "query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds = [] support_masks", "pc_attribs: ptcloud.append(xyz) if 'rgb' in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in", "in black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames =", "num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path self.classes =", "#number of points in this scan if random_sample: sampled_point_inds =", "= data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds, query_labels,", "def __init__(self, data_path, classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None):", "return support_ptclouds, support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds,", "raise NotImplementedError('Mode is unknown!') print('[Pretrain Dataset] Mode: {0} | Num_blocks:", "in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud =", "dataset_name == 'scannet': from dataloaders.scannet import ScanNetDataset self.dataset = ScanNetDataset(cvfold,", "'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32')", "task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks),", "os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind += 1", "read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0]", "batch_sampled_classes = batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return", "= [] for sampled_classes in class_comb: sampled_classes = list(sampled_classes) for", "scan_names, sampled_class, sampled_classes, is_support=False): '''sample K pointclouds and the corresponding", "\\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32),", "x not in black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames)", "query_labels, sampled_classes = data data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds,", "pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path self.classes = classes", "= random.uniform(0, 2 * math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1],", "file_name = self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds,", "make sure that the sampled points contain target class valid_point_inds", "self.data_path = data_path self.n_way = n_way self.k_shot = k_shot self.n_queries", "<filename>dataloaders/loader.py \"\"\" Data Loader for Generating Tasks Author: <NAME>, 2020", "the sampled class if N < num_point: sampled_valid_point_num = len(valid_point_inds)", "axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels, axis=0) return", "from itertools import combinations import torch from torch.utils.data import Dataset", "black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way =", "is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames,", "= os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind +=", "than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\ valid_query_labels = self.generate_one_episode(sampled_valid_classes)", "= sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name, self.classes, random_sample=True) return", "n_test_blocks = int(n_blocks * 0.1) n_train_blocks = n_blocks - n_test_blocks", "Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes,", "support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds, axis=0) labels = np.stack(labels,", "N < num_point: sampled_valid_point_num = len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N)", "support: groundtruth = labels==sampled_class else: groundtruth = np.zeros_like(labels) for i,", "axis=0) return ptclouds, labels def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config,", "pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] == 1: angle", "dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64')", "sigma, clip = 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P", "# mirroring x&y, not z if random.random() < pc_augm_config['mirror_prob'] /", "self.phase = phase self.mode = mode self.num_point = num_point self.pc_attribs", "dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes", "query_labels, sampled_classes ################################################ Pre-train Dataset ################################################ class MyPretrainDataset(Dataset): def __init__(self,", "target class valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0] # indices of", "'metatrain': remain_classes = list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes),", "xyz_max = np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max ptcloud = []", "of points belonging to the sampled class if N <", "torch.utils.data import Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_names,", "S3DISDataset self.dataset = S3DISDataset(cvfold, data_path) elif dataset_name == 'scannet': from", "dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename, data)", "data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def", "data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\\t {0} saved! |", "else: raise NotImplementedError('Unkown mode %s! [Options: train/test]' % mode) print('MODE:", "data_file.close() print('\\t {0} saved! | classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name):", "import random import math import glob import numpy as np", "labels = data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0) xyz -= xyz_min", "= np.zeros_like(labels) for i, label in enumerate(labels): if label in", "pc_augm_config): \"\"\"\" Augmentation on XYZ and jittering of everything \"\"\"", "'s3dis': from dataloaders.s3dis import S3DISDataset self.dataset = S3DISDataset(cvfold, data_path) elif", "import transforms3d from itertools import combinations import torch from torch.utils.data", "= data[sampled_point_inds] xyz = data[:, 0:3] rgb = data[:, 3:6]", "{0} | Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self): return len(self.block_names) def", "= MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs,", "support_masks = data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes", "'train': self.block_names = list(set(train_block_names)) elif mode == 'test': self.block_names =", "n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode == 'train': self.block_names = list(set(train_block_names)) elif", "query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds,", "for support/query set, make sure that the sampled points contain", "torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################ Static Testing Dataset", "__getitem__(self, index): file_name = self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds,", "data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close()", "* 0.1) n_train_blocks = n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode", "self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config if dataset_name == 's3dis':", "[] query_labels = [] black_list = [] # to store", "pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes = list(sampled_classes)", "support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if self.mode == 'train' and", "torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################ Static", "pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M)", "exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way)) # [(),(),(),...]", "= xyz - xyz_min xyz_max = np.amax(XYZ, axis=0) XYZ =", "for sampled_classes in class_comb: sampled_classes = list(sampled_classes) for i in", "'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1) if support:", "* np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32) return P class MyDataset(Dataset):", "\\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds = []", "import ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown dataset", "% ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode", "M) # z=upright assumption if pc_augm_config['mirror_prob'] > 0: # mirroring", "'xyz' in pc_attribs: ptcloud.append(xyz) if 'rgb' in pc_attribs: ptcloud.append(rgb/255.) if", "pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1) if support: groundtruth =", "{1}'.format(mode, len(self.block_names))) def __len__(self): return len(self.block_names) def __getitem__(self, index): block_name", "# to store the sampled scan names, in order to", "xyz_min xyz_max = np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max ptcloud =", "the sampled points contain target class valid_point_inds = np.nonzero(data[:,6] ==", "* clip, clip).astype(np.float32) return P class MyDataset(Dataset): def __init__(self, data_path,", "0, 0]), M) if random.random() < pc_augm_config['mirror_prob'] / 2: M", "== 'train': self.classes = np.array(self.dataset.train_classes) elif mode == 'test': self.classes", "num_point, replace=(N < num_point)) else: # If this point cloud", "sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config):", "list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False) except:", "valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32),", "support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks, axis=0) query_ptclouds", "as np import h5py as h5 import transforms3d from itertools", "corresponding labels for one class (one_way)''' ptclouds = [] labels", "\"\"\" import os import random import math import glob import", "%test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode =", "sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds, axis=0) labels", "data = data[sampled_point_inds] xyz = data[:, 0:3] rgb = data[:,", "Dataset ################################################ class MyPretrainDataset(Dataset): def __init__(self, data_path, classes, class2scans, mode='train',", "mode == 'train': self.classes = np.array(self.dataset.train_classes) elif mode == 'test':", "data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\\t {0} saved! | classes: {1}'.format(out_filename,", "sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way)", "sure that the sampled points contain target class valid_point_inds =", "= len(self.file_names) else: print('Test dataset (%s) does not exist...\\n Constructing...'", "= h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds',", "= h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds", "'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) else: raise", "support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes = data data_file = h5.File(out_filename,", "on XYZ and jittering of everything \"\"\" M = transforms3d.zooms.zfdir2mat(1)", "batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks),", "else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds,", "__init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz',", "= data_path self.classes = classes self.num_point = num_point self.pc_attribs =", "else: raise NotImplementedError('Mode (%s) is unknown!' %mode) if os.path.exists(test_data_path): self.file_names", "data.shape[0] #number of points in this scan if random_sample: sampled_point_inds", "h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds =", "'test': self.block_names = list(set(all_block_names) - set(train_block_names)) else: raise NotImplementedError('Mode is", "import S3DISDataset self.dataset = S3DISDataset(cvfold, data_path) elif dataset_name == 'scannet':", "replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds] xyz =", "for i in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes) out_filename =", "'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot,", "k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name,", "sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N < num_point)) else: # If", "= np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch):", "def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds,", "int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num,", "pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path self.n_way = n_way self.k_shot =", "== 'metatrain': remain_classes = list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes =", "'%d.h5' % episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind += 1 def", "\\ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32),", "xyz_min = np.amin(xyz, axis=0) XYZ = xyz - xyz_min xyz_max", "query_scannames = selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path,", "unknown!') print('[Pretrain Dataset] Mode: {0} | Num_blocks: {1}'.format(mode, len(self.block_names))) def", "clip = 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P +", "valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32),", "for Generating Tasks Author: <NAME>, 2020 \"\"\" import os import", "i, label in enumerate(labels): if label in sampled_classes: groundtruth[i] =", "\\ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\", "np.stack(ptclouds, axis=0) labels = np.stack(labels, axis=0) return ptclouds, labels def", "data[sampled_point_inds] xyz = data[:, 0:3] rgb = data[:, 3:6] labels", "sampled_class)[0] # indices of points belonging to the sampled class", "for one class (one_way)''' ptclouds = [] labels = []", "'test': self.classes = np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode %s! [Options:", "= self.dataset.class2scans def __len__(self): return self.num_episode def __getitem__(self, index, n_way_classes=None):", "def __len__(self): return self.num_episode def __getitem__(self, index, n_way_classes=None): if n_way_classes", "support_masks, query_ptclouds, query_labels, sampled_classes = data data_file = h5.File(out_filename, 'w')", "= np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds,", "axis=0) labels = np.stack(labels, axis=0) return ptclouds, labels def sample_pointcloud(data_path,", "ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown dataset %s!' % dataset_name) if", "self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way", "np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds)", "list(set(train_block_names)) elif mode == 'test': self.block_names = list(set(all_block_names) - set(train_block_names))", "= np.dot(P[:, :3], M.T) if pc_augm_config['jitter']: sigma, clip = 0.01,", "and the corresponding labels for one class (one_way)''' ptclouds =", "random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N < num_point)) else: #", "ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1)", "sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if len(black_list) != 0: all_scannames =", "def write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes = data", "sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes = list(sampled_classes) data = np.load(os.path.join(data_path,", "support_ptclouds = [] support_masks = [] query_ptclouds = [] query_labels", "names, in order to prevent sampling one scan several times...", "0]), M) if random.random() < pc_augm_config['mirror_prob'] / 2: M =", "np.stack(labels, axis=0) return ptclouds, labels def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm,", "dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32')", "self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way =", "test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb,", "np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] == 1: angle = random.uniform(0, 2", "mirroring x&y, not z if random.random() < pc_augm_config['mirror_prob'] / 2:", "num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None):", "support_masks, query_ptclouds, query_labels, sampled_classes ################################################ Pre-train Dataset ################################################ class MyPretrainDataset(Dataset):", "= data.shape[0] #number of points in this scan if random_sample:", "0, 1], angle), M) # z=upright assumption if pc_augm_config['mirror_prob'] >", "everything \"\"\" M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1: s", "valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32),", "mode) print('MODE: {0} | Classes: {1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans", "order to prevent sampling one scan several times... for sampled_class", "self.generate_one_episode(sampled_classes) if self.mode == 'train' and self.phase == 'metatrain': remain_classes", "sampled_classes): support_ptclouds = [] support_masks = [] query_ptclouds = []", "label = sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class,", "'rgb' in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud", "np.amin(xyz, axis=0) xyz -= xyz_min if pc_augm: xyz = augment_pointcloud(xyz,", "= np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames =", "k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path", "!= 0: all_scannames = [x for x in all_scannames if", "sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds = [] support_masks = []", "pc_augm_config if dataset_name == 's3dis': from dataloaders.s3dis import S3DISDataset self.dataset", "if N < num_point: sampled_valid_point_num = len(valid_point_inds) else: valid_ratio =", "pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config train_block_names = []", "if n_way_classes is not None: sampled_classes = np.array(n_way_classes) else: sampled_classes", "= np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] == 1: angle = random.uniform(0,", "= data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return support_ptclouds,", "does not exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way))", "the corresponding labels for one class (one_way)''' ptclouds = []", "super(MyDataset).__init__() self.data_path = data_path self.n_way = n_way self.k_shot = k_shot", "P class MyDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3,", "NotImplementedError('Mode (%s) is unknown!' %mode) if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path,", "pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] == 1:", "\"\"\" Data Loader for Generating Tasks Author: <NAME>, 2020 \"\"\"", "xyz_min if pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in", "in enumerate(labels): if label in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return", "- xyz_min xyz_max = np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max ptcloud", "= phase self.mode = mode self.num_point = num_point self.pc_attribs =", "= list(set(train_block_names)) elif mode == 'test': self.block_names = list(set(all_block_names) -", "pc_augm self.pc_augm_config = pc_augm_config if dataset_name == 's3dis': from dataloaders.s3dis", "+ np.clip(sigma * np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32) return P", "return data ################################################ Static Testing Dataset ################################################ class MyTestDataset(Dataset): def", "unknown!' %mode) if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode =", "mode == 'train': self.block_names = list(set(train_block_names)) elif mode == 'test':", "that the sampled points contain target class valid_point_inds = np.nonzero(data[:,6]", "'XYZ' in pc_attribs: xyz_min = np.amin(xyz, axis=0) XYZ = xyz", "np.amin(xyz, axis=0) XYZ = xyz - xyz_min xyz_max = np.amax(XYZ,", "query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else:", "times... for sampled_class in sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if len(black_list)", "len(self.block_names) def __getitem__(self, index): block_name = self.block_names[index] ptcloud, label =", "/ 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M) if", "query_labels = [] black_list = [] # to store the", "black_list = [] # to store the sampled scan names,", "if pc_augm_config['mirror_prob'] > 0: # mirroring x&y, not z if", "sampled_class in sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if len(black_list) != 0:", "torch.from_numpy(task_valid_query_labels)] return data ################################################ Static Testing Dataset ################################################ class MyTestDataset(Dataset):", "= pc_augm_config if dataset_name == 's3dis': from dataloaders.s3dis import S3DISDataset", "itertools import combinations import torch from torch.utils.data import Dataset def", "= np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data =", "len(self.file_names) else: print('Test dataset (%s) does not exist...\\n Constructing...' %test_data_path)", "is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks", "data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes,", "import numpy as np import h5py as h5 import transforms3d", "os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) else:", "task_valid_query_labels = np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4),", "episode_ind = 0 self.file_names = [] for sampled_classes in class_comb:", "= list(set(all_block_names) - set(train_block_names)) else: raise NotImplementedError('Mode is unknown!') print('[Pretrain", "query_labels = np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks, query_ptclouds, query_labels def", "list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode = len(class_comb) * num_episode_per_comb episode_ind", "= sampled_classes.index(label)+1 return ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation", "in pc_attribs: xyz_min = np.amin(xyz, axis=0) XYZ = xyz -", "num_point)) else: # If this point cloud is for support/query", "enumerate(labels): if label in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return ptcloud,", "= num_episode self.phase = phase self.mode = mode self.num_point =", "the sampled scan names, in order to prevent sampling one", "/ 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M) P[:,", "Generating Tasks Author: <NAME>, 2020 \"\"\" import os import random", "ptcloud.append(xyz) if 'rgb' in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs:", "labels for one class (one_way)''' ptclouds = [] labels =", "= np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max ptcloud = [] if", "Dataset ################################################ class MyTestDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100,", "pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot,", "3:6] labels = data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0) xyz -=", "1 def __len__(self): return self.num_episode def __getitem__(self, index): file_name =", "pc_augm_config) if 'XYZ' in pc_attribs: xyz_min = np.amin(xyz, axis=0) XYZ", "saved! | classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file = h5.File(file_name,", "this point cloud is for support/query set, make sure that", "is for support/query set, make sure that the sampled points", "self.k_shot = k_shot self.n_queries = n_queries self.num_episode = num_episode self.phase", "\\ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds = [] support_masks =", "data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes ################################################ Pre-train Dataset", "n_way self.k_shot = k_shot self.n_queries = n_queries self.num_episode = num_episode", "support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes):", "k_shot self.n_queries = n_queries self.num_episode = num_episode self.phase = phase", "import combinations import torch from torch.utils.data import Dataset def sample_K_pointclouds(data_path,", "np.dot(P[:, :3], M.T) if pc_augm_config['jitter']: sigma, clip = 0.01, 0.05", "batch_query_labels, batch_sampled_classes = batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))]", "class if N < num_point: sampled_valid_point_num = len(valid_point_inds) else: valid_ratio", "dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\\t {0} saved! | classes:", "torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def write_episode(out_filename, data): support_ptclouds,", "not None: sampled_classes = np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes, self.n_way,", "\"\"\" M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1: s =", "label in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return ptcloud, groundtruth def", "If this point cloud is for support/query set, make sure", "support/query set, make sure that the sampled points contain target", "% ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) elif mode ==", "num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset =", "self.block_names = list(set(all_block_names) - set(train_block_names)) else: raise NotImplementedError('Mode is unknown!')", "sampled_classes.index(label)+1 return ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation on", "num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds] xyz", "S3DISDataset(cvfold, data_path) elif dataset_name == 'scannet': from dataloaders.scannet import ScanNetDataset", "sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config,", "n_train_blocks = n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode == 'train':", "in pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1) if support: groundtruth", "== sampled_class)[0] # indices of points belonging to the sampled", "np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3),", "return ptclouds, labels def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name,", "def augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation on XYZ and jittering of", "== 'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way,", "xyz -= xyz_min if pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config) if", "= np.amin(xyz, axis=0) XYZ = xyz - xyz_min xyz_max =", "self.class2scans = self.dataset.class2scans def __len__(self): return self.num_episode def __getitem__(self, index,", "torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def write_episode(out_filename, data): support_ptclouds, support_masks,", "[(),(),(),...] self.num_episode = len(class_comb) * num_episode_per_comb episode_ind = 0 self.file_names", "to store the sampled scan names, in order to prevent", "def generate_one_episode(self, sampled_classes): support_ptclouds = [] support_masks = [] query_ptclouds", "write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes = data data_file", "mode == 'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold,", "= int(n_blocks * 0.1) n_train_blocks = n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks])", "- n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode == 'train': self.block_names = list(set(train_block_names))", "################################################ Static Testing Dataset ################################################ class MyTestDataset(Dataset): def __init__(self, data_path,", "dataset (%s) does not exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb =", "class_comb = list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode = len(class_comb) *", "= n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode == 'train': self.block_names", "cvfold, n_way, k_shot, num_episode_per_comb, num_point)) elif mode == 'test': test_data_path", "self.classes = np.array(self.dataset.train_classes) elif mode == 'test': self.classes = np.array(self.dataset.test_classes)", "valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\", "sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud)", "for k, v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v) n_test_blocks", "== 'scannet': from dataloaders.scannet import ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path)", "= list(sampled_classes) for i in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes)", "= self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels,", "pc_augm_config['jitter']: sigma, clip = 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P =", "cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes =", "= os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point))", "self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name, self.classes, random_sample=True) return torch.from_numpy(ptcloud.transpose().astype(np.float32)), torch.from_numpy(label.astype(np.int64))", "2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M) if random.random()", "== 'test': self.classes = np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode %s!", "batch_sampled_classes def write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes =", "self.n_queries = n_queries self.num_episode = num_episode self.phase = phase self.mode", "M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] == 1: angle =", "M) if pc_augm_config['rot'] == 1: angle = random.uniform(0, 2 *", "= pc_augm self.pc_augm_config = pc_augm_config train_block_names = [] all_block_names =", "one class (one_way)''' ptclouds = [] labels = [] for", "test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb,", "glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names) else: print('Test dataset (%s) does", "np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode %s! [Options: train/test]' % mode)", "self.dataset.class2scans def __len__(self): return self.num_episode def __getitem__(self, index, n_way_classes=None): if", "selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames", "n_way_classes=None): if n_way_classes is not None: sampled_classes = np.array(n_way_classes) else:", "data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\\t", "classes self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm", "- set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise", "mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path self.n_way", "%self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32),", "= np.stack(labels, axis=0) return ptclouds, labels def sample_pointcloud(data_path, num_point, pc_attribs,", "remaining classes is less than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds,", "query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks,", "data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\\t {0} saved!", "2020 \"\"\" import os import random import math import glob", "for scan_name in scan_names: ptcloud, label = sample_pointcloud(data_path, num_point, pc_attribs,", "task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds", "data[:, 3:6] labels = data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0) xyz", "data_path self.n_way = n_way self.k_shot = k_shot self.n_queries = n_queries", "num_episode_per_comb episode_ind = 0 self.file_names = [] for sampled_classes in", "1: s = random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s),", "= int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N),", "0]), M) P[:, :3] = np.dot(P[:, :3], M.T) if pc_augm_config['jitter']:", "valid_support_masks, valid_query_ptclouds, \\ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32),", "else: groundtruth = np.zeros_like(labels) for i, label in enumerate(labels): if", "axis=1) if support: groundtruth = labels==sampled_class else: groundtruth = np.zeros_like(labels)", "support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks, axis=0) query_ptclouds =", "for i, label in enumerate(labels): if label in sampled_classes: groundtruth[i]", "return self.num_episode def __getitem__(self, index, n_way_classes=None): if n_way_classes is not", "support_masks = [] query_ptclouds = [] query_labels = [] black_list", "self.block_names = list(set(train_block_names)) elif mode == 'test': self.block_names = list(set(all_block_names)", "np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M) P[:, :3] = np.dot(P[:, :3],", "= [] black_list = [] # to store the sampled", "self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes", "np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds] xyz = data[:, 0:3] rgb", "XYZ = XYZ/xyz_max ptcloud = [] if 'xyz' in pc_attribs:", "axis=0) support_masks = np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels", "Pre-train Dataset ################################################ class MyPretrainDataset(Dataset): def __init__(self, data_path, classes, class2scans,", "if pc_augm_config['rot'] == 1: angle = random.uniform(0, 2 * math.pi)", "sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0)", "= len(v) n_test_blocks = int(n_blocks * 0.1) n_train_blocks = n_blocks", "< pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]),", "of points in this scan if random_sample: sampled_point_inds = np.random.choice(np.arange(N),", "generate_one_episode(self, sampled_classes): support_ptclouds = [] support_masks = [] query_ptclouds =", "np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels)", "num_point)) elif mode == 'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' %", "range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5' %", "in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return ptcloud, groundtruth def augment_pointcloud(P,", "1: angle = random.uniform(0, 2 * math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0,", "mode %s! [Options: train/test]' % mode) print('MODE: {0} | Classes:", "less than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\ valid_query_labels =", "task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds =", "query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if self.mode == 'train' and self.phase", "= np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels =", "'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:]", "assumption if pc_augm_config['mirror_prob'] > 0: # mirroring x&y, not z", "from torch.utils.data import Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config,", "| Classes: {1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans def __len__(self): return", "and self.phase == 'metatrain': remain_classes = list(set(self.classes) - set(sampled_classes)) try:", "support_ptclouds, support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if self.mode == 'train'", "################################################ class MyTestDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3,", "list(sampled_classes) for i in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes) out_filename", "pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds =", "in sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v) n_test_blocks = int(n_blocks *", "dataloaders.s3dis import S3DISDataset self.dataset = S3DISDataset(cvfold, data_path) elif dataset_name ==", "= pc_augm self.pc_augm_config = pc_augm_config if dataset_name == 's3dis': from", "if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names) else:", "== 'test': self.block_names = list(set(all_block_names) - set(train_block_names)) else: raise NotImplementedError('Mode", "https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P + np.clip(sigma * np.random.randn(*P.shape), -1 *", "[torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def write_episode(out_filename, data):", "import h5py as h5 import transforms3d from itertools import combinations", "return len(self.block_names) def __getitem__(self, index): block_name = self.block_names[index] ptcloud, label", "raise NotImplementedError('Unknown dataset %s!' % dataset_name) if mode == 'train':", "os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names) else: print('Test", "pc_attribs: xyz_min = np.amin(xyz, axis=0) XYZ = xyz - xyz_min", "support=False, random_sample=False): sampled_classes = list(sampled_classes) data = np.load(os.path.join(data_path, 'data', '%s.npy'", "num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label)", "return ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation on XYZ", "set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise NotImplementedError('Error!", "dtype='int32') data_file.close() print('\\t {0} saved! | classes: {1}'.format(out_filename, sampled_classes)) def", "sampled_classes = list(sampled_classes) for i in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind,", "np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels, axis=0)", "from dataloaders.s3dis import S3DISDataset self.dataset = S3DISDataset(cvfold, data_path) elif dataset_name", "jittering of everything \"\"\" M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] >", "= random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if", "= np.concatenate(ptcloud, axis=1) if support: groundtruth = labels==sampled_class else: groundtruth", "self.phase == 'metatrain': remain_classes = list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes", "sampled_classes = np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels =", "data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096,", "np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M) if random.random() < pc_augm_config['mirror_prob'] /", "dataset.classes if mode == 'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' %", "XYZ and jittering of everything \"\"\" M = transforms3d.zooms.zfdir2mat(1) if", "= self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64),", "\\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds)", "pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path self.n_way = n_way self.k_shot", "np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds]", "= S3DISDataset(cvfold, data_path) elif dataset_name == 'scannet': from dataloaders.scannet import", "data = dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5' % episode_ind)", "data) self.file_names.append(out_filename) episode_ind += 1 def __len__(self): return self.num_episode def", "query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels, axis=0) return support_ptclouds,", "to the sampled class if N < num_point: sampled_valid_point_num =", "sampled_classes = list(sampled_classes) data = np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N", "data, batch_sampled_classes def write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes", "ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1) if support: groundtruth = labels==sampled_class", "in class_comb: sampled_classes = list(sampled_classes) for i in range(num_episode_per_comb): data", "class MyTestDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5,", "several times... for sampled_class in sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if", "len(class_comb) * num_episode_per_comb episode_ind = 0 self.file_names = [] for", "self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config if", "points in this scan if random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point,", "= data[:, 3:6] labels = data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0)", "sampled_class=0, support=False, random_sample=False): sampled_classes = list(sampled_classes) data = np.load(os.path.join(data_path, 'data',", "sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename)", "sampled_classes = data data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32')", "numpy as np import h5py as h5 import transforms3d from", "selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs,", "data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:]", "sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False):", "task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data", "NotImplementedError('Unknown dataset %s!' % dataset_name) if mode == 'train': self.classes", "n_blocks = len(v) n_test_blocks = int(n_blocks * 0.1) n_train_blocks =", "np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds,", "if len(black_list) != 0: all_scannames = [x for x in", "data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels',", "h5 import transforms3d from itertools import combinations import torch from", "< num_point: sampled_valid_point_num = len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num", "M.T) if pc_augm_config['jitter']: sigma, clip = 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74", "np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32) return P class MyDataset(Dataset): def", "elif mode == 'test': self.classes = np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown", "valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\", "query_ptclouds = [] query_labels = [] black_list = [] #", "k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes if", "(%s) is unknown!' %mode) if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5'))", "################################################ class MyPretrainDataset(Dataset): def __init__(self, data_path, classes, class2scans, mode='train', num_point=4096,", "pc_augm_config train_block_names = [] all_block_names = [] for k, v", "[] all_block_names = [] for k, v in sorted(class2scans.items()): all_block_names.extend(v)", "= k_shot self.n_queries = n_queries self.num_episode = num_episode self.phase =", "dataset_name) if mode == 'train': self.classes = np.array(self.dataset.train_classes) elif mode", "black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries]", "def __len__(self): return self.num_episode def __getitem__(self, index): file_name = self.file_names[index]", "angle = random.uniform(0, 2 * math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0,", "0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P + np.clip(sigma *", "support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm,", "pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes if mode == 'valid': test_data_path", "= [] for k, v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks =", "Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self): return len(self.block_names) def __getitem__(self, index):", "belonging to the sampled class if N < num_point: sampled_valid_point_num", "one scan several times... for sampled_class in sampled_classes: all_scannames =", "[] for k, v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v)", "n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name, cvfold=cvfold,", "| Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self): return len(self.block_names) def __getitem__(self,", "= np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks,", "and jittering of everything \"\"\" M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale']", "is not None: sampled_classes = np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes,", "'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot,", "not in black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames", "n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes if mode", "def __getitem__(self, index): block_name = self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path,", "random import math import glob import numpy as np import", "to prevent sampling one scan several times... for sampled_class in", "# If this point cloud is for support/query set, make", "class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path", "set(train_block_names)) else: raise NotImplementedError('Mode is unknown!') print('[Pretrain Dataset] Mode: {0}", "ptcloud, label = sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes,", "except: raise NotImplementedError('Error! The number remaining classes is less than", "n_queries self.num_episode = num_episode self.phase = phase self.mode = mode", "= np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks,", "support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\", "sampled_class, sampled_classes, is_support=False): '''sample K pointclouds and the corresponding labels", "== 1: angle = random.uniform(0, 2 * math.pi) M =", "[] labels = [] for scan_name in scan_names: ptcloud, label", "if 'xyz' in pc_attribs: ptcloud.append(xyz) if 'rgb' in pc_attribs: ptcloud.append(rgb/255.)", "labels.append(label) ptclouds = np.stack(ptclouds, axis=0) labels = np.stack(labels, axis=0) return", "points contain target class valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0] #", "classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file = h5.File(file_name, 'r') support_ptclouds", "M) P[:, :3] = np.dot(P[:, :3], M.T) if pc_augm_config['jitter']: sigma,", "\\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds", "data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return support_ptclouds, support_masks,", "Author: <NAME>, 2020 \"\"\" import os import random import math", "= list(sampled_classes) data = np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N =", "M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1: s = random.uniform(1", "= [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def write_episode(out_filename,", "v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v) n_test_blocks = int(n_blocks", "self.num_episode = len(class_comb) * num_episode_per_comb episode_ind = 0 self.file_names =", "num_point: sampled_valid_point_num = len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num =", "import math import glob import numpy as np import h5py", "ptclouds = np.stack(ptclouds, axis=0) labels = np.stack(labels, axis=0) return ptclouds,", "self.mode == 'train' and self.phase == 'metatrain': remain_classes = list(set(self.classes)", "data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels,", "num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes if mode == 'valid':", "query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\", "\"\"\"\" Augmentation on XYZ and jittering of everything \"\"\" M", "else: raise NotImplementedError('Unknown dataset %s!' % dataset_name) if mode ==", "= np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode %s! [Options: train/test]' %", "pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M)", "pc_augm=False) self.classes = dataset.classes if mode == 'valid': test_data_path =", "(%s) does not exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes,", "cloud is for support/query set, make sure that the sampled", "self.num_episode = len(self.file_names) else: print('Test dataset (%s) does not exist...\\n", "[] # to store the sampled scan names, in order", "all_block_names = [] for k, v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks", "torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################ Static Testing Dataset ################################################", "sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point))", "all_block_names.extend(v) n_blocks = len(v) n_test_blocks = int(n_blocks * 0.1) n_train_blocks", "+= 1 def __len__(self): return self.num_episode def __getitem__(self, index): file_name", "P + np.clip(sigma * np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32) return", "labels==sampled_class else: groundtruth = np.zeros_like(labels) for i, label in enumerate(labels):", "= list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode = len(class_comb) * num_episode_per_comb", "data_path, classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path", "axis=0) XYZ = XYZ/xyz_max ptcloud = [] if 'xyz' in", "pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path self.classes = classes self.num_point", "[] for scan_name in scan_names: ptcloud, label = sample_pointcloud(data_path, num_point,", "np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N = data.shape[0] #number of points", "n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path =", "= sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True)", "pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False): '''sample K pointclouds and", "cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False,", "as h5 import transforms3d from itertools import combinations import torch", "= np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M) P[:, :3] = np.dot(P[:,", "= data[:, 0:3] rgb = data[:, 3:6] labels = data[:,6].astype(np.int)", "query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks =", "k_shot, num_episode_per_comb, num_point)) elif mode == 'test': test_data_path = os.path.join(data_path,", "all_scannames if x not in black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries,", "dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\\t {0}", "= np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes)", "ptcloud = [] if 'xyz' in pc_attribs: ptcloud.append(xyz) if 'rgb'", "Dataset] Mode: {0} | Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self): return", "NotImplementedError('Error! The number remaining classes is less than %d_way' %self.n_way)", "self.classes = dataset.classes if mode == 'valid': test_data_path = os.path.join(data_path,", "class_comb: sampled_classes = list(sampled_classes) for i in range(num_episode_per_comb): data =", "index): block_name = self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs,", "else: # If this point cloud is for support/query set,", "transforms3d from itertools import combinations import torch from torch.utils.data import", "\\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32),", "h5py as h5 import transforms3d from itertools import combinations import", "num_episode_per_comb, num_point)) elif mode == 'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d'", "= pc_augm_config train_block_names = [] all_block_names = [] for k,", "self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name,", "labels = np.stack(labels, axis=0) return ptclouds, labels def sample_pointcloud(data_path, num_point,", "len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds =", "= augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in pc_attribs: xyz_min = np.amin(xyz,", "batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3),", "dataset_name == 's3dis': from dataloaders.s3dis import S3DISDataset self.dataset = S3DISDataset(cvfold,", "def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0] data", "label in enumerate(labels): if label in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1", "pc_augm self.pc_augm_config = pc_augm_config train_block_names = [] all_block_names = []", "< pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]),", "np.random.choice(np.arange(N), num_point, replace=(N < num_point)) else: # If this point", "is unknown!' %mode) if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode", "np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds,", "torch from torch.utils.data import Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm,", "angle), M) # z=upright assumption if pc_augm_config['mirror_prob'] > 0: #", ":3], M.T) if pc_augm_config['jitter']: sigma, clip = 0.01, 0.05 #", "P[:, :3] = np.dot(P[:, :3], M.T) if pc_augm_config['jitter']: sigma, clip", "scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds, axis=0)", "np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0)", "n_way)) # [(),(),(),...] self.num_episode = len(class_comb) * num_episode_per_comb episode_ind =", "raise NotImplementedError('Mode (%s) is unknown!' %mode) if os.path.exists(test_data_path): self.file_names =", "label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name, self.classes, random_sample=True)", "= np.random.choice(np.arange(N), num_point, replace=(N < num_point)) else: # If this", "| classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file = h5.File(file_name, 'r')", "in order to prevent sampling one scan several times... for", "= dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename,", "support_masks = np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels =", "data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32')", "self.data_path = data_path self.classes = classes self.num_point = num_point self.pc_attribs", "z if random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1,", "train/test]' % mode) print('MODE: {0} | Classes: {1}'.format(mode, self.classes)) self.class2scans", "len(black_list) != 0: all_scannames = [x for x in all_scannames", "batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels", "mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes if mode ==", "= data data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks',", "pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path self.classes = classes self.num_point =", "data_path) elif dataset_name == 'scannet': from dataloaders.scannet import ScanNetDataset self.dataset", "NotImplementedError('Unkown mode %s! [Options: train/test]' % mode) print('MODE: {0} |", "(one_way)''' ptclouds = [] labels = [] for scan_name in", "sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name, self.classes, random_sample=True) return torch.from_numpy(ptcloud.transpose().astype(np.float32)),", "self.pc_augm_config = pc_augm_config train_block_names = [] all_block_names = [] for", "support_ptclouds = data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels", "is unknown!') print('[Pretrain Dataset] Mode: {0} | Num_blocks: {1}'.format(mode, len(self.block_names)))", "query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes,", "[] query_ptclouds = [] query_labels = [] black_list = []", "clip).astype(np.float32) return P class MyDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0,", "'%s.npy' %scan_name)) N = data.shape[0] #number of points in this", "= list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds =", "data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0) xyz -= xyz_min if pc_augm:", "math import glob import numpy as np import h5py as", "scan if random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N < num_point))", "self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way,", "axis=0) query_labels = np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks, query_ptclouds, query_labels", "= list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False)", "batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0] data =", "if self.mode == 'train' and self.phase == 'metatrain': remain_classes =", "sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds,", "= self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config,", "data = np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N = data.shape[0] #number", "replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds])", "sampled_classes)) def read_episode(file_name): data_file = h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:]", "support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes ################################################ Pre-train Dataset ################################################ class", "'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) elif mode", "groundtruth = np.zeros_like(labels) for i, label in enumerate(labels): if label", "data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes',", "ptclouds, labels def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes,", "self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way)", "dataset = MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point,", "write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind += 1 def __len__(self): return self.num_episode", "scan_name in scan_names: ptcloud, label = sample_pointcloud(data_path, num_point, pc_attribs, pc_augm,", "self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way)", "num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way,", "> 1: s = random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M =", "print('\\t {0} saved! | classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file", "if support: groundtruth = labels==sampled_class else: groundtruth = np.zeros_like(labels) for", "torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds,", "pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds", "clip, clip).astype(np.float32) return P class MyDataset(Dataset): def __init__(self, data_path, dataset_name,", "for sampled_class in sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if len(black_list) !=", "np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks)", "elif mode == 'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % (", "= np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data =", "task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks =", "'''sample K pointclouds and the corresponding labels for one class", "{1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans def __len__(self): return self.num_episode def", "num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode (%s) is unknown!' %mode) if", "torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################ Static Testing", "= np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks),", "pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes =", "'*.h5')) self.num_episode = len(self.file_names) else: print('Test dataset (%s) does not", "if mode == 'train': self.classes = np.array(self.dataset.train_classes) elif mode ==", "number remaining classes is less than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks,", "\\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \\", "task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels", "task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds", ":3] = np.dot(P[:, :3], M.T) if pc_augm_config['jitter']: sigma, clip =", "sampled class if N < num_point: sampled_valid_point_num = len(valid_point_inds) else:", "Static Testing Dataset ################################################ class MyTestDataset(Dataset): def __init__(self, data_path, dataset_name,", "= np.stack(ptclouds, axis=0) labels = np.stack(labels, axis=0) return ptclouds, labels", "np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels)", "pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False): '''sample K pointclouds", "= selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config,", "self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way)", "np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds)", "np import h5py as h5 import transforms3d from itertools import", "valid_query_ptclouds, \\ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\", "= labels==sampled_class else: groundtruth = np.zeros_like(labels) for i, label in", "os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) elif", "= [x for x in all_scannames if x not in", "np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise NotImplementedError('Error! The number remaining classes", "= os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point))", "is_support=False): '''sample K pointclouds and the corresponding labels for one", "= np.nonzero(data[:,6] == sampled_class)[0] # indices of points belonging to", "= [] labels = [] for scan_name in scan_names: ptcloud,", "np.concatenate(ptcloud, axis=1) if support: groundtruth = labels==sampled_class else: groundtruth =", "not z if random.random() < pc_augm_config['mirror_prob'] / 2: M =", "def __init__(self, data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None,", "Classes: {1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans def __len__(self): return self.num_episode", "elif mode == 'test': self.block_names = list(set(all_block_names) - set(train_block_names)) else:", "query_ptclouds, query_labels, sampled_classes ################################################ Pre-train Dataset ################################################ class MyPretrainDataset(Dataset): def", "mode == 'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold,", "self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point,", "sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds] xyz = data[:,", "= num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config =", "x in all_scannames if x not in black_list] selected_scannames =", "= dataset.classes if mode == 'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d'", "0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P + np.clip(sigma * np.random.randn(*P.shape),", "M) if random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1,", "axis=0) return support_ptclouds, support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks,", "dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__()", "data data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks,", "num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config", "= data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes ################################################ Pre-train", "################################################ Pre-train Dataset ################################################ class MyPretrainDataset(Dataset): def __init__(self, data_path, classes,", "os import random import math import glob import numpy as", "self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path,", "len(v) n_test_blocks = int(n_blocks * 0.1) n_train_blocks = n_blocks -", "in scan_names: ptcloud, label = sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config,", "sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds,", "labels def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0,", "random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0,", "np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4),", "pc_augm_config['rot'] == 1: angle = random.uniform(0, 2 * math.pi) M", "replace=(N < num_point)) else: # If this point cloud is", "sampled_classes = np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds,", "data_path self.classes = classes self.num_point = num_point self.pc_attribs = pc_attribs", "pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config if dataset_name ==", "random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot']", "__len__(self): return self.num_episode def __getitem__(self, index, n_way_classes=None): if n_way_classes is", "n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode == 'train': self.block_names =", "dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz',", "self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config train_block_names", "if pc_augm_config['jitter']: sigma, clip = 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P", "dataset %s!' % dataset_name) if mode == 'train': self.classes =", "point cloud is for support/query set, make sure that the", "{0} saved! | classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file =", "import torch from torch.utils.data import Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs,", "math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M) # z=upright", "raise NotImplementedError('Unkown mode %s! [Options: train/test]' % mode) print('MODE: {0}", "num_point, pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False): '''sample K", "print('[Pretrain Dataset] Mode: {0} | Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self):", "sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data", "valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64),", "[] black_list = [] # to store the sampled scan", "self.mode = mode self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm", "np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels),", "index): file_name = self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks,", "- set(train_block_names)) else: raise NotImplementedError('Mode is unknown!') print('[Pretrain Dataset] Mode:", "return self.num_episode def __getitem__(self, index): file_name = self.file_names[index] return read_episode(file_name)", "xyz = data[:, 0:3] rgb = data[:, 3:6] labels =", "= np.amin(xyz, axis=0) xyz -= xyz_min if pc_augm: xyz =", "pc_augm_config['scale'] > 1: s = random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M", "s = random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M)", "super(MyPretrainDataset).__init__() self.data_path = data_path self.classes = classes self.num_point = num_point", "== 'train': self.block_names = list(set(train_block_names)) elif mode == 'test': self.block_names", "= glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names) else: print('Test dataset (%s)", "%d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return", "query_labels = self.generate_one_episode(sampled_classes) if self.mode == 'train' and self.phase ==", "= 0 self.file_names = [] for sampled_classes in class_comb: sampled_classes", "%scan_name)) N = data.shape[0] #number of points in this scan", "data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)]", "list(set(all_block_names) - set(train_block_names)) else: raise NotImplementedError('Mode is unknown!') print('[Pretrain Dataset]", "Augmentation on XYZ and jittering of everything \"\"\" M =", "data ################################################ Static Testing Dataset ################################################ class MyTestDataset(Dataset): def __init__(self,", "= data_path self.n_way = n_way self.k_shot = k_shot self.n_queries =", "n_way, k_shot, num_episode_per_comb, num_point)) elif mode == 'test': test_data_path =", "sampled points contain target class valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0]", "else: sampled_classes = np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels", "pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False): '''sample K pointclouds and the", "support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\", "phase self.mode = mode self.num_point = num_point self.pc_attribs = pc_attribs", "print('MODE: {0} | Classes: {1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans def", "= self.generate_one_episode(sampled_classes) if self.mode == 'train' and self.phase == 'metatrain':", "query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs,", "= [] if 'xyz' in pc_attribs: ptcloud.append(xyz) if 'rgb' in", "classes is less than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\", "K pointclouds and the corresponding labels for one class (one_way)'''", "sampled_other_point_inds]) data = data[sampled_point_inds] xyz = data[:, 0:3] rgb =", "sampled_classes in class_comb: sampled_classes = list(sampled_classes) for i in range(num_episode_per_comb):", "%s! [Options: train/test]' % mode) print('MODE: {0} | Classes: {1}'.format(mode,", "torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################ Static Testing Dataset ################################################ class", "( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) elif mode == 'test':", "sampled scan names, in order to prevent sampling one scan", "= transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1: s = random.uniform(1 /", "# [(),(),(),...] self.num_episode = len(class_comb) * num_episode_per_comb episode_ind = 0", "__getitem__(self, index, n_way_classes=None): if n_way_classes is not None: sampled_classes =", "combinations import torch from torch.utils.data import Dataset def sample_K_pointclouds(data_path, num_point,", "groundtruth = labels==sampled_class else: groundtruth = np.zeros_like(labels) for i, label", "sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm,", "= np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels,", "{1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file = h5.File(file_name, 'r') support_ptclouds =", "MyTestDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1,", "pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds,", "np.clip(sigma * np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32) return P class", "task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks)", "if pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in pc_attribs:", "return data, batch_sampled_classes def write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds, query_labels,", "= np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds =", "pc_augm_config['mirror_prob'] > 0: # mirroring x&y, not z if random.random()", "[] for sampled_classes in class_comb: sampled_classes = list(sampled_classes) for i", "h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds,", "class MyDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5,", "phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path", "i in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path,", "2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M) P[:, :3]", "augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in pc_attribs: xyz_min = np.amin(xyz, axis=0)", "M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M) # z=upright assumption", "np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max ptcloud = [] if 'xyz'", "0 self.file_names = [] for sampled_classes in class_comb: sampled_classes =", "xyz = augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in pc_attribs: xyz_min =", "self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\", "in this scan if random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N", "[0, 1, 0]), M) P[:, :3] = np.dot(P[:, :3], M.T)", "num_point)) else: raise NotImplementedError('Mode (%s) is unknown!' %mode) if os.path.exists(test_data_path):", "classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path =", "[torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data", "np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks, query_ptclouds,", "pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path self.n_way = n_way", "__init__(self, data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None, mode='train',", "0: all_scannames = [x for x in all_scannames if x", "M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M) P[:, :3] =", "= sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False)", "def __getitem__(self, index): file_name = self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch):", "= data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes =", "selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames,", "sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise NotImplementedError('Error! The number", "\\ valid_support_ptclouds.astype(np.float32), \\ valid_support_masks.astype(np.int32), \\ valid_query_ptclouds.astype(np.float32), \\ valid_query_labels.astype(np.int64) else: return", "if mode == 'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % (", "ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation on XYZ and", "if random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0,", "scan names, in order to prevent sampling one scan several", "MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False)", "0.1) n_train_blocks = n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode ==", "axis=0) xyz -= xyz_min if pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config)", "if pc_augm_config['scale'] > 1: s = random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale'])", "sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way,", "from dataloaders.scannet import ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path) else: raise", "= self.class2scans[sampled_class].copy() if len(black_list) != 0: all_scannames = [x for", "task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels =", "sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False): '''sample", "augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation on XYZ and jittering of everything", "self.classes = np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode %s! [Options: train/test]'", "== 'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way,", "Tasks Author: <NAME>, 2020 \"\"\" import os import random import", "mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries,", "ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown dataset %s!'", "scan several times... for sampled_class in sampled_classes: all_scannames = self.class2scans[sampled_class].copy()", "= n_way self.k_shot = k_shot self.n_queries = n_queries self.num_episode =", "replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if self.mode ==", "support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class,", "scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes = list(sampled_classes) data =", "0:3] rgb = data[:, 3:6] labels = data[:,6].astype(np.int) xyz_min =", "self.num_episode def __getitem__(self, index): file_name = self.file_names[index] return read_episode(file_name) def", "data_file = h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:]", "num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes", "set, make sure that the sampled points contain target class", "if x not in black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False)", "ptcloud, label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name, self.classes,", "query_ptclouds, query_labels, sampled_classes = data data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds',", "# https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P + np.clip(sigma * np.random.randn(*P.shape), -1", "[x for x in all_scannames if x not in black_list]", "# z=upright assumption if pc_augm_config['mirror_prob'] > 0: # mirroring x&y,", "= [] query_labels = [] black_list = [] # to", "self.class2scans[sampled_class].copy() if len(black_list) != 0: all_scannames = [x for x", "[] support_masks = [] query_ptclouds = [] query_labels = []", "= ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown dataset %s!' % dataset_name)", "= [] all_block_names = [] for k, v in sorted(class2scans.items()):", "dataloaders.scannet import ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown", "XYZ = xyz - xyz_min xyz_max = np.amax(XYZ, axis=0) XYZ", "= len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False)", "query_labels = data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds,", "pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud,", "class MyPretrainDataset(Dataset): def __init__(self, data_path, classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz',", "Data Loader for Generating Tasks Author: <NAME>, 2020 \"\"\" import", "ptcloud = np.concatenate(ptcloud, axis=1) if support: groundtruth = labels==sampled_class else:", "else: raise NotImplementedError('Mode is unknown!') print('[Pretrain Dataset] Mode: {0} |", "data): support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes = data data_file =", "= [] # to store the sampled scan names, in", "in pc_attribs: ptcloud.append(xyz) if 'rgb' in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ'", "valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0] # indices of points belonging", "n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path,", "support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes,", "def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False,", "Testing Dataset ################################################ class MyTestDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0,", "import os import random import math import glob import numpy", "= [] for scan_name in scan_names: ptcloud, label = sample_pointcloud(data_path,", "P = P + np.clip(sigma * np.random.randn(*P.shape), -1 * clip,", "[Options: train/test]' % mode) print('MODE: {0} | Classes: {1}'.format(mode, self.classes))", "remain_classes = list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way,", "if label in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return ptcloud, groundtruth", "k, v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v) n_test_blocks =", "np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M) # z=upright assumption if pc_augm_config['mirror_prob']", "def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False):", "os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode = len(class_comb)", "is less than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \\ valid_query_labels", "np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:]", "query_ptclouds = data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return", "if mode == 'train': self.block_names = list(set(train_block_names)) elif mode ==", "%mode) if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names)", "cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset", "batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes", "data_path) else: raise NotImplementedError('Unknown dataset %s!' % dataset_name) if mode", "self.classes)) self.class2scans = self.dataset.class2scans def __len__(self): return self.num_episode def __getitem__(self,", "data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:]", "if dataset_name == 's3dis': from dataloaders.s3dis import S3DISDataset self.dataset =", "self.num_episode = num_episode self.phase = phase self.mode = mode self.num_point", "self.n_way, replace=False) except: raise NotImplementedError('Error! The number remaining classes is", "mode == 'test': self.block_names = list(set(all_block_names) - set(train_block_names)) else: raise", "< num_point)) else: # If this point cloud is for", "if 'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1) if", "0: # mirroring x&y, not z if random.random() < pc_augm_config['mirror_prob']", "= np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M) if random.random() < pc_augm_config['mirror_prob']", "* math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M) #", "> 0: # mirroring x&y, not z if random.random() <", "store the sampled scan names, in order to prevent sampling", "if 'XYZ' in pc_attribs: xyz_min = np.amin(xyz, axis=0) XYZ =", "= pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config train_block_names =", "block_name = self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm,", "if random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1,", "= np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise NotImplementedError('Error! The number remaining", "return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ valid_support_ptclouds.astype(np.float32),", "n_way=3, k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__()", "print('Test dataset (%s) does not exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb", "self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names) else: print('Test dataset", "% mode) print('MODE: {0} | Classes: {1}'.format(mode, self.classes)) self.class2scans =", "list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds)", "self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config train_block_names = [] all_block_names", "1], angle), M) # z=upright assumption if pc_augm_config['mirror_prob'] > 0:", "np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if", "__getitem__(self, index): block_name = self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path, self.num_point,", "= selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point,", "data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes", "= mode self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm =", "sampled_classes, is_support=False): '''sample K pointclouds and the corresponding labels for", "xyz_min = np.amin(xyz, axis=0) xyz -= xyz_min if pc_augm: xyz", "raise NotImplementedError('Error! The number remaining classes is less than %d_way'", "query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks,", "def __getitem__(self, index, n_way_classes=None): if n_way_classes is not None: sampled_classes", "train_block_names = [] all_block_names = [] for k, v in", "MyDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1,", "sampling one scan several times... for sampled_class in sampled_classes: all_scannames", "axis=0) XYZ = xyz - xyz_min xyz_max = np.amax(XYZ, axis=0)", "if random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N < num_point)) else:", "elif dataset_name == 'scannet': from dataloaders.scannet import ScanNetDataset self.dataset =", "in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5'", "return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32)", "len(self.block_names))) def __len__(self): return len(self.block_names) def __getitem__(self, index): block_name =", "replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way", "len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds", "data=sampled_classes, dtype='int32') data_file.close() print('\\t {0} saved! | classes: {1}'.format(out_filename, sampled_classes))", "cvfold, n_way, k_shot, num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode (%s) is", "sampled_classes ################################################ Pre-train Dataset ################################################ class MyPretrainDataset(Dataset): def __init__(self, data_path,", "np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds =", "ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds, axis=0) labels = np.stack(labels, axis=0)", "self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds", "import glob import numpy as np import h5py as h5", "self.n_way = n_way self.k_shot = k_shot self.n_queries = n_queries self.num_episode", "import Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class,", "= len(class_comb) * num_episode_per_comb episode_ind = 0 self.file_names = []", "pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in pc_attribs: xyz_min", "= batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data,", "else: return support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\", "support_ptclouds.astype(np.float32), \\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def", "np.zeros_like(labels) for i, label in enumerate(labels): if label in sampled_classes:", "else: print('Test dataset (%s) does not exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path)", "rgb = data[:, 3:6] labels = data[:,6].astype(np.int) xyz_min = np.amin(xyz,", "= [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return", "in all_scannames if x not in black_list] selected_scannames = np.random.choice(all_scannames,", "= sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support)", "[] if 'xyz' in pc_attribs: ptcloud.append(xyz) if 'rgb' in pc_attribs:", "= n_queries self.num_episode = num_episode self.phase = phase self.mode =", "glob import numpy as np import h5py as h5 import", "= P + np.clip(sigma * np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32)", "self.classes = classes self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm", "groundtruth def augment_pointcloud(P, pc_augm_config): \"\"\"\" Augmentation on XYZ and jittering", "this scan if random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N <", "# indices of points belonging to the sampled class if", "NotImplementedError('Mode is unknown!') print('[Pretrain Dataset] Mode: {0} | Num_blocks: {1}'.format(mode,", "list(sampled_classes) data = np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N = data.shape[0]", "None: sampled_classes = np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes, self.n_way, replace=False)", "of everything \"\"\" M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1:", "%s!' % dataset_name) if mode == 'train': self.classes = np.array(self.dataset.train_classes)", "batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2),", "np.nonzero(data[:,6] == sampled_class)[0] # indices of points belonging to the", "-= xyz_min if pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config) if 'XYZ'", "% dataset_name) if mode == 'train': self.classes = np.array(self.dataset.train_classes) elif", "def __init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096,", "query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds =", "data[:, 0:3] rgb = data[:, 3:6] labels = data[:,6].astype(np.int) xyz_min", "= 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P + np.clip(sigma", "valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num,", "num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path self.n_way =", "if 'rgb' in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs: ptcloud.append(XYZ)", "( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode (%s)", "task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds", "pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes = list(sampled_classes) data", "task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels", "episode_ind += 1 def __len__(self): return self.num_episode def __getitem__(self, index):", "train_block_names.extend(v[:n_train_blocks]) if mode == 'train': self.block_names = list(set(train_block_names)) elif mode", "= np.array(self.dataset.train_classes) elif mode == 'test': self.classes = np.array(self.dataset.test_classes) else:", "in sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if len(black_list) != 0: all_scannames", "'scannet': from dataloaders.scannet import ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path) else:", "super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test',", "{0} | Classes: {1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans def __len__(self):", "= np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks =", "not exist...\\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way)) #", "return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes =", "__init__(self, data_path, classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__()", "2 * math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M)", "Mode: {0} | Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self): return len(self.block_names)", "mode == 'test': self.classes = np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode", "== 's3dis': from dataloaders.s3dis import S3DISDataset self.dataset = S3DISDataset(cvfold, data_path)", "scan_names: ptcloud, label = sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name,", "sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds =", "* num_episode_per_comb episode_ind = 0 self.file_names = [] for sampled_classes", "read_episode(file_name): data_file = h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks =", "MyPretrainDataset(Dataset): def __init__(self, data_path, classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False,", "xyz - xyz_min xyz_max = np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max", "sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds, axis=0) labels =", "\\ support_masks.astype(np.int32), \\ query_ptclouds.astype(np.float32), \\ query_labels.astype(np.int64), \\ sampled_classes.astype(np.int32) def generate_one_episode(self,", "return support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes ################################################ Pre-train Dataset ################################################", "= np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3),", "self.file_names.append(out_filename) episode_ind += 1 def __len__(self): return self.num_episode def __getitem__(self,", "def read_episode(file_name): data_file = h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks", "__len__(self): return len(self.block_names) def __getitem__(self, index): block_name = self.block_names[index] ptcloud,", "-1 * clip, clip).astype(np.float32) return P class MyDataset(Dataset): def __init__(self,", "task_train_query_ptclouds, task_train_query_labels, \\ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds", "class (one_way)''' ptclouds = [] labels = [] for scan_name", "= len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds", "= XYZ/xyz_max ptcloud = [] if 'xyz' in pc_attribs: ptcloud.append(xyz)", "self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if self.mode", "replace=False) except: raise NotImplementedError('Error! The number remaining classes is less", "n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes", "self.file_names = [] for sampled_classes in class_comb: sampled_classes = list(sampled_classes)", "groundtruth[i] = sampled_classes.index(label)+1 return ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config): \"\"\"\"", "transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1: s = random.uniform(1 / pc_augm_config['scale'],", "'train': self.classes = np.array(self.dataset.train_classes) elif mode == 'test': self.classes =", "support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds =", "self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config", "self.pc_augm_config = pc_augm_config if dataset_name == 's3dis': from dataloaders.s3dis import", "sampled_classes = data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes ################################################", "= np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N = data.shape[0] #number of", "np.array(self.dataset.train_classes) elif mode == 'test': self.classes = np.array(self.dataset.test_classes) else: raise", "query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class,", "= classes self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm =", "sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v) n_test_blocks = int(n_blocks * 0.1)", "= np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels =", "n_way, k_shot, num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode (%s) is unknown!'", "= data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0) xyz -= xyz_min if", "1, 0]), M) P[:, :3] = np.dot(P[:, :3], M.T) if", "for x in all_scannames if x not in black_list] selected_scannames", "'train' and self.phase == 'metatrain': remain_classes = list(set(self.classes) - set(sampled_classes))", "mode self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm", "int(n_blocks * 0.1) n_train_blocks = n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if", "random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1,", "data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'):", "Loader for Generating Tasks Author: <NAME>, 2020 \"\"\" import os", "out_filename = os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind", "self.dataset = S3DISDataset(cvfold, data_path) elif dataset_name == 'scannet': from dataloaders.scannet", "XYZ/xyz_max ptcloud = [] if 'xyz' in pc_attribs: ptcloud.append(xyz) if" ]
[ "conditions Conditions in CLVM have either format of (opcode, var1)", "import dataclass from typing import List from greendoge.types.condition_opcodes import ConditionOpcode", "parsed CLVM conditions Conditions in CLVM have either format of", "from greendoge.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable): \"\"\"", "Streamable, streamable @dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable): \"\"\" This structure is", "@dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable): \"\"\" This structure is used to", "typing import List from greendoge.types.condition_opcodes import ConditionOpcode from greendoge.util.streamable import", "import List from greendoge.types.condition_opcodes import ConditionOpcode from greendoge.util.streamable import Streamable,", "@streamable class ConditionWithArgs(Streamable): \"\"\" This structure is used to store", "dataclass from typing import List from greendoge.types.condition_opcodes import ConditionOpcode from", "streamable @dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable): \"\"\" This structure is used", "to store parsed CLVM conditions Conditions in CLVM have either", "dataclasses import dataclass from typing import List from greendoge.types.condition_opcodes import", "List from greendoge.types.condition_opcodes import ConditionOpcode from greendoge.util.streamable import Streamable, streamable", "\"\"\" This structure is used to store parsed CLVM conditions", "Conditions in CLVM have either format of (opcode, var1) or", "structure is used to store parsed CLVM conditions Conditions in", "format of (opcode, var1) or (opcode, var1, var2) \"\"\" opcode:", "of (opcode, var1) or (opcode, var1, var2) \"\"\" opcode: ConditionOpcode", "ConditionOpcode from greendoge.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable):", "greendoge.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable): \"\"\" This", "class ConditionWithArgs(Streamable): \"\"\" This structure is used to store parsed", "either format of (opcode, var1) or (opcode, var1, var2) \"\"\"", "have either format of (opcode, var1) or (opcode, var1, var2)", "from greendoge.types.condition_opcodes import ConditionOpcode from greendoge.util.streamable import Streamable, streamable @dataclass(frozen=True)", "(opcode, var1) or (opcode, var1, var2) \"\"\" opcode: ConditionOpcode vars:", "from typing import List from greendoge.types.condition_opcodes import ConditionOpcode from greendoge.util.streamable", "ConditionWithArgs(Streamable): \"\"\" This structure is used to store parsed CLVM", "This structure is used to store parsed CLVM conditions Conditions", "store parsed CLVM conditions Conditions in CLVM have either format", "CLVM have either format of (opcode, var1) or (opcode, var1,", "import Streamable, streamable @dataclass(frozen=True) @streamable class ConditionWithArgs(Streamable): \"\"\" This structure", "used to store parsed CLVM conditions Conditions in CLVM have", "in CLVM have either format of (opcode, var1) or (opcode,", "var1) or (opcode, var1, var2) \"\"\" opcode: ConditionOpcode vars: List[bytes]", "import ConditionOpcode from greendoge.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class", "CLVM conditions Conditions in CLVM have either format of (opcode,", "from dataclasses import dataclass from typing import List from greendoge.types.condition_opcodes", "greendoge.types.condition_opcodes import ConditionOpcode from greendoge.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable", "is used to store parsed CLVM conditions Conditions in CLVM" ]
[ "}, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): \"\"\"Base", "DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( DEVICE_FIRMWARE,", "device_info(self) -> DeviceInfo: \"\"\"Return the device_info of the device.\"\"\" firmware", "coordinator, device_info, room_name, unique_id): \"\"\"Initialize the entity.\"\"\" super().__init__(coordinator) self._room_name =", "(dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class", "via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in self._shade.shade_types: if shade.shade_type ==", "device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break if FIRMWARE not in self._shade.raw_data:", "shade, shade_name): \"\"\"Initialize the shade.\"\"\" super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name", "if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break if FIRMWARE", "self._room_name = room_name self._unique_id = unique_id self._device_info = device_info @property", "__init__(self, coordinator, device_info, room_name, shade, shade_name): \"\"\"Initialize the shade.\"\"\" super().__init__(coordinator,", "device_info(self) -> DeviceInfo: \"\"\"Return the device_info of the device.\"\"\" device_info", "in self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break", "room_name, unique_id): \"\"\"Initialize the entity.\"\"\" super().__init__(coordinator) self._room_name = room_name self._unique_id", "self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER,", "the device_info of the device.\"\"\" device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)},", "id.\"\"\" return self._unique_id @property def device_info(self) -> DeviceInfo: \"\"\"Return the", "homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL,", "coordinator, device_info, room_name, shade, shade_name): \"\"\"Initialize the shade.\"\"\" super().__init__(coordinator, device_info,", "manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in self._shade.shade_types: if", "super().__init__(coordinator) self._room_name = room_name self._unique_id = unique_id self._device_info = device_info", "device_info, room_name, shade, shade_name): \"\"\"Initialize the shade.\"\"\" super().__init__(coordinator, device_info, room_name,", "( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION,", "DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION,", "__init__(self, coordinator, device_info, room_name, unique_id): \"\"\"Initialize the entity.\"\"\" super().__init__(coordinator) self._room_name", "-> DeviceInfo: \"\"\"Return the device_info of the device.\"\"\" firmware =", "import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity import", "entities.\"\"\" def __init__(self, coordinator, device_info, room_name, unique_id): \"\"\"Initialize the entity.\"\"\"", "device_info of the device.\"\"\" device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name,", "-> DeviceInfo: \"\"\"Return the device_info of the device.\"\"\" device_info =", "DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL],", "= shade_name self._shade = shade @property def device_info(self) -> DeviceInfo:", "FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity): \"\"\"Base class for", "of the device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return", "FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity): \"\"\"Base class for hunter douglas", "return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name,", "entity.\"\"\" super().__init__(coordinator) self._room_name = room_name self._unique_id = unique_id self._device_info =", "== device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break if FIRMWARE not in", "DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, )", "CoordinatorEntity from .const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER,", "sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS])", "shade_name): \"\"\"Initialize the shade.\"\"\" super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name =", "\"\"\"Initialize the shade.\"\"\" super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name = shade_name", "firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])},", ".const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE,", "ShadeEntity(HDEntity): \"\"\"Base class for hunter douglas shade entities.\"\"\" def __init__(self,", "f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME],", "identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for", "the device.\"\"\" device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER,", "for hunter douglas shade entities.\"\"\" def __init__(self, coordinator, device_info, room_name,", "room_name self._unique_id = unique_id self._device_info = device_info @property def unique_id(self):", "ATTR_TYPE from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr", "class for hunter douglas entities.\"\"\" def __init__(self, coordinator, device_info, room_name,", ") for shade in self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL]", "aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry", "DeviceInfo: \"\"\"Return the device_info of the device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE]", "homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import", "the entity.\"\"\" super().__init__(coordinator) self._room_name = room_name self._unique_id = unique_id self._device_info", "if FIRMWARE not in self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE]", "homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import", "self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]:", "not in self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE] sw_version =", "device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN,", "DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), )", "as dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity", "self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity):", "FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity): \"\"\"Base class", "DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER,", "device_info @property def unique_id(self): \"\"\"Return the unique id.\"\"\" return self._unique_id", "in self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\"", "for hunter douglas entities.\"\"\" def __init__(self, coordinator, device_info, room_name, unique_id):", "douglas entities.\"\"\" def __init__(self, coordinator, device_info, room_name, unique_id): \"\"\"Initialize the", "of the device.\"\"\" device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name,", "\"\"\"Base class for hunter douglas entities.\"\"\" def __init__(self, coordinator, device_info,", "unique_id(self): \"\"\"Return the unique id.\"\"\" return self._unique_id @property def device_info(self)", "identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version,", "self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" device_info[ATTR_SW_VERSION]", "firmware = self._shade.raw_data[FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" device_info[ATTR_SW_VERSION] = sw_version return", "self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade", "device_info, room_name, shade.id) self._shade_name = shade_name self._shade = shade @property", "name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in", "return device_info firmware = self._shade.raw_data[FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" device_info[ATTR_SW_VERSION] =", "\"\"\"Base class for hunter douglas shade entities.\"\"\" def __init__(self, coordinator,", "HDEntity(CoordinatorEntity): \"\"\"Base class for hunter douglas entities.\"\"\" def __init__(self, coordinator,", "device.\"\"\" device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]),", "shade.\"\"\" super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name = shade_name self._shade =", "the device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo(", "from .const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN,", "@property def device_info(self) -> DeviceInfo: \"\"\"Return the device_info of the", "sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): \"\"\"Base class for hunter douglas", "manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): \"\"\"Base class for hunter douglas shade", "= self._shade.raw_data[FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" device_info[ATTR_SW_VERSION] = sw_version return device_info", "name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): \"\"\"Base class", "@property def unique_id(self): \"\"\"Return the unique id.\"\"\" return self._unique_id @property", "nexia integration base entity.\"\"\" from aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const", "entities.\"\"\" def __init__(self, coordinator, device_info, room_name, shade, shade_name): \"\"\"Initialize the", "def __init__(self, coordinator, device_info, room_name, unique_id): \"\"\"Initialize the entity.\"\"\" super().__init__(coordinator)", "self._device_info = device_info @property def unique_id(self): \"\"\"Return the unique id.\"\"\"", "def unique_id(self): \"\"\"Return the unique id.\"\"\" return self._unique_id @property def", "super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name = shade_name self._shade = shade", "\"\"\"Return the unique id.\"\"\" return self._unique_id @property def device_info(self) ->", "douglas shade entities.\"\"\" def __init__(self, coordinator, device_info, room_name, shade, shade_name):", "import homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator", "DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity):", "def device_info(self) -> DeviceInfo: \"\"\"Return the device_info of the device.\"\"\"", "import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import (", "unique_id): \"\"\"Initialize the entity.\"\"\" super().__init__(coordinator) self._room_name = room_name self._unique_id =", "model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in self._shade.shade_types: if shade.shade_type", "def __init__(self, coordinator, device_info, room_name, shade, shade_name): \"\"\"Initialize the shade.\"\"\"", ") class HDEntity(CoordinatorEntity): \"\"\"Base class for hunter douglas entities.\"\"\" def", "FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity): \"\"\"Base class for hunter", "hunter douglas shade entities.\"\"\" def __init__(self, coordinator, device_info, room_name, shade,", "entity.\"\"\" from aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION", "homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity", "the unique id.\"\"\" return self._unique_id @property def device_info(self) -> DeviceInfo:", "ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity import DeviceInfo", "= unique_id self._device_info = device_info @property def unique_id(self): \"\"\"Return the", "connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, )", "suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in self._shade.shade_types:", "hunter douglas entities.\"\"\" def __init__(self, coordinator, device_info, room_name, unique_id): \"\"\"Initialize", "= shade @property def device_info(self) -> DeviceInfo: \"\"\"Return the device_info", "unique id.\"\"\" return self._unique_id @property def device_info(self) -> DeviceInfo: \"\"\"Return", "ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity import DeviceInfo from", "import CoordinatorEntity from .const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME,", "\"\"\"Initialize the entity.\"\"\" super().__init__(coordinator) self._room_name = room_name self._unique_id = unique_id", "shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break if FIRMWARE not", "FIRMWARE not in self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE] sw_version", "self._shade_name = shade_name self._shade = shade @property def device_info(self) ->", "= DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]),", "device_info firmware = self._shade.raw_data[FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" device_info[ATTR_SW_VERSION] = sw_version", "self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break if", "MANUFACTURER, ) class HDEntity(CoordinatorEntity): \"\"\"Base class for hunter douglas entities.\"\"\"", "shade.description break if FIRMWARE not in self._shade.raw_data: return device_info firmware", "self._unique_id @property def device_info(self) -> DeviceInfo: \"\"\"Return the device_info of", "device_info[ATTR_MODEL] = shade.description break if FIRMWARE not in self._shade.raw_data: return", "from aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import", "import ATTR_TYPE from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as", "shade_name self._shade = shade @property def device_info(self) -> DeviceInfo: \"\"\"Return", "shade entities.\"\"\" def __init__(self, coordinator, device_info, room_name, shade, shade_name): \"\"\"Initialize", "the device_info of the device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE] sw_version =", "class for hunter douglas shade entities.\"\"\" def __init__(self, coordinator, device_info,", "the shade.\"\"\" super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name = shade_name self._shade", "\"\"\"The nexia integration base entity.\"\"\" from aiopvapi.resources.shade import ATTR_TYPE from", "unique_id self._device_info = device_info @property def unique_id(self): \"\"\"Return the unique", "room_name, shade.id) self._shade_name = shade_name self._shade = shade @property def", "device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN,", "break if FIRMWARE not in self._shade.raw_data: return device_info firmware =", "= self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={", "import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD,", "self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC,", "shade.id) self._shade_name = shade_name self._shade = shade @property def device_info(self)", "self._shade = shade @property def device_info(self) -> DeviceInfo: \"\"\"Return the", "suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): \"\"\"Base class for", "base entity.\"\"\" from aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const import ATTR_MODEL,", "= f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) },", "DeviceInfo: \"\"\"Return the device_info of the device.\"\"\" device_info = DeviceInfo(", "\"\"\"Return the device_info of the device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE] sw_version", "class ShadeEntity(HDEntity): \"\"\"Base class for hunter douglas shade entities.\"\"\" def", "class HDEntity(CoordinatorEntity): \"\"\"Base class for hunter douglas entities.\"\"\" def __init__(self,", ") class ShadeEntity(HDEntity): \"\"\"Base class for hunter douglas shade entities.\"\"\"", "self._unique_id = unique_id self._device_info = device_info @property def unique_id(self): \"\"\"Return", "room_name, shade, shade_name): \"\"\"Initialize the shade.\"\"\" super().__init__(coordinator, device_info, room_name, shade.id)", "model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): \"\"\"Base class for hunter", "dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from", "= shade.description break if FIRMWARE not in self._shade.raw_data: return device_info", "device_info, room_name, unique_id): \"\"\"Initialize the entity.\"\"\" super().__init__(coordinator) self._room_name = room_name", "\"\"\"Return the device_info of the device.\"\"\" device_info = DeviceInfo( identifiers={(DOMAIN,", "device_info of the device.\"\"\" firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f\"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}\"", "shade @property def device_info(self) -> DeviceInfo: \"\"\"Return the device_info of", "DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity): \"\"\"Base", "for shade in self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] =", "from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr from", "integration base entity.\"\"\" from aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const import", "shade in self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description", "= device_info @property def unique_id(self): \"\"\"Return the unique id.\"\"\" return", "from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS,", "= room_name self._unique_id = unique_id self._device_info = device_info @property def", "return self._unique_id @property def device_info(self) -> DeviceInfo: \"\"\"Return the device_info", "DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class", "from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const" ]
[ "to the given client. \"\"\" return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client)", "highest version it supports, but no higher than the requested", "# a parser bug with nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"),", "ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct( # inline", "-- X-Resource extension module # # Copyright (C) 2021 <NAME>", "the X server about its usage of various resources. For", "will return the counts of each type of resource. \"\"\"", "rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"),", "identify a given set of clients with some identification method.", "rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self,", "= 2 ResQueryClientPixmapBytes = 3 # v1.2 ResQueryClientIds = 4", "= rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "counts of each type of resource. \"\"\" return QueryClientResources( display=self.display,", "def __init__(self, name, size, item_size): rq.LengthOf.__init__(self, name, size) self.item_size =", "a client to query the X server about its usage", "calculate the sizes of chosen resources and returns an estimate", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "whose size may vary, e.g. List \"\"\" def __init__(self, name,", "display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request", "for size calculation. The server tries to calculate the sizes", "= rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply =", "server and the server sends the highest version it supports,", "Free Software Foundation; either version 2.1 # of the License,", "Free Software Foundation, Inc., # 51 Franklin Street, # Fifth", "some identification method. The request sends a list of specifiers", "rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\", Client)) def query_clients(self): \"\"\"Request the list", "Type)) def query_client_resources(self, client): \"\"\"Request the number of resources owned", "rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\",", "calculation. The server tries to calculate the sizes of chosen", "that can be attributed to the given client. \"\"\" return", "2021 <NAME> <<EMAIL>> # # This library is free software;", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "# Free Software Foundation, Inc., # 51 Franklin Street, #", "rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request", "list of specifiers that selects resources for size calculation. The", "rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec)) _reply", "with some identification method. The request sends a list of", "rq.List(\"specs\", ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\",", "client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\"))", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See", "following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\"", "currently connected clients.\"\"\" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct(", "a copy of the GNU Lesser General Public # License", "sizes of resources from X server. The request sends a", "server sends the highest version it supports, but no higher", "rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"),", "display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\", query_version)", "of various resources. For detailed description see any of the", "you can redistribute it and/or # modify it under the", "# of the License, or (at your option) any later", "rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(),", "specifiers that select clients and identification methods to server. The", "along with this library; if not, write to the #", "client. \"\"\" return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): \"\"\"A", "rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def", "2.1 # of the License, or (at your option) any", "of each type of resource. \"\"\" return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname),", "_request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply", "MA 02110-1301 USA \"\"\"X-Resource extension allows a client to query", "rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\", Type)) def query_client_resources(self, client): \"\"\"Request", "to server. The server then tries to identify the chosen", "the GNU Lesser General Public License for more details. #", "\"X-Resource\" # v1.0 ResQueryVersion = 0 ResQueryClients = 1 ResQueryClientResources", "= 1 << 0 LocalClientPIDMask = 1 << 1 ClientIdSpec", "rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply = rq.Struct(", "server. The server then tries to identify the chosen clients", "clients using the identification methods specified for each client. The", "The request sends a list of specifiers that selects resources", "objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct( rq.Object(\"size\",", "0 ResQueryClients = 1 ResQueryClientResources = 2 ResQueryClientPixmapBytes = 3", "ResourceSizeValue)) def query_resource_bytes(self, client, specs): \"\"\"Query the sizes of resources", "For detailed description see any of the following documents. Protocol", "The server then tries to identify the chosen clients using", "methods specified for each client. The server returns IDs for", "the highest version it supports, but no higher than the", "it supports, but no higher than the requested version.\"\"\" return", "General Public License for more details. # # You should", "\"\"\" return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request =", "to query the X server about its usage of various", "= 1 ResQueryClientResources = 2 ResQueryClientPixmapBytes = 3 # v1.2", "rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"),", "GNU Lesser General Public License # as published by the", "server tries to calculate the sizes of chosen resources and", "identify the chosen clients using the identification methods specified for", "Software Foundation, Inc., # 51 Franklin Street, # Fifth Floor,", "to calculate the sizes of chosen resources and returns an", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "= rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec)) _reply", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "an estimate for a resource only if the size could", "bug with nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue", "rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\",", "sends the highest supported version to the server and the", "supports, but no higher than the requested version.\"\"\" return QueryVersion(", "display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes),", "rq.List(\"specs\", ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\",", "each type of resource. \"\"\" return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client)", "rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def", "in bytes of some other Field whose size may vary,", "rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(),", "# Xlib.ext.res -- X-Resource extension module # # Copyright (C)", "QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"),", "usage of some client. The returned number is a sum", "4), rq.List(\"specs\", ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(),", "# See the GNU Lesser General Public License for more", "return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class", "= 1 RES_MINOR_VERSION = 2 extname = \"X-Resource\" # v1.0", "have received a copy of the GNU Lesser General Public", "server. The request sends a list of specifiers that selects", "of specifiers that selects resources for size calculation. The server", "\"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes) disp.extension_add_method(\"display\", \"res_query_client_ids\",", "rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength())", "self.item_size = item_size def parse_value(self, length, display): return length //", "= 1 << 1 ClientIdSpec = rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue", "vary, e.g. List \"\"\" def __init__(self, name, size, item_size): rq.LengthOf.__init__(self,", "list of specifiers that select clients and identification methods to", "QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec", "of all currently connected clients.\"\"\" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type", "<NAME> <<EMAIL>> # # This library is free software; you", "were successfully identified. \"\"\" return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec", "License for more details. # # You should have received", "<< 1 ClientIdSpec = rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue = rq.Struct(", "Copyright (C) 2021 <NAME> <<EMAIL>> # # This library is", "ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4),", "a parser bug with nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"),", "sends a list of specifiers that select clients and identification", "client=client) class SizeOf(rq.LengthOf): \"\"\"A SizeOf stores the size in bytes", "QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client = rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\"))", "be determined \"\"\" return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def", "rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self, client): \"\"\"Query the pixmap", "\"\"\"Request the list of all currently connected clients.\"\"\" return QueryClients(", "def parse_value(self, length, display): return length // self.item_size ClientXIDMask =", "version.\"\"\" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client = rq.Struct(", "method. The request sends a list of specifiers that select", "(C) 2021 <NAME> <<EMAIL>> # # This library is free", "# as published by the Free Software Foundation; either version", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20),", "modify it under the terms of the GNU Lesser General", "sum of memory usage of each pixmap that can be", "X server. The request sends a list of specifiers that", "rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\"))", "the number of resources owned by a client. The server", "https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol import rq", "rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply", "the terms of the GNU Lesser General Public License #", "<<EMAIL>> # # This library is free software; you can", "connected clients.\"\"\" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32(\"resource_type\"),", "details. # # You should have received a copy of", "QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2))", "QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4),", "QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\",", "disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes) disp.extension_add_method(\"display\",", "library is free software; you can redistribute it and/or #", "module # # Copyright (C) 2021 <NAME> <<EMAIL>> # #", "__init__(self, name, size, item_size): rq.LengthOf.__init__(self, name, size) self.item_size = item_size", "rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"),", "rq.List(\"types\", Type)) def query_client_resources(self, client): \"\"\"Request the number of resources", "other Field whose size may vary, e.g. List \"\"\" def", "4), rq.Pad(20), rq.List(\"types\", Type)) def query_client_resources(self, client): \"\"\"Request the number", "rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self, client, specs): \"\"\"Query the sizes of", "type of resource. \"\"\" return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class", "5 class QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"),", "some client. The returned number is a sum of memory", "rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"),", "for each client. The server returns IDs for those clients", "# inline struct ResourceIdSpec to work around # a parser", "rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def query_client_ids(self,", "= rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(),", "set of clients with some identification method. The request sends", "resource only if the size could be determined \"\"\" return", "client. The server returns IDs for those clients that were", "= 3 # v1.2 ResQueryClientIds = 4 ResQueryResourceBytes = 5", "the server and the server sends the highest version it", "to identify the chosen clients using the identification methods specified", "rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources),", "the Free Software Foundation; either version 2.1 # of the", "PARTICULAR PURPOSE. # See the GNU Lesser General Public License", "chosen resources and returns an estimate for a resource only", "Street, # Fifth Floor, # Boston, MA 02110-1301 USA \"\"\"X-Resource", "\"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes) disp.extension_add_method(\"display\", \"res_query_client_ids\", query_client_ids) disp.extension_add_method(\"display\", \"res_query_resource_bytes\",", "List \"\"\" def __init__(self, name, size, item_size): rq.LengthOf.__init__(self, name, size)", "rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(),", "extname = \"X-Resource\" # v1.0 ResQueryVersion = 0 ResQueryClients =", "rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query the protocol version", "General Public License # as published by the Free Software", "stores the size in bytes of some other Field whose", "opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(),", "rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self, client):", "# modify it under the terms of the GNU Lesser", "by the X server. The client sends the highest supported", "def query_client_pixmap_bytes(self, client): \"\"\"Query the pixmap usage of some client.", "display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client = rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class", "\"\"\"Request the number of resources owned by a client. The", "class SizeOf(rq.LengthOf): \"\"\"A SizeOf stores the size in bytes of", "rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(),", "is a sum of memory usage of each pixmap that", "RES_MAJOR_VERSION = 1 RES_MINOR_VERSION = 2 extname = \"X-Resource\" #", "rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self, client): \"\"\"Query", "License along with this library; if not, write to the", "rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"),", "client. The returned number is a sum of memory usage", "LocalClientPIDMask = 1 << 1 ClientIdSpec = rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\"))", "XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol import rq RES_MAJOR_VERSION", "it and/or # modify it under the terms of the", "a resource only if the size could be determined \"\"\"", "the pixmap usage of some client. The returned number is", "that it will be useful, # but WITHOUT ANY WARRANTY;", "RES_MINOR_VERSION = 2 extname = \"X-Resource\" # v1.0 ResQueryVersion =", "return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client = rq.Struct( rq.Card32(\"resource_base\"),", "rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(),", "rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self, client): \"\"\"Query the pixmap usage of", "This library is distributed in the hope that it will", "rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec)) _reply = rq.Struct(", "ResQueryClientIds = 4 ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest): _request =", "ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct(", "rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query the protocol", "the X server. The client sends the highest supported version", "the identification methods specified for each client. The server returns", "item_size def parse_value(self, length, display): return length // self.item_size ClientXIDMask", "more details. # # You should have received a copy", "rq.Card32(\"mask\")) ClientIdValue = rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4, 4), rq.List(\"value\",", "of chosen resources and returns an estimate for a resource", "protocol version supported by the X server. The client sends", "clients.\"\"\" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\"))", "rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self, client): \"\"\"Query the", "\"\"\"A SizeOf stores the size in bytes of some other", "be useful, # but WITHOUT ANY WARRANTY; without even the", "_request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(),", "Inc., # 51 Franklin Street, # Fifth Floor, # Boston,", "request sends a list of specifiers that select clients and", "and/or # modify it under the terms of the GNU", "return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\"))", "the protocol version supported by the X server. The client", "either version 2.1 # of the License, or (at your", "resource. \"\"\" return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request", "with this library; if not, write to the # Free", "description see any of the following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt", "for those clients that were successfully identified. \"\"\" return QueryClientIds(", "QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct(", "sizes of chosen resources and returns an estimate for a", "returns IDs for those clients that were successfully identified. \"\"\"", "specs): \"\"\"Request to identify a given set of clients with", "_request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\",", "length, display): return length // self.item_size ClientXIDMask = 1 <<", "<reponame>daxter-army/key-cast # Xlib.ext.res -- X-Resource extension module # # Copyright", "to the # Free Software Foundation, Inc., # 51 Franklin", "# # Copyright (C) 2021 <NAME> <<EMAIL>> # # This", "= rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest):", "specs=specs) def init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients)", "client sends the highest supported version to the server and", "rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self, client, specs):", "query_resource_bytes(self, client, specs): \"\"\"Query the sizes of resources from X", "should have received a copy of the GNU Lesser General", "be attributed to the given client. \"\"\" return QueryClientPixmapBytes( display=self.display,", "return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): \"\"\"A SizeOf stores", "software; you can redistribute it and/or # modify it under", "about its usage of various resources. For detailed description see", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the", "51 Franklin Street, # Fifth Floor, # Boston, MA 02110-1301", "rq.Pad(20), rq.List(\"types\", Type)) def query_client_resources(self, client): \"\"\"Request the number of", "later version. # # This library is distributed in the", "Foundation; either version 2.1 # of the License, or (at", "rq.Pad(16)) def query_client_pixmap_bytes(self, client): \"\"\"Query the pixmap usage of some", "rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol", "# # This library is free software; you can redistribute", "rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"),", "1 ClientIdSpec = rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue = rq.Struct( rq.Object(\"spec\",", "4), rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes),", "each client. The server returns IDs for those clients that", "resources from X server. The request sends a list of", "resources for size calculation. The server tries to calculate the", "QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest):", "4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self, client, specs): \"\"\"Query the", "rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self, client, specs): \"\"\"Query the sizes", "of specifiers that select clients and identification methods to server.", "or (at your option) any later version. # # This", "attributed to the given client. \"\"\" return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname),", "parse_value(self, length, display): return length // self.item_size ClientXIDMask = 1", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "then tries to identify the chosen clients using the identification", "\"\"\"Query the sizes of resources from X server. The request", "item_size): rq.LengthOf.__init__(self, name, size) self.item_size = item_size def parse_value(self, length,", "4 ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"),", "ResourceSizeSpec = rq.Struct( # inline struct ResourceIdSpec to work around", "rq.Pad(20), rq.List(\"clients\", Client)) def query_clients(self): \"\"\"Request the list of all", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "// self.item_size ClientXIDMask = 1 << 0 LocalClientPIDMask = 1", "ResQueryVersion = 0 ResQueryClients = 1 ResQueryClientResources = 2 ResQueryClientPixmapBytes", "returns an estimate for a resource only if the size", "of the GNU Lesser General Public # License along with", "4, 4), rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"),", "query_client_resources(self, client): \"\"\"Request the number of resources owned by a", "self.item_size ClientXIDMask = 1 << 0 LocalClientPIDMask = 1 <<", "specified for each client. The server returns IDs for those", "under the terms of the GNU Lesser General Public License", "specifiers that selects resources for size calculation. The server tries", "return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp, info): disp.extension_add_method(\"display\",", "rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(),", "it will be useful, # but WITHOUT ANY WARRANTY; without", "class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\",", "by the Free Software Foundation; either version 2.1 # of", "of clients with some identification method. The request sends a", "highest supported version to the server and the server sends", "redistribute it and/or # modify it under the terms of", "= rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue = rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\",", "a list of specifiers that selects resources for size calculation.", "The client sends the highest supported version to the server", "return length // self.item_size ClientXIDMask = 1 << 0 LocalClientPIDMask", "the counts of each type of resource. \"\"\" return QueryClientResources(", "of resources from X server. The request sends a list", "hope that it will be useful, # but WITHOUT ANY", "size) self.item_size = item_size def parse_value(self, length, display): return length", "rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4),", "memory usage of each pixmap that can be attributed to", "various resources. For detailed description see any of the following", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20),", "library is distributed in the hope that it will be", "class QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply =", "the License, or (at your option) any later version. #", "rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\", Type)) def", "supported by the X server. The client sends the highest", "Software Foundation; either version 2.1 # of the License, or", "select clients and identification methods to server. The server then", "can be attributed to the given client. \"\"\" return QueryClientPixmapBytes(", "# 51 Franklin Street, # Fifth Floor, # Boston, MA", "\"\"\" return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp, info):", "Xlib.ext.res -- X-Resource extension module # # Copyright (C) 2021", "= rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4, 4), rq.List(\"value\", rq.Card32Obj)) class", "rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue = rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4,", "rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec)) _reply =", "Franklin Street, # Fifth Floor, # Boston, MA 02110-1301 USA", "will be useful, # but WITHOUT ANY WARRANTY; without even", "sends the highest version it supports, but no higher than", "4), rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds),", "of memory usage of each pixmap that can be attributed", "ResQueryClients = 1 ResQueryClientResources = 2 ResQueryClientPixmapBytes = 3 #", "client): \"\"\"Request the number of resources owned by a client.", "to identify a given set of clients with some identification", "its usage of various resources. For detailed description see any", "those clients that were successfully identified. \"\"\" return QueryClientIds( display=self.display,", "size could be determined \"\"\" return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client,", "return the counts of each type of resource. \"\"\" return", "any of the following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol", "rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request =", "the requested version.\"\"\" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client", "extension allows a client to query the X server about", "QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): \"\"\"A SizeOf stores the", "specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol import rq RES_MAJOR_VERSION = 1", "rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\",", "query_client_pixmap_bytes(self, client): \"\"\"Query the pixmap usage of some client. The", "rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4, 4), rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request", "client, specs): \"\"\"Query the sizes of resources from X server.", "number of resources owned by a client. The server will", "ResourceIdSpec to work around # a parser bug with nested", "chosen clients using the identification methods specified for each client.", "rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4),", "client to query the X server about its usage of", "def query_client_resources(self, client): \"\"\"Request the number of resources owned by", "This library is free software; you can redistribute it and/or", "rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION):", "client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query the protocol version supported by the", "may vary, e.g. List \"\"\" def __init__(self, name, size, item_size):", "# This library is distributed in the hope that it", "rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec)) _reply = rq.Struct(", "owned by a client. The server will return the counts", "rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\", Client)) def", "for more details. # # You should have received a", "and returns an estimate for a resource only if the", "ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion),", "some other Field whose size may vary, e.g. List \"\"\"", "a given set of clients with some identification method. The", "struct ResourceIdSpec to work around # a parser bug with", "_request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct(", "ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"),", "the # Free Software Foundation, Inc., # 51 Franklin Street,", "for a resource only if the size could be determined", "free software; you can redistribute it and/or # modify it", "detailed description see any of the following documents. Protocol specification:", "rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\", Type)) def query_client_resources(self, client): \"\"\"Request the", "published by the Free Software Foundation; either version 2.1 #", "opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct(", "Client = rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request = rq.Struct(", "rq.Card8(\"client_minor\"), rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"),", "rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\", Type)) def query_client_resources(self,", "SizeOf(rq.LengthOf): \"\"\"A SizeOf stores the size in bytes of some", "\"\"\" return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"),", "given client. \"\"\" return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf):", "is free software; you can redistribute it and/or # modify", "= rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"),", "Field whose size may vary, e.g. List \"\"\" def __init__(self,", "rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"),", "info): disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources)", "usage of various resources. For detailed description see any of", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query the protocol version supported by", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\", ClientIdValue))", "that were successfully identified. \"\"\" return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs)", "received a copy of the GNU Lesser General Public #", "option) any later version. # # This library is distributed", "See the GNU Lesser General Public License for more details.", "= rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec))", "\"\"\" Query the protocol version supported by the X server.", "License, or (at your option) any later version. # #", "display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec =", "the hope that it will be useful, # but WITHOUT", "specs): \"\"\"Query the sizes of resources from X server. The", "4), rq.Pad(20), rq.List(\"clients\", Client)) def query_clients(self): \"\"\"Request the list of", "query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes) disp.extension_add_method(\"display\", \"res_query_client_ids\", query_client_ids)", "X server about its usage of various resources. For detailed", "Lesser General Public License # as published by the Free", "server about its usage of various resources. For detailed description", "rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct( # inline struct ResourceIdSpec", "rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(),", "version 2.1 # of the License, or (at your option)", "# v1.2 ResQueryClientIds = 4 ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest):", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\",", "SizeOf stores the size in bytes of some other Field", "2 extname = \"X-Resource\" # v1.0 ResQueryVersion = 0 ResQueryClients", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\",", "rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def query_client_ids(self, specs): \"\"\"Request to identify a", "rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct( # inline struct ResourceIdSpec to", "or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU", "by a client. The server will return the counts of", "clients that were successfully identified. \"\"\" return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname),", "library; if not, write to the # Free Software Foundation,", "requested version.\"\"\" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client =", "FOR A PARTICULAR PURPOSE. # See the GNU Lesser General", "opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): \"\"\"A SizeOf stores the size in", "\"\"\" def __init__(self, name, size, item_size): rq.LengthOf.__init__(self, name, size) self.item_size", "the size could be determined \"\"\" return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname),", "rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\"", "query_client_ids(self, specs): \"\"\"Request to identify a given set of clients", "version supported by the X server. The client sends the", "02110-1301 USA \"\"\"X-Resource extension allows a client to query the", "determined \"\"\" return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp,", "_request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct(", "of resource. \"\"\" return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest):", "def query_resource_bytes(self, client, specs): \"\"\"Query the sizes of resources from", "opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client = rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest):", "You should have received a copy of the GNU Lesser", "rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClients),", "rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"),", "list of all currently connected clients.\"\"\" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname))", "server returns IDs for those clients that were successfully identified.", "resources. For detailed description see any of the following documents.", "rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(),", "\"\"\"Query the pixmap usage of some client. The returned number", "to work around # a parser bug with nested objects", "rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply", "Fifth Floor, # Boston, MA 02110-1301 USA \"\"\"X-Resource extension allows", "v1.2 ResQueryClientIds = 4 ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest): _request", "name, size, item_size): rq.LengthOf.__init__(self, name, size) self.item_size = item_size def", "not, write to the # Free Software Foundation, Inc., #", "rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\",", "client. The server will return the counts of each type", "server will return the counts of each type of resource.", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20))", "with nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue =", "length // self.item_size ClientXIDMask = 1 << 0 LocalClientPIDMask =", "of some other Field whose size may vary, e.g. List", "distributed in the hope that it will be useful, #", "1 RES_MINOR_VERSION = 2 extname = \"X-Resource\" # v1.0 ResQueryVersion", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def", "rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION = 2 extname = \"X-Resource\"", "rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\", Client)) def query_clients(self): \"\"\"Request", "of the License, or (at your option) any later version.", "rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self, client): \"\"\"Query the pixmap usage", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\", Type))", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #", "of the following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification:", "if the size could be determined \"\"\" return QueryResourceBytes( display=self.display,", "of resources owned by a client. The server will return", "0 LocalClientPIDMask = 1 << 1 ClientIdSpec = rq.Struct( rq.Card32(\"client\"),", "disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\",", "only if the size could be determined \"\"\" return QueryResourceBytes(", "as published by the Free Software Foundation; either version 2.1", "rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from", "given set of clients with some identification method. The request", "client_minor=RES_MINOR_VERSION): \"\"\" Query the protocol version supported by the X", "rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"),", "rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4),", "version it supports, but no higher than the requested version.\"\"\"", "X server. The client sends the highest supported version to", "from Xlib.protocol import rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION = 2", "number is a sum of memory usage of each pixmap", "of each pixmap that can be attributed to the given", "The request sends a list of specifiers that select clients", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20),", "Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol import rq RES_MAJOR_VERSION =", "# Fifth Floor, # Boston, MA 02110-1301 USA \"\"\"X-Resource extension", "ClientIdValue = rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4, 4), rq.List(\"value\", rq.Card32Obj))", "= rq.Struct( # inline struct ResourceIdSpec to work around #", "# You should have received a copy of the GNU", "IDs for those clients that were successfully identified. \"\"\" return", "parser bug with nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\"))", "Lesser General Public License for more details. # # You", "ClientIdSpec = rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue = rq.Struct( rq.Object(\"spec\", ClientIdSpec),", "4), rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def query_client_ids(self, specs): \"\"\"Request to identify", "sends a list of specifiers that selects resources for size", "identification methods specified for each client. The server returns IDs", "query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes)", "rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue = rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4, 4),", "could be determined \"\"\" return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs)", "usage of each pixmap that can be attributed to the", "rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\", Client)) def query_clients(self): \"\"\"Request the", "rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self, client, specs): \"\"\"Query", "the chosen clients using the identification methods specified for each", "a list of specifiers that select clients and identification methods", "resources owned by a client. The server will return the", "server. The client sends the highest supported version to the", "rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(),", "client): \"\"\"Query the pixmap usage of some client. The returned", "ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4),", "The server will return the counts of each type of", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16)) def query_client_pixmap_bytes(self,", "the sizes of chosen resources and returns an estimate for", "query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes) disp.extension_add_method(\"display\", \"res_query_client_ids\", query_client_ids) disp.extension_add_method(\"display\", \"res_query_resource_bytes\", query_resource_bytes)", "class QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4),", "the following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\", Client))", "Foundation, Inc., # 51 Franklin Street, # Fifth Floor, #", "4), rq.List(\"specs\", ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(),", "tries to calculate the sizes of chosen resources and returns", "successfully identified. \"\"\" return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec =", "v1.0 ResQueryVersion = 0 ResQueryClients = 1 ResQueryClientResources = 2", "Client)) def query_clients(self): \"\"\"Request the list of all currently connected", "1 << 1 ClientIdSpec = rq.Struct( rq.Card32(\"client\"), rq.Card32(\"mask\")) ClientIdValue =", "1 << 0 LocalClientPIDMask = 1 << 1 ClientIdSpec =", "the GNU Lesser General Public License # as published by", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue))", "rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def query_client_ids(self, specs):", "nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct(", "init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\",", "rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query the", "SizeOf(\"value\", 4, 4), rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request = rq.Struct(", "size may vary, e.g. List \"\"\" def __init__(self, name, size,", "rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def query_client_ids(self, specs): \"\"\"Request to", "of the GNU Lesser General Public License # as published", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\",", "each pixmap that can be attributed to the given client.", "query_clients(self): \"\"\"Request the list of all currently connected clients.\"\"\" return", "of some client. The returned number is a sum of", "\"\"\"Request to identify a given set of clients with some", "selects resources for size calculation. The server tries to calculate", "USA \"\"\"X-Resource extension allows a client to query the X", "def init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\",", "terms of the GNU Lesser General Public License # as", "extension module # # Copyright (C) 2021 <NAME> <<EMAIL>> #", "# # This library is distributed in the hope that", "= 5 class QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(),", "write to the # Free Software Foundation, Inc., # 51", "1 ResQueryClientResources = 2 ResQueryClientPixmapBytes = 3 # v1.2 ResQueryClientIds", "= rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(),", "pixmap that can be attributed to the given client. \"\"\"", "identification method. The request sends a list of specifiers that", "3 # v1.2 ResQueryClientIds = 4 ResQueryResourceBytes = 5 class", "higher than the requested version.\"\"\" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major,", "QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply =", "see any of the following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB", "rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self,", "it under the terms of the GNU Lesser General Public", "identification methods to server. The server then tries to identify", "name, size) self.item_size = item_size def parse_value(self, length, display): return", "class QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"),", "around # a parser bug with nested objects rq.Card32(\"resource\"), rq.Card32(\"type\"),", "inline struct ResourceIdSpec to work around # a parser bug", "version. # # This library is distributed in the hope", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "# Copyright (C) 2021 <NAME> <<EMAIL>> # # This library", "Public License # as published by the Free Software Foundation;", "rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8(\"client_major\"), rq.Card8(\"client_minor\"), rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "copy of the GNU Lesser General Public # License along", "ResQueryClientResources = 2 ResQueryClientPixmapBytes = 3 # v1.2 ResQueryClientIds =", "e.g. List \"\"\" def __init__(self, name, size, item_size): rq.LengthOf.__init__(self, name,", "rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "Public License for more details. # # You should have", "the sizes of resources from X server. The request sends", "Boston, MA 02110-1301 USA \"\"\"X-Resource extension allows a client to", "opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request =", "and identification methods to server. The server then tries to", "the highest supported version to the server and the server", "ClientIdSpec), SizeOf(\"value\", 4, 4), rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request =", "rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\", ResourceSizeValue)) def query_resource_bytes(self, client,", "size in bytes of some other Field whose size may", "rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec))", "_request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ClientIdSpec))", "FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser", "rq.LengthOf.__init__(self, name, size) self.item_size = item_size def parse_value(self, length, display):", "Xlib.protocol import rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION = 2 extname", "<< 0 LocalClientPIDMask = 1 << 1 ClientIdSpec = rq.Struct(", "version to the server and the server sends the highest", "rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\",", "Public # License along with this library; if not, write", "= 0 ResQueryClients = 1 ResQueryClientResources = 2 ResQueryClientPixmapBytes =", "any later version. # # This library is distributed in", "PURPOSE. # See the GNU Lesser General Public License for", "rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION,", "GNU Lesser General Public License for more details. # #", "License # as published by the Free Software Foundation; either", "specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol import", "The returned number is a sum of memory usage of", "clients and identification methods to server. The server then tries", "display): return length // self.item_size ClientXIDMask = 1 << 0", "ResourceSizeValue = rq.Struct( rq.Object(\"size\", ResourceSizeSpec), rq.LengthOf(\"cross_references\", 4), rq.List(\"cross_references\", ResourceSizeSpec)) class", "than the requested version.\"\"\" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor)", "and the server sends the highest version it supports, but", "this library; if not, write to the # Free Software", "# This library is free software; you can redistribute it", "rq.List(\"ids\", ClientIdValue)) def query_client_ids(self, specs): \"\"\"Request to identify a given", "General Public # License along with this library; if not,", "server then tries to identify the chosen clients using the", "rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct( # inline struct ResourceIdSpec to work", "\"\"\" return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): \"\"\"A SizeOf", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20), rq.List(\"sizes\",", "# v1.0 ResQueryVersion = 0 ResQueryClients = 1 ResQueryClientResources =", "identified. \"\"\" return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct(", "https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml \"\"\" from Xlib.protocol import rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION", "a client. The server will return the counts of each", "rq.List(\"clients\", Client)) def query_clients(self): \"\"\"Request the list of all currently", "def query_client_ids(self, specs): \"\"\"Request to identify a given set of", "query the X server about its usage of various resources.", "return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct(", "rq.ReplyLength(), rq.LengthOf(\"ids\", 4), rq.Pad(20), rq.List(\"ids\", ClientIdValue)) def query_client_ids(self, specs): \"\"\"Request", "# Boston, MA 02110-1301 USA \"\"\"X-Resource extension allows a client", "import rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION = 2 extname =", "can redistribute it and/or # modify it under the terms", "= 4 ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest): _request = rq.Struct(", "rq.Struct( rq.Object(\"spec\", ClientIdSpec), SizeOf(\"value\", 4, 4), rq.List(\"value\", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest):", "= rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct( # inline struct", "request sends a list of specifiers that selects resources for", "class QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply", "the given client. \"\"\" return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class", "size, item_size): rq.LengthOf.__init__(self, name, size) self.item_size = item_size def parse_value(self,", "rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(),", "specs=specs) ResourceIdSpec = rq.Struct( rq.Card32(\"resource\"), rq.Card32(\"type\")) ResourceSizeSpec = rq.Struct( #", "= \"X-Resource\" # v1.0 ResQueryVersion = 0 ResQueryClients = 1", "= rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card16(\"server_major\"), rq.Card16(\"server_minor\"), rq.Pad(20)) def", "def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): \"\"\" Query the protocol version supported", "the server sends the highest version it supports, but no", "using the identification methods specified for each client. The server", "client_minor=client_minor) Client = rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request =", "The server returns IDs for those clients that were successfully", "\"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\", query_clients) disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\",", "X-Resource extension module # # Copyright (C) 2021 <NAME> <<EMAIL>>", "bytes of some other Field whose size may vary, e.g.", "opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\",", "the size in bytes of some other Field whose size", "pixmap usage of some client. The returned number is a", "returned number is a sum of memory usage of each", "rq.Struct( # inline struct ResourceIdSpec to work around # a", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"sizes\", 4), rq.Pad(20),", "no higher than the requested version.\"\"\" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname),", "rq.Card32(\"resource\"), rq.Card32(\"type\"), rq.Card32(\"bytes\"), rq.Card32(\"ref_count\"), rq.Card32(\"use_count\")) ResourceSizeValue = rq.Struct( rq.Object(\"size\", ResourceSizeSpec),", "= rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"),", "2 ResQueryClientPixmapBytes = 3 # v1.2 ResQueryClientIds = 4 ResQueryResourceBytes", "all currently connected clients.\"\"\" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type =", "Floor, # Boston, MA 02110-1301 USA \"\"\"X-Resource extension allows a", "to the server and the server sends the highest version", "in the hope that it will be useful, # but", "but no higher than the requested version.\"\"\" return QueryVersion( display=self.display,", "that select clients and identification methods to server. The server", "your option) any later version. # # This library is", "Type = rq.Struct( rq.Card32(\"resource_type\"), rq.Card32(\"count\")) class QueryClientResources(rq.ReplyRequest): _request = rq.Struct(", "rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"types\", 4), rq.Pad(20), rq.List(\"types\", Type)) def query_client_resources(self, client):", "supported version to the server and the server sends the", "client_major=client_major, client_minor=client_minor) Client = rq.Struct( rq.Card32(\"resource_base\"), rq.Card32(\"resource_mask\")) class QueryClients(rq.ReplyRequest): _request", "work around # a parser bug with nested objects rq.Card32(\"resource\"),", "ClientIdValue)) def query_client_ids(self, specs): \"\"\"Request to identify a given set", "= 2 extname = \"X-Resource\" # v1.0 ResQueryVersion = 0", "methods to server. The server then tries to identify the", "estimate for a resource only if the size could be", "\"\"\"X-Resource extension allows a client to query the X server", "disp.extension_add_method(\"display\", \"res_query_client_resources\", query_client_resources) disp.extension_add_method(\"display\", \"res_query_client_pixmap_bytes\", query_client_pixmap_bytes) disp.extension_add_method(\"display\", \"res_query_client_ids\", query_client_ids) disp.extension_add_method(\"display\",", "GNU Lesser General Public # License along with this library;", "tries to identify the chosen clients using the identification methods", "def query_clients(self): \"\"\"Request the list of all currently connected clients.\"\"\"", "= item_size def parse_value(self, length, display): return length // self.item_size", "display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): \"\"\"A SizeOf stores the size", "# License along with this library; if not, write to", "the list of all currently connected clients.\"\"\" return QueryClients( display=self.display,", "QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf(\"specs\", 4), rq.List(\"specs\",", "rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1),", "the GNU Lesser General Public # License along with this", "(at your option) any later version. # # This library", "Query the protocol version supported by the X server. The", "clients with some identification method. The request sends a list", "allows a client to query the X server about its", "ClientXIDMask = 1 << 0 LocalClientPIDMask = 1 << 1", "from X server. The request sends a list of specifiers", "resources and returns an estimate for a resource only if", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "A PARTICULAR PURPOSE. # See the GNU Lesser General Public", "Lesser General Public # License along with this library; if", "that selects resources for size calculation. The server tries to", "\"\"\" from Xlib.protocol import rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION =", "is distributed in the hope that it will be useful,", "QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8(\"opcode\"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32(\"client\")) _reply =", "rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.LengthOf(\"clients\", 4), rq.Pad(20), rq.List(\"clients\", Client)) def query_clients(self):", "client=client, specs=specs) def init(disp, info): disp.extension_add_method(\"display\", \"res_query_version\", query_version) disp.extension_add_method(\"display\", \"res_query_clients\",", "if not, write to the # Free Software Foundation, Inc.,", "The server tries to calculate the sizes of chosen resources", "# # You should have received a copy of the", "rq.Card8(\"opcode\"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32(\"client\"), rq.LengthOf(\"specs\", 4), rq.List(\"specs\", ResourceIdSpec)) _reply =", "a sum of memory usage of each pixmap that can", "size calculation. The server tries to calculate the sizes of", "ResQueryClientPixmapBytes = 3 # v1.2 ResQueryClientIds = 4 ResQueryResourceBytes =", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "_reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16(\"sequence_number\"), rq.ReplyLength(), rq.Card32(\"bytes\"), rq.Card32(\"bytes_overflow\"), rq.Pad(16))" ]
[ "the pipeline. import argparse from version import rubra_version def get_cmdline_args():", "help='end points (tasks) for the pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart',", "get_cmdline_args(): return parser.parse_args() parser = argparse.ArgumentParser( description='A bioinformatics pipeline system.')", "metavar='TASKNAME', type=str, required=False, help='end points (tasks) for the pipeline') parser.add_argument(", "verbosity level: 0 = quiet; 1 = normal; \\ 2", "type=str, choices=('print', 'run', 'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline behaviour: print;", "(tasks) for the pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'), required=False,", "version import rubra_version def get_cmdline_args(): return parser.parse_args() parser = argparse.ArgumentParser(", "pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline stages", "# Process the unix command line of the pipeline. import", "start tasks (default is fromstart)') parser.add_argument( '--version', action='version', version='%(prog)s '", "from end tasks or forwards \\ from start tasks (default", "'--style', type=str, choices=('print', 'run', 'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline behaviour:", "regardless of timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False, help='end points", "= chatty (default is 1)') parser.add_argument( '--style', type=str, choices=('print', 'run',", "metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline stages (a Python module)') parser.add_argument(", "from version import rubra_version def get_cmdline_args(): return parser.parse_args() parser =", "be out of date regardless of timestamps') parser.add_argument( '--end', metavar='TASKNAME',", "help='Pipeline behaviour: print; run; touchfiles; flowchart (default is print)') parser.add_argument(", "outputs by working back from end tasks or forwards \\", "'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline behaviour: print; run; touchfiles; flowchart", "import rubra_version def get_cmdline_args(): return parser.parse_args() parser = argparse.ArgumentParser( description='A", "quiet; 1 = normal; \\ 2 = chatty (default is", "2), required=False, default=1, help='Output verbosity level: 0 = quiet; 1", "parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False, help='end points (tasks) for the", "type=str, required=False, default=[], nargs='+', help='tasks which are forced to be", "= normal; \\ 2 = chatty (default is 1)') parser.add_argument(", "is print)') parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False, default=[], nargs='+', help='tasks", "parser = argparse.ArgumentParser( description='A bioinformatics pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE',", "1)') parser.add_argument( '--style', type=str, choices=('print', 'run', 'flowchart', 'touchfiles'), required=False, default='print',", "argparse from version import rubra_version def get_cmdline_args(): return parser.parse_args() parser", "the unix command line of the pipeline. import argparse from", "back from end tasks or forwards \\ from start tasks", "pipeline. import argparse from version import rubra_version def get_cmdline_args(): return", "return parser.parse_args() parser = argparse.ArgumentParser( description='A bioinformatics pipeline system.') parser.add_argument(", "parser.parse_args() parser = argparse.ArgumentParser( description='A bioinformatics pipeline system.') parser.add_argument( 'pipeline',", "required=False, default=1, help='Output verbosity level: 0 = quiet; 1 =", "tasks or forwards \\ from start tasks (default is fromstart)')", "(Python modules)') parser.add_argument( '--verbose', type=int, choices=(0, 1, 2), required=False, default=1,", "or forwards \\ from start tasks (default is fromstart)') parser.add_argument(", "required=False, default='print', help='Pipeline behaviour: print; run; touchfiles; flowchart (default is", "help='rebuild outputs by working back from end tasks or forwards", "1 = normal; \\ 2 = chatty (default is 1)')", "= quiet; 1 = normal; \\ 2 = chatty (default", "'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline stages (a Python module)')", "= argparse.ArgumentParser( description='A bioinformatics pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str,", "help='Output verbosity level: 0 = quiet; 1 = normal; \\", "module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One or more", "help='One or more configuration files (Python modules)') parser.add_argument( '--verbose', type=int,", "Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One or", "'touchfiles'), required=False, default='print', help='Pipeline behaviour: print; run; touchfiles; flowchart (default", "required=False, help='end points (tasks) for the pipeline') parser.add_argument( '--rebuild', type=str,", "type=str, help='Your Ruffus pipeline stages (a Python module)') parser.add_argument( '--config',", "(default is fromstart)') parser.add_argument( '--version', action='version', version='%(prog)s ' + rubra_version)", "system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline stages (a", "modules)') parser.add_argument( '--verbose', type=int, choices=(0, 1, 2), required=False, default=1, help='Output", "'--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One or more configuration files", "or more configuration files (Python modules)') parser.add_argument( '--verbose', type=int, choices=(0,", "run; touchfiles; flowchart (default is print)') parser.add_argument( '--force', metavar='TASKNAME', type=str,", "rubra_version def get_cmdline_args(): return parser.parse_args() parser = argparse.ArgumentParser( description='A bioinformatics", "(default is 1)') parser.add_argument( '--style', type=str, choices=('print', 'run', 'flowchart', 'touchfiles'),", "is 1)') parser.add_argument( '--style', type=str, choices=('print', 'run', 'flowchart', 'touchfiles'), required=False,", "working back from end tasks or forwards \\ from start", "default='print', help='Pipeline behaviour: print; run; touchfiles; flowchart (default is print)')", "help='Your Ruffus pipeline stages (a Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE',", "bioinformatics pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline", "help='tasks which are forced to be out of date regardless", "choices=('print', 'run', 'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline behaviour: print; run;", "pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild outputs", "out of date regardless of timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str,", "metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One or more configuration files (Python", "default=1, help='Output verbosity level: 0 = quiet; 1 = normal;", "def get_cmdline_args(): return parser.parse_args() parser = argparse.ArgumentParser( description='A bioinformatics pipeline", "points (tasks) for the pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'),", "more configuration files (Python modules)') parser.add_argument( '--verbose', type=int, choices=(0, 1,", "required=False, default='fromstart', help='rebuild outputs by working back from end tasks", "default=[], nargs='+', help='tasks which are forced to be out of", "pipeline stages (a Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+',", "import argparse from version import rubra_version def get_cmdline_args(): return parser.parse_args()", "to be out of date regardless of timestamps') parser.add_argument( '--end',", "parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One or more configuration", "normal; \\ 2 = chatty (default is 1)') parser.add_argument( '--style',", "default='fromstart', help='rebuild outputs by working back from end tasks or", "description='A bioinformatics pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus", "parser.add_argument( '--style', type=str, choices=('print', 'run', 'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline", "of date regardless of timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False,", "\\ from start tasks (default is fromstart)') parser.add_argument( '--version', action='version',", "print)') parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False, default=[], nargs='+', help='tasks which", "type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild outputs by working back", "date regardless of timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False, help='end", "behaviour: print; run; touchfiles; flowchart (default is print)') parser.add_argument( '--force',", "are forced to be out of date regardless of timestamps')", "parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False, default=[], nargs='+', help='tasks which are", "choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild outputs by working back from", "forwards \\ from start tasks (default is fromstart)') parser.add_argument( '--version',", "for the pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart',", "of timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False, help='end points (tasks)", "end tasks or forwards \\ from start tasks (default is", "configuration files (Python modules)') parser.add_argument( '--verbose', type=int, choices=(0, 1, 2),", "level: 0 = quiet; 1 = normal; \\ 2 =", "parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline stages (a Python", "'--force', metavar='TASKNAME', type=str, required=False, default=[], nargs='+', help='tasks which are forced", "1, 2), required=False, default=1, help='Output verbosity level: 0 = quiet;", "'--rebuild', type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild outputs by working", "tasks (default is fromstart)') parser.add_argument( '--version', action='version', version='%(prog)s ' +", "'--verbose', type=int, choices=(0, 1, 2), required=False, default=1, help='Output verbosity level:", "\\ 2 = chatty (default is 1)') parser.add_argument( '--style', type=str,", "argparse.ArgumentParser( description='A bioinformatics pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your", "Process the unix command line of the pipeline. import argparse", "nargs='+', help='tasks which are forced to be out of date", "'run', 'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline behaviour: print; run; touchfiles;", "files (Python modules)') parser.add_argument( '--verbose', type=int, choices=(0, 1, 2), required=False,", "stages (a Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True,", "Ruffus pipeline stages (a Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str,", "which are forced to be out of date regardless of", "the pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild", "metavar='TASKNAME', type=str, required=False, default=[], nargs='+', help='tasks which are forced to", "flowchart (default is print)') parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False, default=[],", "timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False, help='end points (tasks) for", "'fromend'), required=False, default='fromstart', help='rebuild outputs by working back from end", "0 = quiet; 1 = normal; \\ 2 = chatty", "from start tasks (default is fromstart)') parser.add_argument( '--version', action='version', version='%(prog)s", "(a Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One", "forced to be out of date regardless of timestamps') parser.add_argument(", "of the pipeline. import argparse from version import rubra_version def", "type=int, choices=(0, 1, 2), required=False, default=1, help='Output verbosity level: 0", "touchfiles; flowchart (default is print)') parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False,", "type=str, required=False, help='end points (tasks) for the pipeline') parser.add_argument( '--rebuild',", "by working back from end tasks or forwards \\ from", "parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild outputs by", "nargs='+', required=True, help='One or more configuration files (Python modules)') parser.add_argument(", "choices=(0, 1, 2), required=False, default=1, help='Output verbosity level: 0 =", "required=True, help='One or more configuration files (Python modules)') parser.add_argument( '--verbose',", "chatty (default is 1)') parser.add_argument( '--style', type=str, choices=('print', 'run', 'flowchart',", "required=False, default=[], nargs='+', help='tasks which are forced to be out", "2 = chatty (default is 1)') parser.add_argument( '--style', type=str, choices=('print',", "unix command line of the pipeline. import argparse from version", "command line of the pipeline. import argparse from version import", "parser.add_argument( '--verbose', type=int, choices=(0, 1, 2), required=False, default=1, help='Output verbosity", "'--end', metavar='TASKNAME', type=str, required=False, help='end points (tasks) for the pipeline')", "line of the pipeline. import argparse from version import rubra_version", "(default is print)') parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False, default=[], nargs='+',", "type=str, nargs='+', required=True, help='One or more configuration files (Python modules)')", "print; run; touchfiles; flowchart (default is print)') parser.add_argument( '--force', metavar='TASKNAME'," ]
[ "longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude, longitude)) if __name__ == '__main__': main()", "generator = Generator() latitude, longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude, longitude)) if", "import config from Generator import Generator def main(): generator =", "main(): generator = Generator() latitude, longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude, longitude))", "config from Generator import Generator def main(): generator = Generator()", "Generator import Generator def main(): generator = Generator() latitude, longitude", "= Generator() latitude, longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude, longitude)) if __name__", "import Generator def main(): generator = Generator() latitude, longitude =", "def main(): generator = Generator() latitude, longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude,", "Generator def main(): generator = Generator() latitude, longitude = generator.getCoordinates()", "latitude, longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude, longitude)) if __name__ == '__main__':", "webbrowser import config from Generator import Generator def main(): generator", "from Generator import Generator def main(): generator = Generator() latitude,", "import webbrowser import config from Generator import Generator def main():", "Generator() latitude, longitude = generator.getCoordinates() webbrowser.open(config.api_request.format(latitude, longitude)) if __name__ ==" ]
[ "client = HelperClient(server=(host, port)) if op == \"GET\": if path", "print(\"Path cannot be empty for a POST request\") usage() sys.exit(2)", "expecting return def do_sequence_knx_idevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\",", "#json_string = json.dumps(json_data, indent=2, sort_keys=True) print (response.payload.decode()) # do_get(response.payload.decode(), client)", "HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60)", "print(\" check: \") print (check_string) if check_string == json_string: print(\"", "= cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\")", "50 my_url = url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\") return mybase[0] def", "json_data def install(my_base): sn = get_sn(my_base) print (\" SN :", "[ {0: 1, 11: \".knx\", 7:[1], 12 :\"blah.blah\" } ]", "60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content)", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [", "= cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) print (response.payload.decode()) #", "==> 7 # st 6 def do_sequence_knx_knx_int(my_base): # url, content,", "a GET-None request\") usage() sys.exit(2) response = client.get_non(path, None, None,", "print (\"=========\") print (response.payload) print (\"=========\") else: print (\"payload: none\")", "== \"n\" or chosen == \"N\" or chosen == \"y\"", "json_string: print(\" =+++===> OK \") else: print(\" =+++===> NOT OK", "if \"000002\" == sn : # actuator ==> receipient #", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "7777 , 6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\",", "\"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]} ]", "== defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try: print (type(response.payload), len(response.payload)) print (\"=========\")", "**ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload) json_string", "mypath); return; host, port, path = parse_uri(mypath) try: tmp =", "60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx resource def do_sequence_knx_knx(my_base): #", "\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\",", "json.dumps(json_data, indent=2, sort_keys=True) except: print(\"error in cbor..\") print (json_string) print", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base): #", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"loadComplete\"}", "if mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath); return;", "request\") usage() sys.exit(2) response = client.get_non(path, None, None, **ct) print((response.pretty_print()))", "content) # ca content = { 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60,", "(\"JSON ::\") print (json_string) client.stop() elif op == \"OBSERVE\": if", "type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\") return #print(response.pretty_print()) if", "[ {0: 1, 11: \"/p/push\", 7:[1], 12 :\"blah.blah\" } ]", ":\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\")", "60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base): # url, content,", "print (\" not handled: \", response) else: print (\" Response", "chosen == \"Y\": while True: rst = eval(input(\"Send RST message?", "str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload) cbor_data = cbor.loads(json_data) payload = cbor_data", "execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base): # url, content, accept,", "# ./knx resource # sia ==> 4 # ga ==>", "# - parameter exchange: 15 (rnd)- return value # -", "response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2,", "transmit = 3 update = 4 content = [ {", "print (response.payload) print (\"=========\") else: print (\"payload: none\") elif response.content_type", "60, 60, content) content = 2 print(\"set IA :\", content);", "print(\"===================\") print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get HWV :\");", "# sia ==> 4 # ga ==> 7 # st", "# - credential exchange: 10 - return value # -", "port)) #nclientcheck = HelperClient(server=(host, port)) payload = 0 if accept", "= data[0] return url[1:] def get_ct(line): tagvalues = line.split(\";\") for", "sort_keys=True) print (\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/cbor\"]:", "data[0] return url[1:] def get_ct(line): tagvalues = line.split(\";\") for tag", "SN: \", sn) content = True print(\"set PM :\", content);", "None: print(\"Path cannot be empty for a DELETE request\") usage()", "in opts: if o in (\"-o\", \"--operation\"): op = a", "url, content, accept, contents content = [ {\"id\": 1, \"ia\":", "json.loads(payload) cbor_data = cbor.dumps(json_data) payload = bytes(cbor_data) if ct['accept'] ==", "usage() sys.exit(2) if __name__ == '__main__': # pragma: no cover", "(\" SN : \", sn) print(\"===================\") print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\",", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\",", "print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content = True print(\"set", "60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base): # url, content, accept, contents", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content =", "payload = 0 response = nclient.delete(path, None, None, **ct) client_callback(response)", "cannot be empty for a GET request\") usage() sys.exit(2) client.observe(path,", "ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload) cbor_data = cbor.dumps(json_data) payload", "= {} my_base = \"\" def usage(): # pragma: no", "\"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2", "{2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def", "port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host =", "def do_sequence_a_sen(my_base): # url, content, accept, contents content = {2:", "HelperClient from coapthon.utils import parse_uri from coapthon import defines client", "== 60: payload = cbor.dumps(content) else: payload = content print", "\"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\",", "\"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2", "content = [ {0: 1, 11: \"p/push\", 7:[1], 8: [2]", "response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2,", "indent=2, sort_keys=True) print (json_string) client.stop() elif op == \"PUT\": if", "client_callback_observe) elif op == \"DELETE\": if path is None: print(\"Path", "# ga ==> 7 # st 6 def do_sequence_knx_knx_int(my_base): #", "False ct = {} ct['accept'] = ct_value ct['content_type'] = ct_value", "6 def do_sequence_knx_knx_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60)", "(\"=========\") print (response.payload) print (\"=========\") #json_data = loads(response.payload) #print(json_data) #print", "o in (\"-P\", \"--payload\"): payload = a elif o in", "path = None payload = None content_type = None #ct", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"startLoading\"}", "content) content = False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60,", "\"path\": \"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60)", "json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data", "loads(response.payload) #print(json_data) #print (\"=========\") json_string = \"\" try: json_data =", "break else: break def execute_get(mypath, ct_value): print (\"---------------------------\") print (\"execute_get:", "60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content = 44 print(\"set", "execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient table #", "== application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {0: 2,", "\"/p/push\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content)", "HelperClient(server=(host, port)) payload = 0 response = nclient.delete(path, None, None,", "client.get_non(path, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]: json_data", "40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {0:", "60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content = 44 print(\"set IA", "b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # ca content =", "None content_type = None #ct = {'content_type': defines.Content_types[\"application/link-format\"]} ct =", "counter = 2 try: while counter > 0: time.sleep(1) counter", "2: \"loadComplete\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "=+++===> NOT OK \") print (json_string) elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]:", "= cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if", "rst != \"\" and not (rst == \"n\" or rst", "60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base): # url, content,", "response = client.put(path, payload) print((response.pretty_print())) client.stop() elif op == \"DISCOVER\":", "request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of the request\") print(\"\\t-f, --payload-file=\\t\\tFile with payload", "# should use /fp/r print (\"--------------------\") print (\"installing SN: \",", "is not None: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload)", "ct_value[0] return \"\" def get_base(url): # python3 knxcoapclient.py -o GET", "== \"GET\": if path is None: print(\"Path cannot be empty", "- parameter exchange: 15 (rnd)- return value # - credential", "None, None, **ct) client_callback(response) nclient.stop() return response def execute_del(mypath, ct_value):", "::\") print (response.payload.decode()) print (\"\\n\\n\") if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data", "False break else: break def execute_get(mypath, ct_value): print (\"---------------------------\") print", "8: [1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40)", "2, 12: \"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]}, {0: 3, 12: \"xxxxyyyia3\",", "print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content =", "tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass client", "try: while counter > 0: time.sleep(1) counter = counter -", "read = 1, write = 2, transmit = 3 update", "1: False } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60,", "or chosen == \"N\" or chosen == \"y\" or chosen", "format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {0: 2, 12: \"xxxxyyyia2\",", "def do_sequence_dev(my_base): print(\"===================\") print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60)", "= [ {0: 1, 12: \"Ia.IA1\", 112: \"path1\", 7:[2222,3333]} ]", "= [ { 0: 1, 11: \"/p/light\", 7:[1], 8: [1]", "10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # ca content", "[ { 0: 1, 12: \"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]} ]", "60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60)", "must be specified\") usage() sys.exit(2) if not path.startswith(\"coap://\"): print(\"Path must", "do_sequence_knx_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content =", "len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") #json_data = loads(response.payload)", "paths_extend lines = payload.splitlines() # add the if len(paths) ==", "{0: 3, 12: \"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60,", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\":", "= 2, transmit = 3 update = 4 content =", "= 40 try: opts, args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\",", "error+++\") return #print(response.pretty_print()) if response.content_type == defines.Content_types[\"text/plain\"]: if response.payload is", "#do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx", "\"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]}, {0: 3, 12: \"xxxxyyyia3\", 112: \"path3\",", "recognized\") usage() sys.exit(2) if __name__ == '__main__': # pragma: no", "execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content = \"my", "accept == 60: #print(\" content :\", content) payload = cbor.dumps(content)", "==> 11 # ga ==> 7 # cflag ==> 8", "ga ==> 7 # st 6 def do_sequence_knx_knx_int(my_base): # url,", "coap://host[:port]/path\") usage() sys.exit(2) host, port, path = parse_uri(path) try: tmp", "0 if accept == 60: #print(\" content :\", content) payload", "credential exchange: 10 - return value # - pase verification", "a PUT request\") usage() sys.exit(2) if payload is None: print(\"Payload", "python import getopt import socket import sys import cbor #from", "not None: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print", "60) print(\"===================\") content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\",", "60) content = {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "payload, None, None , None, **ct) client_callback(response) nclient.stop() def main():", "11: \"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content)", "= { 4: 5678, \"st\": 55, 7: 1, \"value\": 100", "[1,4,5], 7:[44,55,33]}, {0: 3, 1: \"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]} ]", ".knx # ga (7 )= 1 # cflags (8) =", "\"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\",", "60, 60, content) content = 1 print(\"set IA :\", content);", "accept, contents # sequence: # - parameter exchange: 15 (rnd)-", "== defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else: if response.payload is not None:", "sys.exit(2) client.observe(path, client_callback_observe) elif op == \"DELETE\": if path is", "application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {0: 2, 12:", "not None: print (\"type, len\", type(response.payload), len(response.payload)) print (response.payload) #else:", "def do_sequence_fp_r(my_base): # url, content, accept, contents content = [", "{} ct['accept'] = accept ct['content_type'] = ct_value if mypath.startswith(\"coap://\") ==", "accept, contents content = [ {0: 1, 12: \"Ia.IA1\", 112:", "(json_string) elif response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else: if response.payload", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "while check: chosen = eval(input(\"Stop observing? [y/N]: \")) if chosen", "client_callback_discovery(response, checkdata=None): print(\" --- Discovery Callback ---\") global my_base if", "client_callback(response) nclient.stop() def main(): # pragma: no cover global client", "content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content = False print(\"set PM :\", content);", "is not None: print (\"response code:\",response.code) print (\"response type:\",response.content_type) if", "print help information and exit: print((str(err))) # will print something", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base):", "(json_string) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string =", "None, **ct) client_callback(response) nclient.stop() return response def execute_del(mypath, ct_value): print", "execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base): #sn = get_sn(my_base) install(my_base)", "{ 5: { 6: 1, 7: 1, 1: True }", "print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string", "= [ {\"id\": 2, \"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3,", "pa content = { 10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60,", "cannot be empty for a PUT request\") usage() sys.exit(2) if", "execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base): # url, content, accept, contents content", "def do_sequence_knx_idevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def", "content :\", content) payload = cbor.dumps(content) else: payload = content", "4 content = [ {0: 1, 11: \"/p/push\", 7:[1], 12", "False } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60,", "if \"000001\" == sn : # sensor, e.g sending print", "check = True while check: chosen = eval(input(\"Stop observing? [y/N]:", "SN : \", sn) print(\"===================\") print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60)", "(json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string =", "print (\"=========\") #json_data = loads(response.payload) #print(json_data) #print (\"=========\") json_string =", "SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data = cbor.loads(sn.payload) #print", "IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content = iid", "response.code > 100: print(\"+++returned error+++\") return #print(response.pretty_print()) if response.content_type ==", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do a post content", "print (\"JSON ::\") print (json_string) client.stop() elif op == \"GETNONE\":", "if check_string == json_string: print(\" =+++===> OK \") else: print(\"", "cbor.loads(response.payload) print (json_data) print (\"---------\") except: traceback.print_exc() json_string = json.dumps(json_data,", "(\"execute_put: \", ct_value, mypath) do_exit = False ct = {}", "if response is not None: print (\"response code:\",response.code) print (\"response", "== \"OBSERVE\": if path is None: print(\"Path cannot be empty", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content = { 1 :", "coapthon import defines client = None paths = {} paths_extend", "#!/usr/bin/env python import getopt import socket import sys import cbor", "be conform to coap://host[:port]/path\") usage() sys.exit(2) host, port, path =", "continue elif chosen == \"y\" or chosen == \"Y\": while", "\"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\",", "= [ {0: 1, 11: \"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]} ]", "pass nclient = HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host, port)) payload", "try: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\")", "1, \"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60,", "= 2 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content)", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group object table", "60, 60, content) content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content)", "client_callback(response, checkdata=None): print(\" --- Callback ---\") if response is not", "for POST (ascii):\", payload ) print (ct['accept'] ) if ct['accept']", "print (\" Response : None\") #check = True #while check:", "chosen == \"y\" or chosen == \"Y\"): print(\"Unrecognized choose.\") continue", "== \"n\" or rst == \"N\" or rst == \"y\"", "-c 50 my_url = url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\") return mybase[0]", "ct_value = ct_value_all[1].split(\",\") return ct_value[0] return \"\" def get_base(url): #", "sort_keys=True) print (\"JSON ::\") print (json_string) client.stop() elif op ==", "if mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath); return", "content) content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60,", "/fp/r print (\"--------------------\") print (\"installing SN: \", sn) content =", "{} ct['accept'] = 40 try: opts, args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\",", "= client.discover( path, client_callback, None, **ct) response = client.discover( path,", "**ct) response = client.discover( path, None, None, **ct) if response", "2, \"href\": \"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\": 3, \"href\": \"xxxxyyy3\",", "execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data = cbor.loads(sn.payload) #print (\"SN : \", json_data)", "# actuator ==> receipient # should use /fp/r print (\"--------------------\")", "eval(input(\"Send RST message? [Y/n]: \")) if rst != \"\" and", "::\") print (json_string) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload)", "{ 4 : 5, 7: 7777 , 6 : \"rp\"}}", "HelperClient(server=(host, port)) response = nclient.get(path, None, None, **ct) client_callback(response) nclient.stop()", "== str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload) cbor_data = cbor.dumps(json_data) payload =", "conform to coap://host[:port]/path\") usage() sys.exit(2) host, port, path = parse_uri(path)", "60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base): # url, content, accept, contents", "cbor.dumps(content) else: payload = content print (\"payload: \", payload) response", "= cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) client.stop()", "\"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError as err: # print help", "= payload.splitlines() # add the if len(paths) == 0: my_base", "content) # no json tags as strings def do_sequence_dev(my_base): print(\"===================\")", "do_sequence_fp_g_int(my_base): # url, content, accept, contents content = [ {0:", "60) content = { 1 : 5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\",", "\"payload for POST (ascii):\", payload ) print (ct['accept'] ) if", "\"DELETE\": if path is None: print(\"Path cannot be empty for", "execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\",", "accept, contents content = {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content)", ": 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content)", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base): # url,", "60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id ==> 0 #", "execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) content = False print(\"set PM :\",", "# add the if len(paths) == 0: my_base = get_base(get_url(lines[0]))", "= 4 content = [ { 0: 1, 11: \"/p/light\",", "{ 0: 2, 12: \"r-Ia.IA2\", 10: \"url2\", 112: \"r-path2\", 7:[44,55,33]},", "= tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port)) nclientcheck", "#print (\"SN : \", json_data) return json_data def install(my_base): sn", "#execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content) # no", "content_type = None #ct = {'content_type': defines.Content_types[\"application/link-format\"]} ct = {}", "sn = get_sn(my_base) print (\" SN : \", sn) iid", "1, 11: \"/p/light\", 7:[1], 8: [1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60,", "paths_extend = {} my_base = \"\" def usage(): # pragma:", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = { 2:", "port)) nclientcheck = HelperClient(server=(host, port)) payload = 0 if accept", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher table # id", "execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base): # url, content, accept,", "sort_keys=True) print(\" check: \") print (check_string) if check_string == json_string:", "if (mypath is None or len(mypath) < 5): return if", "print (\"execute_get: \", ct_value, mypath) print (type(mypath)) if (mypath is", "= tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port)) #nclientcheck", "def do_sequence_knx_knx_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content", "GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url = url.replace(\"coap://\",\"\") mybase =", "tag.split(\"=\") ct_value = ct_value_all[1].split(\",\") return ct_value[0] return \"\" def get_base(url):", "(rnd)- return value # - credential exchange: 10 - return", "choose.\") continue elif rst == \"\" or rst == \"y\"", "a elif o in (\"-c\", \"--content-type\"): ct['accept'] = a print", "accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base): # url, content, accept,", ":\", content) payload = cbor.dumps(content) else: payload = content response", "from coapthon.utils import parse_uri from coapthon import defines client =", "**ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string", "{\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx", "11: \"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]}, {0: 3, 1: \"xxxxyyy3\", 8:", ": None\") #check = True #while check: # chosen =", "= [ {0: 2, 11: \"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]}, {0:", "7:[1], 8: [1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\",", "= HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host, port)) payload = 0", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { 4", "my_url = url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\") return mybase[0] def get_base_from_link(payload):", "checkdata=None): print(\" --- Discovery Callback ---\") global my_base if response", "None, **ct) client_callback(response) nclient.stop() def main(): # pragma: no cover", "] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) content = False print(\"set PM", "if checkdata is not None: check_data = cbor.loads(checkdata) check_string =", "= client.get_non(path, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]:", "\"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\",", "for a GET request\") usage() sys.exit(2) client.observe(path, client_callback_observe) elif op", "execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content =", "# url ==> 10 # ga ==> 7 def do_sequence_fp_r_int(my_base):", "one is a bit dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\",", "None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload)", "7: 7777 , 6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content)", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base): # url, content, accept, contents content", "sys.exit(2) response = client.get_non(path, None, None, **ct) print((response.pretty_print())) if response.content_type", ": 5, 7: 7777 , 6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60,", "id ==> 0 # ia ==> 12 # path ==>", "= cbor.dumps(content) else: payload = content print (\"payload: \", payload)", "== \"POST\": if path is None: print(\"Path cannot be empty", "in (\"-p\", \"--path\"): path = a elif o in (\"-P\",", "print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60)", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\":", "\"(Not Found)\" if code == 133: return \"(METHOD_NOT_ALLOWED)\" if code", "import time import traceback from coapthon.client.helperclient import HelperClient from coapthon.utils", "{\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content =", "accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base): # url, content, accept,", "f: payload = f.read() elif o in (\"-h\", \"--help\"): usage()", "do_sequence_fp_p(my_base): # url, content, accept, contents content = [ {\"id\":", "] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content", "(\" ---------------------\") do_exit = False ct = {} ct['accept'] =", "code2string(response.code)) print (\"response type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\")", "(json_string) client.stop() elif op == \"GETNONE\": if path is None:", "\"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) def do_sequence_a_sen(my_base): # url, content,", "= HelperClient(server=(host, port)) #nclientcheck = HelperClient(server=(host, port)) payload = 0", "hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\")", "print (\"payload: none\") elif response.content_type == defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload))", "content = {2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "# ga ==> 7 def do_sequence_fp_r_int(my_base): # url, content, accept,", "\"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError as err:", "client_callback(response) nclient.stop() def execute_post(mypath, ct_value, accept, content): print (\"---------------------------\") print", "(1) #content = { 5: { 6: 1, 7: 1,", "True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content", "mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths global paths_extend lines =", "do a post content = {\"sia\": 5678, \"st\": 55, \"ga\":", "== str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload) cbor_data = cbor.loads(json_data) payload =", "content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60,", "content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content = {0: b\"id\",", "content) content = { 2: \"loadComplete\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\",", "= nclient.delete(path, None, None, **ct) client_callback(response) #nclient.stop() #sys.exit(2) print (\"=======\")", "(json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string =", "60) print(\"===================\") print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get Model", "print (\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data", "] ; read = 1, write = 2, transmit =", ":\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) content = False", "lines = payload.splitlines() # add the if len(paths) == 0:", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content", "sort_keys=True) print (response.payload.decode()) # do_get(response.payload.decode(), client) client_callback_discovery(response) counter = 2", "= json.dumps(json_data, indent=2, sort_keys=True) print (json_string) elif response.content_type == defines.Content_types[\"application/link-format\"]:", "execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {\"id\": 2, \"ia\": \"xxxxyyyia2\", \"path\":", "contents content = [ {0: 1, 12: \"Ia.IA1\", 112: \"path1\",", "return \"(Not Found)\" if code == 133: return \"(METHOD_NOT_ALLOWED)\" if", "content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\",", "code == 68: return \"(Changed)\" if code == 69: return", "json_data = json.loads(payload) cbor_data = cbor.loads(json_data) payload = cbor_data response", "==> 4 # ga ==> 7 # st 6 def", "do_sequence_oscore(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60)", "the request\") print(\"\\t-f, --payload-file=\\t\\tFile with payload of the request\") def", "not None: check_data = cbor.loads(checkdata) check_string = json.dumps(check_data, indent=2, sort_keys=True)", "hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base): #sn =", "\")) # if chosen != \"\" and not (chosen ==", "--- Callback ---\") if response is not None: print (\"response", "name\" print(\"set hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\",", "{ 2: \"startLoading\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "a GET request\") usage() sys.exit(2) response = client.get(path, None, None,", "[ {0: 1, 12: \"Ia.IA1\", 112: \"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\",", "print((response.pretty_print())) client.stop() elif op == \"DISCOVER\": #response = client.discover( path,", "do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None): print(\" --- Discovery Callback ---\") global", "cannot be empty for a POST request\") usage() sys.exit(2) if", "---------------------\") do_exit = False ct = {} ct['accept'] = accept", "defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print", "= get_sn(my_base) install(my_base) return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base)", "defines client = None paths = {} paths_extend = {}", "\"N\" or chosen == \"y\" or chosen == \"Y\"): #", "mypath); return host, port, path = parse_uri(mypath) try: tmp =", "type(response.payload), len(response.payload)) print (response.payload) #else: # print (\" not handled:", "exchange: 14 - no return value content = { 15:", "None: print(\"Payload cannot be empty for a POST request\") usage()", "# python3 knxcoapclient.py -o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url", "(\"application/vnd.ocf+cbor\") try: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print", "60, content) # no json tags as strings def do_sequence_dev(my_base):", "print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn = get_sn(my_base)", "in (\"-c\", \"--content-type\"): ct['accept'] = a print (\"content type request", "content = [ {\"id\": 2, \"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\":", "60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) #", "be empty for a DELETE request\") usage() sys.exit(2) response =", "# note this one is a bit dirty hard coded...", "sn = get_sn(my_base) print (\" SN : \", sn) print(\"===================\")", "\") print (check_string) if check_string == json_string: print(\" =+++===> OK", "print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data = cbor.loads(sn.payload)", "rst == \"y\" or rst == \"Y\": client.cancel_observing(response, True) else:", "7 # cflag ==> 8 def do_sequence_fp_g_int(my_base): # url, content,", "get_sn(my_base) install(my_base) return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base)", "as f: payload = f.read() elif o in (\"-h\", \"--help\"):", "#sys.exit(2) print (\"=======\") def execute_put(mypath, ct_value, accept, content): print (\"---------------------------\")", "executing: \", mypath); return; ct = {} ct['accept'] = ct_value", "cannot be empty for a DELETE request\") usage() sys.exit(2) response", ": \", sn) print(\"===================\") print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\")", "60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id ==> 0 #", ", 6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60)", "(8) = [\"r\" ] ; read = 1, write =", "] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) content = False print(\"set PM", "host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host) host", "content = {\"value\": { 4 : 5, 7: 7777 ,", "for a PUT request\") usage() sys.exit(2) response = client.put(path, payload)", "2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40)", "return json_data def install(my_base): sn = get_sn(my_base) print (\" SN", "bytes(cbor_data) if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload) cbor_data =", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "and not (rst == \"n\" or rst == \"N\" or", "60) sn = get_sn(my_base) print (\" SN : \", sn)", "response = nclient.get(path, None, None, **ct) client_callback(response) nclient.stop() return response", "60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) #", "client.stop() elif op == \"PUT\": if path is None: print(\"Path", "==> 0 # href ==> 11 # ga ==> 7", "len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") json_data = cbor.loads(response.payload)", "json import time import traceback from coapthon.client.helperclient import HelperClient from", "cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print", "# will print something like \"option -a not recognized\" usage()", "defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print", "accept, contents content = [ {0: 1, 11: \"xxxx1\", 8:", "usage() sys.exit(2) client.observe(path, client_callback_observe) elif op == \"DELETE\": if path", "False: print(\" not executing: \", mypath); return host, port, path", "69: return \"(Content)\" if code == 132: return \"(Not Found)\"", "accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content = { 1 : 5,", "if response.payload is not None: print (\"type, len\", type(response.payload), len(response.payload))", "json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print (json_string)", "must be conform to coap://host[:port]/path\") usage() sys.exit(2) host, port, path", "= eval(input(\"Send RST message? [Y/n]: \")) if rst != \"\"", "def do_sequence_fp_p_int(my_base): # url, content, accept, contents content = [", "contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base): # url, content, accept, contents", "mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath); return host,", "# 40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [", "0: 1, 12: \"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60,", "format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {\"id\": 2, \"ia\": \"xxxxyyyia2\",", "\"--path\"): path = a elif o in (\"-P\", \"--payload\"): payload", "\"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\": 3, \"href\": \"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}", "do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None): print(\" ---", "= {\"value\": { \"sia\" : 5, \"ga\": 7, \"st\": \"rp\"}}", "60) content = {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "3, \"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60,", "execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60,", "# do_get(response.payload.decode(), client) client_callback_discovery(response) counter = 2 try: while counter", "None, None, **ct) if response is not None: print(response.pretty_print()) if", "= f.read() elif o in (\"-h\", \"--help\"): usage() sys.exit() else:", "(\"=========\") else: print (\"payload: none\") elif response.content_type == defines.Content_types[\"application/cbor\"]: print", "port)) response = nclient.get(path, None, None, **ct) client_callback(response) nclient.stop() return", "(type(mypath)) if (mypath is None or len(mypath) < 5): return", "} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher", "len(response.payload)) print (response.payload) #else: # print (\" not handled: \",", "print((str(err))) # will print something like \"option -a not recognized\"", "execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base): # url, content, accept, contents content", "#print(response.pretty_print()) if response.content_type == defines.Content_types[\"text/plain\"]: if response.payload is not None:", "op = a elif o in (\"-p\", \"--path\"): path =", "\"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\",", "= cbor.loads(checkdata) check_string = json.dumps(check_data, indent=2, sort_keys=True) print(\" check: \")", "(\"response type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\") return if", "be empty for a GET-None request\") usage() sys.exit(2) response =", "if path is None: print(\"Path cannot be empty for a", "{0: 2, 12: \"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]}, {0: 3, 12:", "else: payload = content response = nclient.post(path, payload, None, None", "1, \"value\": 100 } # st ga value (1) #content", "of the request\") def get_url(line): data = line.split(\">\") url =", "(rst == \"n\" or rst == \"N\" or rst ==", "print (\"execute_post: \", ct_value, mypath) print (content) print (\" ---------------------\")", "empty for a GET request\") usage() sys.exit(2) response = client.get(path,", "cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) except: print(\"error in cbor..\")", "= a elif o in (\"-p\", \"--path\"): path = a", ")= 1 # cflags (8) = [\"r\" ] ; read", "iid xxx\" print(\"set iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content)", "not path.startswith(\"coap://\"): print(\"Path must be conform to coap://host[:port]/path\") usage() sys.exit(2)", "contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60,", "2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) def do_sequence_a_sen(my_base): # url,", "ct = {} ct['accept'] = ct_value host, port, path =", "7 def do_sequence_fp_p_int(my_base): # url, content, accept, contents content =", "3, 12: \"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60,", "# url, content, accept, contents content = [ {0: 1,", "content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base): # url, content,", "or chosen == \"y\" or chosen == \"Y\"): # print(\"Unrecognized", "= cbor.loads(json_data) payload = cbor_data response = client.post(path, payload, None,", "\"path2\", 7:[44,55,33]}, {0: 3, 12: \"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]} ]", "= execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data = cbor.loads(sn.payload) #print (\"SN : \",", "(json_data) print (\"---------\") except: traceback.print_exc() json_string = json.dumps(json_data, indent=2, sort_keys=True)", "execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\",", "print(\"Path must be specified\") usage() sys.exit(2) if not path.startswith(\"coap://\"): print(\"Path", "execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content", "= cbor.loads(sn.payload) #print (\"SN : \", json_data) return json_data def", "60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content = \"my host", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient table # id (0)= 1 #", "\"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base): #", "cmd ==> 2 def do_sequence_lsm_int(my_base): # url, content, accept, contents", "#print(json_data) #print (\"=========\") json_string = \"\" try: json_data = cbor.loads(response.payload)", "\"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base): #", "40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base): #", "content = {\"value\": { \"sia\" : 5, \"ga\": 7, \"st\":", "execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40 == application-link", "content = \"my host name\" print(\"set hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\",", "elif response.content_type == defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload)) print (\"=========\") print", "op == \"POST\": if path is None: print(\"Path cannot be", "except: traceback.print_exc() json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) elif", "print(\" --- Callback ---\") if response is not None: print", "sys.exit(2) if path is None: print(\"Path must be specified\") usage()", "60, content) content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\",", "print (type(mypath)) if (mypath is None or len(mypath) < 5):", "open(a, 'r') as f: payload = f.read() elif o in", "{\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content =", "7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40", "accept ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False: print(\" not", "try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass", "(\"--------------------\") print (\"installing SN: \", sn) content = True print(\"set", "def execute_get(mypath, ct_value): print (\"---------------------------\") print (\"execute_get: \", ct_value, mypath)", "} } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content)", "json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON", "def main(): # pragma: no cover global client op =", "SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn = get_sn(my_base) print", "print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\",", "= [\"r\" ] ; read = 1, write = 2,", "content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = { 2: \"loadComplete\"}", "11: \".knx\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60,", "\"y\" or rst == \"Y\": client.cancel_observing(response, True) else: client.cancel_observing(response, False)", "accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base): # url, content, accept,", "True: rst = eval(input(\"Send RST message? [Y/n]: \")) if rst", "11: \"/p/push\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60,", "pragma: no cover global client print(\"Callback_observe\") check = True while", "0: 1, 11: \"/p/light\", 7:[1], 8: [1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\",", "payload.splitlines() # add the if len(paths) == 0: my_base =", "client.observe(path, client_callback_observe) elif op == \"DELETE\": if path is None:", "1, 12: \"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60,", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base): # url,", "= { 1 : 5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60,", "40) content = [ {\"id\": 2, \"href\": \"xxxxyyy2\", \"cflag\": [1,4,5],", "\"n\" or chosen == \"N\" or chosen == \"y\" or", "sort_keys=True) #print (\"JSON ::\") print (response.payload.decode()) print (\"\\n\\n\") if response.content_type", "nclient.post(path, payload, None, None , None, **ct) client_callback(response) nclient.stop() def", "or rst == \"N\" or rst == \"y\" or rst", "60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content = 1050", "note this one is a bit dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\",", "(response.payload) print (\"=========\") #json_data = loads(response.payload) #print(json_data) #print (\"=========\") json_string", "[1,4,5], \"ga\":[44,55,33]}, {\"id\": 3, \"href\": \"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]} ]", "60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx resource def do_sequence_knx_knx(my_base):", "def do_sequence_lsm(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content", "do_sequence_auth_at(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content", "content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id ==>", "url, content, accept, contents content = [ {0: 1, 12:", "if code == 69: return \"(Content)\" if code == 132:", "44 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\",", "port, path = parse_uri(mypath) try: tmp = socket.gethostbyname(host) host =", ":\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\")", "60) # 40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content =", "ct['accept'] = 40 try: opts, args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\",", "{} my_base = \"\" def usage(): # pragma: no cover", "def usage(): # pragma: no cover print(\"Command:\\tknxcoapclient.py -o -p [-P]\")", "#return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base)", "60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base): # url, content, accept,", "getopt.GetoptError as err: # print help information and exit: print((str(err)))", "\"reset\"} print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) content =", "execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40)", "choose.\") # continue def client_callback_observe(response): # pragma: no cover global", "60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def", "content = {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "-o -p [-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of the", "object table # id (0)= 1 # url (11)= /p/light", "{0: 1, 12: \"Ia.IA1\", 112: \"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60,", "print(\"Client Shutdown\") #client.stop() #execute_list() client.stop() else: print(\"Operation not recognized\") usage()", "content, accept, contents content = {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60,", ":\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\")", "5678, 5: { 6: 1, 7: 1, 1: False }", "# url (11)= /p/light # ga (7 )= 1 #", "\") else: print(\" =+++===> NOT OK \") print (json_string) elif", "f.read() elif o in (\"-h\", \"--help\"): usage() sys.exit() else: usage()", "ct_value, accept, content): print (\"---------------------------\") print (\"execute_put: \", ct_value, mypath)", "3, \"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content)", "60) # group object table # id (0)= 1 #", "ct_value): print (\"---------------------------\") print (\"execute_del: \", ct_value, mypath) do_exit =", "{ 6: 1, 7: 1, 1: True } } #execute_post(\"coap://\"+my_base+\"/.knx\",", "cflag ==> 8 def do_sequence_fp_g_int(my_base): # url, content, accept, contents", "#else: # print (\" not handled: \", response) else: print", "else: print (\" Response : None\") #check = True #while", "0: time.sleep(1) counter = counter - 1 #client.stop() except KeyboardInterrupt:", "payload, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data", "= { 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # expecting", "True #while check: # chosen = eval(input(\"Stop observing? [y/N]: \"))", "60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {0: 2, 11: \"xxxxyyy2\",", "sn) content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60,", "usage() sys.exit(2) response = client.delete(path) print((response.pretty_print())) client.stop() elif op ==", "print (check_string) if check_string == json_string: print(\" =+++===> OK \")", "== \"PUT\": if path is None: print(\"Path cannot be empty", "[ {0: 2, 12: \"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]}, {0: 3,", "content) content = {0: b\"id2\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\",", "do_get(response.payload.decode(), client) client_callback_discovery(response) counter = 2 try: while counter >", "def client_callback_observe(response): # pragma: no cover global client print(\"Callback_observe\") check", "def client_callback_discovery(response, checkdata=None): print(\" --- Discovery Callback ---\") global my_base", "sys.exit(2) for o, a in opts: if o in (\"-o\",", "content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient table # id (0)= 1", "code:\",response.code, code2string(response.code)) print (\"response type:\",response.content_type) if response.code > 100: print(\"+++returned", "3, 1: \"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60,", "60) def do_sequence_lsm(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "response is not None: print (\"response code:\",response.code) print (\"response type:\",response.content_type)", "is not None: print(response.pretty_print()) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data =", ":\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data = cbor.loads(sn.payload) #print (\"SN", "12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) content =", "60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base): # url, content, accept,", "(response.payload.decode()) print (\"\\n\\n\") if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload)", "payload ) print (ct['accept'] ) if ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data", "14 - no return value content = { 15: b\"a-15-sdfsdred\"}", "not executing: \", mypath); return; host, port, path = parse_uri(mypath)", "# pa content = { 10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60,", "60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base): # url, content, accept, contents", "1 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content", "} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) content = False print(\"set", "usage() sys.exit(2) response = client.get(path, None, None, **ct) print((response.pretty_print())) if", "json_string = \"\" try: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data,", "port)) payload = 0 if accept == 60: #print(\" content", "100: print(\"+++returned error+++\") return if response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode())", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"unload\"}", "def do_sequence_fp_r_int(my_base): # url, content, accept, contents content = [", "a POST request\") usage() sys.exit(2) if payload is None: print(\"Payload", "content) # expecting return def do_sequence_knx_idevid(my_base): # url, content, accept,", "content = [ {0: 2, 11: \"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]},", "a in opts: if o in (\"-o\", \"--operation\"): op =", "nclient.stop() def execute_post(mypath, ct_value, accept, content): print (\"---------------------------\") print (\"execute_post:", "= json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]:", "\"loadComplete\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "2 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content", "content = [ {0: 1, 11: \"/p/push\", 7:[1], 12 :\"blah.blah\"", "check_data = cbor.loads(checkdata) check_string = json.dumps(check_data, indent=2, sort_keys=True) print(\" check:", "= parse_uri(mypath) try: tmp = socket.gethostbyname(host) host = tmp except", "cbor.loads(sn.payload) #print (\"SN : \", json_data) return json_data def install(my_base):", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx resource # sia ==>", "print (\"--------------------\") print (\"installing SN: \", sn) content = True", "== \"DELETE\": if path is None: print(\"Path cannot be empty", "= False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content)", "usage() sys.exit() else: usage() sys.exit(2) if op is None: print(\"Operation", "print(\"===================\") print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get Model :\");", "do_sequence(my_base): #sn = get_sn(my_base) install(my_base) return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base)", "usage(): # pragma: no cover print(\"Command:\\tknxcoapclient.py -o -p [-P]\") print(\"Options:\")", "#do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base)", "\", sn) iid = \"5\" # installation id if \"000001\"", "print (\"---------------------------\") print (\"execute_get: \", ct_value, mypath) print (type(mypath)) if", "\"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]}", "60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\",", "print(\"\\t-c, --contenttype=\\t\\tcontenttype of the request\") print(\"\\t-f, --payload-file=\\t\\tFile with payload of", "update = 4 content = [ {0: 1, 11: \"/p/push\",", "not executing: \", mypath); return host, port, path = parse_uri(mypath)", "return my_base def get_sn(my_base): print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\",", "{\"value\": { \"sia\" : 5, \"ga\": 7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\",", "elif o in (\"-p\", \"--path\"): path = a elif o", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2", "#json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) #print (\"JSON", "execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id ==> 0", "execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { 4 : 5, 7:", "{ 6: 1, 7: 1, 1: False } } #execute_post(\"coap://\"+my_base+\"/.knx\",", "or len(mypath) < 5): return if mypath.startswith(\"coap://\") == False: print(\"", "#do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base)", "client_callback_discovery(response) counter = 2 try: while counter > 0: time.sleep(1)", "4 content = [ {0: 1, 11: \".knx\", 7:[1], 12", "time.sleep(1) counter = counter - 1 #client.stop() except KeyboardInterrupt: print(\"Client", "path = parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp", "\"5\" # installation id if \"000001\" == sn : #", "usage() sys.exit(2) if not path.startswith(\"coap://\"): print(\"Path must be conform to", "None: print(\"Path cannot be empty for a POST request\") usage()", "(\"=========\") json_data = cbor.loads(response.payload) print (json_data) print (\"---------\") except: traceback.print_exc()", "def do_sequence_fp_g(my_base): # url, content, accept, contents content = [", "7:[1], 8: [2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\",", "60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def", "print (json_string) print (\"===+++===\") if checkdata is not None: check_data", "# pragma: no cover global client op = None path", "recipient table # id (0)= 1 # ia (12) #", "def do_sequence_knx_spake(my_base): # url, content, accept, contents # sequence: #", "6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) content = {0: b\"id2\", 1", "#execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content) # no json tags as strings", "= \"5\" # installation id if \"000001\" == sn :", "60, content) content = 1 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\",", "\"sia\" : 5, \"ga\": 7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60,", "1, \"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60,", "nclient.delete(path, None, None, **ct) client_callback(response) #nclient.stop() #sys.exit(2) print (\"=======\") def", "install(my_base) return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base)", "be empty for a PUT request\") usage() sys.exit(2) if payload", "::\") print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload)", "sensor, e.g sending print (\"--------------------\") print (\"Installing SN: \", sn)", "= my_url.split(\"/\") return mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths global", "contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base): # url, content, accept, contents", "= {2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "client.cancel_observing(response, True) else: client.cancel_observing(response, False) check = False break else:", "indent=2, sort_keys=True) print (\"JSON ::\") print (json_string) if response.content_type ==", "content, accept, contents content = [ {\"id\": 1, \"ia\": \"r-Ia.IA1\",", "my_base = \"\" def usage(): # pragma: no cover print(\"Command:\\tknxcoapclient.py", "contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { \"sia\" : 5,", "= [ {\"id\": 1, \"ia\": \"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]} ]", "60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {\"id\":", "== 68: return \"(Changed)\" if code == 69: return \"(Content)\"", "content = 44 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60,", "json_data = cbor.loads(sn.payload) #print (\"SN : \", json_data) return json_data", "else: print(\" =+++===> NOT OK \") print (json_string) elif response.content_type", "resource # sia ==> 4 # ga ==> 7 #", "my_base if response is not None: print (\"response code:\",response.code) print", "ga ==> 7 # cflag ==> 8 def do_sequence_fp_g_int(my_base): #", "socket.gaierror: pass nclient = HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host, port))", "try: opts, args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\", \"payload=\",", "execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60)", "\"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content) def do_sequence_auth(my_base): # url, content,", "== \"Y\": while True: rst = eval(input(\"Send RST message? [Y/n]:", "**ct) if response is not None: print(response.pretty_print()) if response.content_type ==", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd ==>", "execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60,", "= HelperClient(server=(host, port)) if op == \"GET\": if path is", "def get_sn(my_base): print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data", "content): print (\"---------------------------\") print (\"execute_post: \", ct_value, mypath) print (content)", "60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def", "indent=2, sort_keys=True) print(\" check: \") print (check_string) if check_string ==", "ct_value_all[1].split(\",\") return ct_value[0] return \"\" def get_base(url): # python3 knxcoapclient.py", "execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\",", "content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base): # url, content, accept, contents", "(11)= .knx # ga (7 )= 1 # cflags (8)", "print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") #json_data", "\"--content-type\"): ct['accept'] = a print (\"content type request : \",", "==> 8 def do_sequence_fp_g_int(my_base): # url, content, accept, contents content", "path is None: print(\"Path cannot be empty for a GET-None", "json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if response.content_type ==", "execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content = 44 print(\"set IA :\", content);", "iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) content = { 2: \"startLoading\"}", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\" == sn : # actuator ==>", "(response.payload.decode()) my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code): if code ==", "= [ {0: 2, 12: \"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]}, {0:", "= json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]:", "counter = counter - 1 #client.stop() except KeyboardInterrupt: print(\"Client Shutdown\")", "sys.exit(2) host, port, path = parse_uri(path) try: tmp = socket.gethostbyname(host)", "60, 60, content) content = { 2: \"loadComplete\"} print(\"lsm :\",", "**ct) client_callback(response) nclient.stop() def main(): # pragma: no cover global", "if response.code > 100: print(\"+++returned error+++\") return if response.content_type ==", "cbor.loads(checkdata) check_string = json.dumps(check_data, indent=2, sort_keys=True) print(\" check: \") print", "not None: print(response.pretty_print()) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload)", "{0: 1, 11: \"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60,", "PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\")", "==> 7 def do_sequence_fp_p_int(my_base): # url, content, accept, contents content", "do_sequence_fp_g(my_base): # url, content, accept, contents content = [ {\"id\":", "content, accept, contents content = [ {\"id\": 1, \"href\": \"xxxx1\",", "sys.exit(2) if __name__ == '__main__': # pragma: no cover main()", "4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) content = {0:", "else: break def execute_get(mypath, ct_value): print (\"---------------------------\") print (\"execute_get: \",", "False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\",", "ct = {} ct['accept'] = 40 try: opts, args =", "5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60)", "global paths_extend lines = payload.splitlines() # add the if len(paths)", "\"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) #", "[Y/n]: \")) if rst != \"\" and not (rst ==", "cannot be empty for a GET request\") usage() sys.exit(2) response", "payload) response = nclient.put(path, payload, None, None , None, **ct)", "\"url2\", 112: \"r-path2\", 7:[44,55,33]}, {0: 3, 12: \"r-Ia.IA3\", 112: \"r-path3\",", "OK \") print (json_string) elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\")", "table # id (0)= 1 # ia (12) # url", "60) def do_sequence_knx_spake(my_base): # url, content, accept, contents # sequence:", "if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload) cbor_data = cbor.loads(json_data)", "else: if response.payload is not None: print (\"type, len\", type(response.payload),", "contents content = {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content) def", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do a post content = {\"sia\": 5678,", "op is None: print(\"Operation must be specified\") usage() sys.exit(2) if", "content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40)", "112 # url ==> 10 # ga ==> 7 def", "(\"\\n\\n\") if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string =", "8: [1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60)", "my_base def get_sn(my_base): print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60)", "return if mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath);", "(\"execute_post: \", ct_value, mypath) print (content) print (\" ---------------------\") do_exit", "4 content = [ {0: 1, 11: \"p/push\", 7:[1], 8:", "1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base): #", "o in (\"-c\", \"--content-type\"): ct['accept'] = a print (\"content type", "print(\"===================\") print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get FWV :\");", "1, 11: \"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60,", "return \"(Content)\" if code == 132: return \"(Not Found)\" if", "execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {\"id\": 2, \"href\":", "id (0)= 1 # url (11)= /p/light # ga (7", "str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload) cbor_data = cbor.dumps(json_data) payload = bytes(cbor_data)", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content = {0:", "\"\" def usage(): # pragma: no cover print(\"Command:\\tknxcoapclient.py -o -p", "(\"payload: \", payload) response = nclient.put(path, payload, None, None ,", "60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base): # url, content,", "code == 69: return \"(Content)\" if code == 132: return", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40 == application-link format", "content) payload = cbor.dumps(content) else: payload = content response =", "check: chosen = eval(input(\"Stop observing? [y/N]: \")) if chosen !=", "o in (\"-p\", \"--path\"): path = a elif o in", "if not path.startswith(\"coap://\"): print(\"Path must be conform to coap://host[:port]/path\") usage()", "cbor.dumps(json_data) payload = bytes(cbor_data) if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data =", "# cflag ==> 8 def do_sequence_fp_g_int(my_base): # url, content, accept,", "iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) #", "do_sequence_a_sen(my_base): # url, content, accept, contents content = {2: \"reset\"}", "while counter > 0: time.sleep(1) counter = counter - 1", "update = 4 content = [ {0: 1, 11: \"p/push\",", "def do_sequence_knx_ldevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def", "client.stop() else: print(\"Operation not recognized\") usage() sys.exit(2) if __name__ ==", "elif response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else: if response.payload is", "= content response = nclient.post(path, payload, None, None , None,", "len(paths) == 0: my_base = get_base(get_url(lines[0])) return my_base def get_sn(my_base):", "content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher table # id (0)= 1", "==> 7 # cflag ==> 8 def do_sequence_fp_g_int(my_base): # url,", "(content) print (\" ---------------------\") do_exit = False ct = {}", "\"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60)", "(7 )= 1 # cflags (8) = [\"r\" ] ;", "return mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths global paths_extend lines", "= cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) #print (\"JSON ::\")", "content = [ { 0: 1, 11: \"/p/light\", 7:[1], 8:", "60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {\"id\": 2, \"href\": \"xxxxyyy2\",", "12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) content =", "execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd ==> 2", "execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd", "== defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True)", "def do_sequence_fp_p(my_base): # url, content, accept, contents content = [", "value content = { 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content)", "do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) #", "# cflags (8) = [\"r\" ] ; read = 1,", "content) content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) content =", "= json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print (json_string) if", "print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string =", "execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base): # url,", "socket.gethostbyname(host) host = tmp except socket.gaierror: pass nclient = HelperClient(server=(host,", "\"GETNONE\": if path is None: print(\"Path cannot be empty for", "specified\") usage() sys.exit(2) if not path.startswith(\"coap://\"): print(\"Path must be conform", "5678, \"st\": 55, \"ga\": 1, \"value\": 100 } content =", "import socket import sys import cbor #from cbor2 import dumps,", "(\"---------------------------\") print (\"execute_get: \", ct_value, mypath) print (type(mypath)) if (mypath", "content) content = 1 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60,", "PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = {", "\"(INTERNAL_SERVER_ERROR)\" return \"\" def client_callback(response, checkdata=None): print(\" --- Callback ---\")", "12 # path ==> 112 # url ==> 10 #", "payload = cbor_data response = client.post(path, payload, None, None, **ct)", "if response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base)", "] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40 ==", "60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ {", "**ct) client_callback(response) nclient.stop() return response def execute_del(mypath, ct_value): print (\"---------------------------\")", "print(\"error in cbor..\") print (json_string) print (\"===+++===\") if checkdata is", "60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd ==> 2 def do_sequence_lsm_int(my_base): #", "bit dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base):", "checkdata is not None: check_data = cbor.loads(checkdata) check_string = json.dumps(check_data,", "ct_value ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False: print(\" not", "content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\",", "response.content_type == defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2,", "\"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\",", "= loads(response.payload) #print(json_data) #print (\"=========\") json_string = \"\" try: json_data", "- no return value content = { 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\",", "execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content = \" iid xxx\" print(\"set iid", "6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\",", "content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) content = True print(\"set PM", "0 # href ==> 11 # ga ==> 7 #", "1, 12: \"Ia.IA1\", 112: \"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60,", "= { 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # pa", "no json tags as strings def do_sequence_dev(my_base): print(\"===================\") print(\"Get SN", "(0)= 1 # ia (12) # url (11)= .knx #", "client.stop() elif op == \"GETNONE\": if path is None: print(\"Path", "no cover global client op = None path = None", "tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) if op", "4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\",", "== 60: #print(\" content :\", content) payload = cbor.dumps(content) else:", "== \"Y\"): print(\"Unrecognized choose.\") continue elif rst == \"\" or", "= True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content)", "request : \", ct) elif o in (\"-f\", \"--payload-file\"): with", "60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base): # url, content,", "content = {4: 5678, 5: { 6: 1, 7: 1,", "\"ga\": 1, \"value\": 100 } content = { 4: 5678,", "3 update = 4 content = [ {0: 1, 11:", "= { 2: \"loadComplete\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "accept, contents content = [ {\"id\": 1, \"ia\": \"Ia.IA1\", \"path\":", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "#check = True #while check: # chosen = eval(input(\"Stop observing?", "[1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\",", "if tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\") ct_value = ct_value_all[1].split(\",\") return ct_value[0]", "5): return if mypath.startswith(\"coap://\") == False: print(\" not executing: \",", ": \", ct) elif o in (\"-f\", \"--payload-file\"): with open(a,", "return if response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base = get_base_from_link(response.payload.decode())", "b\"id2\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60,", "= {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content", "getopt import socket import sys import cbor #from cbor2 import", "get_url(line): data = line.split(\">\") url = data[0] return url[1:] def", "sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn = get_sn(my_base) print (\" SN", "execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = { 2: \"loadComplete\"} print(\"lsm", "{\"id\": 1, \"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60,", "= 4 content = [ {0: 1, 11: \"/p/push\", 7:[1],", "4 content = [ { 0: 1, 11: \"/p/light\", 7:[1],", "sn) iid = \"5\" # installation id if \"000001\" ==", "#json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) print (response.payload.decode())", "execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id ==> 0", "op == \"GETNONE\": if path is None: print(\"Path cannot be", "import sys import cbor #from cbor2 import dumps, loads import", "== \"\" or rst == \"y\" or rst == \"Y\":", "not recognized\" usage() sys.exit(2) for o, a in opts: if", "content, accept, contents content = [ {0: 1, 12: \"Ia.IA1\",", "= False ct = {} ct['accept'] = accept ct['content_type'] =", "8 def do_sequence_fp_g_int(my_base): # url, content, accept, contents content =", "= a elif o in (\"-c\", \"--content-type\"): ct['accept'] = a", "exchange: 10 - return value # - pase verification exchange:", "content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base): #", "coapthon.utils import parse_uri from coapthon import defines client = None", "= content print (\"payload: \", payload) response = nclient.put(path, payload,", "] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient table", "payload = f.read() elif o in (\"-h\", \"--help\"): usage() sys.exit()", "execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) content = False print(\"set PM :\",", "60) print(\"===================\") content = 44 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\",", "pragma: no cover global client op = None path =", "60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base): # url, content, accept, contents", "40) def do_sequence(my_base): #sn = get_sn(my_base) install(my_base) return do_sequence_dev(my_base) #return", "== defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True)", "\", mypath); return; ct = {} ct['accept'] = ct_value host,", "\"\" and not (rst == \"n\" or rst == \"N\"", "{ 4: 5678, \"st\": 55, 7: 1, \"value\": 100 }", "== 0: my_base = get_base(get_url(lines[0])) return my_base def get_sn(my_base): print(\"Get", "execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content = \"my host name\" print(\"set hostname", "--payload=\\t\\tPayload of the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of the request\") print(\"\\t-f,", "#content = { 5: { 6: 1, 7: 1, 1:", "def do_sequence_auth_at(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) #", "=+++===> OK \") else: print(\" =+++===> NOT OK \") print", "== \"GETNONE\": if path is None: print(\"Path cannot be empty", "content = [ {\"id\": 1, \"ia\": \"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]}", "accept, contents content = [ {\"id\": 1, \"ia\": \"r-Ia.IA1\", \"path\":", "60, 60, content) # ca content = { 14: b\"a15sdfsdred\"}", "print(\"Unrecognized choose.\") # continue def client_callback_observe(response): # pragma: no cover", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\",", "contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content = {0: b\"id\", 1 :", "2, transmit = 3 update = 4 content = [", "pase verification exchange: 14 - no return value content =", "print(\"\\t-p, --path=\\t\\t\\tPath of the request\") print(\"\\t-P, --payload=\\t\\tPayload of the request\")", "print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") else:", "print (\"---------\") except: traceback.print_exc() json_string = json.dumps(json_data, indent=2, sort_keys=True) print", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group object table # id (0)=", "resource def do_sequence_knx_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60)", "# - pase verification exchange: 14 - no return value", "chosen == \"N\" or chosen == \"y\" or chosen ==", "\"\" try: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True)", "chosen == \"Y\"): # print(\"Unrecognized choose.\") # continue def client_callback_observe(response):", "if code == 160: return \"(INTERNAL_SERVER_ERROR)\" return \"\" def client_callback(response,", "accept, content): print (\"---------------------------\") print (\"execute_post: \", ct_value, mypath) print", "content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do a", "print (json_data) print (\"---------\") except: traceback.print_exc() json_string = json.dumps(json_data, indent=2,", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base): # url,", "= [ {\"id\": 1, \"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ]", "if response.code > 100: print(\"+++returned error+++\") return #print(response.pretty_print()) if response.content_type", "#print (\"JSON ::\") print (response.payload.decode()) print (\"\\n\\n\") if response.content_type ==", "sys.exit(2) if payload is None: print(\"Payload cannot be empty for", "60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content) # no json", "print (response.payload.decode()) my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code): if code", "mypath) do_exit = False ct = {} ct['accept'] = accept", "# id (0)= 1 # ia (12) # url (11)=", "\", mypath); return; host, port, path = parse_uri(mypath) try: tmp", "[1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\",", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx resource # sia", "= getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError", "empty for a PUT request\") usage() sys.exit(2) response = client.put(path,", "60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ {\"id\":", "60, 60, content) def do_sequence_a_sen(my_base): # url, content, accept, contents", "- pase verification exchange: 14 - no return value content", "40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base): #", ": \", sn) iid = \"5\" # installation id if", "do_exit = False ct = {} ct['accept'] = ct_value ct['content_type']", "contents content = [ { 0: 1, 12: \"r-Ia.IA1\", 112:", "(\"content type request : \", ct) elif o in (\"-f\",", "12: \"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content)", "\"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\",", "(0)= 1 # url (11)= /p/light # ga (7 )=", "60) # ./knx resource def do_sequence_knx_knx(my_base): # url, content, accept,", "rst == \"y\" or rst == \"Y\"): print(\"Unrecognized choose.\") continue", "def get_ct(line): tagvalues = line.split(\";\") for tag in tagvalues: if", ": 5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) def do_sequence_a_sen(my_base):", "{0: b\"id2\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\",", "a post content = {\"sia\": 5678, \"st\": 55, \"ga\": 1,", "for a DELETE request\") usage() sys.exit(2) response = client.delete(path) print((response.pretty_print()))", "0 response = nclient.delete(path, None, None, **ct) client_callback(response) #nclient.stop() #sys.exit(2)", "exchange: 15 (rnd)- return value # - credential exchange: 10", "def get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths global paths_extend lines = payload.splitlines()", "# url, content, accept, contents content = {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\",", "elif rst == \"\" or rst == \"y\" or rst", "return \"\" def client_callback(response, checkdata=None): print(\" --- Callback ---\") if", "socket.gaierror: pass client = HelperClient(server=(host, port)) if op == \"GET\":", "get_base(get_url(lines[0])) return my_base def get_sn(my_base): print(\"Get SN :\"); sn =", "True } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) content = {4:", "== defines.Content_types[\"text/plain\"]: if response.payload is not None: print (type(response.payload), len(response.payload))", "host name\" print(\"set hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content)", "(response.payload) print (\"=========\") json_data = cbor.loads(response.payload) print (json_data) print (\"---------\")", "60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\",", "= False ct = {} ct['accept'] = ct_value ct['content_type'] =", "8: [1,4,5], 7:[44,55,33]}, {0: 3, 1: \"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]}", "= 1 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content)", "\"000001\" == sn : # sensor, e.g sending print (\"--------------------\")", "return; ct = {} ct['accept'] = ct_value host, port, path", "-p [-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of the request\")", "is not None: print (\"type, len\", type(response.payload), len(response.payload)) print (response.payload)", "ga value (1) #content = { 5: { 6: 1,", "json tags as strings def do_sequence_dev(my_base): print(\"===================\") print(\"Get SN :\");", "except socket.gaierror: pass nclient = HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host,", "60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\",", "print (\"execute_del: \", ct_value, mypath) do_exit = False ct =", "= 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base):", "== defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code):", "do_sequence_knx_crc(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base):", "= nclient.post(path, payload, None, None , None, **ct) client_callback(response) nclient.stop()", "do_sequence_auth(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base):", "content, accept, contents # sequence: # - parameter exchange: 15", "url, content, accept, contents # sequence: # - parameter exchange:", "content = [ {0: 1, 12: \"Ia.IA1\", 112: \"path1\", 7:[2222,3333]}", "{0: b\"id\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\",", "# ./knx resource def do_sequence_knx_knx(my_base): # url, content, accept, contents", "112: \"path2\", 7:[44,55,33]}, {0: 3, 12: \"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]}", "None , None, **ct) client_callback(response) nclient.stop() def execute_post(mypath, ct_value, accept,", "; read = 1, write = 2, transmit = 3", "--- Discovery Callback ---\") global my_base if response is not", "empty for a POST request\") usage() sys.exit(2) if payload is", "else: print (\"payload: none\") elif response.content_type == defines.Content_types[\"application/cbor\"]: print (type(response.payload),", "cover print(\"Command:\\tknxcoapclient.py -o -p [-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath", "a bit dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def", "(\"response type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\") return #print(response.pretty_print())", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content = { 1 : 5, 2:", "json_string = json.dumps(json_data, indent=2, sort_keys=True) except: print(\"error in cbor..\") print", "response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else: if response.payload is not", "print (json_string) client.stop() elif op == \"GETNONE\": if path is", "\"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ]", "cbor.loads(json_data) payload = cbor_data response = client.post(path, payload, None, None,", ": # sensor, e.g sending print (\"--------------------\") print (\"Installing SN:", "#nclient.stop() #sys.exit(2) print (\"=======\") def execute_put(mypath, ct_value, accept, content): print", "empty for a DELETE request\") usage() sys.exit(2) response = client.delete(path)", "[\"r\" ] ; read = 1, write = 2, transmit", "5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) def do_sequence_a_sen(my_base): #", "(type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") #json_data =", "sort_keys=True) print (\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]:", "print(\"Path must be conform to coap://host[:port]/path\") usage() sys.exit(2) host, port,", "return value # - pase verification exchange: 14 - no", "(\"---------\") except: traceback.print_exc() json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string)", "5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) content = {0: b\"id2\",", ":\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) content = True print(\"set", "--contenttype=\\t\\tcontenttype of the request\") print(\"\\t-f, --payload-file=\\t\\tFile with payload of the", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "==> 12 # path ==> 112 # url ==> 10", "40) # cmd ==> 2 def do_sequence_lsm_int(my_base): # url, content,", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base): # url, content,", "a GET request\") usage() sys.exit(2) client.observe(path, client_callback_observe) elif op ==", "execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base): # url, content, accept,", "of the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of the request\") print(\"\\t-f, --payload-file=\\t\\tFile", "#from cbor2 import dumps, loads import json import time import", "# ca content = { 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60,", "= 0 if accept == 60: payload = cbor.dumps(content) else:", "\"my host name\" print(\"set hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60,", "\"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx resource", "b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # expecting return def do_sequence_knx_idevid(my_base):", "except: print(\"error in cbor..\") print (json_string) print (\"===+++===\") if checkdata", "print (\"=========\") print (response.payload) print (\"=========\") json_data = cbor.loads(response.payload) print", "json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) except: print(\"error", "GET-None request\") usage() sys.exit(2) response = client.get_non(path, None, None, **ct)", "\"Y\": client.cancel_observing(response, True) else: client.cancel_observing(response, False) check = False break", "(\"=========\") #json_data = loads(response.payload) #print(json_data) #print (\"=========\") json_string = \"\"", "10: \"url2\", 112: \"r-path2\", 7:[44,55,33]}, {0: 3, 12: \"r-Ia.IA3\", 112:", "cannot be empty for a POST request\") usage() sys.exit(2) print", "2 def do_sequence_lsm_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "print (\"response type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\") return", "(\"JSON ::\") print (json_string) client.stop() elif op == \"GETNONE\": if", "st 6 def do_sequence_knx_knx_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\",", "something like \"option -a not recognized\" usage() sys.exit(2) for o,", "True) else: client.cancel_observing(response, False) check = False break else: break", "client_callback(response) nclient.stop() return response def execute_del(mypath, ct_value): print (\"---------------------------\") print", "112: \"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60)", "path is None: print(\"Path cannot be empty for a GET", "content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ {\"id\": 2,", "== 132: return \"(Not Found)\" if code == 133: return", "sn) print(\"===================\") print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get HWV", "return #print(response.pretty_print()) if response.content_type == defines.Content_types[\"text/plain\"]: if response.payload is not", "execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base): # url,", "14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # expecting return def", "None, **ct) response = client.discover( path, None, None, **ct) if", "response.payload is not None: print (type(response.payload), len(response.payload)) print (\"=========\") print", "\"href\": \"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\": 3, \"href\": \"xxxxyyy3\", \"cflag\":", "def execute_put(mypath, ct_value, accept, content): print (\"---------------------------\") print (\"execute_put: \",", "counter - 1 #client.stop() except KeyboardInterrupt: print(\"Client Shutdown\") #client.stop() #execute_list()", "def do_sequence_knx_crc(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def", "None payload = None content_type = None #ct = {'content_type':", "(json_string) client.stop() elif op == \"PUT\": if path is None:", "\"y\" or chosen == \"Y\"): # print(\"Unrecognized choose.\") # continue", "indent=2, sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data =", "\"path\": \"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60)", "60, content) def do_sequence_auth(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\",", "print(response.pretty_print()) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string =", "execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base):", "do_sequence_fp_r_int(my_base): # url, content, accept, contents content = [ {", "\"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\":", "{'content_type': defines.Content_types[\"application/link-format\"]} ct = {} ct['accept'] = 40 try: opts,", "if op == \"GET\": if path is None: print(\"Path cannot", "60, 60, content) content = False print(\"set PM :\", content);", "[ {\"id\": 1, \"ia\": \"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\",", "None: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\")", "payload = cbor.dumps(content) else: payload = content print (\"payload: \",", "execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content =", "nclient = HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host, port)) payload =", "def do_sequence(my_base): #sn = get_sn(my_base) install(my_base) return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base)", "\"ga\": 7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60)", "content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60,", "client.stop() elif op == \"OBSERVE\": if path is None: print(\"Path", "client.discover( path, None, None, **ct) if response is not None:", "\"000002\" == sn : # actuator ==> receipient # should", "cbor.dumps(content) else: payload = content response = nclient.post(path, payload, None,", "print(\" =+++===> NOT OK \") print (json_string) elif response.content_type ==", "id ==> 0 # href ==> 11 # ga ==>", "None: print (\"type, len\", type(response.payload), len(response.payload)) print (response.payload) #else: #", "or chosen == \"y\" or chosen == \"Y\"): print(\"Unrecognized choose.\")", "7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) content", "(\"-h\", \"--help\"): usage() sys.exit() else: usage() sys.exit(2) if op is", "execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base): # url,", "content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base): # url, content, accept, contents", "ct_value, accept, content): print (\"---------------------------\") print (\"execute_post: \", ct_value, mypath)", "type request : \", ct) elif o in (\"-f\", \"--payload-file\"):", "if response.content_type == defines.Content_types[\"text/plain\"]: if response.payload is not None: print", "cover global client print(\"Callback_observe\") check = True while check: chosen", "60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ { 0: 2, 12:", "return response def execute_del(mypath, ct_value): print (\"---------------------------\") print (\"execute_del: \",", "\"y\" or chosen == \"Y\": while True: rst = eval(input(\"Send", "(\"---------------------------\") print (\"execute_post: \", ct_value, mypath) print (content) print (\"", "for tag in tagvalues: if tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\") ct_value", "(chosen == \"n\" or chosen == \"N\" or chosen ==", "\"N\" or chosen == \"y\" or chosen == \"Y\"): print(\"Unrecognized", "None, None , None, **ct) client_callback(response) nclient.stop() def execute_post(mypath, ct_value,", "ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False: print(\" not executing:", "68: return \"(Changed)\" if code == 69: return \"(Content)\" if", "HelperClient(server=(host, port)) payload = 0 if accept == 60: #print(\"", "content = { 1 : 5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60,", "= line.split(\">\") url = data[0] return url[1:] def get_ct(line): tagvalues", "the request\") def get_url(line): data = line.split(\">\") url = data[0]", "\"\" or rst == \"y\" or rst == \"Y\": client.cancel_observing(response,", "mypath) do_exit = False ct = {} ct['accept'] = ct_value", "contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base): # url, content, accept, contents", "do_sequence_fp_p_int(my_base): # url, content, accept, contents content = [ {0:", "write = 2, transmit = 3 update = 4 content", "None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload)", "client.stop() elif op == \"POST\": if path is None: print(\"Path", "[ {\"id\": 1, \"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\",", "print (\"type, len\", type(response.payload), len(response.payload)) print (response.payload) #else: # print", "ct_value_all = tag.split(\"=\") ct_value = ct_value_all[1].split(\",\") return ct_value[0] return \"\"", "op = None path = None payload = None content_type", "print (json_string) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string", "elif o in (\"-h\", \"--help\"): usage() sys.exit() else: usage() sys.exit(2)", "(\"response code:\",response.code) print (\"response type:\",response.content_type) if response.code > 100: print(\"+++returned", "5, 7: 7777 , 6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60,", "(\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data =", "cbor_data = cbor.loads(json_data) payload = cbor_data response = client.post(path, payload,", "3, 12: \"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60,", "execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content = {0: b\"id\", 1 : 20,", "execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content = True print(\"set PM :\", content);", "response.content_type == defines.Content_types[\"text/plain\"]: if response.payload is not None: print (type(response.payload),", "not handled: \", response) else: print (\" Response : None\")", "(\" Response : None\") #check = True #while check: #", "indent=2, sort_keys=True) #print (\"JSON ::\") print (response.payload.decode()) print (\"\\n\\n\") if", "line.split(\";\") for tag in tagvalues: if tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\")", "7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60)", "4 # ga ==> 7 # st 6 def do_sequence_knx_knx_int(my_base):", "execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\",", "path = parse_uri(mypath) try: tmp = socket.gethostbyname(host) host = tmp", "# publisher table # id (0)= 1 # ia (12)", "contents content = [ {\"id\": 1, \"ia\": \"Ia.IA1\", \"path\": \"path1\",", "id (0)= 1 # ia (12) # url (11)= .knx", "in tagvalues: if tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\") ct_value = ct_value_all[1].split(\",\")", "\"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\",", "cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) #print (\"JSON ::\") print", "help information and exit: print((str(err))) # will print something like", "no cover global client print(\"Callback_observe\") check = True while check:", "\"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40)", "\", ct_value, mypath) print (type(mypath)) if (mypath is None or", "1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60,", "eval(input(\"Stop observing? [y/N]: \")) # if chosen != \"\" and", "client_callback(response) #nclient.stop() #sys.exit(2) print (\"=======\") def execute_put(mypath, ct_value, accept, content):", "./knx resource # sia ==> 4 # ga ==> 7", "if code == 132: return \"(Not Found)\" if code ==", "o in (\"-o\", \"--operation\"): op = a elif o in", "execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\",", "60) content = {2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "0: 2, 12: \"r-Ia.IA2\", 10: \"url2\", 112: \"r-path2\", 7:[44,55,33]}, {0:", "err: # print help information and exit: print((str(err))) # will", "not executing: \", mypath); return; ct = {} ct['accept'] =", "\"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60,", "execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60)", "return \"(Changed)\" if code == 69: return \"(Content)\" if code", "specified\") usage() sys.exit(2) if path is None: print(\"Path must be", "== \"N\" or rst == \"y\" or rst == \"Y\"):", "usage() sys.exit(2) for o, a in opts: if o in", "= \"my host name\" print(\"set hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60,", "content = [ {\"id\": 1, \"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]}", "print(\"===================\") content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60,", "execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id ==> 0 # ia", "\"value\": 100 } # st ga value (1) #content =", "[1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\",", "mypath) print (type(mypath)) if (mypath is None or len(mypath) <", "= {\"sia\": 5678, \"st\": 55, \"ga\": 1, \"value\": 100 }", "132: return \"(Not Found)\" if code == 133: return \"(METHOD_NOT_ALLOWED)\"", "execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\",", "data = line.split(\">\") url = data[0] return url[1:] def get_ct(line):", "\"option -a not recognized\" usage() sys.exit(2) for o, a in", "if chosen != \"\" and not (chosen == \"n\" or", "= client.delete(path) print((response.pretty_print())) client.stop() elif op == \"POST\": if path", "== \"y\" or rst == \"Y\": client.cancel_observing(response, True) else: client.cancel_observing(response,", "cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if response.content_type", ".knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base)", "60) def do_sequence_knx_crc(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60)", "content, accept, contents content = [ {0: 1, 11: \"xxxx1\",", "40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id ==>", "(response.payload) print (\"=========\") else: print (\"payload: none\") elif response.content_type ==", "\"payload_file=\",\"content-type\"]) except getopt.GetoptError as err: # print help information and", "print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload) json_string =", "= ct_value if mypath.startswith(\"coap://\") == False: print(\" not executing: \",", "path is None: print(\"Path must be specified\") usage() sys.exit(2) if", "1: \"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content)", "content = \" iid xxx\" print(\"set iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\",", "is None: print(\"Payload cannot be empty for a PUT request\")", "in (\"-h\", \"--help\"): usage() sys.exit() else: usage() sys.exit(2) if op", "payload = None content_type = None #ct = {'content_type': defines.Content_types[\"application/link-format\"]}", "print(\"Path cannot be empty for a PUT request\") usage() sys.exit(2)", "{\"id\": 3, \"ia\": \"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60,", "60, content) content = {4: 5678, 5: { 6: 1,", "= {2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "usage() sys.exit(2) if payload is None: print(\"Payload cannot be empty", "execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\",", "port)) payload = 0 if accept == 60: payload =", "mypath) print (content) print (\" ---------------------\") do_exit = False ct", "Discovery Callback ---\") global my_base if response is not None:", "= client.put(path, payload) print((response.pretty_print())) client.stop() elif op == \"DISCOVER\": #response", "code == 132: return \"(Not Found)\" if code == 133:", "parameter exchange: 15 (rnd)- return value # - credential exchange:", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\",", "elif op == \"GETNONE\": if path is None: print(\"Path cannot", "import dumps, loads import json import time import traceback from", "execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get", "(json_string) elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try: print (type(response.payload),", "content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id ==> 0 # href ==>", "> 100: print(\"+++returned error+++\") return #print(response.pretty_print()) if response.content_type == defines.Content_types[\"text/plain\"]:", "(\"-p\", \"--path\"): path = a elif o in (\"-P\", \"--payload\"):", "request\") usage() sys.exit(2) response = client.delete(path) print((response.pretty_print())) client.stop() elif op", "response = client.discover( path, None, None, **ct) if response is", "elif op == \"POST\": if path is None: print(\"Path cannot", "print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\",", "contents content = [ {\"id\": 1, \"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5],", "content) content = {4: 5678, 5: { 6: 1, 7:", "1 #client.stop() except KeyboardInterrupt: print(\"Client Shutdown\") #client.stop() #execute_list() client.stop() else:", "11 # ga ==> 7 # cflag ==> 8 def", "= get_base(get_url(lines[0])) return my_base def get_sn(my_base): print(\"Get SN :\"); sn", "ca content = { 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content)", "<reponame>WAvdBeek/CoAPthon3 #!/usr/bin/env python import getopt import socket import sys import", "execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id", "content) def do_sequence_a_sen(my_base): # url, content, accept, contents content =", "chosen == \"y\" or chosen == \"Y\"): # print(\"Unrecognized choose.\")", "2: \"startLoading\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "# pragma: no cover global client print(\"Callback_observe\") check = True", "content) def do_sequence_auth(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40)", "(ascii):\", payload ) print (ct['accept'] ) if ct['accept'] == str(defines.Content_types[\"application/cbor\"]):", "o, a in opts: if o in (\"-o\", \"--operation\"): op", "content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content = \" iid xxx\" print(\"set", "Callback ---\") global my_base if response is not None: print", "usage() sys.exit(2) if path is None: print(\"Path must be specified\")", "\", ct) elif o in (\"-f\", \"--payload-file\"): with open(a, 'r')", "(ct['accept'] ) if ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload) cbor_data", "# .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base)", "execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 2 print(\"set IA :\",", "40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base): # url, content,", "SN : \", sn) iid = \"5\" # installation id", "\"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\",", "# id (0)= 1 # url (11)= /p/light # ga", "value # - credential exchange: 10 - return value #", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher table # id (0)= 1 #", "continue def client_callback_observe(response): # pragma: no cover global client print(\"Callback_observe\")", "= accept ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False: print(\"", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base): #", "do_sequence_f(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40) # note", "= { 2: \"startLoading\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "./knx resource def do_sequence_knx_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\",", "is None: print(\"Path must be specified\") usage() sys.exit(2) if not", "60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id ==> 0 # ia ==>", "\"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\",", "do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base)", "payload of the request\") def get_url(line): data = line.split(\">\") url", "dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base): #sn", "print (\"response code:\",response.code) print (\"response type:\",response.content_type) if response.code > 100:", "(type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") else: print", "ga ==> 7 def do_sequence_fp_r_int(my_base): # url, content, accept, contents", "def do_sequence_core_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content", "False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content", "execute_post(mypath, ct_value, accept, content): print (\"---------------------------\") print (\"execute_post: \", ct_value,", "do_sequence_knx_spake(my_base): # url, content, accept, contents # sequence: # -", "content = {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\",", "} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # ca content = {", "payload = content response = nclient.post(path, payload, None, None ,", "60, content) content = False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\",", "60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60)", "payload is None: print(\"Payload cannot be empty for a PUT", "content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group object", "url, content, accept, contents content = [ {0: 1, 11:", "transmit = 3 update = 4 content = [ {0:", "--path=\\t\\t\\tPath of the request\") print(\"\\t-P, --payload=\\t\\tPayload of the request\") print(\"\\t-c,", "for a GET request\") usage() sys.exit(2) response = client.get(path, None,", "get_sn(my_base) print (\" SN : \", sn) iid = \"5\"", "chosen = eval(input(\"Stop observing? [y/N]: \")) # if chosen !=", "# do a post content = {\"sia\": 5678, \"st\": 55,", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx resource # sia ==> 4", "check: \") print (check_string) if check_string == json_string: print(\" =+++===>", "] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\",", "#json_string = json.dumps(json_data, indent=2, sort_keys=True) #print (\"JSON ::\") print (response.payload.decode())", "content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ { 0:", "elif op == \"PUT\": if path is None: print(\"Path cannot", "eval(input(\"Stop observing? [y/N]: \")) if chosen != \"\" and not", "execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ { 0: 2, 12: \"r-Ia.IA2\",", "40) # id ==> 0 # ia ==> 12 #", "== sn : # sensor, e.g sending print (\"--------------------\") print", "elif o in (\"-P\", \"--payload\"): payload = a elif o", "content, accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40) # note this one is", "20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\",", "= tmp except socket.gaierror: pass client = HelperClient(server=(host, port)) if", "add the if len(paths) == 0: my_base = get_base(get_url(lines[0])) return", "content = { 2: \"reset\"} print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60,", "request\") usage() sys.exit(2) print ( \"payload for POST (ascii):\", payload", "ct_value host, port, path = parse_uri(mypath) try: tmp = socket.gethostbyname(host)", "recognized\" usage() sys.exit(2) for o, a in opts: if o", "# continue def client_callback_observe(response): # pragma: no cover global client", "\", json_data) return json_data def install(my_base): sn = get_sn(my_base) print", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id", "**ct) client_callback(response) #nclient.stop() #sys.exit(2) print (\"=======\") def execute_put(mypath, ct_value, accept,", "112: \"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60)", "# sequence: # - parameter exchange: 15 (rnd)- return value", "print (\"content type request : \", ct) elif o in", "{ \"sia\" : 5, \"ga\": 7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60,", "do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base)", "(json_string) print (\"===+++===\") if checkdata is not None: check_data =", "==> 10 # ga ==> 7 def do_sequence_fp_r_int(my_base): # url,", "= ct_value ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False: print(\"", "url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\") return mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\") global", "print(\" not executing: \", mypath); return; ct = {} ct['accept']", "usage() sys.exit(2) response = client.put(path, payload) print((response.pretty_print())) client.stop() elif op", "8: [2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40)", "do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base)", "= { 2: \"reset\"} print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60,", "None: print(response.pretty_print()) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string", "print (\"application/vnd.ocf+cbor\") try: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload)", "60) content = {\"value\": { 4 : 5, 7: 7777", "path is None: print(\"Path cannot be empty for a PUT", "40) content = [ {\"id\": 2, \"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\",", "12: \"Ia.IA1\", 112: \"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content)", "\"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]}", "(\"-c\", \"--content-type\"): ct['accept'] = a print (\"content type request :", "sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data = cbor.loads(sn.payload) #print (\"SN :", "60, 60, content) # no json tags as strings def", "40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base): #sn = get_sn(my_base) install(my_base) return", "as strings def do_sequence_dev(my_base): print(\"===================\") print(\"Get SN :\"); sn =", "json_data = cbor.loads(response.payload) print (json_data) print (\"---------\") except: traceback.print_exc() json_string", "Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content = True print(\"set PM", "None\") #check = True #while check: # chosen = eval(input(\"Stop", "ct_value): print (\"---------------------------\") print (\"execute_get: \", ct_value, mypath) print (type(mypath))", "# expecting return def do_sequence_knx_idevid(my_base): # url, content, accept, contents", "do_exit = False ct = {} ct['accept'] = accept ct['content_type']", "== \"y\" or chosen == \"Y\"): # print(\"Unrecognized choose.\") #", "executing: \", mypath); return host, port, path = parse_uri(mypath) try:", "cover global client op = None path = None payload", "HelperClient(server=(host, port)) if op == \"GET\": if path is None:", "accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/crc\", 60) def do_sequence_oscore(my_base): # url, content, accept,", "code == 160: return \"(INTERNAL_SERVER_ERROR)\" return \"\" def client_callback(response, checkdata=None):", "ct = {} ct['accept'] = accept ct['content_type'] = ct_value if", "if response.content_type == defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data,", "client) client_callback_discovery(response) counter = 2 try: while counter > 0:", "print (\"=========\") json_data = cbor.loads(response.payload) print (json_data) print (\"---------\") except:", "nclient.put(path, payload, None, None , None, **ct) client_callback(response) nclient.stop() def", "print(\"\\t-P, --payload=\\t\\tPayload of the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of the request\")", "print(\"set hostname :\", content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60)", "payload = content print (\"payload: \", payload) response = nclient.put(path,", "\")) if rst != \"\" and not (rst == \"n\"", "\"ia\": \"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content)", "response = client.get_non(path, None, None, **ct) print((response.pretty_print())) if response.content_type ==", "import getopt import socket import sys import cbor #from cbor2", "GET request\") usage() sys.exit(2) response = client.get(path, None, None, **ct)", "with payload of the request\") def get_url(line): data = line.split(\">\")", "= get_sn(my_base) print (\" SN : \", sn) iid =", "(\"SN : \", json_data) return json_data def install(my_base): sn =", "cbor..\") print (json_string) print (\"===+++===\") if checkdata is not None:", "json_data) return json_data def install(my_base): sn = get_sn(my_base) print (\"", "\"r-Ia.IA2\", 10: \"url2\", 112: \"r-path2\", 7:[44,55,33]}, {0: 3, 12: \"r-Ia.IA3\",", ", None, **ct) client_callback(response) nclient.stop() def main(): # pragma: no", "= 4 content = [ {0: 1, 11: \".knx\", 7:[1],", "PUT request\") usage() sys.exit(2) response = client.put(path, payload) print((response.pretty_print())) client.stop()", "import json import time import traceback from coapthon.client.helperclient import HelperClient", "mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath); return; host,", "content = { 2: \"startLoading\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "{\"value\": { 4 : 5, 7: 7777 , 6 :", "accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { \"sia\" :", "= cbor_data response = client.post(path, payload, None, None, **ct) print((response.pretty_print()))", "None #ct = {'content_type': defines.Content_types[\"application/link-format\"]} ct = {} ct['accept'] =", "payload, None, None , None, **ct) client_callback(response) nclient.stop() def execute_post(mypath,", "import defines client = None paths = {} paths_extend =", "print (\"---------------------------\") print (\"execute_put: \", ct_value, mypath) do_exit = False", "[ {0: 1, 11: \"p/push\", 7:[1], 8: [2] } ]", "== defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print", "print(\" not executing: \", mypath); return host, port, path =", "\"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\",", "application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {\"id\": 2, \"ia\":", ": 5, \"ga\": 7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content)", "ia (12) # url (11)= .knx # ga (7 )=", "== False: print(\" not executing: \", mypath); return; host, port,", "= None path = None payload = None content_type =", "import parse_uri from coapthon import defines client = None paths", "if ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload) cbor_data = cbor.dumps(json_data)", "client.stop() elif op == \"DISCOVER\": #response = client.discover( path, client_callback,", "nclientcheck = HelperClient(server=(host, port)) payload = 0 if accept ==", "def get_url(line): data = line.split(\">\") url = data[0] return url[1:]", "sort_keys=True) print (\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]:", "= client.get(path, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]:", "HelperClient(server=(host, port)) payload = 0 if accept == 60: payload", "execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher table #", "# href ==> 11 # ga ==> 7 # cflag", "if response is not None: print(response.pretty_print()) if response.content_type == defines.Content_types[\"application/cbor\"]:", "\"st\": 55, 7: 1, \"value\": 100 } # st ga", "#do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base)", "{\"id\": 2, \"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"xxxxyyyia3\",", "print (\"=========\") print (response.payload) print (\"=========\") #json_data = loads(response.payload) #print(json_data)", "a DELETE request\") usage() sys.exit(2) response = client.delete(path) print((response.pretty_print())) client.stop()", "payload) print((response.pretty_print())) client.stop() elif op == \"DISCOVER\": #response = client.discover(", "7: 1, \"value\": 100 } # st ga value (1)", "= {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) #", "# url, content, accept, contents # sequence: # - parameter", "content) content = 2 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60,", "payload = a elif o in (\"-c\", \"--content-type\"): ct['accept'] =", "content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 2 print(\"set IA", "0 # ia ==> 12 # path ==> 112 #", ": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base):", "::\") print (json_string) client.stop() elif op == \"OBSERVE\": if path", "= cbor.dumps(json_data) payload = bytes(cbor_data) if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data", "print(\"set iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60)", "==> 2 def do_sequence_lsm_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\",", "False) check = False break else: break def execute_get(mypath, ct_value):", "global paths global paths_extend lines = payload.splitlines() # add the", "not (rst == \"n\" or rst == \"N\" or rst", "response.payload is not None: print (\"type, len\", type(response.payload), len(response.payload)) print", "print(\"Unrecognized choose.\") continue elif chosen == \"y\" or chosen ==", "request\") usage() sys.exit(2) response = client.put(path, payload) print((response.pretty_print())) client.stop() elif", "[ { 0: 2, 12: \"r-Ia.IA2\", 10: \"url2\", 112: \"r-path2\",", "observing? [y/N]: \")) if chosen != \"\" and not (chosen", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [", "do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base)", "tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port)) #nclientcheck =", "= get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code): if code == 68: return", "1, 7: 1, 1: True } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60,", "{ 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # pa content", "= {0: b\"id\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"}", "(\" SN : \", sn) iid = \"5\" # installation", "- credential exchange: 10 - return value # - pase", "PUT request\") usage() sys.exit(2) if payload is None: print(\"Payload cannot", "print (content) print (\" ---------------------\") do_exit = False ct =", "\"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\",", "\"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\",", "indent=2, sort_keys=True) except: print(\"error in cbor..\") print (json_string) print (\"===+++===\")", "content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx resource def do_sequence_knx_knx(my_base): # url,", "= [ {0: 1, 11: \"p/push\", 7:[1], 8: [2] }", "60) def do_sequence_oscore(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40)", "socket.gaierror: pass nclient = HelperClient(server=(host, port)) #nclientcheck = HelperClient(server=(host, port))", "print (\"=========\") else: print (\"payload: none\") elif response.content_type == defines.Content_types[\"application/cbor\"]:", "(\"--------------------\") print (\"Installing SN: \", sn) content = { 2:", "request\") usage() sys.exit(2) response = client.get(path, None, None, **ct) print((response.pretty_print()))", "print (response.payload.decode()) # do_get(response.payload.decode(), client) client_callback_discovery(response) counter = 2 try:", "print (\"---------------------------\") print (\"execute_post: \", ct_value, mypath) print (content) print", "112: \"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60)", "ct_value if mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath);", "request\") def get_url(line): data = line.split(\">\") url = data[0] return", "sn : # actuator ==> receipient # should use /fp/r", "> 0: time.sleep(1) counter = counter - 1 #client.stop() except", "none\") elif response.content_type == defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload)) print (\"=========\")", "cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) client.stop() elif", "be specified\") usage() sys.exit(2) if path is None: print(\"Path must", "60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content = \" iid xxx\"", "payload is None: print(\"Payload cannot be empty for a POST", "cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) print (response.payload.decode()) # do_get(response.payload.decode(),", "= 4 content = [ {0: 1, 11: \"p/push\", 7:[1],", "282) def do_sequence_knx_ldevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282)", "= json.dumps(json_data, indent=2, sort_keys=True) print (json_string) client.stop() elif op ==", "7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40)", "= parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except", "parse_uri(path) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror:", "\"y\" or rst == \"Y\"): print(\"Unrecognized choose.\") continue elif rst", "execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id ==> 0", "client = None paths = {} paths_extend = {} my_base", "print(\"+++returned error+++\") return if response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base", "print(\"===================\") content = \" iid xxx\" print(\"set iid :\", content);", "7:[44,55,33]}, {0: 3, 12: \"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\",", "sort_keys=True) print (json_string) elif response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else:", "execute_get(\"coap://\"+my_base+\"/fp/p\", 40) # id ==> 0 # ia ==> 12", "POST request\") usage() sys.exit(2) print ( \"payload for POST (ascii):\",", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do a post content = {\"sia\":", "100 } content = { 4: 5678, \"st\": 55, 7:", "or rst == \"Y\"): print(\"Unrecognized choose.\") continue elif rst ==", "import traceback from coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri", "# chosen = eval(input(\"Stop observing? [y/N]: \")) # if chosen", "PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content", "content) content = { 2: \"startLoading\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\",", "nclient.get(path, None, None, **ct) client_callback(response) nclient.stop() return response def execute_del(mypath,", "loads import json import time import traceback from coapthon.client.helperclient import", "coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url = url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\") return", "o in (\"-h\", \"--help\"): usage() sys.exit() else: usage() sys.exit(2) if", "= {} ct['accept'] = ct_value ct['content_type'] = ct_value if mypath.startswith(\"coap://\")", "# st ga value (1) #content = { 5: {", "execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx resource def", "client.cancel_observing(response, False) check = False break else: break def execute_get(mypath,", "== False: print(\" not executing: \", mypath); return; ct =", "dumps, loads import json import time import traceback from coapthon.client.helperclient", "**ct) client_callback(response) nclient.stop() def execute_post(mypath, ct_value, accept, content): print (\"---------------------------\")", "None: print(\"Path must be specified\") usage() sys.exit(2) if not path.startswith(\"coap://\"):", "60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content = \"my host name\"", "= HelperClient(server=(host, port)) payload = 0 response = nclient.delete(path, None,", "= HelperClient(server=(host, port)) payload = 0 if accept == 60:", "be empty for a PUT request\") usage() sys.exit(2) response =", "{\"id\": 1, \"ia\": \"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60,", "checkdata=None): print(\" --- Callback ---\") if response is not None:", "== application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {\"id\": 2,", "print (response.payload.decode()) print (\"\\n\\n\") if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data =", "# cmd ==> 2 def do_sequence_lsm_int(my_base): # url, content, accept,", "content = { 4: 5678, \"st\": 55, 7: 1, \"value\":", "HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host, port)) payload = 0 if", "json.dumps(json_data, indent=2, sort_keys=True) print (json_string) elif response.content_type == defines.Content_types[\"application/link-format\"]: print", "3 update = 4 content = [ { 0: 1,", "parse_uri(mypath) try: tmp = socket.gethostbyname(host) host = tmp except socket.gaierror:", "opts, args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"])", "DELETE request\") usage() sys.exit(2) response = client.delete(path) print((response.pretty_print())) client.stop() elif", "execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def do_sequence_fp_p(my_base): # url,", "7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60)", "= [ {0: 1, 11: \".knx\", 7:[1], 12 :\"blah.blah\" }", "print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) content = True", "content = [ {0: 1, 11: \"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]}", "do_sequence_core_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content =", "0: my_base = get_base(get_url(lines[0])) return my_base def get_sn(my_base): print(\"Get SN", "actuator ==> receipient # should use /fp/r print (\"--------------------\") print", "\"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) #", "\")) if chosen != \"\" and not (chosen == \"n\"", "= cbor.dumps(content) else: payload = content response = nclient.post(path, payload,", "7 # st 6 def do_sequence_knx_knx_int(my_base): # url, content, accept,", "= counter - 1 #client.stop() except KeyboardInterrupt: print(\"Client Shutdown\") #client.stop()", "60) content = False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60,", "# content = {0: b\"id\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\",", "installation id if \"000001\" == sn : # sensor, e.g", "execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) content = {0: b\"id2\", 1 :", "ga (7 )= 1 # cflags (8) = [\"r\" ]", "::\") print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload)", "json.dumps(json_data, indent=2, sort_keys=True) print (json_string) client.stop() elif op == \"PUT\":", "execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content", "path, client_callback, None, **ct) response = client.discover( path, None, None,", "return value content = { 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60,", "40) content = [ { 0: 2, 12: \"r-Ia.IA2\", 10:", ":\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group", "print(\" not executing: \", mypath); return; host, port, path =", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id ==> 0 #", "opts: if o in (\"-o\", \"--operation\"): op = a elif", "content, accept, contents content = [ { 0: 1, 12:", "execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # pa content = { 10:", "ct_value, mypath) do_exit = False ct = {} ct['accept'] =", "None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]: json_data =", "print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if", "execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base): # url, content, accept, contents #", "5: { 6: 1, 7: 1, 1: False } }", "indent=2, sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data =", "print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of the request\") print(\"\\t-P, --payload=\\t\\tPayload", "except getopt.GetoptError as err: # print help information and exit:", "json.dumps(json_data, indent=2, sort_keys=True) #print (\"JSON ::\") print (response.payload.decode()) print (\"\\n\\n\")", "7: 1, 1: False } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content)", "indent=2, sort_keys=True) print (\"JSON ::\") print (json_string) client.stop() elif op", "op == \"GET\": if path is None: print(\"Path cannot be", "60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base): # url, content,", "time import traceback from coapthon.client.helperclient import HelperClient from coapthon.utils import", "accept, contents content = [ { 0: 1, 12: \"r-Ia.IA1\",", "content = {\"sia\": 5678, \"st\": 55, \"ga\": 1, \"value\": 100", "{2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content) def do_sequence_auth(my_base): # url,", "accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) def do_sequence_fp_g(my_base): #", "def do_sequence_knx_osn(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def", "7:[44,55,33]}, {0: 3, 1: \"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\",", "content = {2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "40) # content = {0: b\"id\", 1 : 20, 2:b\"ms\",3:\"hkdf\",", "or chosen == \"Y\"): print(\"Unrecognized choose.\") continue elif chosen ==", "= 3 update = 4 content = [ {0: 1,", "= client.discover( path, None, None, **ct) if response is not", "[ {\"id\": 2, \"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3,", "# ga (7 )= 1 # cflags (8) = [\"r\"", "{ 2: \"reset\"} print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content)", "continue elif rst == \"\" or rst == \"y\" or", "RST message? [Y/n]: \")) if rst != \"\" and not", "tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port)) response =", "do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base)", "usage() sys.exit(2) if op is None: print(\"Operation must be specified\")", "publisher table # id (0)= 1 # ia (12) #", "b\"id\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60,", "will print something like \"option -a not recognized\" usage() sys.exit(2)", "print(\"Unrecognized choose.\") continue elif rst == \"\" or rst ==", "content = 2 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60,", "# url, content, accept, contents content = [ { 0:", "== \"Y\"): print(\"Unrecognized choose.\") continue elif chosen == \"y\" or", "sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload)", "15 (rnd)- return value # - credential exchange: 10 -", "content = 1 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60,", "json_data = json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON", "5678, \"st\": 55, 7: 1, \"value\": 100 } # st", "\"ga\":[44,55,33]}, {\"id\": 3, \"href\": \"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\",", "] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\",", "print (\"execute_put: \", ct_value, mypath) do_exit = False ct =", "print(\"+++returned error+++\") return #print(response.pretty_print()) if response.content_type == defines.Content_types[\"text/plain\"]: if response.payload", "content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\",", "ct['accept'] = ct_value host, port, path = parse_uri(mypath) try: tmp", "10 # ga ==> 7 def do_sequence_fp_p_int(my_base): # url, content,", "60, content) content = { 2: \"loadComplete\"} print(\"lsm :\", content);", "60) if \"000002\" == sn : # actuator ==> receipient", "path ==> 112 # url ==> 10 # ga ==>", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\",", "{0: 1, 11: \"p/push\", 7:[1], 8: [2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\",", "cbor2 import dumps, loads import json import time import traceback", "[ {\"id\": 1, \"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\",", ": \", json_data) return json_data def install(my_base): sn = get_sn(my_base)", "rst = eval(input(\"Send RST message? [Y/n]: \")) if rst !=", "if op is None: print(\"Operation must be specified\") usage() sys.exit(2)", ", None, **ct) client_callback(response) nclient.stop() def execute_post(mypath, ct_value, accept, content):", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base): # url,", "60, content) # pa content = { 10: b\"s10dfsdfsfs\" }", "Callback ---\") if response is not None: print (\"response code:\",response.code,", "--payload-file=\\t\\tFile with payload of the request\") def get_url(line): data =", "\".knx\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content)", "None or len(mypath) < 5): return if mypath.startswith(\"coap://\") == False:", "60) content = {2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "\"N\" or rst == \"y\" or rst == \"Y\"): print(\"Unrecognized", "exit: print((str(err))) # will print something like \"option -a not", "55, \"ga\": 1, \"value\": 100 } content = { 4:", "print(\"Path cannot be empty for a DELETE request\") usage() sys.exit(2)", "accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\",", "def do_sequence_lsm_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content", "return \"(METHOD_NOT_ALLOWED)\" if code == 160: return \"(INTERNAL_SERVER_ERROR)\" return \"\"", "None: check_data = cbor.loads(checkdata) check_string = json.dumps(check_data, indent=2, sort_keys=True) print(\"", "def get_base(url): # python3 knxcoapclient.py -o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c", "tagvalues = line.split(\";\") for tag in tagvalues: if tag.startswith(\"ct\"): ct_value_all", "== json_string: print(\" =+++===> OK \") else: print(\" =+++===> NOT", "= False break else: break def execute_get(mypath, ct_value): print (\"---------------------------\")", "elif o in (\"-f\", \"--payload-file\"): with open(a, 'r') as f:", "None: print(\"Path cannot be empty for a PUT request\") usage()", "{0: 3, 1: \"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60,", "{4: 5678, 5: { 6: 1, 7: 1, 1: False", "contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "pragma: no cover print(\"Command:\\tknxcoapclient.py -o -p [-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\")", "url ==> 10 # ga ==> 7 def do_sequence_fp_p_int(my_base): #", "is a bit dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40)", "do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response,", "(\"=========\") print (response.payload) print (\"=========\") json_data = cbor.loads(response.payload) print (json_data)", "(response.payload.decode()) else: if response.payload is not None: print (\"type, len\",", "content = { 2: \"loadComplete\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "host = tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port))", "print (\"Installing SN: \", sn) content = { 2: \"reset\"}", "\"p/push\", 7:[1], 8: [2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content)", "60) content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60)", "of the request\") print(\"\\t-f, --payload-file=\\t\\tFile with payload of the request\")", "[2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) #", "return value # - credential exchange: 10 - return value", "handled: \", response) else: print (\" Response : None\") #check", "print (response.payload) print (\"=========\") json_data = cbor.loads(response.payload) print (json_data) print", "15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # pa content =", "SN: \", sn) content = { 2: \"reset\"} print(\"reset :\",", "traceback.print_exc() json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) elif response.content_type", "60, 60, content) # expecting return def do_sequence_knx_idevid(my_base): # url,", "do_sequence_fp_r(my_base): # url, content, accept, contents content = [ {\"id\":", "value # - pase verification exchange: 14 - no return", "= \"\" try: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2,", "receipient # should use /fp/r print (\"--------------------\") print (\"installing SN:", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40) # note this", "tagvalues: if tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\") ct_value = ct_value_all[1].split(\",\") return", "execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn = get_sn(my_base) print (\" SN : \",", "40) def do_sequence_fp_p(my_base): # url, content, accept, contents content =", "(\"execute_get: \", ct_value, mypath) print (type(mypath)) if (mypath is None", "} } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) content = {4: 5678,", "#response = client.discover( path, client_callback, None, **ct) response = client.discover(", "parse_uri from coapthon import defines client = None paths =", "for a POST request\") usage() sys.exit(2) if payload is None:", "{} paths_extend = {} my_base = \"\" def usage(): #", "False: print(\" not executing: \", mypath); return; host, port, path", "==> receipient # should use /fp/r print (\"--------------------\") print (\"installing", "{ 10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # ca", "print(\" --- Discovery Callback ---\") global my_base if response is", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base): #", "json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) client.stop() elif op", "is None: print(\"Operation must be specified\") usage() sys.exit(2) if path", "must be specified\") usage() sys.exit(2) if path is None: print(\"Path", "# ga ==> 7 # cflag ==> 8 def do_sequence_fp_g_int(my_base):", "\"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\",", "print (ct['accept'] ) if ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload)", "= True while check: chosen = eval(input(\"Stop observing? [y/N]: \"))", "{2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content", "payload = 0 if accept == 60: #print(\" content :\",", "content, accept, contents content = [ {\"id\": 1, \"ia\": \"Ia.IA1\",", "print (\"---------------------------\") print (\"execute_del: \", ct_value, mypath) do_exit = False", "} content = { 4: 5678, \"st\": 55, 7: 1,", "== defines.Content_types[\"application/cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True)", "2, 12: \"r-Ia.IA2\", 10: \"url2\", 112: \"r-path2\", 7:[44,55,33]}, {0: 3,", "rst == \"Y\"): print(\"Unrecognized choose.\") continue elif rst == \"\"", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx resource # sia ==> 4 #", "execute_get(\"coap://\"+my_base+\"/f\", 40) # note this one is a bit dirty", "get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code): if code == 68: return \"(Changed)\"", "response is not None: print(response.pretty_print()) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data", "print(\"Payload cannot be empty for a PUT request\") usage() sys.exit(2)", "40) content = [ {\"id\": 2, \"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]},", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content =", "\"(METHOD_NOT_ALLOWED)\" if code == 160: return \"(INTERNAL_SERVER_ERROR)\" return \"\" def", "execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content = False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\",", "= 44 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content)", "else: payload = content print (\"payload: \", payload) response =", "print (\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data", "] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher table", "content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 1 print(\"set IA", "elif op == \"DISCOVER\": #response = client.discover( path, client_callback, None,", "== False: print(\" not executing: \", mypath); return host, port,", "\"r-path2\", 7:[44,55,33]}, {0: 3, 12: \"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]} ]", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"unload\"}", "not None: print (\"response code:\",response.code, code2string(response.code)) print (\"response type:\",response.content_type) if", "60, content) content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) content", "60, 60, content) content = True print(\"set PM :\", content);", "= [ {\"id\": 2, \"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\":", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group object table # id (0)= 1", "2, \"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"xxxxyyyia3\", \"path\":", "empty for a POST request\") usage() sys.exit(2) print ( \"payload", "= tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port)) response", "= [ {\"id\": 2, \"href\": \"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\":", "{0: 1, 11: \"/p/push\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\",", "60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {0:", "Found)\" if code == 133: return \"(METHOD_NOT_ALLOWED)\" if code ==", "sending print (\"--------------------\") print (\"Installing SN: \", sn) content =", "60: payload = cbor.dumps(content) else: payload = content print (\"payload:", "= tag.split(\"=\") ct_value = ct_value_all[1].split(\",\") return ct_value[0] return \"\" def", "execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def do_sequence_core_knx(my_base): # url,", "like \"option -a not recognized\" usage() sys.exit(2) for o, a", "op == \"OBSERVE\": if path is None: print(\"Path cannot be", "e.g sending print (\"--------------------\") print (\"Installing SN: \", sn) content", "-a not recognized\" usage() sys.exit(2) for o, a in opts:", "\"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\": 3, \"href\": \"xxxxyyy3\", \"cflag\": [1,4,5],", "20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) content", "\"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\",", "return url[1:] def get_ct(line): tagvalues = line.split(\";\") for tag in", "return ct_value[0] return \"\" def get_base(url): # python3 knxcoapclient.py -o", "print(\"Command:\\tknxcoapclient.py -o -p [-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of", "is None: print(\"Path cannot be empty for a DELETE request\")", "(\"---------------------------\") print (\"execute_put: \", ct_value, mypath) do_exit = False ct", "for a POST request\") usage() sys.exit(2) print ( \"payload for", "response) else: print (\" Response : None\") #check = True", "= execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn = get_sn(my_base) print (\" SN :", "= { 10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) #", "\"Y\"): # print(\"Unrecognized choose.\") # continue def client_callback_observe(response): # pragma:", "ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload) cbor_data = cbor.loads(json_data) payload", "{} ct['accept'] = ct_value host, port, path = parse_uri(mypath) try:", "10 # ga ==> 7 def do_sequence_fp_r_int(my_base): # url, content,", "def code2string(code): if code == 68: return \"(Changed)\" if code", "response def execute_del(mypath, ct_value): print (\"---------------------------\") print (\"execute_del: \", ct_value,", "execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base): # url,", "1, 11: \".knx\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60,", "as err: # print help information and exit: print((str(err))) #", "content = [ {\"id\": 2, \"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]},", "\"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def do_sequence_knx_spake(my_base):", "sort_keys=True) except: print(\"error in cbor..\") print (json_string) print (\"===+++===\") if", ":\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\"", "chosen = eval(input(\"Stop observing? [y/N]: \")) if chosen != \"\"", "= json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print (json_string) client.stop()", "defines.Content_types[\"text/plain\"]: if response.payload is not None: print (type(response.payload), len(response.payload)) print", "if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data,", "client print(\"Callback_observe\") check = True while check: chosen = eval(input(\"Stop", "content = { 10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content)", "content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"startLoading\"}", "None path = None payload = None content_type = None", "2 try: while counter > 0: time.sleep(1) counter = counter", "= True #while check: # chosen = eval(input(\"Stop observing? [y/N]:", "} #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) content = {4: 5678, 5:", "60, content) # ca content = { 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\",", "print (json_string) elif response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else: if", "None: print (\"response code:\",response.code) print (\"response type:\",response.content_type) if response.code >", "if response.content_type == defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload) json_string = json.dumps(json_data,", "do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base)", "(mypath is None or len(mypath) < 5): return if mypath.startswith(\"coap://\")", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group object table #", "execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40)", "execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) content = { 2: \"startLoading\"} print(\"lsm", "do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None): print(\"", "POST request\") usage() sys.exit(2) if payload is None: print(\"Payload cannot", "elif o in (\"-c\", \"--content-type\"): ct['accept'] = a print (\"content", "{\"id\": 2, \"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3, \"ia\":", "execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f\",", "content = [ {\"id\": 1, \"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]}", "NOT OK \") print (json_string) elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print", "content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {0: 2,", "usage() sys.exit(2) host, port, path = parse_uri(path) try: tmp =", "execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get", "print (\"===+++===\") if checkdata is not None: check_data = cbor.loads(checkdata)", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content", "type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\") return if response.content_type", "282) def do_sequence_knx_osn(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60)", "2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) content =", "None: print(\"Operation must be specified\") usage() sys.exit(2) if path is", "::\") print (json_string) client.stop() elif op == \"GETNONE\": if path", "POST (ascii):\", payload ) print (ct['accept'] ) if ct['accept'] ==", "id if \"000001\" == sn : # sensor, e.g sending", "update = 4 content = [ { 0: 1, 11:", "do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None): print(\" --- Discovery", "\"\" and not (chosen == \"n\" or chosen == \"N\"", "print(\"get_base_from_link\\n\") global paths global paths_extend lines = payload.splitlines() # add", "url[1:] def get_ct(line): tagvalues = line.split(\";\") for tag in tagvalues:", "return \"(INTERNAL_SERVER_ERROR)\" return \"\" def client_callback(response, checkdata=None): print(\" --- Callback", "sia ==> 4 # ga ==> 7 # st 6", "1, write = 2, transmit = 3 update = 4", "cannot be empty for a PUT request\") usage() sys.exit(2) response", "execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60,", "socket import sys import cbor #from cbor2 import dumps, loads", "content = False print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60,", "# ia (12) # url (11)= .knx # ga (7", "is not None: check_data = cbor.loads(checkdata) check_string = json.dumps(check_data, indent=2,", "60, content) # expecting return def do_sequence_knx_idevid(my_base): # url, content,", "sys.exit(2) response = client.get(path, None, None, **ct) print((response.pretty_print())) if response.content_type", "1 # url (11)= /p/light # ga (7 )= 1", "execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd ==> 2 def do_sequence_lsm_int(my_base):", "sys.exit(2) response = client.delete(path) print((response.pretty_print())) client.stop() elif op == \"POST\":", "[y/N]: \")) if chosen != \"\" and not (chosen ==", "url (11)= .knx # ga (7 )= 1 # cflags", "= json.dumps(json_data, indent=2, sort_keys=True) print (response.payload.decode()) # do_get(response.payload.decode(), client) client_callback_discovery(response)", "print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60)", "defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\")", "content print (\"payload: \", payload) response = nclient.put(path, payload, None,", "information and exit: print((str(err))) # will print something like \"option", ": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content =", "def do_sequence_knx_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content", "content = { 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) #", "== 133: return \"(METHOD_NOT_ALLOWED)\" if code == 160: return \"(INTERNAL_SERVER_ERROR)\"", "if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data,", "False: print(\" not executing: \", mypath); return; ct = {}", "60) content = {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "(type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") json_data =", "accept, content): print (\"---------------------------\") print (\"execute_put: \", ct_value, mypath) do_exit", "or rst == \"y\" or rst == \"Y\"): print(\"Unrecognized choose.\")", "# print help information and exit: print((str(err))) # will print", "= 0 if accept == 60: #print(\" content :\", content)", "60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content = False print(\"set PM :\",", "(12) # url (11)= .knx # ga (7 )= 1", "code:\",response.code) print (\"response type:\",response.content_type) if response.code > 100: print(\"+++returned error+++\")", "= get_sn(my_base) print (\" SN : \", sn) print(\"===================\") print(\"Get", "\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60)", "response = nclient.delete(path, None, None, **ct) client_callback(response) #nclient.stop() #sys.exit(2) print", "print(\"Path cannot be empty for a GET request\") usage() sys.exit(2)", "60) def do_sequence_core_knx(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60)", "60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd ==> 2 def", "content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content) # no json tags as", "response is not None: print (\"response code:\",response.code, code2string(response.code)) print (\"response", "#json_data = loads(response.payload) #print(json_data) #print (\"=========\") json_string = \"\" try:", "defines.Content_types[\"application/link-format\"]} ct = {} ct['accept'] = 40 try: opts, args", "= 1, write = 2, transmit = 3 update =", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content = { 1", "\"GET\": if path is None: print(\"Path cannot be empty for", "= json.dumps(check_data, indent=2, sort_keys=True) print(\" check: \") print (check_string) if", "(\"-o\", \"--operation\"): op = a elif o in (\"-p\", \"--path\"):", "is None: print(\"Payload cannot be empty for a POST request\")", "client.discover( path, client_callback, None, **ct) response = client.discover( path, None,", "= eval(input(\"Stop observing? [y/N]: \")) # if chosen != \"\"", "None: print(\"Payload cannot be empty for a PUT request\") usage()", "= line.split(\";\") for tag in tagvalues: if tag.startswith(\"ct\"): ct_value_all =", "{ 0: 1, 12: \"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\",", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base): # url, content,", "\"n\" or rst == \"N\" or rst == \"y\" or", "= { 5: { 6: 1, 7: 1, 1: True", "path = a elif o in (\"-P\", \"--payload\"): payload =", "content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content =", "try: json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) except:", "= bytes(cbor_data) if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload) cbor_data", "= [ {\"id\": 1, \"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]} ]", "== \"y\" or chosen == \"Y\"): print(\"Unrecognized choose.\") continue elif", "sys.exit(2) if op is None: print(\"Operation must be specified\") usage()", "while True: rst = eval(input(\"Send RST message? [Y/n]: \")) if", "60, 60, content) def do_sequence_auth(my_base): # url, content, accept, contents", "[\"help\", \"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError as err: #", "\"DISCOVER\": #response = client.discover( path, client_callback, None, **ct) response =", "--operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of the request\") print(\"\\t-P, --payload=\\t\\tPayload of the", "content = [ {\"id\": 2, \"href\": \"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]},", "print (\"--------------------\") print (\"Installing SN: \", sn) content = {", "print (\" ---------------------\") do_exit = False ct = {} ct['accept']", "path, None, None, **ct) if response is not None: print(response.pretty_print())", "# print(\"Unrecognized choose.\") # continue def client_callback_observe(response): # pragma: no", "else: print(\"Operation not recognized\") usage() sys.exit(2) if __name__ == '__main__':", "coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri from coapthon import", "40) # note this one is a bit dirty hard", "40) def do_sequence_fp_r(my_base): # url, content, accept, contents content =", "except socket.gaierror: pass nclient = HelperClient(server=(host, port)) response = nclient.get(path,", "be empty for a GET request\") usage() sys.exit(2) response =", "= eval(input(\"Stop observing? [y/N]: \")) if chosen != \"\" and", "a elif o in (\"-P\", \"--payload\"): payload = a elif", "# url ==> 10 # ga ==> 7 def do_sequence_fp_p_int(my_base):", "if code == 68: return \"(Changed)\" if code == 69:", "= {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content) def do_sequence_auth(my_base): #", "counter > 0: time.sleep(1) counter = counter - 1 #client.stop()", "check_string = json.dumps(check_data, indent=2, sort_keys=True) print(\" check: \") print (check_string)", "response = client.post(path, payload, None, None, **ct) print((response.pretty_print())) if response.content_type", "no cover print(\"Command:\\tknxcoapclient.py -o -p [-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p,", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content = {", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # group object table # id", "accept == 60: payload = cbor.dumps(content) else: payload = content", "[1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\",", "60, content) content = { 2: \"startLoading\"} print(\"lsm :\", content);", "do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def", "json.dumps(json_data, indent=2, sort_keys=True) print (response.payload.decode()) # do_get(response.payload.decode(), client) client_callback_discovery(response) counter", ": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content =", "path is None: print(\"Path cannot be empty for a DELETE", "url, content, accept, contents content = {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60,", "{} ct['accept'] = ct_value ct['content_type'] = ct_value if mypath.startswith(\"coap://\") ==", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\" == sn", "60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # publisher table # id (0)=", "print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string", "OK \") else: print(\" =+++===> NOT OK \") print (json_string)", "} # st ga value (1) #content = { 5:", "and not (chosen == \"n\" or chosen == \"N\" or", "tmp except socket.gaierror: pass nclient = HelperClient(server=(host, port)) nclientcheck =", "content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content = 44 print(\"set IA :\",", "print (\"JSON ::\") print (json_string) client.stop() elif op == \"OBSERVE\":", "= [ { 0: 2, 12: \"r-Ia.IA2\", 10: \"url2\", 112:", "execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {0: 2, 12: \"xxxxyyyia2\", 112:", "return \"\" def get_base(url): # python3 knxcoapclient.py -o GET -p", "(\"=========\") print (response.payload) print (\"=========\") else: print (\"payload: none\") elif", "usage() sys.exit(2) response = client.get_non(path, None, None, **ct) print((response.pretty_print())) if", "== defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True)", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id", "a PUT request\") usage() sys.exit(2) response = client.put(path, payload) print((response.pretty_print()))", "7 def do_sequence_fp_r_int(my_base): # url, content, accept, contents content =", "execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # ca content = { 14:", "= nclient.put(path, payload, None, None , None, **ct) client_callback(response) nclient.stop()", "do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base)", "None paths = {} paths_extend = {} my_base = \"\"", "value (1) #content = { 5: { 6: 1, 7:", "(response.payload.decode()) # do_get(response.payload.decode(), client) client_callback_discovery(response) counter = 2 try: while", "accept, contents content = [ {\"id\": 1, \"href\": \"xxxx1\", \"cflag\":", "execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40)", "40) content = [ {0: 2, 12: \"xxxxyyyia2\", 112: \"path2\",", "ct['accept'] = a print (\"content type request : \", ct)", "= {} ct['accept'] = ct_value host, port, path = parse_uri(mypath)", "json.dumps(check_data, indent=2, sort_keys=True) print(\" check: \") print (check_string) if check_string", "is None: print(\"Path cannot be empty for a POST request\")", "= [ {0: 1, 11: \"/p/push\", 7:[1], 12 :\"blah.blah\" }", "break def execute_get(mypath, ct_value): print (\"---------------------------\") print (\"execute_get: \", ct_value,", "60) print(\"===================\") print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content =", "execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base): #sn = get_sn(my_base) install(my_base) return do_sequence_dev(my_base)", ": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx", "content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60,", "\"path\": \"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60)", "!= \"\" and not (chosen == \"n\" or chosen ==", "ia ==> 12 # path ==> 112 # url ==>", "\"Y\"): print(\"Unrecognized choose.\") continue elif rst == \"\" or rst", "execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60)", "iid = \"5\" # installation id if \"000001\" == sn", "1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60,", "client.get(path, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/json\"]: json_data", "print (\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data", "12: \"r-Ia.IA2\", 10: \"url2\", 112: \"r-path2\", 7:[44,55,33]}, {0: 3, 12:", "contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "==> 0 # ia ==> 12 # path ==> 112", "contents # sequence: # - parameter exchange: 15 (rnd)- return", "\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60)", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { \"sia\"", "in (\"-o\", \"--operation\"): op = a elif o in (\"-p\",", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\",", "= nclient.get(path, None, None, **ct) client_callback(response) nclient.stop() return response def", "= 0 response = nclient.delete(path, None, None, **ct) client_callback(response) #nclient.stop()", "request\") print(\"\\t-f, --payload-file=\\t\\tFile with payload of the request\") def get_url(line):", "except socket.gaierror: pass client = HelperClient(server=(host, port)) if op ==", "60, content) content = 2 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\",", "observing? [y/N]: \")) # if chosen != \"\" and not", "{ 0: 1, 11: \"/p/light\", 7:[1], 8: [1] } ]", "= {\"value\": { 4 : 5, 7: 7777 , 6", "(response.payload) #else: # print (\" not handled: \", response) else:", "# url, content, accept, contents content = [ {\"id\": 1,", "content = {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "40) # publisher table # id (0)= 1 # ia", "12: \"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content)", "execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40)", "= {0: b\"id2\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"}", "60) # id ==> 0 # href ==> 11 #", "content = {2: \"reset\"} execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content) def do_sequence_auth(my_base):", "line.split(\">\") url = data[0] return url[1:] def get_ct(line): tagvalues =", "= {2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "(\"type, len\", type(response.payload), len(response.payload)) print (response.payload) #else: # print (\"", "elif op == \"DELETE\": if path is None: print(\"Path cannot", "\"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError as err: # print help information", "#do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base) #do_sequence_lsm(my_base) do_sequence_lsm_int(my_base) # .knx do_sequence_knx_knx_int(my_base) #do_sequence_knx_knx(my_base) do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base)", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": {", "# recipient table # id (0)= 1 # ia (12)", "my_base = get_base(get_url(lines[0])) return my_base def get_sn(my_base): print(\"Get SN :\");", "if code == 133: return \"(METHOD_NOT_ALLOWED)\" if code == 160:", "\"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError as err: # print", "defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print", "1, 11: \"/p/push\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60,", "in cbor..\") print (json_string) print (\"===+++===\") if checkdata is not", "socket.gethostbyname(host) host = tmp except socket.gaierror: pass client = HelperClient(server=(host,", "= {} paths_extend = {} my_base = \"\" def usage():", "execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # expecting return def do_sequence_knx_idevid(my_base): #", "(check_string) if check_string == json_string: print(\" =+++===> OK \") else:", "check_string == json_string: print(\" =+++===> OK \") else: print(\" =+++===>", "print (response.payload) #else: # print (\" not handled: \", response)", "# st 6 def do_sequence_knx_knx_int(my_base): # url, content, accept, contents", "len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") else: print (\"payload:", "60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content = False print(\"set PM", "\"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]}, {0: 3, 1: \"xxxxyyy3\", 8: [1,4,5],", "(\" not handled: \", response) else: print (\" Response :", "host, port, path = parse_uri(mypath) try: tmp = socket.gethostbyname(host) host", "op == \"DISCOVER\": #response = client.discover( path, client_callback, None, **ct)", "= None #ct = {'content_type': defines.Content_types[\"application/link-format\"]} ct = {} ct['accept']", "---\") if response is not None: print (\"response code:\",response.code, code2string(response.code))", "mybase = my_url.split(\"/\") return mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths", "choose.\") continue elif chosen == \"y\" or chosen == \"Y\":", "pass nclient = HelperClient(server=(host, port)) response = nclient.get(path, None, None,", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base): # url,", "check = False break else: break def execute_get(mypath, ct_value): print", "---\") global my_base if response is not None: print (\"response", "nclient.stop() def main(): # pragma: no cover global client op", "content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content = False", "( \"payload for POST (ascii):\", payload ) print (ct['accept'] )", "sys import cbor #from cbor2 import dumps, loads import json", "global client print(\"Callback_observe\") check = True while check: chosen =", "2, 11: \"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]}, {0: 3, 1: \"xxxxyyy3\",", "execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\",", "60, 60, content) # pa content = { 10: b\"s10dfsdfsfs\"", "= {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content", "'r') as f: payload = f.read() elif o in (\"-h\",", "or chosen == \"Y\"): # print(\"Unrecognized choose.\") # continue def", "indent=2, sort_keys=True) print (json_string) elif response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode())", "execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 1 print(\"set IA :\",", "do_sequence_knx_ldevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base):", ":\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do", "{ 14: b\"a15sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # expecting return", "{0: 2, 11: \"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]}, {0: 3, 1:", "(11)= /p/light # ga (7 )= 1 # cflags (8)", "contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base): # url, content, accept, contents", "KeyboardInterrupt: print(\"Client Shutdown\") #client.stop() #execute_list() client.stop() else: print(\"Operation not recognized\")", "content = {0: b\"id\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\",", "b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) # pa content = {", "response.content_type == defines.Content_types[\"application/json\"]: json_data = json.loads(response.payload) json_string = json.dumps(json_data, indent=2,", "\"Ia.IA1\", 112: \"path1\", 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\",", "href ==> 11 # ga ==> 7 # cflag ==>", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id ==> 0 # ia ==> 12", "True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\",", "execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) def do_sequence_fp_r(my_base):", "-p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url = url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\")", "traceback from coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri from", "accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40) # content = {0: b\"id\", 1", "tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\") ct_value = ct_value_all[1].split(\",\") return ct_value[0] return", "= {'content_type': defines.Content_types[\"application/link-format\"]} ct = {} ct['accept'] = 40 try:", "112: \"r-path2\", 7:[44,55,33]}, {0: 3, 12: \"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]}", "{2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content", "\", ct_value, mypath) print (content) print (\" ---------------------\") do_exit =", "usage() sys.exit(2) print ( \"payload for POST (ascii):\", payload )", "Shutdown\") #client.stop() #execute_list() client.stop() else: print(\"Operation not recognized\") usage() sys.exit(2)", "cbor #from cbor2 import dumps, loads import json import time", "\"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\",", "nclient = HelperClient(server=(host, port)) #nclientcheck = HelperClient(server=(host, port)) payload =", "\"PUT\": if path is None: print(\"Path cannot be empty for", "60) json_data = cbor.loads(sn.payload) #print (\"SN : \", json_data) return", "print (\" SN : \", sn) print(\"===================\") print(\"Get HWT :\");", "HelperClient(server=(host, port)) nclientcheck = HelperClient(server=(host, port)) payload = 0 response", "client_callback, None, **ct) response = client.discover( path, None, None, **ct)", "60) print(\"===================\") content = \" iid xxx\" print(\"set iid :\",", "# ia ==> 12 # path ==> 112 # url", "client_callback_observe(response): # pragma: no cover global client print(\"Callback_observe\") check =", "= ct_value host, port, path = parse_uri(mypath) try: tmp =", ") if ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data = json.loads(payload) cbor_data =", "\") print (json_string) elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try:", "content = [ {0: 1, 11: \".knx\", 7:[1], 12 :\"blah.blah\"", "message? [Y/n]: \")) if rst != \"\" and not (rst", "60) content = {\"value\": { \"sia\" : 5, \"ga\": 7,", "== 160: return \"(INTERNAL_SERVER_ERROR)\" return \"\" def client_callback(response, checkdata=None): print(\"", "execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id ==> 0 # ia", "is None or len(mypath) < 5): return if mypath.startswith(\"coap://\") ==", "the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of the request\") print(\"\\t-f, --payload-file=\\t\\tFile with", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content", "should use /fp/r print (\"--------------------\") print (\"installing SN: \", sn)", "content = [ { 0: 2, 12: \"r-Ia.IA2\", 10: \"url2\",", "1, 11: \"p/push\", 7:[1], 8: [2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60,", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base): # url, content, accept,", "6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) #", "None , None, **ct) client_callback(response) nclient.stop() def main(): # pragma:", "= None content_type = None #ct = {'content_type': defines.Content_types[\"application/link-format\"]} ct", "print(\"Payload cannot be empty for a POST request\") usage() sys.exit(2)", "= iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) content = { 2:", "print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content =", "\"y\" or chosen == \"Y\"): print(\"Unrecognized choose.\") continue elif chosen", "= {} ct['accept'] = accept ct['content_type'] = ct_value if mypath.startswith(\"coap://\")", "get_sn(my_base): print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) json_data =", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 :", "pass client = HelperClient(server=(host, port)) if op == \"GET\": if", "defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) #print", "40 try: opts, args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\",", "\"href\": \"xxxx1\", \"cflag\": [1,2,3,4,5], \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content)", "for a PUT request\") usage() sys.exit(2) if payload is None:", "get_sn(my_base) print (\" SN : \", sn) print(\"===================\") print(\"Get HWT", "elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try: print (type(response.payload), len(response.payload))", "# id ==> 0 # href ==> 11 # ga", "\"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx resource", "\"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"r-Ia.IA3\", \"path\":", "response = nclient.put(path, payload, None, None , None, **ct) client_callback(response)", "return def do_sequence_knx_idevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282)", "== \"Y\"): # print(\"Unrecognized choose.\") # continue def client_callback_observe(response): #", "7: 1, 1: True } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content)", "= 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60)", "\"Y\": while True: rst = eval(input(\"Send RST message? [Y/n]: \"))", ":\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn = get_sn(my_base) print (\"", "getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except getopt.GetoptError as", "def do_sequence_auth(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def", "print (\"response code:\",response.code, code2string(response.code)) print (\"response type:\",response.content_type) if response.code >", "payload = cbor.dumps(content) else: payload = content response = nclient.post(path,", "the request\") print(\"\\t-P, --payload=\\t\\tPayload of the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of", "(\"---------------------------\") print (\"execute_del: \", ct_value, mypath) do_exit = False ct", "= a print (\"content type request : \", ct) elif", "4 : 5, 7: 7777 , 6 : \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\",", "7:[44,55,33]}, {0: 3, 12: \"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\",", "ct_value, mypath) print (content) print (\" ---------------------\") do_exit = False", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base): # url,", "to coap://host[:port]/path\") usage() sys.exit(2) host, port, path = parse_uri(path) try:", "client.delete(path) print((response.pretty_print())) client.stop() elif op == \"POST\": if path is", "do_sequence_dev(my_base): print(\"===================\") print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn", "if rst != \"\" and not (rst == \"n\" or", "request\") usage() sys.exit(2) if payload is None: print(\"Payload cannot be", "# url (11)= .knx # ga (7 )= 1 #", "5, \"ga\": 7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\",", "\"cflag\": [1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60)", "table # id (0)= 1 # url (11)= /p/light #", "1: True } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) content =", "= HelperClient(server=(host, port)) response = nclient.get(path, None, None, **ct) client_callback(response)", "# if chosen != \"\" and not (chosen == \"n\"", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content", "0 if accept == 60: payload = cbor.dumps(content) else: payload", "json.dumps(json_data, indent=2, sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data", "1, 1: True } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) content", "{\"id\": 2, \"href\": \"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\": 3, \"href\":", "be specified\") usage() sys.exit(2) if not path.startswith(\"coap://\"): print(\"Path must be", "mypath); return; ct = {} ct['accept'] = ct_value host, port,", "be empty for a GET request\") usage() sys.exit(2) client.observe(path, client_callback_observe)", "a elif o in (\"-p\", \"--path\"): path = a elif", "def execute_post(mypath, ct_value, accept, content): print (\"---------------------------\") print (\"execute_post: \",", "12: \"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content)", "chosen != \"\" and not (chosen == \"n\" or chosen", "execute_post(\"coap://\"+my_base+\"/a/sen\", 60, 60, content) def do_sequence_auth(my_base): # url, content, accept,", "do_sequence_lsm_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content =", "execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content =", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient table # id", "60, content) content = {0: b\"id2\", 1 : 20, 2:b\"ms\",3:\"hkdf\",", "json_data = json.loads(payload) cbor_data = cbor.dumps(json_data) payload = bytes(cbor_data) if", "len(mypath) < 5): return if mypath.startswith(\"coap://\") == False: print(\" not", "install(my_base): sn = get_sn(my_base) print (\" SN : \", sn)", "(\"installing SN: \", sn) content = True print(\"set PM :\",", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base): #", "use /fp/r print (\"--------------------\") print (\"installing SN: \", sn) content", "6: 1, 7: 1, 1: True } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60,", "content) # pa content = { 10: b\"s10dfsdfsfs\" } execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\",", "execute_put(mypath, ct_value, accept, content): print (\"---------------------------\") print (\"execute_put: \", ct_value,", "content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\",", "print (json_string) client.stop() elif op == \"OBSERVE\": if path is", "# group object table # id (0)= 1 # url", "cflags (8) = [\"r\" ] ; read = 1, write", "== sn : # actuator ==> receipient # should use", "1 : 5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) def", "args = getopt.getopt(sys.argv[1:], \"ho:p:P:f:c:\", [\"help\", \"operation=\", \"path=\", \"payload=\", \"payload_file=\",\"content-type\"]) except", "-o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url = url.replace(\"coap://\",\"\") mybase", "= client.post(path, payload, None, None, **ct) print((response.pretty_print())) if response.content_type ==", "60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\",", "\"--payload-file\"): with open(a, 'r') as f: payload = f.read() elif", "print(\"===================\") content = \"my host name\" print(\"set hostname :\", content);", "(\"===+++===\") if checkdata is not None: check_data = cbor.loads(checkdata) check_string", "response = nclient.post(path, payload, None, None , None, **ct) client_callback(response)", "\", ct_value, mypath) do_exit = False ct = {} ct['accept']", "be empty for a POST request\") usage() sys.exit(2) print (", "None: print (\"response code:\",response.code, code2string(response.code)) print (\"response type:\",response.content_type) if response.code", "< 5): return if mypath.startswith(\"coap://\") == False: print(\" not executing:", "sn) content = { 2: \"reset\"} print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\",", "#execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) content = {4: 5678, 5: {", ":\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content = True print(\"set PM :\",", "execute_del(mypath, ct_value): print (\"---------------------------\") print (\"execute_del: \", ct_value, mypath) do_exit", "= json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\")", "60, 60, content) content = {0: b\"id2\", 1 : 20,", "\"\" def get_base(url): # python3 knxcoapclient.py -o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\",", ": 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\", 6:b\"contextId2\"} execute_post(\"coap://\"+my_base+\"/auth/at\", 60, 60, content)", "get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths global paths_extend lines = payload.splitlines() #", "do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None):", "content response = nclient.post(path, payload, None, None , None, **ct)", "60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60)", "\", sn) print(\"===================\") print(\"Get HWT :\"); execute_get(\"coap://\"+my_base+\"/dev/hwt\", 60) print(\"===================\") print(\"Get", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\" == sn : # actuator", "content = {0: b\"id2\", 1 : 20, 2:b\"ms\",3:\"hkdf\", 4:\"alg\", 5:b\"salt\",", "HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60)", "nclient.stop() return response def execute_del(mypath, ct_value): print (\"---------------------------\") print (\"execute_del:", "\", payload) response = nclient.put(path, payload, None, None , None,", "print(\"Callback_observe\") check = True while check: chosen = eval(input(\"Stop observing?", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base): # url, content, accept, contents", "\"startLoading\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60)", "\"href\": \"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content)", "content = { 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60, 60, content) #", "sys.exit(2) response = client.put(path, payload) print((response.pretty_print())) client.stop() elif op ==", "for o, a in opts: if o in (\"-o\", \"--operation\"):", "{ 1 : 5, 2: \"reset\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content)", "sys.exit(2) print ( \"payload for POST (ascii):\", payload ) print", "\"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\":", "response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base) def", "= None payload = None content_type = None #ct =", "contents content = [ {0: 1, 11: \"xxxx1\", 8: [1,2,3,4,5],", "def do_sequence_fp_g_int(my_base): # url, content, accept, contents content = [", "url, content, accept, contents content = [ { 0: 1,", "# installation id if \"000001\" == sn : # sensor,", "def do_sequence_f(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40) #", "return; host, port, path = parse_uri(mypath) try: tmp = socket.gethostbyname(host)", "60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content = \" iid", "\"xxxxyyyia3\", \"path\": \"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60)", "request\") print(\"\\t-P, --payload=\\t\\tPayload of the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype of the", "execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ {\"id\": 2, \"ia\":", "execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) content = True print(\"set PM :\",", "path.startswith(\"coap://\"): print(\"Path must be conform to coap://host[:port]/path\") usage() sys.exit(2) host,", "print((response.pretty_print())) client.stop() elif op == \"POST\": if path is None:", "#nclientcheck = HelperClient(server=(host, port)) payload = 0 if accept ==", "{\"id\": 3, \"href\": \"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60,", "60) print(\"===================\") content = \"my host name\" print(\"set hostname :\",", "\"--help\"): usage() sys.exit() else: usage() sys.exit(2) if op is None:", "55, 7: 1, \"value\": 100 } # st ga value", "10 - return value # - pase verification exchange: 14", "= 3 update = 4 content = [ { 0:", "strings def do_sequence_dev(my_base): print(\"===================\") print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\",", "content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content = \"my host name\" print(\"set", "- 1 #client.stop() except KeyboardInterrupt: print(\"Client Shutdown\") #client.stop() #execute_list() client.stop()", "and exit: print((str(err))) # will print something like \"option -a", "> 100: print(\"+++returned error+++\") return if response.content_type == defines.Content_types[\"application/link-format\"]: print", "(\"JSON ::\") print (response.payload.decode()) print (\"\\n\\n\") if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]:", "60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\",", "= \" iid xxx\" print(\"set iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60,", "my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code): if code == 68:", "response = client.get(path, None, None, **ct) print((response.pretty_print())) if response.content_type ==", "FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\", 60) print(\"===================\") print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60)", "code2string(code): if code == 68: return \"(Changed)\" if code ==", "\"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content)", "= None paths = {} paths_extend = {} my_base =", "execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60)", "11: \"/p/light\", 7:[1], 8: [1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60,", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 2 print(\"set", "execute_get(\"coap://\"+my_base+\"/.well-known/knx\", 60) content = { 1 : 5, 2: \"reset\"}", "if len(paths) == 0: my_base = get_base(get_url(lines[0])) return my_base def", "= a elif o in (\"-P\", \"--payload\"): payload = a", "empty for a GET-None request\") usage() sys.exit(2) response = client.get_non(path,", "else: client.cancel_observing(response, False) check = False break else: break def", "= json.dumps(json_data, indent=2, sort_keys=True) #print (\"JSON ::\") print (response.payload.decode()) print", "\"(Content)\" if code == 132: return \"(Not Found)\" if code", "11: \"p/push\", 7:[1], 8: [2] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60,", "\"xxxxyyyia3\", 112: \"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\",", "60: #print(\" content :\", content) payload = cbor.dumps(content) else: payload", "# print (\" not handled: \", response) else: print (\"", "2: \"reset\"} print(\"reset :\", content); execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) content", "IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\")", "#client.stop() #execute_list() client.stop() else: print(\"Operation not recognized\") usage() sys.exit(2) if", "print(\"===================\") content = 44 print(\"set IA :\", content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60,", "except KeyboardInterrupt: print(\"Client Shutdown\") #client.stop() #execute_list() client.stop() else: print(\"Operation not", "= ct_value_all[1].split(\",\") return ct_value[0] return \"\" def get_base(url): # python3", "ct = {} ct['accept'] = ct_value ct['content_type'] = ct_value if", "None, **ct) client_callback(response) nclient.stop() def execute_post(mypath, ct_value, accept, content): print", "content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {\"id\": 2,", "do_sequence_knx_spake(my_base) do_sequence_knx_idevid(my_base) do_sequence_knx_ldevid(my_base) do_sequence_knx_crc(my_base) do_sequence_knx_osn(my_base) do_sequence_oscore(my_base) do_sequence_core_knx(my_base) do_sequence_a_sen(my_base) do_sequence_auth(my_base) do_sequence_auth_at(my_base)", "client.post(path, payload, None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/cbor\"]:", "\"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40)", "7, \"st\": \"rp\"}} execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/.knx\", 60) def", "except socket.gaierror: pass nclient = HelperClient(server=(host, port)) #nclientcheck = HelperClient(server=(host,", "} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) content = False print(\"set", "\"value\": 100 } content = { 4: 5678, \"st\": 55,", "HelperClient(server=(host, port)) #nclientcheck = HelperClient(server=(host, port)) payload = 0 if", "content = {2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\",", "PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 1", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content =", "60) # ./knx resource # sia ==> 4 # ga", "client op = None path = None payload = None", "def install(my_base): sn = get_sn(my_base) print (\" SN : \",", "contents execute_get(\"coap://\"+my_base+\"/f\", 40) # note this one is a bit", "check: # chosen = eval(input(\"Stop observing? [y/N]: \")) # if", "this one is a bit dirty hard coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40)", "\"Y\"): print(\"Unrecognized choose.\") continue elif chosen == \"y\" or chosen", "port)) payload = 0 response = nclient.delete(path, None, None, **ct)", "== \"DISCOVER\": #response = client.discover( path, client_callback, None, **ct) response", "xxx\" print(\"set iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\",", "12: \"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]}, {0: 3, 12: \"xxxxyyyia3\", 112:", "import HelperClient from coapthon.utils import parse_uri from coapthon import defines", "main(): # pragma: no cover global client op = None", "{0: 1, 11: \".knx\", 7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\",", "or chosen == \"Y\": while True: rst = eval(input(\"Send RST", "json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print (json_string) client.stop() elif", "content = iid execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60, content) content = {", "tmp = socket.gethostbyname(host) host = tmp except socket.gaierror: pass nclient", "] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content", "client.put(path, payload) print((response.pretty_print())) client.stop() elif op == \"DISCOVER\": #response =", "in (\"-P\", \"--payload\"): payload = a elif o in (\"-c\",", "\" iid xxx\" print(\"set iid :\", content); execute_put(\"coap://\"+my_base+\"/dev/iid\", 60, 60,", "not (chosen == \"n\" or chosen == \"N\" or chosen", "== \"Y\": client.cancel_observing(response, True) else: client.cancel_observing(response, False) check = False", "= url.replace(\"coap://\",\"\") mybase = my_url.split(\"/\") return mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\")", "empty for a PUT request\") usage() sys.exit(2) if payload is", "\"OBSERVE\": if path is None: print(\"Path cannot be empty for", "1, 1: False } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\",", "[ {0: 2, 11: \"xxxxyyy2\", 8: [1,4,5], 7:[44,55,33]}, {0: 3,", "print(\" =+++===> OK \") else: print(\" =+++===> NOT OK \")", "{\"sia\": 5678, \"st\": 55, \"ga\": 1, \"value\": 100 } content", "(\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data =", "# no json tags as strings def do_sequence_dev(my_base): print(\"===================\") print(\"Get", "do_sequence(my_base) def code2string(code): if code == 68: return \"(Changed)\" if", "for a GET-None request\") usage() sys.exit(2) response = client.get_non(path, None,", "post content = {\"sia\": 5678, \"st\": 55, \"ga\": 1, \"value\":", "len\", type(response.payload), len(response.payload)) print (response.payload) #else: # print (\" not", "contents content = [ {\"id\": 1, \"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\",", "40) # recipient table # id (0)= 1 # ia", "a POST request\") usage() sys.exit(2) print ( \"payload for POST", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 :", "do_sequence_knx_idevid(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base):", "!= \"\" and not (rst == \"n\" or rst ==", "None: print(\"Path cannot be empty for a GET-None request\") usage()", "sys.exit() else: usage() sys.exit(2) if op is None: print(\"Operation must", "60) def do_sequence_f(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40)", "/p/light # ga (7 )= 1 # cflags (8) =", "\", sn) content = True print(\"set PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\",", "60, content) execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id ==> 0 # href", "execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40)", "verification exchange: 14 - no return value content = {", "#ct = {'content_type': defines.Content_types[\"application/link-format\"]} ct = {} ct['accept'] = 40", "host = tmp except socket.gaierror: pass client = HelperClient(server=(host, port))", "is None: print(\"Path cannot be empty for a PUT request\")", "\"st\": 55, \"ga\": 1, \"value\": 100 } content = {", "code == 133: return \"(METHOD_NOT_ALLOWED)\" if code == 160: return", "empty for a GET request\") usage() sys.exit(2) client.observe(path, client_callback_observe) elif", "= cbor.loads(response.payload) print (json_data) print (\"---------\") except: traceback.print_exc() json_string =", "(\"execute_del: \", ct_value, mypath) do_exit = False ct = {}", "[1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) #", "# url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth\", 40) def do_sequence_auth_at(my_base): #", "(\"=======\") def execute_put(mypath, ct_value, accept, content): print (\"---------------------------\") print (\"execute_put:", "1 # ia (12) # url (11)= .knx # ga", "the if len(paths) == 0: my_base = get_base(get_url(lines[0])) return my_base", "} #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content) #", "60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ {\"id\": 2, \"ia\": \"r-Ia.IA2\",", "content = [ {0: 2, 12: \"xxxxyyyia2\", 112: \"path2\", 7:[44,55,33]},", "None, None , None, **ct) client_callback(response) nclient.stop() def main(): #", "no return value content = { 15: b\"a-15-sdfsdred\"} execute_post(\"coap://\"+my_base+\"/.well-known/knx/spake\", 60,", "import cbor #from cbor2 import dumps, loads import json import", "100 } # st ga value (1) #content = {", "socket.gaierror: pass nclient = HelperClient(server=(host, port)) response = nclient.get(path, None,", "execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {0: 2, 11:", "get_base(url): # python3 knxcoapclient.py -o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50", "print (\" SN : \", sn) iid = \"5\" #", "accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base): # url, content, accept,", "payload = 0 if accept == 60: payload = cbor.dumps(content)", "\"--payload\"): payload = a elif o in (\"-c\", \"--content-type\"): ct['accept']", "60) # do a post content = {\"sia\": 5678, \"st\":", "print (\"payload: \", payload) response = nclient.put(path, payload, None, None", "40 == application-link format execute_get(\"coap://\"+my_base+\"/fp/p\", 40) content = [ {\"id\":", "= json.loads(payload) cbor_data = cbor.dumps(json_data) payload = bytes(cbor_data) if ct['accept']", "paths = {} paths_extend = {} my_base = \"\" def", "40) content = [ {0: 2, 11: \"xxxxyyy2\", 8: [1,4,5],", "content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\" ==", "nclientcheck = HelperClient(server=(host, port)) payload = 0 response = nclient.delete(path,", "port)) if op == \"GET\": if path is None: print(\"Path", "json.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print", "8: [1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60)", "60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) #", "content = [ { 0: 1, 12: \"r-Ia.IA1\", 112: \"r-path1\",", "print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload) print (\"=========\") json_data", "st ga value (1) #content = { 5: { 6:", "def do_sequence_oscore(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\",", "chosen == \"y\" or chosen == \"Y\": while True: rst", "execute_get(mypath, ct_value): print (\"---------------------------\") print (\"execute_get: \", ct_value, mypath) print", "execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) print(\"===================\") content = 44", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\" == sn : #", "coded... execute_get(\"coap://\"+my_base+\"/f/417\", 40) execute_get(\"coap://\"+my_base+\"/.well-known/core\", 40) def do_sequence(my_base): #sn = get_sn(my_base)", "\"POST\": if path is None: print(\"Path cannot be empty for", "(json_string) client.stop() elif op == \"OBSERVE\": if path is None:", "- return value # - pase verification exchange: 14 -", "1, \"ia\": \"Ia.IA1\", \"path\": \"path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60,", "#print(\" content :\", content) payload = cbor.dumps(content) else: payload =", "execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/pm\", 60) content = False print(\"set", "rst == \"N\" or rst == \"y\" or rst ==", "print(\"Operation not recognized\") usage() sys.exit(2) if __name__ == '__main__': #", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do a post", "execute_get(\"coap://\"+my_base+\"/dev/iid\", 60) # id ==> 0 # href ==> 11", "(\"JSON ::\") print (json_string) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data =", "rst == \"\" or rst == \"y\" or rst ==", "not recognized\") usage() sys.exit(2) if __name__ == '__main__': # pragma:", "\"xxxxyyy3\", 8: [1,4,5], 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\",", "= {} ct['accept'] = 40 try: opts, args = getopt.getopt(sys.argv[1:],", "#execute_list() client.stop() else: print(\"Operation not recognized\") usage() sys.exit(2) if __name__", "7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60)", "print(\"Path cannot be empty for a GET-None request\") usage() sys.exit(2)", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"loadComplete\"}", "execute_get(\"coap://\"+my_base+\"/fp/r\", 40) # cmd ==> 2 def do_sequence_lsm_int(my_base): # url,", "print(\"Operation must be specified\") usage() sys.exit(2) if path is None:", "do_sequence_lsm(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content =", "content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) def", "not None: print (\"response code:\",response.code) print (\"response type:\",response.content_type) if response.code", "if response is not None: print (\"response code:\",response.code, code2string(response.code)) print", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "chosen == \"Y\"): print(\"Unrecognized choose.\") continue elif chosen == \"y\"", "(\"=========\") json_string = \"\" try: json_data = cbor.loads(response.payload) json_string =", "else: usage() sys.exit(2) if op is None: print(\"Operation must be", "None: print(\"Path cannot be empty for a GET request\") usage()", "print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) #", "160: return \"(INTERNAL_SERVER_ERROR)\" return \"\" def client_callback(response, checkdata=None): print(\" ---", "ct_value, mypath) print (type(mypath)) if (mypath is None or len(mypath)", "\"--operation\"): op = a elif o in (\"-p\", \"--path\"): path", "in (\"-f\", \"--payload-file\"): with open(a, 'r') as f: payload =", "or rst == \"y\" or rst == \"Y\": client.cancel_observing(response, True)", "1, \"value\": 100 } content = { 4: 5678, \"st\":", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\",", "100: print(\"+++returned error+++\") return #print(response.pretty_print()) if response.content_type == defines.Content_types[\"text/plain\"]: if", "\"/p/light\", 7:[1], 8: [1] } ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content)", "#while check: # chosen = eval(input(\"Stop observing? [y/N]: \")) #", "\"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/1\", 60) # 40", "url, content, accept, contents content = [ {\"id\": 1, \"href\":", "sys.exit(2) if not path.startswith(\"coap://\"): print(\"Path must be conform to coap://host[:port]/path\")", "\"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content)", "60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) execute_del(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/p\", 40) def", "if response.payload is not None: print (type(response.payload), len(response.payload)) print (\"=========\")", "(\"-f\", \"--payload-file\"): with open(a, 'r') as f: payload = f.read()", "port)) nclientcheck = HelperClient(server=(host, port)) payload = 0 response =", "if o in (\"-o\", \"--operation\"): op = a elif o", "indent=2, sort_keys=True) print (response.payload.decode()) # do_get(response.payload.decode(), client) client_callback_discovery(response) counter =", "sort_keys=True) print (json_string) client.stop() elif op == \"PUT\": if path", "==> 10 # ga ==> 7 def do_sequence_fp_p_int(my_base): # url,", "60, content) execute_get(\"coap://\"+my_base+\"/auth/at\", 40) execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base):", "60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # do a post content =", "json.loads(payload) cbor_data = cbor.loads(json_data) payload = cbor_data response = client.post(path,", "from coapthon.client.helperclient import HelperClient from coapthon.utils import parse_uri from coapthon", "#client.stop() except KeyboardInterrupt: print(\"Client Shutdown\") #client.stop() #execute_list() client.stop() else: print(\"Operation", "response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try: print (type(response.payload), len(response.payload)) print", "60, content) def do_sequence_a_sen(my_base): # url, content, accept, contents content", "def execute_del(mypath, ct_value): print (\"---------------------------\") print (\"execute_del: \", ct_value, mypath)", "response.content_type == defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload)) print (\"=========\") print (response.payload)", "# ga ==> 7 def do_sequence_fp_p_int(my_base): # url, content, accept,", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) def do_sequence_lsm(my_base): # url, content,", "request\") usage() sys.exit(2) client.observe(path, client_callback_observe) elif op == \"DELETE\": if", "elif op == \"OBSERVE\": if path is None: print(\"Path cannot", "print (response.payload) print (\"=========\") #json_data = loads(response.payload) #print(json_data) #print (\"=========\")", "of the request\") print(\"\\t-P, --payload=\\t\\tPayload of the request\") print(\"\\t-c, --contenttype=\\t\\tcontenttype", "defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload) #json_string = json.dumps(json_data, indent=2, sort_keys=True) print", "4: 5678, \"st\": 55, 7: 1, \"value\": 100 } #", "GET request\") usage() sys.exit(2) client.observe(path, client_callback_observe) elif op == \"DELETE\":", "= 2 try: while counter > 0: time.sleep(1) counter =", "url = data[0] return url[1:] def get_ct(line): tagvalues = line.split(\";\")", "print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of the request\") print(\"\\t-P, --payload=\\t\\tPayload of", "execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { \"sia\" : 5, \"ga\":", "ct) elif o in (\"-f\", \"--payload-file\"): with open(a, 'r') as", "print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get FWV :\"); execute_get(\"coap://\"+my_base+\"/dev/fwv\",", "print ( \"payload for POST (ascii):\", payload ) print (ct['accept']", "return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base) #do_sequence_fp_p(my_base) do_sequence_fp_r_int(my_base) #do_sequence_fp_r(my_base) do_sequence_lsm_int(my_base)", "do_sequence_knx_knx_int(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content =", "with open(a, 'r') as f: payload = f.read() elif o", "execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ {\"id\": 2, \"ia\": \"r-Ia.IA2\", \"path\":", "#sn = get_sn(my_base) install(my_base) return do_sequence_dev(my_base) #return do_sequence_fp_g_int(my_base) #do_sequence_fp_g(my_base) do_sequence_fp_p_int(my_base)", "112: \"path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60)", "response = client.delete(path) print((response.pretty_print())) client.stop() elif op == \"POST\": if", "Response : None\") #check = True #while check: # chosen", "python3 knxcoapclient.py -o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url =", "\"path3\",\"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/p/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/p/3\", 60)", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/ldevid\", 282) def do_sequence_knx_osn(my_base): # url, content,", "(\"Installing SN: \", sn) content = { 2: \"reset\"} print(\"reset", "ct['accept'] = ct_value ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False:", "a print (\"content type request : \", ct) elif o", "[ {0: 1, 11: \"xxxx1\", 8: [1,2,3,4,5], 7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\",", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"loadComplete\"} execute_post(\"coap://\"+my_base+\"/a/lsm\",", "60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient table # id (0)=", "{\"id\": 1, \"ia\": \"r-Ia.IA1\", \"path\": \"r-path1\", \"ga\":[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60,", "1 # cflags (8) = [\"r\" ] ; read =", "== \"y\" or rst == \"Y\"): print(\"Unrecognized choose.\") continue elif", "error+++\") return if response.content_type == defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base =", "1, 7: 1, 1: False } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60, 60,", "60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) if \"000002\" == sn :", "return host, port, path = parse_uri(mypath) try: tmp = socket.gethostbyname(host)", "is not None: print (\"response code:\",response.code, code2string(response.code)) print (\"response type:\",response.content_type)", "or rst == \"Y\": client.cancel_observing(response, True) else: client.cancel_observing(response, False) check", "print (\"\\n\\n\") if response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: json_data = cbor.loads(response.payload) json_string", "execute_post(\"coap://\"+my_base+\"/.well-known/knx\", 60, 60, content) def do_sequence_a_sen(my_base): # url, content, accept,", "defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) else: if response.payload is not None: print", "be empty for a POST request\") usage() sys.exit(2) if payload", "execute_get(\"coap://\"+my_base+\"/.knx\", 60) # ./knx resource def do_sequence_knx_knx(my_base): # url, content,", "105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60) content", "\", mypath); return host, port, path = parse_uri(mypath) try: tmp", "json_data = cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string)", "do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None): print(\" --- Discovery Callback ---\")", "if accept == 60: #print(\" content :\", content) payload =", "accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\",", "60, 60, content) content = {4: 5678, 5: { 6:", "response.code > 100: print(\"+++returned error+++\") return if response.content_type == defines.Content_types[\"application/link-format\"]:", "2, \"ia\": \"r-Ia.IA2\", \"path\": \"r-path2\", \"ga\":[44,55,33]}, {\"id\": 3, \"ia\": \"r-Ia.IA3\",", "content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base): # url, content,", "[y/N]: \")) # if chosen != \"\" and not (chosen", "None, None, **ct) client_callback(response) #nclient.stop() #sys.exit(2) print (\"=======\") def execute_put(mypath,", "elif chosen == \"y\" or chosen == \"Y\": while True:", "print(\"===================\") print(\"Get SN :\"); sn = execute_get(\"coap://\"+my_base+\"/dev/sn\", 60) sn =", "contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { 4 : 5,", "PM :\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 2", "print(\"===================\") print(\"Get Model :\"); execute_get(\"coap://\"+my_base+\"/dev/model\", 60) print(\"===================\") content = True", "if accept == 60: payload = cbor.dumps(content) else: payload =", "ga ==> 7 def do_sequence_fp_p_int(my_base): # url, content, accept, contents", "execute_get(\"coap://\"+my_base+\"/auth/at/id\", 60) execute_del(\"coap://\"+my_base+\"/auth/at/id\", 60) def do_sequence_f(my_base): # url, content, accept,", "#print (\"=========\") json_string = \"\" try: json_data = cbor.loads(response.payload) json_string", "url ==> 10 # ga ==> 7 def do_sequence_fp_r_int(my_base): #", "do_sequence_auth(my_base) do_sequence_auth_at(my_base) do_sequence_f(my_base) def client_callback_discovery(response, checkdata=None): print(\" --- Discovery Callback", "= [ { 0: 1, 12: \"r-Ia.IA1\", 112: \"r-path1\", 7:[2222,3333]}", "from coapthon import defines client = None paths = {}", "60) print(\"===================\") print(\"Get HWV :\"); execute_get(\"coap://\"+my_base+\"/dev/hwv\", 60) print(\"===================\") print(\"Get FWV", "(\"response code:\",response.code, code2string(response.code)) print (\"response type:\",response.content_type) if response.code > 100:", "if path is None: print(\"Path must be specified\") usage() sys.exit(2)", "60) content = {2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "url (11)= /p/light # ga (7 )= 1 # cflags", "# path ==> 112 # url ==> 10 # ga", "== \"y\" or chosen == \"Y\": while True: rst =", "40) def do_sequence_auth_at(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/auth/at\", 40)", "print (json_string) elif response.content_type == defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try: print", "None, **ct) if response is not None: print(response.pretty_print()) if response.content_type", "# sensor, e.g sending print (\"--------------------\") print (\"Installing SN: \",", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {\"id\": 2, \"href\": \"xxxxyyy2\", \"cflag\":", "3, \"href\": \"xxxxyyy3\", \"cflag\": [1,4,5], \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60,", "contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/idevid\", 282) def do_sequence_knx_ldevid(my_base): # url, content, accept, contents", ": # actuator ==> receipient # should use /fp/r print", "40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content = 105 execute_put(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60, 60, content)", ") print (ct['accept'] ) if ct['accept'] == str(defines.Content_types[\"application/cbor\"]): json_data =", "update = 4 content = [ {0: 1, 11: \".knx\",", "\"\" def client_callback(response, checkdata=None): print(\" --- Callback ---\") if response", "40) def do_sequence_fp_g(my_base): # url, content, accept, contents content =", "\", response) else: print (\" Response : None\") #check =", "sequence: # - parameter exchange: 15 (rnd)- return value #", "= json.dumps(json_data, indent=2, sort_keys=True) except: print(\"error in cbor..\") print (json_string)", "rst == \"Y\": client.cancel_observing(response, True) else: client.cancel_observing(response, False) check =", "accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40) # note this one is a", "print (json_string) client.stop() elif op == \"PUT\": if path is", "# id ==> 0 # ia ==> 12 # path", "== \"N\" or chosen == \"y\" or chosen == \"Y\"):", "[-P]\") print(\"Options:\") print(\"\\t-o, --operation=\\tGET|GETNONE|PUT|POST|DELETE|DISCOVER|OBSERVE\") print(\"\\t-p, --path=\\t\\t\\tPath of the request\") print(\"\\t-P,", "sort_keys=True) print (json_string) if response.content_type == defines.Content_types[\"application/link-format\"]: #json_data = cbor.loads(response.payload)", "get_ct(line): tagvalues = line.split(\";\") for tag in tagvalues: if tag.startswith(\"ct\"):", "[ {\"id\": 2, \"href\": \"xxxxyyy2\", \"cflag\": [1,4,5], \"ga\":[44,55,33]}, {\"id\": 3,", "execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) # ./knx resource #", "7:[2222,3333]} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40)", "content); execute_put(\"coap://\"+my_base+\"/dev/ia\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/ia\", 60) print(\"===================\") content =", "5: { 6: 1, 7: 1, 1: True } }", "== 69: return \"(Content)\" if code == 132: return \"(Not", "= json.loads(payload) cbor_data = cbor.loads(json_data) payload = cbor_data response =", "print (\"=======\") def execute_put(mypath, ct_value, accept, content): print (\"---------------------------\") print", "= cbor.loads(response.payload) json_string = json.dumps(json_data, indent=2, sort_keys=True) except: print(\"error in", "ct['accept'] = accept ct['content_type'] = ct_value if mypath.startswith(\"coap://\") == False:", "\", sn) content = { 2: \"reset\"} print(\"reset :\", content);", "7:[1], 12 :\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/p\", 60, 60, content) content", "def client_callback(response, checkdata=None): print(\" --- Callback ---\") if response is", "defines.Content_types[\"application/link-format\"]: print (response.payload.decode()) my_base = get_base_from_link(response.payload.decode()) do_sequence(my_base) def code2string(code): if", "40) execute_del(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id ==>", "\"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\",", "nclient = HelperClient(server=(host, port)) response = nclient.get(path, None, None, **ct)", "= socket.gethostbyname(host) host = tmp except socket.gaierror: pass nclient =", "if payload is None: print(\"Payload cannot be empty for a", "None, **ct) client_callback(response) #nclient.stop() #sys.exit(2) print (\"=======\") def execute_put(mypath, ct_value,", "mypath.startswith(\"coap://\") == False: print(\" not executing: \", mypath); return; ct", "group object table # id (0)= 1 # url (11)=", "133: return \"(METHOD_NOT_ALLOWED)\" if code == 160: return \"(INTERNAL_SERVER_ERROR)\" return", "payload = bytes(cbor_data) if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]): json_data = json.loads(payload)", "execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/g/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40)", "= socket.gethostbyname(host) host = tmp except socket.gaierror: pass client =", "print (response.payload.decode()) else: if response.payload is not None: print (\"type,", "sn : # sensor, e.g sending print (\"--------------------\") print (\"Installing", "content, accept, contents execute_get(\"coap://\"+my_base+\"/f/oscore\", 40) execute_get(\"coap://\"+my_base+\"/p/oscore/replwdo\", 60) content = 105", ":\"blah.blah\" } ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60, 60, content) content = False", "60) content = 1050 execute_put(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/p/oscore/osndelay\", 60)", "my_url.split(\"/\") return mybase[0] def get_base_from_link(payload): print(\"get_base_from_link\\n\") global paths global paths_extend", "accept, contents execute_get(\"coap://\"+my_base+\"/.knx\", 60) content = {\"value\": { 4 :", "cbor_data response = client.post(path, payload, None, None, **ct) print((response.pretty_print())) if", "content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\",", "60, content) #execute_post(\"coap://[FF02::FD]:5683/.knx\", 60, 60, content) # no json tags", "==> 112 # url ==> 10 # ga ==> 7", "print something like \"option -a not recognized\" usage() sys.exit(2) for", "op == \"PUT\": if path is None: print(\"Path cannot be", "(\"-P\", \"--payload\"): payload = a elif o in (\"-c\", \"--content-type\"):", "url, content, accept, contents execute_get(\"coap://\"+my_base+\"/f\", 40) # note this one", "global my_base if response is not None: print (\"response code:\",response.code)", "cannot be empty for a GET-None request\") usage() sys.exit(2) response", "60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/r/2\", 60) execute_get(\"coap://\"+my_base+\"/fp/r/3\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) execute_del(\"coap://\"+my_base+\"/fp/r/3\",", "op == \"DELETE\": if path is None: print(\"Path cannot be", "o in (\"-f\", \"--payload-file\"): with open(a, 'r') as f: payload", "content); execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content =", "= \"\" def usage(): # pragma: no cover print(\"Command:\\tknxcoapclient.py -o", "do_sequence_knx_osn(my_base): # url, content, accept, contents execute_get(\"coap://\"+my_base+\"/.well-known/knx/osn\", 60) def do_sequence_knx_crc(my_base):", "\"(Changed)\" if code == 69: return \"(Content)\" if code ==", "None, None, **ct) print((response.pretty_print())) if response.content_type == defines.Content_types[\"application/cbor\"]: json_data =", "is None: print(\"Path cannot be empty for a GET-None request\")", "execute_put(\"coap://\"+my_base+\"/dev/hostname\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/dev/hostname\", 60) print(\"===================\") content = \"", "print(\"\\t-f, --payload-file=\\t\\tFile with payload of the request\") def get_url(line): data", "execute_get(\"coap://\"+my_base+\"/fp/g\", 40) content = [ {0: 2, 11: \"xxxxyyy2\", 8:", "json_string = json.dumps(json_data, indent=2, sort_keys=True) print (json_string) elif response.content_type ==", "content): print (\"---------------------------\") print (\"execute_put: \", ct_value, mypath) do_exit =", "(\"payload: none\") elif response.content_type == defines.Content_types[\"application/cbor\"]: print (type(response.payload), len(response.payload)) print", "defines.Content_types[\"application/vnd.ocf+cbor\"]: print (\"application/vnd.ocf+cbor\") try: print (type(response.payload), len(response.payload)) print (\"=========\") print", "60, 60, content) content = { 2: \"startLoading\"} print(\"lsm :\",", "execute_get(\"coap://\"+my_base+\"/fp/r/1\", 60) execute_get(\"coap://\"+my_base+\"/fp/r\", 40) content = [ { 0: 2,", "True while check: chosen = eval(input(\"Stop observing? [y/N]: \")) if", "json.dumps(json_data, indent=2, sort_keys=True) print (\"JSON ::\") print (json_string) if response.content_type", "60) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # id ==> 0 # ia ==>", "content) execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"unload\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60,", "==> 7 def do_sequence_fp_r_int(my_base): # url, content, accept, contents content", "knxcoapclient.py -o GET -p coap://[fe80::6513:3050:71a7:5b98]:63914/a -c 50 my_url = url.replace(\"coap://\",\"\")", "{ 2: \"loadComplete\"} print(\"lsm :\", content); execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "{\"id\": 3, \"ia\": \"r-Ia.IA3\", \"path\": \"r-path3\", \"ga\":[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60,", "is None: print(\"Path cannot be empty for a GET request\")", "6: 1, 7: 1, 1: False } } #execute_post(\"coap://\"+my_base+\"/.knx\", 60,", "executing: \", mypath); return; host, port, path = parse_uri(mypath) try:", "} ] execute_post(\"coap://\"+my_base+\"/fp/g\", 60, 60, content) execute_get(\"coap://\"+my_base+\"/fp/g\", 40) # recipient", "cbor_data = cbor.dumps(json_data) payload = bytes(cbor_data) if ct['accept'] == str(defines.Content_types[\"application/vnd.ocf+cbor\"]):", "False ct = {} ct['accept'] = accept ct['content_type'] = ct_value", "tags as strings def do_sequence_dev(my_base): print(\"===================\") print(\"Get SN :\"); sn", "[ {\"id\": 2, \"ia\": \"xxxxyyyia2\", \"path\": \"path2\",\"ga\":[44,55,33]}, {\"id\": 3, \"ia\":", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {2 : \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60,", "global client op = None path = None payload =", "pass nclient = HelperClient(server=(host, port)) #nclientcheck = HelperClient(server=(host, port)) payload", "# pragma: no cover print(\"Command:\\tknxcoapclient.py -o -p [-P]\") print(\"Options:\") print(\"\\t-o,", "path is None: print(\"Path cannot be empty for a POST", ":\", content); execute_put(\"coap://\"+my_base+\"/dev/pm\", 60, 60, content) content = 1 print(\"set", "paths global paths_extend lines = payload.splitlines() # add the if", "{0: 3, 12: \"r-Ia.IA3\", 112: \"r-path3\", 7:[44,55,33]} ] execute_post(\"coap://\"+my_base+\"/fp/r\", 60,", "execute_get(\"coap://\"+my_base+\"/a/lsm\", 60) content = {\"cmd\": \"startLoading\"} execute_post(\"coap://\"+my_base+\"/a/lsm\", 60, 60, content)", "[ { 0: 1, 11: \"/p/light\", 7:[1], 8: [1] }", "tag in tagvalues: if tag.startswith(\"ct\"): ct_value_all = tag.split(\"=\") ct_value =", "= {4: 5678, 5: { 6: 1, 7: 1, 1:", "print (\"installing SN: \", sn) content = True print(\"set PM" ]
[ "= ['sip', 'PyQt4.QtGui', 'PyQt4._qt'] from PyInstaller.hooks.hookutils import qt4_plugins_binaries def hook(mod):", "hiddenimports = ['sip', 'PyQt4.QtGui', 'PyQt4._qt'] from PyInstaller.hooks.hookutils import qt4_plugins_binaries def", "['sip', 'PyQt4.QtGui', 'PyQt4._qt'] from PyInstaller.hooks.hookutils import qt4_plugins_binaries def hook(mod): mod.binaries.extend(qt4_plugins_binaries('phonon_backend'))", "'PyQt4._qt'] from PyInstaller.hooks.hookutils import qt4_plugins_binaries def hook(mod): mod.binaries.extend(qt4_plugins_binaries('phonon_backend')) return mod", "'PyQt4.QtGui', 'PyQt4._qt'] from PyInstaller.hooks.hookutils import qt4_plugins_binaries def hook(mod): mod.binaries.extend(qt4_plugins_binaries('phonon_backend')) return" ]
[ "greeks and volatility information (option only), defaults to False :type", "def option_expirations( self, symbol: str, includeAllRoots: Union[str, bool] = \"\",", "query :type symbol: str :param interval: Interval of time per", "out their APIs for more in-depth options data. :param symbol:", "chain :type expiration: Union[str, datetime] :param greeks: Add greeks and", "to \"daily\" :type interval: str, optional :param start: Start date", "= False) -> dict: \"\"\"Get a list of symbols using", ") -> dict: \"\"\"Get all quotes in an option chain.", "data. :param symbol: Underlying symbol of the chain :type symbol:", "Sales (timesales) is typically used for charting purposes. It captures", "option chain :rtype: dict \"\"\" return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\",", "includeAllRoots: Union[str, bool], optional :param strikes: Add strike prices to", "datetime import datetime class MarketData(BasePyTradier): \"\"\"All Methods currently only support", "check out their APIs for more in-depth options data. :param", "the OCC option symbol (ex. AAPL220617C00270000) as the symbol. :param", "symbols using a keyword lookup on the symbols description. Results", "functions :param symbols: Comma-delimited list of symbols (equity or option)", "{\"rootSymbol\": underlying, \"options\": [list of option symbols]} :rtype: dict \"\"\"", "start/end times. You can fetch historical pricing for options by", "\"\", ) -> list: \"\"\"Get expiration dates for a particular", "expiration: Union[str, datetime] :param greeks: Add greeks and volatility information,", "monthly, defaults to \"daily\" :type interval: str, optional :param start:", "an options strike prices for a specified expiration date. :param", "symbol (ex. AAPL220617C00270000) as the symbol. :param symbol: Symbol to", "downloads time reasonable.` :param symbol: A single security symbol. :type", "a list of symbols using a keyword lookup on the", "start: str :param end: Start date/time for timesales range represented", "'open', 'high', 'close', low', 'volume', 'vwap'] :rtype: list \"\"\" return", ":param strikes: Add strike prices to each expiration, defaults to", "of the company if sending reasonable start/end times. You can", "A single security symbol. :type symbol: str :param start: Start", "\"quotes\"), ) def option_chain( self, symbol: str, expiration: Union[str, datetime],", "the given underlying. This will include additional option roots (ex.", ":type symbol: str :param interval: Interval of time per timesale.", "from datetime import datetime class MarketData(BasePyTradier): \"\"\"All Methods currently only", "needs to be much smaller to keep downloads time reasonable.`", "for the given underlying. This will include additional option roots", "Results are in descending order by average volume of the", "in-depth options data. :param symbol: Underlying symbol of the chain", "and volatility information (option only), defaults to False :type greeks:", "'price', 'open', 'high', 'close', low', 'volume', 'vwap'] :rtype: list \"\"\"", "def option_strike(self, symbol: str, expiration: Union[str, datetime]) -> list: \"\"\"Get", "None :type start: str, optional :param end: End date represented", "= None, end: str = None ) -> list: \"\"\"Get", "str %Y-%m-%d :rtype: list \"\"\" response = self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals())", "symbol: str :param expiration: Expiration for the chain :type expiration:", "historic_quotes( self, symbol: str, interval: str = \"daily\", start: str", "list of dictionaries containing keys of ['time', 'timestamp', 'price', 'open',", "chain :rtype: dict \"\"\" return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"),", "to '' :type strikes: Union[str, bool], optional :return: list of", ":type end: str, optional :return: [description] :rtype: list \"\"\" return", "\"\"\" def quotes(self, symbols: Union[str, list], greeks: bool = False)", "as YYYY-MM-DD HH:MM :type end: str :param interval: Interval of", "-> dict: \"\"\"Get all quotes in an option chain. Greek", "(RUT/RUTW, SPX/SPXW). To make sure you see all expirations, make", "as YYYY-MM-DD, defaults to None :type end: str, optional :return:", "Interval of time per timesale. One of: daily, weekly, monthly,", "end: str :param interval: Interval of time per timesale. One", "\"\"\"Get all options symbols for the given underlying. This will", "False :type greeks: bool, optional :return: quotes for requested symbols", "is also available through this endpoint. This results in a", "(ex. SPXW, RUTW) if applicable. :param underlying: Underlying symbol of", ":return: Get all quotes in an option chain :rtype: dict", "make sure to send the includeAllRoots parameter. This will also", "list of symbols (equity or option) :type symbols: Union[str, list]", "def historic_quotes( self, symbol: str, interval: str = \"daily\", start:", "requested symbols :rtype: dict \"\"\" symbols = self._symbol_prep(symbols) return self._get(", "(AAPL1) are returned. :param symbol: Underlying symbol of the chain", "\"\"\"All Methods currently only support string API calls, no datetime,", "typically used for charting purposes. It captures pricing across a", "SPXW, RUTW) if applicable. :param underlying: Underlying symbol of the", "expiration dates as str %Y-%m-%d :rtype: list \"\"\" response =", "strike prices to each expiration, defaults to '' :type strikes:", "defaults to None :type start: str, optional :param end: End", "symbol for their weekly options (RUT/RUTW, SPX/SPXW). To make sure", "passing the OCC option symbol (ex. AAPL220617C00270000) as the symbol.", "as the symbol. :param symbol: Symbol to query :type symbol:", "self, symbol: str, interval: str = \"daily\", start: str =", "symbol: A single security symbol. :type symbol: str :param start:", "any unique options due to corporate actions (AAPL1) are returned.", "\"false\", ) -> dict: \"\"\"Get all quotes in an option", "API calls, no datetime, bools, etc \"\"\" def quotes(self, symbols:", "underlying: Underlying symbol of the chain :type underlying: str :return:", "symbol. :param symbol: Symbol to query :type symbol: str :param", "dictionaries containing keys of ['time', 'timestamp', 'price', 'open', 'high', 'close',", "list of expiration dates as str %Y-%m-%d :rtype: list \"\"\"", "for requested symbols :rtype: dict \"\"\" symbols = self._symbol_prep(symbols) return", "str :param end: Start date/time for timesales range represented as", "symbol of the chain :type symbol: str :param includeAllRoots: Send", "calls, no datetime, bools, etc \"\"\" def quotes(self, symbols: Union[str,", "options strike prices for a specified expiration date. :param symbol:", "an option chain. Greek and IV data is included courtesy", "greeks and volatility information, defaults to \"false\" :type greeks: Union[str,", "to \"1min\" :type interval: str, optional :return: list of dictionaries", "option chain. Greek and IV data is included courtesy of", "\"\"\" symbols = self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"),", "\"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def option_expirations( self, symbol: str, includeAllRoots: Union[str,", "smaller to keep downloads time reasonable.` :param symbol: A single", "containing keys of ['time', 'timestamp', 'price', 'open', 'high', 'close', low',", "from utils import printer data = MarketData() symbol = \"AAPL\"", "ORATS. Please check out their APIs for more in-depth options", "list], greeks: bool = False) -> dict: \"\"\"Get a list", "15min, defaults to \"1min\" :type interval: str, optional :return: list", "of symbols using a keyword lookup on the symbols description.", "slice at predefined intervals. Tick data is also available through", "be used for simple search functions :param symbols: Comma-delimited list", "dict_args=(\"history\", \"day\"), ) def time_and_sales( self, symbol: str, start: str,", "prices to each expiration, defaults to '' :type strikes: Union[str,", "'volume', 'vwap'] :rtype: list \"\"\" return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\",", "data set for high-volume symbols, so the time slice needs", "the includeAllRoots parameter. This will also ensure any unique options", ":type strikes: Union[str, bool], optional :return: list of expiration dates", "typing import Union from datetime import datetime class MarketData(BasePyTradier): \"\"\"All", "for timesales range represented as YYYY-MM-DD HH:MM :type start: str", "optional :return: list of expiration dates as str %Y-%m-%d :rtype:", "greeks: Add greeks and volatility information (option only), defaults to", "symbol: str, expiration: Union[str, datetime], greeks: Union[str, bool] = \"false\",", "APIs for more in-depth options data. :param symbol: Underlying symbol", ":param expiration: Expiration for the chain :type expiration: Union[str, datetime]", "symbol: Underlying symbol of the chain :type symbol: str :param", "can fetch historical pricing for options by passing the OCC", "None :type end: str, optional :return: [description] :rtype: list \"\"\"", "prices for a specified expiration date. :param symbol: Underlying symbol", "str :param includeAllRoots: Send expirations related to all option roots,", "\"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"), ) if __name__ == \"__main__\": from", "from typing import Union from datetime import datetime class MarketData(BasePyTradier):", "range represented as YYYY-MM-DD HH:MM :type start: str :param end:", "average volume of the security. This can be used for", "to each expiration, defaults to '' :type strikes: Union[str, bool],", "Union[str, bool] = \"false\", ) -> dict: \"\"\"Get all quotes", "None, end: str = None ) -> list: \"\"\"Get historical", ") return response def historic_quotes( self, symbol: str, interval: str", "bool] = \"false\", ) -> dict: \"\"\"Get all quotes in", "= None ) -> list: \"\"\"Get historical pricing for a", "self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), ) def option_chain( self, symbol:", "symbol of the chain :type symbol: str :param expiration: Expiration", ") -> list: \"\"\"Get historical pricing for a security. This", "params=self.create_params(locals()), dict_args=(\"series\", \"data\"), ) if __name__ == \"__main__\": from utils", ":param interval: Interval of time per timesale. One of: tick,", "keep downloads time reasonable.` :param symbol: A single security symbol.", "MarketData(BasePyTradier): \"\"\"All Methods currently only support string API calls, no", "by passing the OCC option symbol (ex. AAPL220617C00270000) as the", "usually cover the entire lifetime of the company if sending", "\"day\"), ) def time_and_sales( self, symbol: str, start: str, end:", ":param symbol: A single security symbol. :type symbol: str :param", "option symbols]} :rtype: dict \"\"\" return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) )", "company if sending reasonable start/end times. You can fetch historical", "bool] = \"\", ) -> list: \"\"\"Get expiration dates for", "the chain :type symbol: str :param includeAllRoots: Send expirations related", ":rtype: list \"\"\" response = self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return", "a very large data set for high-volume symbols, so the", "It captures pricing across a time slice at predefined intervals.", "(ex. AAPL220617C00270000) as the symbol. :param symbol: Symbol to query", "= self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), ) def", "entire lifetime of the company if sending reasonable start/end times.", "str :param expiration: Expiration for the chain :type expiration: Union[str,", "includeAllRoots parameter. This will also ensure any unique options due", "def option_lookup(self, underlying: str) -> dict: \"\"\"Get all options symbols", "return response def historic_quotes( self, symbol: str, interval: str =", "a specified expiration date. :param symbol: Underlying symbol of the", "str, includeAllRoots: Union[str, bool] = \"\", strikes: Union[str, bool] =", "captures pricing across a time slice at predefined intervals. Tick", "all option roots, defaults to '' :type includeAllRoots: Union[str, bool],", "to corporate actions (AAPL1) are returned. :param symbol: Underlying symbol", "start: Start date represented as YYYY-MM-DD, defaults to None :type", "optional :return: quotes for requested symbols :rtype: dict \"\"\" symbols", "Start date/time for timesales range represented as YYYY-MM-DD HH:MM :type", "for more in-depth options data. :param symbol: Underlying symbol of", "str = None, end: str = None ) -> list:", "One of: tick, 1min, 5min, 15min, defaults to \"1min\" :type", ":return: [description] :rtype: list \"\"\" return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) )", "response def historic_quotes( self, symbol: str, interval: str = \"daily\",", ":param start: Start date represented as YYYY-MM-DD, defaults to None", "reasonable.` :param symbol: A single security symbol. :type symbol: str", "False) -> dict: \"\"\"Get a list of symbols using a", "This data will usually cover the entire lifetime of the", "Tick data is also available through this endpoint. This results", "timesales range represented as YYYY-MM-DD HH:MM :type start: str :param", "quotes(self, symbols: Union[str, list], greeks: bool = False) -> dict:", "a particular underlying. Note that some underlying securities use a", "the entire lifetime of the company if sending reasonable start/end", "interval: str, optional :param start: Start date represented as YYYY-MM-DD,", "from PyTradier.base import BasePyTradier from typing import Union from datetime", "str, expiration: Union[str, datetime], greeks: Union[str, bool] = \"false\", )", "str = \"daily\", start: str = None, end: str =", "self, symbol: str, start: str, end: str, interval: str =", ":type symbol: str :param includeAllRoots: Send expirations related to all", ":param greeks: Add greeks and volatility information, defaults to \"false\"", ") def option_lookup(self, underlying: str) -> dict: \"\"\"Get all options", "for options by passing the OCC option symbol (ex. AAPL220617C00270000)", "datetime]) -> list: \"\"\"Get an options strike prices for a", "End date represented as YYYY-MM-DD, defaults to None :type end:", "self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def option_lookup(self, underlying: str) -> dict:", "None ) -> list: \"\"\"Get historical pricing for a security.", "search functions :param symbols: Comma-delimited list of symbols (equity or", "only support string API calls, no datetime, bools, etc \"\"\"", "\"\"\"Get expiration dates for a particular underlying. Note that some", "on the symbols description. Results are in descending order by", "option_expirations( self, symbol: str, includeAllRoots: Union[str, bool] = \"\", strikes:", "'' :type strikes: Union[str, bool], optional :return: list of expiration", "dict_args=(\"quotes\", \"quotes\"), ) def option_chain( self, symbol: str, expiration: Union[str,", "return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"), ) if __name__ ==", "\"daily\", start: str = None, end: str = None )", "== \"__main__\": from utils import printer data = MarketData() symbol", ":type greeks: bool, optional :return: quotes for requested symbols :rtype:", "greeks: Add greeks and volatility information, defaults to \"false\" :type", "dates for a particular underlying. Note that some underlying securities", "To make sure you see all expirations, make sure to", ") def option_strike(self, symbol: str, expiration: Union[str, datetime]) -> list:", "of the chain :type underlying: str :return: dict {\"rootSymbol\": underlying,", "more in-depth options data. :param symbol: Underlying symbol of the", "options due to corporate actions (AAPL1) are returned. :param symbol:", "YYYY-MM-DD, defaults to None :type start: str, optional :param end:", "import printer data = MarketData() symbol = \"AAPL\" response =", "self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"), ) def option_strike(self, symbol: str,", "You can fetch historical pricing for options by passing the", "\"daily\" :type interval: str, optional :param start: Start date represented", "of ['time', 'timestamp', 'price', 'open', 'high', 'close', low', 'volume', 'vwap']", "the chain :type underlying: str :return: dict {\"rootSymbol\": underlying, \"options\":", "will also ensure any unique options due to corporate actions", "a different symbol for their weekly options (RUT/RUTW, SPX/SPXW). To", ") def option_expirations( self, symbol: str, includeAllRoots: Union[str, bool] =", "as YYYY-MM-DD, defaults to None :type start: str, optional :param", "timesales range represented as YYYY-MM-DD HH:MM :type end: str :param", "dict_args=(\"options\", \"option\"), ) def option_strike(self, symbol: str, expiration: Union[str, datetime])", "%Y-%m-%d :rtype: list \"\"\" response = self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) )", "\"AAPL\" response = data.option_lookup(symbol) # response = data.option_strike(symbol, dates[0]) printer(response)", "be much smaller to keep downloads time reasonable.` :param symbol:", "\"__main__\": from utils import printer data = MarketData() symbol =", "option) :type symbols: Union[str, list] :param greeks: Add greeks and", "some underlying securities use a different symbol for their weekly", "each expiration, defaults to '' :type strikes: Union[str, bool], optional", "option_chain( self, symbol: str, expiration: Union[str, datetime], greeks: Union[str, bool]", "-> dict: \"\"\"Get all options symbols for the given underlying.", "dict \"\"\" symbols = self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\",", "as str %Y-%m-%d :rtype: list \"\"\" response = self._get( \"/v1/markets/options/expirations\",", "Union[str, bool], optional :return: list of expiration dates as str", "params=self.create_params(locals()), dict_args=(\"history\", \"day\"), ) def time_and_sales( self, symbol: str, start:", "additional option roots (ex. SPXW, RUTW) if applicable. :param underlying:", "very large data set for high-volume symbols, so the time", "slice needs to be much smaller to keep downloads time", "= MarketData() symbol = \"AAPL\" response = data.option_lookup(symbol) # response", "options data. :param symbol: Underlying symbol of the chain :type", "keyword lookup on the symbols description. Results are in descending", "single security symbol. :type symbol: str :param start: Start date/time", ":param includeAllRoots: Send expirations related to all option roots, defaults", ":type expiration: Union[str, datetime] :param greeks: Add greeks and volatility", "data is included courtesy of ORATS. Please check out their", "option symbol (ex. AAPL220617C00270000) as the symbol. :param symbol: Symbol", "tick, 1min, 5min, 15min, defaults to \"1min\" :type interval: str,", "lifetime of the company if sending reasonable start/end times. You", ") -> list: \"\"\"Time and Sales (timesales) is typically used", "timesale. One of: tick, 1min, 5min, 15min, defaults to \"1min\"", "dict: \"\"\"Get a list of symbols using a keyword lookup", "params=self.create_params(locals()), dict_args=(\"options\", \"option\"), ) def option_strike(self, symbol: str, expiration: Union[str,", "of time per timesale. One of: tick, 1min, 5min, 15min,", ":type interval: str, optional :return: list of dictionaries containing keys", "\"\"\"Get all quotes in an option chain. Greek and IV", "expiration: Union[str, datetime] :return: [description] :rtype: list \"\"\" return self._get(", "in an option chain :rtype: dict \"\"\" return self._get( \"/v1/markets/options/chains\",", "defaults to None :type end: str, optional :return: [description] :rtype:", "list \"\"\" response = self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return response", "YYYY-MM-DD HH:MM :type end: str :param interval: Interval of time", "def option_chain( self, symbol: str, expiration: Union[str, datetime], greeks: Union[str,", "courtesy of ORATS. Please check out their APIs for more", "of time per timesale. One of: daily, weekly, monthly, defaults", "'timestamp', 'price', 'open', 'high', 'close', low', 'volume', 'vwap'] :rtype: list", "IV data is included courtesy of ORATS. Please check out", "unique options due to corporate actions (AAPL1) are returned. :param", "greeks: bool = False) -> dict: \"\"\"Get a list of", "\"options\": [list of option symbols]} :rtype: dict \"\"\" return self._get(", "strikes: Union[str, bool], optional :return: list of expiration dates as", "a time slice at predefined intervals. Tick data is also", "of the chain :type symbol: str :param includeAllRoots: Send expirations", "optional :param strikes: Add strike prices to each expiration, defaults", "across a time slice at predefined intervals. Tick data is", ":rtype: dict \"\"\" return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def option_expirations(", "of ORATS. Please check out their APIs for more in-depth", "Union[str, list] :param greeks: Add greeks and volatility information (option", "HH:MM :type end: str :param interval: Interval of time per", "no datetime, bools, etc \"\"\" def quotes(self, symbols: Union[str, list],", "interval: str, optional :return: list of dictionaries containing keys of", "information (option only), defaults to False :type greeks: bool, optional", "datetime] :return: [description] :rtype: list \"\"\" return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals())", "= \"\", ) -> list: \"\"\"Get expiration dates for a", "Add greeks and volatility information (option only), defaults to False", "(equity or option) :type symbols: Union[str, list] :param greeks: Add", "includeAllRoots: Union[str, bool] = \"\", strikes: Union[str, bool] = \"\",", "for the chain :type expiration: Union[str, datetime] :return: [description] :rtype:", "-> list: \"\"\"Time and Sales (timesales) is typically used for", "import BasePyTradier from typing import Union from datetime import datetime", "symbols: Union[str, list] :param greeks: Add greeks and volatility information", "also ensure any unique options due to corporate actions (AAPL1)", "YYYY-MM-DD HH:MM :type start: str :param end: Start date/time for", "of the chain :type symbol: str :param expiration: Expiration for", "Underlying symbol of the chain :type underlying: str :return: dict", "self, symbol: str, includeAllRoots: Union[str, bool] = \"\", strikes: Union[str,", "interval: str = \"1min\" ) -> list: \"\"\"Time and Sales", "import Union from datetime import datetime class MarketData(BasePyTradier): \"\"\"All Methods", "corporate actions (AAPL1) are returned. :param symbol: Underlying symbol of", "\"false\" :type greeks: Union[str, bool], optional :return: Get all quotes", "symbol: Symbol to query :type symbol: str :param interval: Interval", "greeks: Union[str, bool], optional :return: Get all quotes in an", "through this endpoint. This results in a very large data", "MarketData() symbol = \"AAPL\" response = data.option_lookup(symbol) # response =", "used for simple search functions :param symbols: Comma-delimited list of", "dates as str %Y-%m-%d :rtype: list \"\"\" response = self._get(", "options (RUT/RUTW, SPX/SPXW). To make sure you see all expirations,", "lookup on the symbols description. Results are in descending order", "strikes: Union[str, bool] = \"\", ) -> list: \"\"\"Get expiration", "list \"\"\" return self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"), ) def", "dict \"\"\" return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"), ) def", "self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"), ) if __name__ == \"__main__\":", "datetime] :param greeks: Add greeks and volatility information, defaults to", "weekly options (RUT/RUTW, SPX/SPXW). To make sure you see all", "range represented as YYYY-MM-DD HH:MM :type end: str :param interval:", "weekly, monthly, defaults to \"daily\" :type interval: str, optional :param", ":rtype: list \"\"\" return self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"), )", "str = None ) -> list: \"\"\"Get historical pricing for", "symbol: str :param includeAllRoots: Send expirations related to all option", "quotes in an option chain :rtype: dict \"\"\" return self._get(", "the chain :type expiration: Union[str, datetime] :param greeks: Add greeks", "at predefined intervals. Tick data is also available through this", ":rtype: dict \"\"\" symbols = self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()),", "def time_and_sales( self, symbol: str, start: str, end: str, interval:", "= \"\", strikes: Union[str, bool] = \"\", ) -> list:", ":param symbol: Symbol to query :type symbol: str :param interval:", "descending order by average volume of the security. This can", "this endpoint. This results in a very large data set", "-> list: \"\"\"Get an options strike prices for a specified", "= self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return response def historic_quotes( self,", ":type symbols: Union[str, list] :param greeks: Add greeks and volatility", "their weekly options (RUT/RUTW, SPX/SPXW). To make sure you see", "str, expiration: Union[str, datetime]) -> list: \"\"\"Get an options strike", "optional :return: list of dictionaries containing keys of ['time', 'timestamp',", "the company if sending reasonable start/end times. You can fetch", "quotes for requested symbols :rtype: dict \"\"\" symbols = self._symbol_prep(symbols)", "chain :type underlying: str :return: dict {\"rootSymbol\": underlying, \"options\": [list", "intervals. Tick data is also available through this endpoint. This", "datetime class MarketData(BasePyTradier): \"\"\"All Methods currently only support string API", "historical pricing for a security. This data will usually cover", "\"\"\" return self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"), ) def time_and_sales(", "represented as YYYY-MM-DD HH:MM :type start: str :param end: Start", "= \"AAPL\" response = data.option_lookup(symbol) # response = data.option_strike(symbol, dates[0])", "\"\"\" response = self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return response def", "list: \"\"\"Get an options strike prices for a specified expiration", ":return: dict {\"rootSymbol\": underlying, \"options\": [list of option symbols]} :rtype:", "This results in a very large data set for high-volume", ":rtype: list \"\"\" return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def option_lookup(self,", "related to all option roots, defaults to '' :type includeAllRoots:", "charting purposes. It captures pricing across a time slice at", "defaults to \"1min\" :type interval: str, optional :return: list of", "use a different symbol for their weekly options (RUT/RUTW, SPX/SPXW).", ":return: list of dictionaries containing keys of ['time', 'timestamp', 'price',", "\"\"\" return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"), ) def option_strike(self,", "etc \"\"\" def quotes(self, symbols: Union[str, list], greeks: bool =", "YYYY-MM-DD, defaults to None :type end: str, optional :return: [description]", "'close', low', 'volume', 'vwap'] :rtype: list \"\"\" return self._get( \"/v1/markets/timesales\",", "date represented as YYYY-MM-DD, defaults to None :type end: str,", "return self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"), ) def time_and_sales( self,", "\"\"\" return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def option_expirations( self, symbol:", "Expiration for the chain :type expiration: Union[str, datetime] :param greeks:", "time per timesale. One of: daily, weekly, monthly, defaults to", "optional :param end: End date represented as YYYY-MM-DD, defaults to", "str, end: str, interval: str = \"1min\" ) -> list:", "in a very large data set for high-volume symbols, so", "currently only support string API calls, no datetime, bools, etc", "option_lookup(self, underlying: str) -> dict: \"\"\"Get all options symbols for", "= \"false\", ) -> dict: \"\"\"Get all quotes in an", ") def time_and_sales( self, symbol: str, start: str, end: str,", "params=self.create_params(locals()) ) def option_expirations( self, symbol: str, includeAllRoots: Union[str, bool]", "chain :type expiration: Union[str, datetime] :return: [description] :rtype: list \"\"\"", "bool] = \"\", strikes: Union[str, bool] = \"\", ) ->", "of: daily, weekly, monthly, defaults to \"daily\" :type interval: str,", ":type greeks: Union[str, bool], optional :return: Get all quotes in", "Underlying symbol of the chain :type symbol: str :param includeAllRoots:", "str, interval: str = \"daily\", start: str = None, end:", "if __name__ == \"__main__\": from utils import printer data =", "large data set for high-volume symbols, so the time slice", "printer data = MarketData() symbol = \"AAPL\" response = data.option_lookup(symbol)", "symbols = self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), )", "\"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"), ) def time_and_sales( self, symbol: str,", ":type end: str :param interval: Interval of time per timesale.", "and IV data is included courtesy of ORATS. Please check", "make sure you see all expirations, make sure to send", ":type expiration: Union[str, datetime] :return: [description] :rtype: list \"\"\" return", "for timesales range represented as YYYY-MM-DD HH:MM :type end: str", "Union[str, bool] = \"\", strikes: Union[str, bool] = \"\", )", "Union[str, datetime] :param greeks: Add greeks and volatility information, defaults", "all options symbols for the given underlying. This will include", "for high-volume symbols, so the time slice needs to be", "[description] :rtype: list \"\"\" return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def", "list \"\"\" return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def option_lookup(self, underlying:", "symbols (equity or option) :type symbols: Union[str, list] :param greeks:", "for simple search functions :param symbols: Comma-delimited list of symbols", "for a specified expiration date. :param symbol: Underlying symbol of", "for the chain :type expiration: Union[str, datetime] :param greeks: Add", "5min, 15min, defaults to \"1min\" :type interval: str, optional :return:", "of: tick, 1min, 5min, 15min, defaults to \"1min\" :type interval:", ":type symbol: str :param start: Start date/time for timesales range", ") def option_chain( self, symbol: str, expiration: Union[str, datetime], greeks:", "\"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"), ) def option_strike(self, symbol: str, expiration:", "\"\", strikes: Union[str, bool] = \"\", ) -> list: \"\"\"Get", "str = \"1min\" ) -> list: \"\"\"Time and Sales (timesales)", "This will also ensure any unique options due to corporate", "symbol: str :param interval: Interval of time per timesale. One", "bool], optional :param strikes: Add strike prices to each expiration,", "end: str, optional :return: [description] :rtype: list \"\"\" return self._get(", "for a particular underlying. Note that some underlying securities use", "\"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), ) def option_chain( self, symbol: str,", "sure you see all expirations, make sure to send the", "self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), ) def option_chain(", "in an option chain. Greek and IV data is included", "an option chain :rtype: dict \"\"\" return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()),", "date. :param symbol: Underlying symbol of the chain :type symbol:", "date/time for timesales range represented as YYYY-MM-DD HH:MM :type end:", "as YYYY-MM-DD HH:MM :type start: str :param end: Start date/time", "to query :type symbol: str :param interval: Interval of time", "interval: Interval of time per timesale. One of: daily, weekly,", "Union[str, list], greeks: bool = False) -> dict: \"\"\"Get a", "pricing for options by passing the OCC option symbol (ex.", "roots, defaults to '' :type includeAllRoots: Union[str, bool], optional :param", ":rtype: dict \"\"\" return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"), )", "Add strike prices to each expiration, defaults to '' :type", "of dictionaries containing keys of ['time', 'timestamp', 'price', 'open', 'high',", "self, symbol: str, expiration: Union[str, datetime], greeks: Union[str, bool] =", "\"\"\"Get a list of symbols using a keyword lookup on", "time reasonable.` :param symbol: A single security symbol. :type symbol:", "list] :param greeks: Add greeks and volatility information (option only),", "will usually cover the entire lifetime of the company if", "data = MarketData() symbol = \"AAPL\" response = data.option_lookup(symbol) #", "time_and_sales( self, symbol: str, start: str, end: str, interval: str", "Symbol to query :type symbol: str :param interval: Interval of", "or option) :type symbols: Union[str, list] :param greeks: Add greeks", "bools, etc \"\"\" def quotes(self, symbols: Union[str, list], greeks: bool", "import datetime class MarketData(BasePyTradier): \"\"\"All Methods currently only support string", "Send expirations related to all option roots, defaults to ''", "to keep downloads time reasonable.` :param symbol: A single security", "\"\"\" return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def option_lookup(self, underlying: str)", "dict_args=(\"series\", \"data\"), ) if __name__ == \"__main__\": from utils import", "set for high-volume symbols, so the time slice needs to", "fetch historical pricing for options by passing the OCC option", "only), defaults to False :type greeks: bool, optional :return: quotes", "and Sales (timesales) is typically used for charting purposes. It", ":param greeks: Add greeks and volatility information (option only), defaults", ":return: [description] :rtype: list \"\"\" return self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\",", "underlying. This will include additional option roots (ex. SPXW, RUTW)", "return self._get( \"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def option_lookup(self, underlying: str) ->", "information, defaults to \"false\" :type greeks: Union[str, bool], optional :return:", "optional :return: [description] :rtype: list \"\"\" return self._get( \"/v1/markets/history\", params=self.create_params(locals()),", "timesale. One of: daily, weekly, monthly, defaults to \"daily\" :type", "list: \"\"\"Get expiration dates for a particular underlying. Note that", "roots (ex. SPXW, RUTW) if applicable. :param underlying: Underlying symbol", "order by average volume of the security. This can be", "of symbols (equity or option) :type symbols: Union[str, list] :param", "defaults to \"false\" :type greeks: Union[str, bool], optional :return: Get", "\"\"\"Get historical pricing for a security. This data will usually", "is included courtesy of ORATS. Please check out their APIs", "interval: Interval of time per timesale. One of: tick, 1min,", "optional :param start: Start date represented as YYYY-MM-DD, defaults to", "str, start: str, end: str, interval: str = \"1min\" )", "used for charting purposes. It captures pricing across a time", "bool], optional :return: list of expiration dates as str %Y-%m-%d", "HH:MM :type start: str :param end: Start date/time for timesales", "quotes in an option chain. Greek and IV data is", "their APIs for more in-depth options data. :param symbol: Underlying", "given underlying. This will include additional option roots (ex. SPXW,", "str :param start: Start date/time for timesales range represented as", "utils import printer data = MarketData() symbol = \"AAPL\" response", "end: Start date/time for timesales range represented as YYYY-MM-DD HH:MM", ":param symbols: Comma-delimited list of symbols (equity or option) :type", "different symbol for their weekly options (RUT/RUTW, SPX/SPXW). To make", "all expirations, make sure to send the includeAllRoots parameter. This", "self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"), ) def time_and_sales( self, symbol:", "Union[str, datetime] :return: [description] :rtype: list \"\"\" return self._get( \"/v1/markets/options/strikes\",", "time slice at predefined intervals. Tick data is also available", "available through this endpoint. This results in a very large", "you see all expirations, make sure to send the includeAllRoots", "defaults to '' :type strikes: Union[str, bool], optional :return: list", "expiration: Union[str, datetime]) -> list: \"\"\"Get an options strike prices", ":type interval: str, optional :param start: Start date represented as", "the time slice needs to be much smaller to keep", "a security. This data will usually cover the entire lifetime", "str) -> dict: \"\"\"Get all options symbols for the given", "start: Start date/time for timesales range represented as YYYY-MM-DD HH:MM", "bool, optional :return: quotes for requested symbols :rtype: dict \"\"\"", "ensure any unique options due to corporate actions (AAPL1) are", "high-volume symbols, so the time slice needs to be much", "'vwap'] :rtype: list \"\"\" return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"),", "response = self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return response def historic_quotes(", ":type underlying: str :return: dict {\"rootSymbol\": underlying, \"options\": [list of", "that some underlying securities use a different symbol for their", "using a keyword lookup on the symbols description. Results are", "datetime, bools, etc \"\"\" def quotes(self, symbols: Union[str, list], greeks:", "Union[str, bool], optional :param strikes: Add strike prices to each", "volatility information (option only), defaults to False :type greeks: bool,", "keys of ['time', 'timestamp', 'price', 'open', 'high', 'close', low', 'volume',", "to all option roots, defaults to '' :type includeAllRoots: Union[str,", "to '' :type includeAllRoots: Union[str, bool], optional :param strikes: Add", "by average volume of the security. This can be used", "also available through this endpoint. This results in a very", "underlying. Note that some underlying securities use a different symbol", "str, optional :param end: End date represented as YYYY-MM-DD, defaults", "defaults to False :type greeks: bool, optional :return: quotes for", "options by passing the OCC option symbol (ex. AAPL220617C00270000) as", "1min, 5min, 15min, defaults to \"1min\" :type interval: str, optional", "OCC option symbol (ex. AAPL220617C00270000) as the symbol. :param symbol:", "Add greeks and volatility information, defaults to \"false\" :type greeks:", "This will include additional option roots (ex. SPXW, RUTW) if", "the security. This can be used for simple search functions", "Union[str, datetime]) -> list: \"\"\"Get an options strike prices for", "= \"daily\", start: str = None, end: str = None", "times. You can fetch historical pricing for options by passing", "for their weekly options (RUT/RUTW, SPX/SPXW). To make sure you", ":param underlying: Underlying symbol of the chain :type underlying: str", "self._get( \"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return response def historic_quotes( self, symbol:", "return self._get( \"/v1/markets/options/chains\", params=self.create_params(locals()), dict_args=(\"options\", \"option\"), ) def option_strike(self, symbol:", "options symbols for the given underlying. This will include additional", "chain :type symbol: str :param includeAllRoots: Send expirations related to", "daily, weekly, monthly, defaults to \"daily\" :type interval: str, optional", "to send the includeAllRoots parameter. This will also ensure any", "all quotes in an option chain :rtype: dict \"\"\" return", "str :return: dict {\"rootSymbol\": underlying, \"options\": [list of option symbols]}", "applicable. :param underlying: Underlying symbol of the chain :type underlying:", "expiration: Expiration for the chain :type expiration: Union[str, datetime] :param", ":type start: str :param end: Start date/time for timesales range", "option roots, defaults to '' :type includeAllRoots: Union[str, bool], optional", "pricing across a time slice at predefined intervals. Tick data", "included courtesy of ORATS. Please check out their APIs for", "'' :type includeAllRoots: Union[str, bool], optional :param strikes: Add strike", "symbol: str, start: str, end: str, interval: str = \"1min\"", "\"\"\"Get an options strike prices for a specified expiration date.", "to None :type start: str, optional :param end: End date", "datetime], greeks: Union[str, bool] = \"false\", ) -> dict: \"\"\"Get", "bool], optional :return: Get all quotes in an option chain", "underlying: str :return: dict {\"rootSymbol\": underlying, \"options\": [list of option", "much smaller to keep downloads time reasonable.` :param symbol: A", "symbol: str, expiration: Union[str, datetime]) -> list: \"\"\"Get an options", "represented as YYYY-MM-DD, defaults to None :type end: str, optional", ":return: list of expiration dates as str %Y-%m-%d :rtype: list", "chain :type symbol: str :param expiration: Expiration for the chain", "PyTradier.base import BasePyTradier from typing import Union from datetime import", "securities use a different symbol for their weekly options (RUT/RUTW,", "and volatility information, defaults to \"false\" :type greeks: Union[str, bool],", "option_strike(self, symbol: str, expiration: Union[str, datetime]) -> list: \"\"\"Get an", "see all expirations, make sure to send the includeAllRoots parameter.", "\"\"\"Time and Sales (timesales) is typically used for charting purposes.", "dict: \"\"\"Get all options symbols for the given underlying. This", "return self._get( \"/v1/markets/quotes\", params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), ) def option_chain( self,", "symbol: str, interval: str = \"daily\", start: str = None,", "RUTW) if applicable. :param underlying: Underlying symbol of the chain", "optional :return: Get all quotes in an option chain :rtype:", "\"1min\" ) -> list: \"\"\"Time and Sales (timesales) is typically", "Underlying symbol of the chain :type symbol: str :param expiration:", "represented as YYYY-MM-DD, defaults to None :type start: str, optional", "Union[str, bool] = \"\", ) -> list: \"\"\"Get expiration dates", "string API calls, no datetime, bools, etc \"\"\" def quotes(self,", "of option symbols]} :rtype: dict \"\"\" return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals())", "Start date represented as YYYY-MM-DD, defaults to None :type start:", "bool = False) -> dict: \"\"\"Get a list of symbols", "greeks: bool, optional :return: quotes for requested symbols :rtype: dict", "predefined intervals. Tick data is also available through this endpoint.", "= \"1min\" ) -> list: \"\"\"Time and Sales (timesales) is", "str :param interval: Interval of time per timesale. One of:", "symbols description. Results are in descending order by average volume", "to \"false\" :type greeks: Union[str, bool], optional :return: Get all", "expiration date. :param symbol: Underlying symbol of the chain :type", "underlying, \"options\": [list of option symbols]} :rtype: dict \"\"\" return", "expiration: Expiration for the chain :type expiration: Union[str, datetime] :return:", "symbol. :type symbol: str :param start: Start date/time for timesales", "This can be used for simple search functions :param symbols:", "of expiration dates as str %Y-%m-%d :rtype: list \"\"\" response", "so the time slice needs to be much smaller to", "__name__ == \"__main__\": from utils import printer data = MarketData()", "to False :type greeks: bool, optional :return: quotes for requested", "support string API calls, no datetime, bools, etc \"\"\" def", "-> dict: \"\"\"Get a list of symbols using a keyword", "list of symbols using a keyword lookup on the symbols", "a keyword lookup on the symbols description. Results are in", "params=self.create_params(locals()), dict_args=(\"quotes\", \"quotes\"), ) def option_chain( self, symbol: str, expiration:", "symbols :rtype: dict \"\"\" symbols = self._symbol_prep(symbols) return self._get( \"/v1/markets/quotes\",", "returned. :param symbol: Underlying symbol of the chain :type symbol:", "str, interval: str = \"1min\" ) -> list: \"\"\"Time and", "symbol: str, includeAllRoots: Union[str, bool] = \"\", strikes: Union[str, bool]", ":param interval: Interval of time per timesale. One of: daily,", "results in a very large data set for high-volume symbols,", "defaults to \"daily\" :type interval: str, optional :param start: Start", "\"data\"), ) if __name__ == \"__main__\": from utils import printer", "data will usually cover the entire lifetime of the company", "defaults to '' :type includeAllRoots: Union[str, bool], optional :param strikes:", "dict \"\"\" return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def option_expirations( self,", "greeks: Union[str, bool] = \"false\", ) -> dict: \"\"\"Get all", "end: str, interval: str = \"1min\" ) -> list: \"\"\"Time", "return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def option_expirations( self, symbol: str,", "represented as YYYY-MM-DD HH:MM :type end: str :param interval: Interval", "end: End date represented as YYYY-MM-DD, defaults to None :type", "volume of the security. This can be used for simple", "include additional option roots (ex. SPXW, RUTW) if applicable. :param", "params=self.create_params(locals()) ) return response def historic_quotes( self, symbol: str, interval:", "Comma-delimited list of symbols (equity or option) :type symbols: Union[str,", "list: \"\"\"Get historical pricing for a security. This data will", "One of: daily, weekly, monthly, defaults to \"daily\" :type interval:", "SPX/SPXW). To make sure you see all expirations, make sure", "Get all quotes in an option chain :rtype: dict \"\"\"", "['time', 'timestamp', 'price', 'open', 'high', 'close', low', 'volume', 'vwap'] :rtype:", "\"/v1/markets/options/strikes\", params=self.create_params(locals()) ) def option_lookup(self, underlying: str) -> dict: \"\"\"Get", "\"/v1/markets/options/expirations\", params=self.create_params(locals()) ) return response def historic_quotes( self, symbol: str,", "low', 'volume', 'vwap'] :rtype: list \"\"\" return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()),", ":param end: End date represented as YYYY-MM-DD, defaults to None", "sending reasonable start/end times. You can fetch historical pricing for", "start: str, end: str, interval: str = \"1min\" ) ->", "[description] :rtype: list \"\"\" return self._get( \"/v1/markets/history\", params=self.create_params(locals()), dict_args=(\"history\", \"day\"),", "\"\"\" return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"), ) if __name__", "expiration dates for a particular underlying. Note that some underlying", "str, optional :return: [description] :rtype: list \"\"\" return self._get( \"/v1/markets/history\",", "Union from datetime import datetime class MarketData(BasePyTradier): \"\"\"All Methods currently", "symbol of the chain :type underlying: str :return: dict {\"rootSymbol\":", "are returned. :param symbol: Underlying symbol of the chain :type", ":param end: Start date/time for timesales range represented as YYYY-MM-DD", ") if __name__ == \"__main__\": from utils import printer data", "are in descending order by average volume of the security.", "underlying securities use a different symbol for their weekly options", "list: \"\"\"Time and Sales (timesales) is typically used for charting", "expiration, defaults to '' :type strikes: Union[str, bool], optional :return:", "expiration: Union[str, datetime], greeks: Union[str, bool] = \"false\", ) ->", "volatility information, defaults to \"false\" :type greeks: Union[str, bool], optional", "class MarketData(BasePyTradier): \"\"\"All Methods currently only support string API calls,", "symbols: Union[str, list], greeks: bool = False) -> dict: \"\"\"Get", "-> list: \"\"\"Get historical pricing for a security. This data", "strike prices for a specified expiration date. :param symbol: Underlying", "start: str = None, end: str = None ) ->", "dict: \"\"\"Get all quotes in an option chain. Greek and", "symbols, so the time slice needs to be much smaller", "specified expiration date. :param symbol: Underlying symbol of the chain", "time per timesale. One of: tick, 1min, 5min, 15min, defaults", "can be used for simple search functions :param symbols: Comma-delimited", "Methods currently only support string API calls, no datetime, bools,", "end: str = None ) -> list: \"\"\"Get historical pricing", "[list of option symbols]} :rtype: dict \"\"\" return self._get( \"/v1/markets/options/lookup\",", "-> list: \"\"\"Get expiration dates for a particular underlying. Note", "underlying: str) -> dict: \"\"\"Get all options symbols for the", "to None :type end: str, optional :return: [description] :rtype: list", "dict {\"rootSymbol\": underlying, \"options\": [list of option symbols]} :rtype: dict", "str, optional :return: list of dictionaries containing keys of ['time',", "AAPL220617C00270000) as the symbol. :param symbol: Symbol to query :type", "particular underlying. Note that some underlying securities use a different", ":param start: Start date/time for timesales range represented as YYYY-MM-DD", "is typically used for charting purposes. It captures pricing across", ":type includeAllRoots: Union[str, bool], optional :param strikes: Add strike prices", "str, optional :param start: Start date represented as YYYY-MM-DD, defaults", "symbols: Comma-delimited list of symbols (equity or option) :type symbols:", "Union[str, datetime], greeks: Union[str, bool] = \"false\", ) -> dict:", "self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def option_expirations( self, symbol: str, includeAllRoots:", "symbol = \"AAPL\" response = data.option_lookup(symbol) # response = data.option_strike(symbol,", "Please check out their APIs for more in-depth options data.", "for charting purposes. It captures pricing across a time slice", "security symbol. :type symbol: str :param start: Start date/time for", "actions (AAPL1) are returned. :param symbol: Underlying symbol of the", "of the security. This can be used for simple search", "due to corporate actions (AAPL1) are returned. :param symbol: Underlying", "purposes. It captures pricing across a time slice at predefined", "(timesales) is typically used for charting purposes. It captures pricing", "if applicable. :param underlying: Underlying symbol of the chain :type", "parameter. This will also ensure any unique options due to", "cover the entire lifetime of the company if sending reasonable", "the chain :type symbol: str :param expiration: Expiration for the", "expirations related to all option roots, defaults to '' :type", "start: str, optional :param end: End date represented as YYYY-MM-DD,", "simple search functions :param symbols: Comma-delimited list of symbols (equity", "description. Results are in descending order by average volume of", "symbols for the given underlying. This will include additional option", "date represented as YYYY-MM-DD, defaults to None :type start: str,", "if sending reasonable start/end times. You can fetch historical pricing", "interval: str = \"daily\", start: str = None, end: str", "reasonable start/end times. You can fetch historical pricing for options", "the chain :type expiration: Union[str, datetime] :return: [description] :rtype: list", "Note that some underlying securities use a different symbol for", "time slice needs to be much smaller to keep downloads", ":param symbol: Underlying symbol of the chain :type symbol: str", "date/time for timesales range represented as YYYY-MM-DD HH:MM :type start:", "all quotes in an option chain. Greek and IV data", "send the includeAllRoots parameter. This will also ensure any unique", "option roots (ex. SPXW, RUTW) if applicable. :param underlying: Underlying", "symbols]} :rtype: dict \"\"\" return self._get( \"/v1/markets/options/lookup\", params=self.create_params(locals()) ) def", "sure to send the includeAllRoots parameter. This will also ensure", "list \"\"\" return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"), ) if", "historical pricing for options by passing the OCC option symbol", "strikes: Add strike prices to each expiration, defaults to ''", "for a security. This data will usually cover the entire", "endpoint. This results in a very large data set for", "\"option\"), ) def option_strike(self, symbol: str, expiration: Union[str, datetime]) ->", "'high', 'close', low', 'volume', 'vwap'] :rtype: list \"\"\" return self._get(", ") -> list: \"\"\"Get expiration dates for a particular underlying.", "BasePyTradier from typing import Union from datetime import datetime class", "the symbols description. Results are in descending order by average", "security. This data will usually cover the entire lifetime of", ":return: quotes for requested symbols :rtype: dict \"\"\" symbols =", "the symbol. :param symbol: Symbol to query :type symbol: str", "(option only), defaults to False :type greeks: bool, optional :return:", "security. This can be used for simple search functions :param", ":type start: str, optional :param end: End date represented as", "Greek and IV data is included courtesy of ORATS. Please", "data is also available through this endpoint. This results in", "in descending order by average volume of the security. This", "chain. Greek and IV data is included courtesy of ORATS.", "Union[str, bool], optional :return: Get all quotes in an option", "Expiration for the chain :type expiration: Union[str, datetime] :return: [description]", "includeAllRoots: Send expirations related to all option roots, defaults to", "per timesale. One of: daily, weekly, monthly, defaults to \"daily\"", ":rtype: list \"\"\" return self._get( \"/v1/markets/timesales\", params=self.create_params(locals()), dict_args=(\"series\", \"data\"), )", "pricing for a security. This data will usually cover the", "\"1min\" :type interval: str, optional :return: list of dictionaries containing", "def quotes(self, symbols: Union[str, list], greeks: bool = False) ->", "symbol: str :param start: Start date/time for timesales range represented", "expirations, make sure to send the includeAllRoots parameter. This will", "to be much smaller to keep downloads time reasonable.` :param", "params=self.create_params(locals()) ) def option_lookup(self, underlying: str) -> dict: \"\"\"Get all", "will include additional option roots (ex. SPXW, RUTW) if applicable.", "Interval of time per timesale. One of: tick, 1min, 5min,", "per timesale. One of: tick, 1min, 5min, 15min, defaults to", ":type symbol: str :param expiration: Expiration for the chain :type" ]
[ "w.configure(name.capitalize(), units_short, units_long) self.values[name] = w w.setContentsMargins(0, 0, 0, 0)", "__init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\")", "LLC # # Licensed under the Apache License, Version 2.0", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "'W', 'Watts'), ('energy', 'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget): def __init__(self,", "MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color : black; color : green; }\")", "= QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {} for", "{ background-color : black; color : green; }\") w.configure(name.capitalize(), units_short,", "w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "display :param statistics: The statistics data structure \"\"\" for name,", "= [ ('current', 'A', 'Amps'), ('voltage', 'V', 'Volts'), ('power', 'W',", "'Joules'), ] class MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args,", "statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self): _translate = QtCore.QCoreApplication.translate self.accumulateButton.setText(_translate(\"meter_widget\", \"Accumulate\"))", "distributed under the License is distributed on an \"AS IS\"", "0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy)", "the multimeter display :param statistics: The statistics data structure \"\"\"", "= QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled)", "= {} for name, units_short, units_long in FIELDS: w =", "black; color : green; }\") w.configure(name.capitalize(), units_short, units_long) self.values[name] =", "d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value']", "= statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self): _translate = QtCore.QCoreApplication.translate self.accumulateButton.setText(_translate(\"meter_widget\",", "the specific language governing permissions and # limitations under the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "[ ('current', 'A', 'Amps'), ('voltage', 'V', 'Volts'), ('power', 'W', 'Watts'),", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "color : green; }\") w.configure(name.capitalize(), units_short, units_long) self.values[name] = w", "self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values", "self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "multimeter display :param statistics: The statistics data structure \"\"\" for", "'Amps'), ('voltage', 'V', 'Volts'), ('power', 'W', 'Watts'), ('energy', 'J', 'Joules'),", "not use this file except in compliance with the License.", "'V', 'Volts'), ('power', 'W', 'Watts'), ('energy', 'J', 'Joules'), ] class", "statistics data structure \"\"\" for name, field in statistics['signals'].items(): d", ": green; }\") w.configure(name.capitalize(), units_short, units_long) self.values[name] = w w.setContentsMargins(0,", "self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {}", "units_short, units_long) self.values[name] = w w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w)", "writing, software # distributed under the License is distributed on", "update(self, statistics): \"\"\"Update the multimeter display :param statistics: The statistics", "in writing, software # distributed under the License is distributed", "QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {} for name,", "('power', 'W', 'Watts'), ('energy', 'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget): def", "\"\"\" for name, field in statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'],", "you may not use this file except in compliance with", "*args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0)", "QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding,", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "logging.getLogger(__name__) FIELDS = [ ('current', 'A', 'Amps'), ('voltage', 'V', 'Volts'),", "language governing permissions and # limitations under the License. from", "self.values[name] = w w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy", "def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self)", "from PySide2 import QtCore, QtWidgets from . import joulescope_rc from", "in FIELDS: w = MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color : black;", "self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool)", "] class MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs)", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "('current', 'A', 'Amps'), ('voltage', 'V', 'Volts'), ('power', 'W', 'Watts'), ('energy',", "import joulescope_rc from .meter_value_widget import MeterValueWidget import logging log =", "data structure \"\"\" for name, field in statistics['signals'].items(): d =", "= checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable = checked def update(self,", "QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable", "= checked self.values['power'].accumulate_enable = checked def update(self, statistics): \"\"\"Update the", "CONDITIONS OF ANY KIND, either express or implied. # See", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable = checked def", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "QtWidgets from . import joulescope_rc from .meter_value_widget import MeterValueWidget import", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "'Watts'), ('energy', 'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget): def __init__(self, *args,", "**kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout", "QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget)", "checked self.values['power'].accumulate_enable = checked def update(self, statistics): \"\"\"Update the multimeter", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "'A', 'Amps'), ('voltage', 'V', 'Volts'), ('power', 'W', 'Watts'), ('energy', 'J',", "self.controlWidget = QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget)", "green; }\") w.configure(name.capitalize(), units_short, units_long) self.values[name] = w w.setContentsMargins(0, 0,", "QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {} for name, units_short, units_long", "= QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20,", "<filename>joulescope_ui/meter_widget.py # Copyright 2018 Jetperch LLC # # Licensed under", "= MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color : black; color : green;", "self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values =", "under the License is distributed on an \"AS IS\" BASIS,", "# Copyright 2018 Jetperch LLC # # Licensed under the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "'Volts'), ('power', 'W', 'Watts'), ('energy', 'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget):", "statistics): \"\"\"Update the multimeter display :param statistics: The statistics data", "License for the specific language governing permissions and # limitations", "limitations under the License. from PySide2 import QtCore, QtWidgets from", "for name, units_short, units_long in FIELDS: w = MeterValueWidget(self) w.setStyleSheet(\"QWidget", "structure \"\"\" for name, field in statistics['signals'].items(): d = field['statistics']", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget)", "}\") w.configure(name.capitalize(), units_short, units_long) self.values[name] = w w.setContentsMargins(0, 0, 0,", "field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge =", ": black; color : green; }\") w.configure(name.capitalize(), units_short, units_long) self.values[name]", "self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def", "import MeterValueWidget import logging log = logging.getLogger(__name__) FIELDS = [", "self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi()", "Jetperch LLC # # Licensed under the Apache License, Version", "*args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self)", "w = MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color : black; color :", "the License for the specific language governing permissions and #", "self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton)", "charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self): _translate = QtCore.QCoreApplication.translate", "\"\"\"Update the multimeter display :param statistics: The statistics data structure", "(the \"License\"); # you may not use this file except", "**kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget", "self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40,", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "MeterValueWidget import logging log = logging.getLogger(__name__) FIELDS = [ ('current',", "name, field in statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'],", "either express or implied. # See the License for the", "= checked def update(self, statistics): \"\"\"Update the multimeter display :param", "= logging.getLogger(__name__) FIELDS = [ ('current', 'A', 'Amps'), ('voltage', 'V',", "= statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self): _translate", "joulescope_rc from .meter_value_widget import MeterValueWidget import logging log = logging.getLogger(__name__)", "OR CONDITIONS OF ANY KIND, either express or implied. #", "def update(self, statistics): \"\"\"Update the multimeter display :param statistics: The", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "name, units_short, units_long in FIELDS: w = MeterValueWidget(self) w.setStyleSheet(\"QWidget {", "units_short, units_long in FIELDS: w = MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color", "the License is distributed on an \"AS IS\" BASIS, #", "self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable =", "self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout =", "and # limitations under the License. from PySide2 import QtCore,", "MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout =", "in compliance with the License. # You may obtain a", "QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\")", "def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable", "statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy =", "Copyright 2018 Jetperch LLC # # Licensed under the Apache", "software # distributed under the License is distributed on an", "checked def update(self, statistics): \"\"\"Update the multimeter display :param statistics:", "statistics: The statistics data structure \"\"\" for name, field in", "self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable =", "for name, field in statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'],", "checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable = checked def update(self, statistics):", "self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer)", "# # Unless required by applicable law or agreed to", "self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value']", "logging log = logging.getLogger(__name__) FIELDS = [ ('current', 'A', 'Amps'),", "energy = statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self):", "v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def", "# limitations under the License. from PySide2 import QtCore, QtWidgets", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge)", "on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable =", "from .meter_value_widget import MeterValueWidget import logging log = logging.getLogger(__name__) FIELDS", "FIELDS = [ ('current', 'A', 'Amps'), ('voltage', 'V', 'Volts'), ('power',", "= QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True)", "checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable = checked", "in statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy", "Version 2.0 (the \"License\"); # you may not use this", "PySide2 import QtCore, QtWidgets from . import joulescope_rc from .meter_value_widget", "FIELDS: w = MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color : black; color", "License. from PySide2 import QtCore, QtWidgets from . import joulescope_rc", "law or agreed to in writing, software # distributed under", ". import joulescope_rc from .meter_value_widget import MeterValueWidget import logging log", "self.values = {} for name, units_short, units_long in FIELDS: w", "= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self,", "permissions and # limitations under the License. from PySide2 import", "background-color : black; color : green; }\") w.configure(name.capitalize(), units_short, units_long)", "w.setStyleSheet(\"QWidget { background-color : black; color : green; }\") w.configure(name.capitalize(),", "field in statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max'])", "= w w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy =", "QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer", "= field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge", "import QtCore, QtWidgets from . import joulescope_rc from .meter_value_widget import", "QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget =", "implied. # See the License for the specific language governing", "units_long in FIELDS: w = MeterValueWidget(self) w.setStyleSheet(\"QWidget { background-color :", "under the Apache License, Version 2.0 (the \"License\"); # you", "the License. from PySide2 import QtCore, QtWidgets from . import", "import logging log = logging.getLogger(__name__) FIELDS = [ ('current', 'A',", "\"License\"); # you may not use this file except in", "units_long) self.values[name] = w w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy()", "self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable", "@QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable = checked", "governing permissions and # limitations under the License. from PySide2", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "w w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,", "('energy', 'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs):", "self.values['power'].accumulate_enable = checked def update(self, statistics): \"\"\"Update the multimeter display", "{} for name, units_short, units_long in FIELDS: w = MeterValueWidget(self)", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "The statistics data structure \"\"\" for name, field in statistics['signals'].items():", "self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "under the License. from PySide2 import QtCore, QtWidgets from .", "from . import joulescope_rc from .meter_value_widget import MeterValueWidget import logging", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked", "to in writing, software # distributed under the License is", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "('voltage', 'V', 'Volts'), ('power', 'W', 'Watts'), ('energy', 'J', 'Joules'), ]", "You may obtain a copy of the License at #", "20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {} for name, units_short,", "self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable = checked def update(self, statistics): \"\"\"Update", "2018 Jetperch LLC # # Licensed under the Apache License,", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "log = logging.getLogger(__name__) FIELDS = [ ('current', 'A', 'Amps'), ('voltage',", "variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy,", "self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName(\"accumulateButton\") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer =", "statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self): _translate =", "required by applicable law or agreed to in writing, software", ":param statistics: The statistics data structure \"\"\" for name, field", "0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0)", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked):", "class MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {} for name, units_short, units_long in", "0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0)", "self.verticalLayout.setObjectName(\"verticalLayout\") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton", "QtCore, QtWidgets from . import joulescope_rc from .meter_value_widget import MeterValueWidget", ".meter_value_widget import MeterValueWidget import logging log = logging.getLogger(__name__) FIELDS =", "self.controlLayout.addItem(self.controlSpacer) self.values = {} for name, units_short, units_long in FIELDS:" ]
[ "\"\"\" Services are the heart of RPyC: each side of", "raise AttributeError(\"access denied\") @classmethod def get_service_aliases(cls): \"\"\"returns a list of", "cls.__name__.upper() if name.endswith(\"SERVICE\"): name = name[:-7] return (name,) @classmethod def", "the connection)\"\"\" pass # Using default defined in 'protocol.Connection._access_attr' for:", "``ALIASES`` class attribute :: class Foobar(Service): ALIASES = [\"foo\", \"bar\",", "is very useful in local, secure networks, but it exposes", "import_custom_exceptions = True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions = True, ))", "conn): \"\"\"called when the connection had already terminated for cleanup", "want to connect to a ``SlaveService`` without exposing any functionality", "get_service_aliases exposed_get_service_name = get_service_name @hybridmethod def _connect(self, channel, config={}): \"\"\"Setup", "conn = self._protocol(self, channel, config) self.on_connect(conn) return conn class VoidService(Service):", "good to go. \"\"\" from functools import partial from rpyc.lib", "SlaveService): \"\"\"Full duplex master/slave service, i.e. both parties have full", "def on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod def _install(conn,", "# 'FOO' FooService.get_service_aliases() # ['FOO'] * To supply a different", "name): raise AttributeError(\"access denied\") def _rpyc_setattr(self, name, value): raise AttributeError(\"access", "expose *service B*. As long as the two can interoperate,", "def exposed_add(self, x, y): return x + y * All", "`self` as root object for backward # compatibility and convenience.", "a :class:`MasterService`, :class:`ClassicService`, or the old ``SlaveService`` (pre v3.5) without", "(not prefixed by ``exposed_``) are local (not accessible to the", "Use this service if you want to connect to a", "note:: You can override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to change", "partial(teleport_function, conn) class ClassicService(MasterService, SlaveService): \"\"\"Full duplex master/slave service, i.e.", "\"__cache\", \"__weakref__\"] def __init__(self, getmodule): self.__getmodule = getmodule self.__cache =", "y * All other names (not prefixed by ``exposed_``) are", "service - an do-nothing service\"\"\" __slots__ = () class ModuleNamespace(object):", "that operate a :class:`MasterService`, :class:`ClassicService` without exposing any functionality to", "(name,) @classmethod def get_service_name(cls): \"\"\"returns the canonical name of the", "the heart of RPyC: each side of the connection exposes", "old ``SlaveService`` (pre v3.5) without exposing any functionality to them.\"\"\"", "implement custom RPyC services: * The name of the class", "None exposed_execute = None exposed_eval = None exposed_getmodule = None", "rpyc.lib import hybridmethod from rpyc.lib.compat import execute, is_py3k from rpyc.core.protocol", "'LALALAND'] * Override :func:`on_connect` to perform custom initialization * Override", "isinstance(self, type): # autovivify if accessed as class method self", "ModuleNamespace(slave.getmodule) builtin = modules.builtins if is_py3k else modules.__builtin__ conn.modules =", "by ``exposed_``) are local (not accessible to the other party)", "FooService.get_service_name() # 'FOO' FooService.get_service_aliases() # ['FOO'] * To supply a", "self._conn class SlaveService(Slave, Service): \"\"\"The SlaveService allows the other side", "to them.\"\"\" __slots__ = () def on_connect(self, conn): super(MasterService, self).on_connect(conn)", "word 'Service') :: class FooService(Service): pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases()", "service if you want to connect to a ``SlaveService`` without", "\"namespace\"] def __init__(self): self._conn = None self.namespace = {} def", "- an do-nothing service\"\"\" __slots__ = () class ModuleNamespace(object): \"\"\"used", "of the connection exposes a *service*, which define the capabilities", "for backward # compatibility and convenience. You could pass in", "Connection class Service(object): \"\"\"The service base-class. Derive from this class", "services by both parties need not be symmetric, e.g., one", "by the word 'Service') :: class FooService(Service): pass FooService.get_service_name() #", "def get_service_aliases(cls): \"\"\"returns a list of the aliases of this", "an do-nothing service\"\"\" __slots__ = () class ModuleNamespace(object): \"\"\"used by", "side to perform arbitrary imports and execution arbitrary code on", "modules conn.eval = slave.eval conn.execute = slave.execute conn.namespace = slave.namespace", ":class:`ClassicService` without exposing any functionality to them.\"\"\" __slots__ = ()", "This service is very useful in local, secure networks, but", "get_service_name @hybridmethod def _connect(self, channel, config={}): \"\"\"Setup a connection via", "_install(conn, slave): modules = ModuleNamespace(slave.getmodule) builtin = modules.builtins if is_py3k", "exposed_eval = None exposed_getmodule = None exposed_getconn = None class", "= True, allow_setattr = True, allow_delattr = True, allow_exposed_attrs =", "@staticmethod def _install(conn, slave): modules = ModuleNamespace(slave.getmodule) builtin = modules.builtins", "networks, but it exposes a **major security risk** otherwise.\"\"\" __slots__", "self.__getmodule = getmodule self.__cache = {} def __contains__(self, name): try:", "\"lalaland\"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND'] *", "_rpyc_setattr(self, name, value): raise AttributeError(\"access denied\") @classmethod def get_service_aliases(cls): \"\"\"returns", "= partial(teleport_function, conn) class ClassicService(MasterService, SlaveService): \"\"\"Full duplex master/slave service,", "long as the two can interoperate, you're good to go.", "SlaveService(Slave, Service): \"\"\"The SlaveService allows the other side to perform", "``_rpyc_setattr`` and ``_rpyc_delattr`` to change attribute lookup -- but beware", "# def _rpyc_getattr(self, name): def _rpyc_delattr(self, name): raise AttributeError(\"access denied\")", "class MasterService(Service): \"\"\"Peer for a new-style (>=v3.5) :class:`SlaveService`. Use this", "service\"\"\" if cls.ALIASES: return tuple(str(n).upper() for n in cls.ALIASES) name", "__getitem__(self, name): if type(name) is tuple: name = \".\".join(name) if", "be symmetric, e.g., one side may exposed *service A*, while", "a list of the aliases of this service\"\"\" if cls.ALIASES:", "provided for compatibility with the classic RPyC (2.6) modus operandi.", "module\"\"\" return __import__(name, None, None, \"*\") def getconn(self): \"\"\"returns the", "__init__(self): self._conn = None self.namespace = {} def execute(self, text):", "can be used for connecting to peers that operate a", "allow_setattr = True, allow_delattr = True, allow_exposed_attrs = False, import_custom_exceptions", "``SlaveService`` without exposing any functionality to them.\"\"\" __slots__ = ()", "self.__cache: self.__cache[name] = self.__getmodule(name) return self.__cache[name] def __getattr__(self, name): return", "builtin from rpyc.utils.classic import teleport_function conn.teleport = partial(teleport_function, conn) class", "self() # Note that we are here passing in `self`", "= modules conn.eval = slave.eval conn.execute = slave.execute conn.namespace =", "conn.modules = modules conn.eval = slave.eval conn.execute = slave.execute conn.namespace", "denied\") @classmethod def get_service_aliases(cls): \"\"\"returns a list of the aliases", "on the server. This is provided for compatibility with the", "conn): \"\"\"called when the connection is established\"\"\" pass def on_disconnect(self,", "both parties.\"\"\" __slots__ = () class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that", "import partial from rpyc.lib import hybridmethod from rpyc.lib.compat import execute,", "super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService that can be used for", "the connection is established\"\"\" pass def on_disconnect(self, conn): \"\"\"called when", "from functools import partial from rpyc.lib import hybridmethod from rpyc.lib.compat", "return False else: return True def __getitem__(self, name): if type(name)", "getmodule(self, name): \"\"\"imports an arbitrary module\"\"\" return __import__(name, None, None,", "= conn self._conn._config.update(dict( allow_all_attrs = True, allow_pickle = True, allow_getattr", "self.namespace) def getmodule(self, name): \"\"\"imports an arbitrary module\"\"\" return __import__(name,", "in `self` as root object for backward # compatibility and", "service is very useful in local, secure networks, but it", "Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND'] * Override :func:`on_connect` to perform", "name = \".\".join(name) if name not in self.__cache: self.__cache[name] =", "functionality to them.\"\"\" __slots__ = () def on_connect(self, conn): super(MasterService,", "FakeSlaveService(VoidService): \"\"\"VoidService that can be used for connecting to peers", "or aliases, use the ``ALIASES`` class attribute :: class Foobar(Service):", "name, value): raise AttributeError(\"access denied\") @classmethod def get_service_aliases(cls): \"\"\"returns a", "that we are here passing in `self` as root object", "slave): modules = ModuleNamespace(slave.getmodule) builtin = modules.builtins if is_py3k else", "implications!** \"\"\" __slots__ = () ALIASES = () _protocol =", "AttributeError(\"access denied\") @classmethod def get_service_aliases(cls): \"\"\"returns a list of the", "'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND'] * Override :func:`on_connect` to", "conn.builtin = builtin conn.builtins = builtin from rpyc.utils.classic import teleport_function", "self._conn = conn self._conn._config.update(dict( allow_all_attrs = True, allow_pickle = True,", "operandi. This service is very useful in local, secure networks,", "first alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name = get_service_name", "in local, secure networks, but it exposes a **major security", "implementing the ``Foo`` service should match the pattern ``FooService`` (suffixed", "and convenience. You could pass in a different root if", "of the aliases of this service\"\"\" if cls.ALIASES: return tuple(str(n).upper()", "other names (not prefixed by ``exposed_``) are local (not accessible", "for connecting to peers that operate a :class:`MasterService`, :class:`ClassicService`, or", "method self = self() # Note that we are here", "to a ``SlaveService`` without exposing any functionality to them.\"\"\" __slots__", "functionality to them.\"\"\" __slots__ = () exposed_namespace = None exposed_execute", "# Using default defined in 'protocol.Connection._access_attr' for: # def _rpyc_getattr(self,", "if isinstance(self, type): # autovivify if accessed as class method", "on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod def _install(conn, slave):", "You can override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to change attribute", "the magical 'module namespace'\"\"\" __slots__ = [\"__getmodule\", \"__cache\", \"__weakref__\"] def", "the other. Must be used by both parties.\"\"\" __slots__ =", "the ``Foo`` service should match the pattern ``FooService`` (suffixed by", "full control over the other. Must be used by both", "which define the capabilities available to the other side. Note", "\"\"\"called when the connection had already terminated for cleanup (must", "other side. Note that the services by both parties need", "True, allow_delattr = True, allow_exposed_attrs = False, import_custom_exceptions = True,", "True, instantiate_oldstyle_exceptions = True, )) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService", "both parties need not be symmetric, e.g., one side may", "in 'protocol.Connection._access_attr' for: # def _rpyc_getattr(self, name): def _rpyc_delattr(self, name):", "text): \"\"\"evaluate arbitrary code (using ``eval``)\"\"\" return eval(text, self.namespace) def", "self[name] class Slave(object): __slots__ = [\"_conn\", \"namespace\"] def __init__(self): self._conn", "'protocol.Connection._access_attr' for: # def _rpyc_getattr(self, name): def _rpyc_delattr(self, name): raise", "self).on_connect(conn) self._install(conn, conn.root) @staticmethod def _install(conn, slave): modules = ModuleNamespace(slave.getmodule)", "initialization * Override :func:`on_disconnect` to perform custom finalization * To", "the connection exposes a *service*, which define the capabilities available", "code (using ``exec``)\"\"\" execute(text, self.namespace) def eval(self, text): \"\"\"evaluate arbitrary", "compatibility with the classic RPyC (2.6) modus operandi. This service", "perform arbitrary imports and execution arbitrary code on the server.", "allow_getattr = True, allow_setattr = True, allow_delattr = True, allow_exposed_attrs", "class ClassicService(MasterService, SlaveService): \"\"\"Full duplex master/slave service, i.e. both parties", "parties need not be symmetric, e.g., one side may exposed", "name by ``exposed_``, e.g. :: class FooService(Service): def exposed_add(self, x,", "None self.namespace = {} def execute(self, text): \"\"\"execute arbitrary code", "without exposing any functionality to them.\"\"\" __slots__ = () def", "peers that operate a :class:`MasterService`, :class:`ClassicService` without exposing any functionality", "try: self[name] except ImportError: return False else: return True def", "conn self._conn._config.update(dict( allow_all_attrs = True, allow_pickle = True, allow_getattr =", "FooService.get_service_aliases() # ['FOO'] * To supply a different name or", "(which is its first alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases", "def getmodule(self, name): \"\"\"imports an arbitrary module\"\"\" return __import__(name, None,", "the other side\"\"\" return self._conn class SlaveService(Slave, Service): \"\"\"The SlaveService", "a different root if # you wanted: conn = self._protocol(self,", "None exposed_getmodule = None exposed_getconn = None class MasterService(Service): \"\"\"Peer", "teleport_function conn.teleport = partial(teleport_function, conn) class ClassicService(MasterService, SlaveService): \"\"\"Full duplex", "in self.__cache: self.__cache[name] = self.__getmodule(name) return self.__cache[name] def __getattr__(self, name):", "perform any IO on the connection)\"\"\" pass # Using default", "of possible **security implications!** \"\"\" __slots__ = () ALIASES =", "= getmodule self.__cache = {} def __contains__(self, name): try: self[name]", "return self._conn class SlaveService(Slave, Service): \"\"\"The SlaveService allows the other", "one side may exposed *service A*, while the other may", "duplex master/slave service, i.e. both parties have full control over", "connecting to peers that operate a :class:`MasterService`, :class:`ClassicService` without exposing", "code (using ``eval``)\"\"\" return eval(text, self.namespace) def getmodule(self, name): \"\"\"imports", "root if # you wanted: conn = self._protocol(self, channel, config)", "\"\"\"The SlaveService allows the other side to perform arbitrary imports", "peers that operate a :class:`MasterService`, :class:`ClassicService`, or the old ``SlaveService``", "capabilities available to the other side. Note that the services", "the pattern ``FooService`` (suffixed by the word 'Service') :: class", "Connection def on_connect(self, conn): \"\"\"called when the connection is established\"\"\"", "to go. \"\"\" from functools import partial from rpyc.lib import", "not in self.__cache: self.__cache[name] = self.__getmodule(name) return self.__cache[name] def __getattr__(self,", "exposed_get_service_name = get_service_name @hybridmethod def _connect(self, channel, config={}): \"\"\"Setup a", "pass def on_disconnect(self, conn): \"\"\"called when the connection had already", "['FOO', 'BAR', 'LALALAND'] * Override :func:`on_connect` to perform custom initialization", "def __getattr__(self, name): return self[name] class Slave(object): __slots__ = [\"_conn\",", "arbitrary code (using ``eval``)\"\"\" return eval(text, self.namespace) def getmodule(self, name):", "This is provided for compatibility with the classic RPyC (2.6)", "= slave.namespace conn.builtin = builtin conn.builtins = builtin from rpyc.utils.classic", "to connect to a ``SlaveService`` without exposing any functionality to", "_protocol = Connection def on_connect(self, conn): \"\"\"called when the connection", "from rpyc.core.protocol import Connection class Service(object): \"\"\"The service base-class. Derive", "= True, allow_delattr = True, allow_exposed_attrs = False, import_custom_exceptions =", "given channel.\"\"\" if isinstance(self, type): # autovivify if accessed as", "+ y * All other names (not prefixed by ``exposed_``)", "security risk** otherwise.\"\"\" __slots__ = () def on_connect(self, conn): self._conn", "risk** otherwise.\"\"\" __slots__ = () def on_connect(self, conn): self._conn =", "import hybridmethod from rpyc.lib.compat import execute, is_py3k from rpyc.core.protocol import", "of this service\"\"\" if cls.ALIASES: return tuple(str(n).upper() for n in", "defined in 'protocol.Connection._access_attr' for: # def _rpyc_getattr(self, name): def _rpyc_delattr(self,", "class FooService(Service): def exposed_add(self, x, y): return x + y", "\"\"\"MasterService that can be used for connecting to peers that", "side may exposed *service A*, while the other may expose", "As long as the two can interoperate, you're good to", "\"\"\" from functools import partial from rpyc.lib import hybridmethod from", "them normally, but prefix their name by ``exposed_``, e.g. ::", "(using ``eval``)\"\"\" return eval(text, self.namespace) def getmodule(self, name): \"\"\"imports an", "self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService that can be used for connecting", "you're good to go. \"\"\" from functools import partial from", "via the given channel.\"\"\" if isinstance(self, type): # autovivify if", "for n in cls.ALIASES) name = cls.__name__.upper() if name.endswith(\"SERVICE\"): name", "you wanted: conn = self._protocol(self, channel, config) self.on_connect(conn) return conn", "else modules.__builtin__ conn.modules = modules conn.eval = slave.eval conn.execute =", "= modules.builtins if is_py3k else modules.__builtin__ conn.modules = modules conn.eval", "Slave(object): __slots__ = [\"_conn\", \"namespace\"] def __init__(self): self._conn = None", "a *service*, which define the capabilities available to the other", "__init__(self, getmodule): self.__getmodule = getmodule self.__cache = {} def __contains__(self,", "without exposing any functionality to them.\"\"\" __slots__ = () exposed_namespace", "for connecting to peers that operate a :class:`MasterService`, :class:`ClassicService` without", "= () ALIASES = () _protocol = Connection def on_connect(self,", "the canonical name of the service (which is its first", "= [\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() # ['FOO',", "hybridmethod from rpyc.lib.compat import execute, is_py3k from rpyc.core.protocol import Connection", "def getconn(self): \"\"\"returns the local connection instance to the other", "two can interoperate, you're good to go. \"\"\" from functools", "new-style (>=v3.5) :class:`SlaveService`. Use this service if you want to", ":func:`on_disconnect` to perform custom finalization * To add exposed methods", "name): def _rpyc_delattr(self, name): raise AttributeError(\"access denied\") def _rpyc_setattr(self, name,", "interoperate, you're good to go. \"\"\" from functools import partial", "may expose *service B*. As long as the two can", "control over the other. Must be used by both parties.\"\"\"", "return __import__(name, None, None, \"*\") def getconn(self): \"\"\"returns the local", "add exposed methods or attributes, simply define them normally, but", "had already terminated for cleanup (must not perform any IO", "\"\"\"imports an arbitrary module\"\"\" return __import__(name, None, None, \"*\") def", "['FOO'] * To supply a different name or aliases, use", "instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions = True, )) super(SlaveService, self).on_connect(conn) class", "name = cls.__name__.upper() if name.endswith(\"SERVICE\"): name = name[:-7] return (name,)", "master/slave service, i.e. both parties have full control over the", "this class to implement custom RPyC services: * The name", "conn.execute = slave.execute conn.namespace = slave.namespace conn.builtin = builtin conn.builtins", "service\"\"\" __slots__ = () class ModuleNamespace(object): \"\"\"used by the :class:`SlaveService`", "aliases, use the ``ALIASES`` class attribute :: class Foobar(Service): ALIASES", "def __init__(self): self._conn = None self.namespace = {} def execute(self,", "\"\"\"returns the local connection instance to the other side\"\"\" return", "(suffixed by the word 'Service') :: class FooService(Service): pass FooService.get_service_name()", "in cls.ALIASES) name = cls.__name__.upper() if name.endswith(\"SERVICE\"): name = name[:-7]", "for cleanup (must not perform any IO on the connection)\"\"\"", "= [\"__getmodule\", \"__cache\", \"__weakref__\"] def __init__(self, getmodule): self.__getmodule = getmodule", "to change attribute lookup -- but beware of possible **security", "-- but beware of possible **security implications!** \"\"\" __slots__ =", "not perform any IO on the connection)\"\"\" pass # Using", "def __getitem__(self, name): if type(name) is tuple: name = \".\".join(name)", "in a different root if # you wanted: conn =", "conn): self._conn = conn self._conn._config.update(dict( allow_all_attrs = True, allow_pickle =", "symmetric, e.g., one side may exposed *service A*, while the", "it exposes a **major security risk** otherwise.\"\"\" __slots__ = ()", "accessible to the other party) .. note:: You can override", "each side of the connection exposes a *service*, which define", "None class MasterService(Service): \"\"\"Peer for a new-style (>=v3.5) :class:`SlaveService`. Use", "() ALIASES = () _protocol = Connection def on_connect(self, conn):", "\"\"\"Peer for a new-style (>=v3.5) :class:`SlaveService`. Use this service if", "accessed as class method self = self() # Note that", "self.namespace) def eval(self, text): \"\"\"evaluate arbitrary code (using ``eval``)\"\"\" return", "name of the service (which is its first alias)\"\"\" return", "class method self = self() # Note that we are", "raise AttributeError(\"access denied\") def _rpyc_setattr(self, name, value): raise AttributeError(\"access denied\")", "__slots__ = () class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that can be", "Override :func:`on_connect` to perform custom initialization * Override :func:`on_disconnect` to", "True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions = True, )) super(SlaveService, self).on_connect(conn)", "self.__cache = {} def __contains__(self, name): try: self[name] except ImportError:", "return self.__cache[name] def __getattr__(self, name): return self[name] class Slave(object): __slots__", "Service): \"\"\"The SlaveService allows the other side to perform arbitrary", "if accessed as class method self = self() # Note", "custom finalization * To add exposed methods or attributes, simply", "= None exposed_execute = None exposed_eval = None exposed_getmodule =", "perform custom finalization * To add exposed methods or attributes,", "``SlaveService`` (pre v3.5) without exposing any functionality to them.\"\"\" __slots__", "object for backward # compatibility and convenience. You could pass", "or attributes, simply define them normally, but prefix their name", "= True, )) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService that can", "Service(object): \"\"\"The service base-class. Derive from this class to implement", "otherwise.\"\"\" __slots__ = () def on_connect(self, conn): self._conn = conn", "All other names (not prefixed by ``exposed_``) are local (not", "the local connection instance to the other side\"\"\" return self._conn", "define them normally, but prefix their name by ``exposed_``, e.g.", "attribute lookup -- but beware of possible **security implications!** \"\"\"", "pass # Using default defined in 'protocol.Connection._access_attr' for: # def", "but beware of possible **security implications!** \"\"\" __slots__ = ()", "the other side. Note that the services by both parties", "get_service_name(cls): \"\"\"returns the canonical name of the service (which is", "that the services by both parties need not be symmetric,", "return (name,) @classmethod def get_service_name(cls): \"\"\"returns the canonical name of", "def __contains__(self, name): try: self[name] except ImportError: return False else:", "any functionality to them.\"\"\" __slots__ = () def on_connect(self, conn):", "conn.teleport = partial(teleport_function, conn) class ClassicService(MasterService, SlaveService): \"\"\"Full duplex master/slave", ":: class FooService(Service): pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases() # ['FOO']", "{} def execute(self, text): \"\"\"execute arbitrary code (using ``exec``)\"\"\" execute(text,", "else: return True def __getitem__(self, name): if type(name) is tuple:", "exposes a *service*, which define the capabilities available to the", "exposed *service A*, while the other may expose *service B*.", "can interoperate, you're good to go. \"\"\" from functools import", "ALIASES = [\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() #", ":: class FooService(Service): def exposed_add(self, x, y): return x +", "v3.5) without exposing any functionality to them.\"\"\" __slots__ = ()", "on the connection)\"\"\" pass # Using default defined in 'protocol.Connection._access_attr'", "class FooService(Service): pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases() # ['FOO'] *", "AttributeError(\"access denied\") def _rpyc_setattr(self, name, value): raise AttributeError(\"access denied\") @classmethod", "to perform arbitrary imports and execution arbitrary code on the", "= Connection def on_connect(self, conn): \"\"\"called when the connection is", "# ['FOO'] * To supply a different name or aliases,", "other. Must be used by both parties.\"\"\" __slots__ = ()", "the other party) .. note:: You can override ``_rpyc_getattr``, ``_rpyc_setattr``", "class VoidService(Service): \"\"\"void service - an do-nothing service\"\"\" __slots__ =", "= {} def __contains__(self, name): try: self[name] except ImportError: return", "local, secure networks, but it exposes a **major security risk**", "() def on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod def", "self._install(conn, conn.root) @staticmethod def _install(conn, slave): modules = ModuleNamespace(slave.getmodule) builtin", "name or aliases, use the ``ALIASES`` class attribute :: class", "name[:-7] return (name,) @classmethod def get_service_name(cls): \"\"\"returns the canonical name", "Note that we are here passing in `self` as root", "a connection via the given channel.\"\"\" if isinstance(self, type): #", "used for connecting to peers that operate a :class:`MasterService`, :class:`ClassicService`", ")) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService that can be used", "= builtin from rpyc.utils.classic import teleport_function conn.teleport = partial(teleport_function, conn)", "rpyc.lib.compat import execute, is_py3k from rpyc.core.protocol import Connection class Service(object):", "\"\"\"Setup a connection via the given channel.\"\"\" if isinstance(self, type):", "= None exposed_getconn = None class MasterService(Service): \"\"\"Peer for a", "when the connection had already terminated for cleanup (must not", "__slots__ = [\"__getmodule\", \"__cache\", \"__weakref__\"] def __init__(self, getmodule): self.__getmodule =", "= None exposed_getmodule = None exposed_getconn = None class MasterService(Service):", "here passing in `self` as root object for backward #", "the services by both parties need not be symmetric, e.g.,", "need not be symmetric, e.g., one side may exposed *service", "= True, allow_getattr = True, allow_setattr = True, allow_delattr =", "= () def on_connect(self, conn): self._conn = conn self._conn._config.update(dict( allow_all_attrs", "if # you wanted: conn = self._protocol(self, channel, config) self.on_connect(conn)", "supply a different name or aliases, use the ``ALIASES`` class", "``eval``)\"\"\" return eval(text, self.namespace) def getmodule(self, name): \"\"\"imports an arbitrary", "self.namespace = {} def execute(self, text): \"\"\"execute arbitrary code (using", "True, allow_getattr = True, allow_setattr = True, allow_delattr = True,", "\".\".join(name) if name not in self.__cache: self.__cache[name] = self.__getmodule(name) return", "[\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR',", "is tuple: name = \".\".join(name) if name not in self.__cache:", "def _rpyc_setattr(self, name, value): raise AttributeError(\"access denied\") @classmethod def get_service_aliases(cls):", "ClassicService(MasterService, SlaveService): \"\"\"Full duplex master/slave service, i.e. both parties have", "used by both parties.\"\"\" __slots__ = () class ClassicClient(MasterService, FakeSlaveService):", "__import__(name, None, None, \"*\") def getconn(self): \"\"\"returns the local connection", "parties have full control over the other. Must be used", "name): if type(name) is tuple: name = \".\".join(name) if name", "them.\"\"\" __slots__ = () def on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn,", "= True, allow_pickle = True, allow_getattr = True, allow_setattr =", "is established\"\"\" pass def on_disconnect(self, conn): \"\"\"called when the connection", "*service*, which define the capabilities available to the other side.", "for a new-style (>=v3.5) :class:`SlaveService`. Use this service if you", "None, None, \"*\") def getconn(self): \"\"\"returns the local connection instance", "conn.builtins = builtin from rpyc.utils.classic import teleport_function conn.teleport = partial(teleport_function,", "a new-style (>=v3.5) :class:`SlaveService`. Use this service if you want", "classic RPyC (2.6) modus operandi. This service is very useful", "or the old ``SlaveService`` (pre v3.5) without exposing any functionality", "return x + y * All other names (not prefixed", "True, allow_pickle = True, allow_getattr = True, allow_setattr = True,", "cls.ALIASES: return tuple(str(n).upper() for n in cls.ALIASES) name = cls.__name__.upper()", "= False, import_custom_exceptions = True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions =", "= slave.execute conn.namespace = slave.namespace conn.builtin = builtin conn.builtins =", "VoidService(Service): \"\"\"void service - an do-nothing service\"\"\" __slots__ = ()", "party) .. note:: You can override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr``", "_rpyc_getattr(self, name): def _rpyc_delattr(self, name): raise AttributeError(\"access denied\") def _rpyc_setattr(self,", "config={}): \"\"\"Setup a connection via the given channel.\"\"\" if isinstance(self,", "@classmethod def get_service_aliases(cls): \"\"\"returns a list of the aliases of", "channel, config) self.on_connect(conn) return conn class VoidService(Service): \"\"\"void service -", ":class:`SlaveService` to implement the magical 'module namespace'\"\"\" __slots__ = [\"__getmodule\",", "'Service') :: class FooService(Service): pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases() #", "* Override :func:`on_connect` to perform custom initialization * Override :func:`on_disconnect`", "arbitrary code on the server. This is provided for compatibility", "def __init__(self, getmodule): self.__getmodule = getmodule self.__cache = {} def", "exposed methods or attributes, simply define them normally, but prefix", "them.\"\"\" __slots__ = () exposed_namespace = None exposed_execute = None", "execute(text, self.namespace) def eval(self, text): \"\"\"evaluate arbitrary code (using ``eval``)\"\"\"", "def _rpyc_getattr(self, name): def _rpyc_delattr(self, name): raise AttributeError(\"access denied\") def", "text): \"\"\"execute arbitrary code (using ``exec``)\"\"\" execute(text, self.namespace) def eval(self,", "may exposed *service A*, while the other may expose *service", "the :class:`SlaveService` to implement the magical 'module namespace'\"\"\" __slots__ =", ":class:`SlaveService`. Use this service if you want to connect to", "this service if you want to connect to a ``SlaveService``", "y): return x + y * All other names (not", "= () class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that can be used", "the server. This is provided for compatibility with the classic", "RPyC: each side of the connection exposes a *service*, which", "MasterService(Service): \"\"\"Peer for a new-style (>=v3.5) :class:`SlaveService`. Use this service", "have full control over the other. Must be used by", "# you wanted: conn = self._protocol(self, channel, config) self.on_connect(conn) return", "* All other names (not prefixed by ``exposed_``) are local", "override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to change attribute lookup --", "To add exposed methods or attributes, simply define them normally,", "**security implications!** \"\"\" __slots__ = () ALIASES = () _protocol", "pattern ``FooService`` (suffixed by the word 'Service') :: class FooService(Service):", "exposed_getconn = None class MasterService(Service): \"\"\"Peer for a new-style (>=v3.5)", "True, allow_exposed_attrs = False, import_custom_exceptions = True, instantiate_custom_exceptions = True,", "Derive from this class to implement custom RPyC services: *", "side. Note that the services by both parties need not", "except ImportError: return False else: return True def __getitem__(self, name):", "the class implementing the ``Foo`` service should match the pattern", "True, allow_setattr = True, allow_delattr = True, allow_exposed_attrs = False,", "() class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that can be used for", "type): # autovivify if accessed as class method self =", "on_connect(self, conn): self._conn = conn self._conn._config.update(dict( allow_all_attrs = True, allow_pickle", "compatibility and convenience. You could pass in a different root", "local connection instance to the other side\"\"\" return self._conn class", "over the other. Must be used by both parties.\"\"\" __slots__", "conn.namespace = slave.namespace conn.builtin = builtin conn.builtins = builtin from", "name): \"\"\"imports an arbitrary module\"\"\" return __import__(name, None, None, \"*\")", "that can be used for connecting to peers that operate", "``Foo`` service should match the pattern ``FooService`` (suffixed by the", "execute(self, text): \"\"\"execute arbitrary code (using ``exec``)\"\"\" execute(text, self.namespace) def", "ImportError: return False else: return True def __getitem__(self, name): if", "getconn(self): \"\"\"returns the local connection instance to the other side\"\"\"", "and execution arbitrary code on the server. This is provided", "class SlaveService(Slave, Service): \"\"\"The SlaveService allows the other side to", "() def on_connect(self, conn): self._conn = conn self._conn._config.update(dict( allow_all_attrs =", "to perform custom initialization * Override :func:`on_disconnect` to perform custom", "parties.\"\"\" __slots__ = () class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that can", "``exec``)\"\"\" execute(text, self.namespace) def eval(self, text): \"\"\"evaluate arbitrary code (using", "its first alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name =", "FooService(Service): pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases() # ['FOO'] * To", "by both parties.\"\"\" __slots__ = () class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService", "canonical name of the service (which is its first alias)\"\"\"", "import Connection class Service(object): \"\"\"The service base-class. Derive from this", "= () def on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod", "Using default defined in 'protocol.Connection._access_attr' for: # def _rpyc_getattr(self, name):", "convenience. You could pass in a different root if #", "\"\"\"execute arbitrary code (using ``exec``)\"\"\" execute(text, self.namespace) def eval(self, text):", "useful in local, secure networks, but it exposes a **major", "() exposed_namespace = None exposed_execute = None exposed_eval = None", "self.__getmodule(name) return self.__cache[name] def __getattr__(self, name): return self[name] class Slave(object):", "can override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to change attribute lookup", "the ``ALIASES`` class attribute :: class Foobar(Service): ALIASES = [\"foo\",", "conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod def _install(conn, slave): modules", "on_disconnect(self, conn): \"\"\"called when the connection had already terminated for", "on_connect(self, conn): \"\"\"called when the connection is established\"\"\" pass def", "(must not perform any IO on the connection)\"\"\" pass #", "pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases() # ['FOO'] * To supply", "connection instance to the other side\"\"\" return self._conn class SlaveService(Slave,", "= None exposed_eval = None exposed_getmodule = None exposed_getconn =", "beware of possible **security implications!** \"\"\" __slots__ = () ALIASES", "{} def __contains__(self, name): try: self[name] except ImportError: return False", "# ['FOO', 'BAR', 'LALALAND'] * Override :func:`on_connect` to perform custom", "def _install(conn, slave): modules = ModuleNamespace(slave.getmodule) builtin = modules.builtins if", "to peers that operate a :class:`MasterService`, :class:`ClassicService` without exposing any", "if type(name) is tuple: name = \".\".join(name) if name not", "to perform custom finalization * To add exposed methods or", "connection is established\"\"\" pass def on_disconnect(self, conn): \"\"\"called when the", "passing in `self` as root object for backward # compatibility", "= () exposed_namespace = None exposed_execute = None exposed_eval =", "methods or attributes, simply define them normally, but prefix their", "do-nothing service\"\"\" __slots__ = () class ModuleNamespace(object): \"\"\"used by the", "= get_service_name @hybridmethod def _connect(self, channel, config={}): \"\"\"Setup a connection", "of RPyC: each side of the connection exposes a *service*,", "# compatibility and convenience. You could pass in a different", "custom initialization * Override :func:`on_disconnect` to perform custom finalization *", "services: * The name of the class implementing the ``Foo``", ".. note:: You can override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to", "_connect(self, channel, config={}): \"\"\"Setup a connection via the given channel.\"\"\"", "namespace'\"\"\" __slots__ = [\"__getmodule\", \"__cache\", \"__weakref__\"] def __init__(self, getmodule): self.__getmodule", "code on the server. This is provided for compatibility with", "is its first alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name", "side\"\"\" return self._conn class SlaveService(Slave, Service): \"\"\"The SlaveService allows the", "to them.\"\"\" __slots__ = () exposed_namespace = None exposed_execute =", "exposed_get_service_aliases = get_service_aliases exposed_get_service_name = get_service_name @hybridmethod def _connect(self, channel,", "__slots__ = () def on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root)", "__slots__ = [\"_conn\", \"namespace\"] def __init__(self): self._conn = None self.namespace", "**major security risk** otherwise.\"\"\" __slots__ = () def on_connect(self, conn):", "name.endswith(\"SERVICE\"): name = name[:-7] return (name,) @classmethod def get_service_name(cls): \"\"\"returns", "finalization * To add exposed methods or attributes, simply define", "the service (which is its first alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases", "\"\"\"void service - an do-nothing service\"\"\" __slots__ = () class", "* Override :func:`on_disconnect` to perform custom finalization * To add", "connection had already terminated for cleanup (must not perform any", "if name not in self.__cache: self.__cache[name] = self.__getmodule(name) return self.__cache[name]", "we are here passing in `self` as root object for", "= \".\".join(name) if name not in self.__cache: self.__cache[name] = self.__getmodule(name)", "exposed_execute = None exposed_eval = None exposed_getmodule = None exposed_getconn", "list of the aliases of this service\"\"\" if cls.ALIASES: return", "slave.execute conn.namespace = slave.namespace conn.builtin = builtin conn.builtins = builtin", "get_service_aliases(cls): \"\"\"returns a list of the aliases of this service\"\"\"", "``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to change attribute lookup -- but", "x + y * All other names (not prefixed by", "any IO on the connection)\"\"\" pass # Using default defined", "= cls.__name__.upper() if name.endswith(\"SERVICE\"): name = name[:-7] return (name,) @classmethod", "value): raise AttributeError(\"access denied\") @classmethod def get_service_aliases(cls): \"\"\"returns a list", "is_py3k from rpyc.core.protocol import Connection class Service(object): \"\"\"The service base-class.", "instance to the other side\"\"\" return self._conn class SlaveService(Slave, Service):", "``FooService`` (suffixed by the word 'Service') :: class FooService(Service): pass", "arbitrary code (using ``exec``)\"\"\" execute(text, self.namespace) def eval(self, text): \"\"\"evaluate", "by both parties need not be symmetric, e.g., one side", "\"\"\"The service base-class. Derive from this class to implement custom", "for compatibility with the classic RPyC (2.6) modus operandi. This", "a **major security risk** otherwise.\"\"\" __slots__ = () def on_connect(self,", ":: class Foobar(Service): ALIASES = [\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name() #", "local (not accessible to the other party) .. note:: You", "name): try: self[name] except ImportError: return False else: return True", "connection exposes a *service*, which define the capabilities available to", "getmodule): self.__getmodule = getmodule self.__cache = {} def __contains__(self, name):", "``_rpyc_delattr`` to change attribute lookup -- but beware of possible", "self.__cache[name] def __getattr__(self, name): return self[name] class Slave(object): __slots__ =", "= [\"_conn\", \"namespace\"] def __init__(self): self._conn = None self.namespace =", "return conn class VoidService(Service): \"\"\"void service - an do-nothing service\"\"\"", "are here passing in `self` as root object for backward", "the other side to perform arbitrary imports and execution arbitrary", "= {} def execute(self, text): \"\"\"execute arbitrary code (using ``exec``)\"\"\"", "an arbitrary module\"\"\" return __import__(name, None, None, \"*\") def getconn(self):", "eval(text, self.namespace) def getmodule(self, name): \"\"\"imports an arbitrary module\"\"\" return", "The name of the class implementing the ``Foo`` service should", "__slots__ = () ALIASES = () _protocol = Connection def", "other party) .. note:: You can override ``_rpyc_getattr``, ``_rpyc_setattr`` and", "established\"\"\" pass def on_disconnect(self, conn): \"\"\"called when the connection had", "to implement custom RPyC services: * The name of the", "Note that the services by both parties need not be", "[\"__getmodule\", \"__cache\", \"__weakref__\"] def __init__(self, getmodule): self.__getmodule = getmodule self.__cache", "= name[:-7] return (name,) @classmethod def get_service_name(cls): \"\"\"returns the canonical", "go. \"\"\" from functools import partial from rpyc.lib import hybridmethod", "'BAR', 'LALALAND'] * Override :func:`on_connect` to perform custom initialization *", "their name by ``exposed_``, e.g. :: class FooService(Service): def exposed_add(self,", "wanted: conn = self._protocol(self, channel, config) self.on_connect(conn) return conn class", "magical 'module namespace'\"\"\" __slots__ = [\"__getmodule\", \"__cache\", \"__weakref__\"] def __init__(self,", "class implementing the ``Foo`` service should match the pattern ``FooService``", "implement the magical 'module namespace'\"\"\" __slots__ = [\"__getmodule\", \"__cache\", \"__weakref__\"]", "very useful in local, secure networks, but it exposes a", "\"\"\" __slots__ = () ALIASES = () _protocol = Connection", "@classmethod def get_service_name(cls): \"\"\"returns the canonical name of the service", "execution arbitrary code on the server. This is provided for", "True def __getitem__(self, name): if type(name) is tuple: name =", "return eval(text, self.namespace) def getmodule(self, name): \"\"\"imports an arbitrary module\"\"\"", "import execute, is_py3k from rpyc.core.protocol import Connection class Service(object): \"\"\"The", "heart of RPyC: each side of the connection exposes a", "server. This is provided for compatibility with the classic RPyC", "by the :class:`SlaveService` to implement the magical 'module namespace'\"\"\" __slots__", "conn.eval = slave.eval conn.execute = slave.execute conn.namespace = slave.namespace conn.builtin", "autovivify if accessed as class method self = self() #", "normally, but prefix their name by ``exposed_``, e.g. :: class", "names (not prefixed by ``exposed_``) are local (not accessible to", "\"\"\"returns a list of the aliases of this service\"\"\" if", "if you want to connect to a ``SlaveService`` without exposing", "import teleport_function conn.teleport = partial(teleport_function, conn) class ClassicService(MasterService, SlaveService): \"\"\"Full", "the connection had already terminated for cleanup (must not perform", "conn) class ClassicService(MasterService, SlaveService): \"\"\"Full duplex master/slave service, i.e. both", "None exposed_eval = None exposed_getmodule = None exposed_getconn = None", "[\"_conn\", \"namespace\"] def __init__(self): self._conn = None self.namespace = {}", "False, import_custom_exceptions = True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions = True,", "= True, allow_exposed_attrs = False, import_custom_exceptions = True, instantiate_custom_exceptions =", "of the class implementing the ``Foo`` service should match the", "False else: return True def __getitem__(self, name): if type(name) is", "exposed_getmodule = None exposed_getconn = None class MasterService(Service): \"\"\"Peer for", "a different name or aliases, use the ``ALIASES`` class attribute", "are local (not accessible to the other party) .. note::", "Services are the heart of RPyC: each side of the", "def on_connect(self, conn): \"\"\"called when the connection is established\"\"\" pass", "= slave.eval conn.execute = slave.execute conn.namespace = slave.namespace conn.builtin =", "slave.namespace conn.builtin = builtin conn.builtins = builtin from rpyc.utils.classic import", "partial from rpyc.lib import hybridmethod from rpyc.lib.compat import execute, is_py3k", "= () class ModuleNamespace(object): \"\"\"used by the :class:`SlaveService` to implement", "the word 'Service') :: class FooService(Service): pass FooService.get_service_name() # 'FOO'", ":func:`on_connect` to perform custom initialization * Override :func:`on_disconnect` to perform", "attribute :: class Foobar(Service): ALIASES = [\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name()", "connection)\"\"\" pass # Using default defined in 'protocol.Connection._access_attr' for: #", "config) self.on_connect(conn) return conn class VoidService(Service): \"\"\"void service - an", "execute, is_py3k from rpyc.core.protocol import Connection class Service(object): \"\"\"The service", "* The name of the class implementing the ``Foo`` service", "when the connection is established\"\"\" pass def on_disconnect(self, conn): \"\"\"called", "terminated for cleanup (must not perform any IO on the", "different root if # you wanted: conn = self._protocol(self, channel,", "conn.root) @staticmethod def _install(conn, slave): modules = ModuleNamespace(slave.getmodule) builtin =", "default defined in 'protocol.Connection._access_attr' for: # def _rpyc_getattr(self, name): def", "pass in a different root if # you wanted: conn", "name of the class implementing the ``Foo`` service should match", "\"\"\"VoidService that can be used for connecting to peers that", "if cls.ALIASES: return tuple(str(n).upper() for n in cls.ALIASES) name =", "exposing any functionality to them.\"\"\" __slots__ = () def on_connect(self,", "allows the other side to perform arbitrary imports and execution", "\"\"\"Full duplex master/slave service, i.e. both parties have full control", "i.e. both parties have full control over the other. Must", "class Foobar(Service): ALIASES = [\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name() # 'FOO'", "attributes, simply define them normally, but prefix their name by", "operate a :class:`MasterService`, :class:`ClassicService` without exposing any functionality to them.\"\"\"", "the other may expose *service B*. As long as the", "arbitrary imports and execution arbitrary code on the server. This", "functools import partial from rpyc.lib import hybridmethod from rpyc.lib.compat import", "the capabilities available to the other side. Note that the", "class FakeSlaveService(VoidService): \"\"\"VoidService that can be used for connecting to", "# Note that we are here passing in `self` as", "= self._protocol(self, channel, config) self.on_connect(conn) return conn class VoidService(Service): \"\"\"void", "prefixed by ``exposed_``) are local (not accessible to the other", "'FOO' FooService.get_service_aliases() # ['FOO'] * To supply a different name", "cleanup (must not perform any IO on the connection)\"\"\" pass", "(using ``exec``)\"\"\" execute(text, self.namespace) def eval(self, text): \"\"\"evaluate arbitrary code", "None, \"*\") def getconn(self): \"\"\"returns the local connection instance to", "(>=v3.5) :class:`SlaveService`. Use this service if you want to connect", "but prefix their name by ``exposed_``, e.g. :: class FooService(Service):", "of the service (which is its first alias)\"\"\" return cls.get_service_aliases()[0]", ":class:`ClassicService`, or the old ``SlaveService`` (pre v3.5) without exposing any", "slave.eval conn.execute = slave.execute conn.namespace = slave.namespace conn.builtin = builtin", "return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name = get_service_name @hybridmethod def", "alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name = get_service_name @hybridmethod", "connecting to peers that operate a :class:`MasterService`, :class:`ClassicService`, or the", "lookup -- but beware of possible **security implications!** \"\"\" __slots__", "as the two can interoperate, you're good to go. \"\"\"", "x, y): return x + y * All other names", "different name or aliases, use the ``ALIASES`` class attribute ::", "from rpyc.lib import hybridmethod from rpyc.lib.compat import execute, is_py3k from", "Must be used by both parties.\"\"\" __slots__ = () class", "'module namespace'\"\"\" __slots__ = [\"__getmodule\", \"__cache\", \"__weakref__\"] def __init__(self, getmodule):", "available to the other side. Note that the services by", "exposed_namespace = None exposed_execute = None exposed_eval = None exposed_getmodule", "as class method self = self() # Note that we", "denied\") def _rpyc_setattr(self, name, value): raise AttributeError(\"access denied\") @classmethod def", "to implement the magical 'module namespace'\"\"\" __slots__ = [\"__getmodule\", \"__cache\",", "the classic RPyC (2.6) modus operandi. This service is very", "secure networks, but it exposes a **major security risk** otherwise.\"\"\"", "None exposed_getconn = None class MasterService(Service): \"\"\"Peer for a new-style", "connect to a ``SlaveService`` without exposing any functionality to them.\"\"\"", "class Slave(object): __slots__ = [\"_conn\", \"namespace\"] def __init__(self): self._conn =", "exposes a **major security risk** otherwise.\"\"\" __slots__ = () def", "used for connecting to peers that operate a :class:`MasterService`, :class:`ClassicService`,", "self.__cache[name] = self.__getmodule(name) return self.__cache[name] def __getattr__(self, name): return self[name]", "__slots__ = () def on_connect(self, conn): self._conn = conn self._conn._config.update(dict(", "\"\"\"evaluate arbitrary code (using ``eval``)\"\"\" return eval(text, self.namespace) def getmodule(self,", "perform custom initialization * Override :func:`on_disconnect` to perform custom finalization", "for: # def _rpyc_getattr(self, name): def _rpyc_delattr(self, name): raise AttributeError(\"access", "FooService(Service): def exposed_add(self, x, y): return x + y *", "IO on the connection)\"\"\" pass # Using default defined in", "allow_pickle = True, allow_getattr = True, allow_setattr = True, allow_delattr", "e.g., one side may exposed *service A*, while the other", "self._protocol(self, channel, config) self.on_connect(conn) return conn class VoidService(Service): \"\"\"void service", "self._conn._config.update(dict( allow_all_attrs = True, allow_pickle = True, allow_getattr = True,", "RPyC (2.6) modus operandi. This service is very useful in", "class Service(object): \"\"\"The service base-class. Derive from this class to", "exposed_add(self, x, y): return x + y * All other", "\"\"\"called when the connection is established\"\"\" pass def on_disconnect(self, conn):", "def execute(self, text): \"\"\"execute arbitrary code (using ``exec``)\"\"\" execute(text, self.namespace)", "aliases of this service\"\"\" if cls.ALIASES: return tuple(str(n).upper() for n", "use the ``ALIASES`` class attribute :: class Foobar(Service): ALIASES =", "operate a :class:`MasterService`, :class:`ClassicService`, or the old ``SlaveService`` (pre v3.5)", "service base-class. Derive from this class to implement custom RPyC", "Override :func:`on_disconnect` to perform custom finalization * To add exposed", "from rpyc.lib.compat import execute, is_py3k from rpyc.core.protocol import Connection class", "def get_service_name(cls): \"\"\"returns the canonical name of the service (which", "be used for connecting to peers that operate a :class:`MasterService`,", "B*. As long as the two can interoperate, you're good", "while the other may expose *service B*. As long as", "type(name) is tuple: name = \".\".join(name) if name not in", "are the heart of RPyC: each side of the connection", "the two can interoperate, you're good to go. \"\"\" from", "``exposed_``) are local (not accessible to the other party) ..", "conn class VoidService(Service): \"\"\"void service - an do-nothing service\"\"\" __slots__", "with the classic RPyC (2.6) modus operandi. This service is", "prefix their name by ``exposed_``, e.g. :: class FooService(Service): def", "return self[name] class Slave(object): __slots__ = [\"_conn\", \"namespace\"] def __init__(self):", ":class:`MasterService`, :class:`ClassicService`, or the old ``SlaveService`` (pre v3.5) without exposing", "def _rpyc_delattr(self, name): raise AttributeError(\"access denied\") def _rpyc_setattr(self, name, value):", "= True, instantiate_oldstyle_exceptions = True, )) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService):", "that operate a :class:`MasterService`, :class:`ClassicService`, or the old ``SlaveService`` (pre", "base-class. Derive from this class to implement custom RPyC services:", "the old ``SlaveService`` (pre v3.5) without exposing any functionality to", "ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that can be used for connecting to", "*service B*. As long as the two can interoperate, you're", "simply define them normally, but prefix their name by ``exposed_``,", "imports and execution arbitrary code on the server. This is", "= ModuleNamespace(slave.getmodule) builtin = modules.builtins if is_py3k else modules.__builtin__ conn.modules", "from rpyc.utils.classic import teleport_function conn.teleport = partial(teleport_function, conn) class ClassicService(MasterService,", "True, )) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService that can be", "both parties have full control over the other. Must be", "is_py3k else modules.__builtin__ conn.modules = modules conn.eval = slave.eval conn.execute", "any functionality to them.\"\"\" __slots__ = () exposed_namespace = None", "a :class:`MasterService`, :class:`ClassicService` without exposing any functionality to them.\"\"\" __slots__", "ALIASES = () _protocol = Connection def on_connect(self, conn): \"\"\"called", "if name.endswith(\"SERVICE\"): name = name[:-7] return (name,) @classmethod def get_service_name(cls):", "you want to connect to a ``SlaveService`` without exposing any", "self._conn = None self.namespace = {} def execute(self, text): \"\"\"execute", "a ``SlaveService`` without exposing any functionality to them.\"\"\" __slots__ =", "exposing any functionality to them.\"\"\" __slots__ = () exposed_namespace =", "allow_delattr = True, allow_exposed_attrs = False, import_custom_exceptions = True, instantiate_custom_exceptions", "super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod def _install(conn, slave): modules =", "is provided for compatibility with the classic RPyC (2.6) modus", "self.on_connect(conn) return conn class VoidService(Service): \"\"\"void service - an do-nothing", "# autovivify if accessed as class method self = self()", "\"\"\"used by the :class:`SlaveService` to implement the magical 'module namespace'\"\"\"", "connection via the given channel.\"\"\" if isinstance(self, type): # autovivify", "other side\"\"\" return self._conn class SlaveService(Slave, Service): \"\"\"The SlaveService allows", "def _connect(self, channel, config={}): \"\"\"Setup a connection via the given", "other side to perform arbitrary imports and execution arbitrary code", "to peers that operate a :class:`MasterService`, :class:`ClassicService`, or the old", "as root object for backward # compatibility and convenience. You", "modules = ModuleNamespace(slave.getmodule) builtin = modules.builtins if is_py3k else modules.__builtin__", "cls.ALIASES) name = cls.__name__.upper() if name.endswith(\"SERVICE\"): name = name[:-7] return", "@hybridmethod def _connect(self, channel, config={}): \"\"\"Setup a connection via the", "() class ModuleNamespace(object): \"\"\"used by the :class:`SlaveService` to implement the", "__contains__(self, name): try: self[name] except ImportError: return False else: return", "allow_all_attrs = True, allow_pickle = True, allow_getattr = True, allow_setattr", "modus operandi. This service is very useful in local, secure", "custom RPyC services: * The name of the class implementing", "be used by both parties.\"\"\" __slots__ = () class ClassicClient(MasterService,", "but it exposes a **major security risk** otherwise.\"\"\" __slots__ =", "__slots__ = () exposed_namespace = None exposed_execute = None exposed_eval", "A*, while the other may expose *service B*. As long", "e.g. :: class FooService(Service): def exposed_add(self, x, y): return x", "Foobar(Service): ALIASES = [\"foo\", \"bar\", \"lalaland\"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases()", "() _protocol = Connection def on_connect(self, conn): \"\"\"called when the", "channel, config={}): \"\"\"Setup a connection via the given channel.\"\"\" if", "this service\"\"\" if cls.ALIASES: return tuple(str(n).upper() for n in cls.ALIASES)", "You could pass in a different root if # you", "__slots__ = () class ModuleNamespace(object): \"\"\"used by the :class:`SlaveService` to", "name): return self[name] class Slave(object): __slots__ = [\"_conn\", \"namespace\"] def", "arbitrary module\"\"\" return __import__(name, None, None, \"*\") def getconn(self): \"\"\"returns", "and ``_rpyc_delattr`` to change attribute lookup -- but beware of", "the aliases of this service\"\"\" if cls.ALIASES: return tuple(str(n).upper() for", "\"*\") def getconn(self): \"\"\"returns the local connection instance to the", "FakeSlaveService): \"\"\"MasterService that can be used for connecting to peers", "to the other side. Note that the services by both", "by ``exposed_``, e.g. :: class FooService(Service): def exposed_add(self, x, y):", "= True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions = True, )) super(SlaveService,", "service should match the pattern ``FooService`` (suffixed by the word", "(not accessible to the other party) .. note:: You can", "class to implement custom RPyC services: * The name of", "cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name = get_service_name @hybridmethod def _connect(self,", "__getattr__(self, name): return self[name] class Slave(object): __slots__ = [\"_conn\", \"namespace\"]", "* To add exposed methods or attributes, simply define them", "= None class MasterService(Service): \"\"\"Peer for a new-style (>=v3.5) :class:`SlaveService`.", "ModuleNamespace(object): \"\"\"used by the :class:`SlaveService` to implement the magical 'module", "possible **security implications!** \"\"\" __slots__ = () ALIASES = ()", "def eval(self, text): \"\"\"evaluate arbitrary code (using ``eval``)\"\"\" return eval(text,", "name not in self.__cache: self.__cache[name] = self.__getmodule(name) return self.__cache[name] def", "could pass in a different root if # you wanted:", "to the other side\"\"\" return self._conn class SlaveService(Slave, Service): \"\"\"The", "= None self.namespace = {} def execute(self, text): \"\"\"execute arbitrary", "* To supply a different name or aliases, use the", "return True def __getitem__(self, name): if type(name) is tuple: name", "class attribute :: class Foobar(Service): ALIASES = [\"foo\", \"bar\", \"lalaland\"]", "change attribute lookup -- but beware of possible **security implications!**", "RPyC services: * The name of the class implementing the", "already terminated for cleanup (must not perform any IO on", "*service A*, while the other may expose *service B*. As", "root object for backward # compatibility and convenience. You could", "\"__weakref__\"] def __init__(self, getmodule): self.__getmodule = getmodule self.__cache = {}", "\"\"\"returns the canonical name of the service (which is its", "tuple(str(n).upper() for n in cls.ALIASES) name = cls.__name__.upper() if name.endswith(\"SERVICE\"):", "other may expose *service B*. As long as the two", "To supply a different name or aliases, use the ``ALIASES``", "def on_connect(self, conn): self._conn = conn self._conn._config.update(dict( allow_all_attrs = True,", "\"bar\", \"lalaland\"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND']", "# 'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND'] * Override :func:`on_connect`", "_rpyc_delattr(self, name): raise AttributeError(\"access denied\") def _rpyc_setattr(self, name, value): raise", "(2.6) modus operandi. This service is very useful in local,", "define the capabilities available to the other side. Note that", "rpyc.utils.classic import teleport_function conn.teleport = partial(teleport_function, conn) class ClassicService(MasterService, SlaveService):", "not be symmetric, e.g., one side may exposed *service A*,", "allow_exposed_attrs = False, import_custom_exceptions = True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions", "def on_disconnect(self, conn): \"\"\"called when the connection had already terminated", "the given channel.\"\"\" if isinstance(self, type): # autovivify if accessed", "self = self() # Note that we are here passing", "= builtin conn.builtins = builtin from rpyc.utils.classic import teleport_function conn.teleport", "eval(self, text): \"\"\"evaluate arbitrary code (using ``eval``)\"\"\" return eval(text, self.namespace)", "class ModuleNamespace(object): \"\"\"used by the :class:`SlaveService` to implement the magical", "match the pattern ``FooService`` (suffixed by the word 'Service') ::", "``exposed_``, e.g. :: class FooService(Service): def exposed_add(self, x, y): return", "n in cls.ALIASES) name = cls.__name__.upper() if name.endswith(\"SERVICE\"): name =", "Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND'] * Override", "self[name] except ImportError: return False else: return True def __getitem__(self,", "= self() # Note that we are here passing in", "if is_py3k else modules.__builtin__ conn.modules = modules conn.eval = slave.eval", "rpyc.core.protocol import Connection class Service(object): \"\"\"The service base-class. Derive from", "side of the connection exposes a *service*, which define the", "= get_service_aliases exposed_get_service_name = get_service_name @hybridmethod def _connect(self, channel, config={}):", "= () _protocol = Connection def on_connect(self, conn): \"\"\"called when", "= self.__getmodule(name) return self.__cache[name] def __getattr__(self, name): return self[name] class", ":class:`MasterService`, :class:`ClassicService` without exposing any functionality to them.\"\"\" __slots__ =", "class ClassicClient(MasterService, FakeSlaveService): \"\"\"MasterService that can be used for connecting", "tuple: name = \".\".join(name) if name not in self.__cache: self.__cache[name]", "builtin conn.builtins = builtin from rpyc.utils.classic import teleport_function conn.teleport =", "from this class to implement custom RPyC services: * The", "(pre v3.5) without exposing any functionality to them.\"\"\" __slots__ =", "modules.__builtin__ conn.modules = modules conn.eval = slave.eval conn.execute = slave.execute", "channel.\"\"\" if isinstance(self, type): # autovivify if accessed as class", "service, i.e. both parties have full control over the other.", "return tuple(str(n).upper() for n in cls.ALIASES) name = cls.__name__.upper() if", "SlaveService allows the other side to perform arbitrary imports and", "should match the pattern ``FooService`` (suffixed by the word 'Service')", "builtin = modules.builtins if is_py3k else modules.__builtin__ conn.modules = modules", "backward # compatibility and convenience. You could pass in a", "to the other party) .. note:: You can override ``_rpyc_getattr``,", "name = name[:-7] return (name,) @classmethod def get_service_name(cls): \"\"\"returns the", "getmodule self.__cache = {} def __contains__(self, name): try: self[name] except", "instantiate_oldstyle_exceptions = True, )) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): \"\"\"VoidService that", "service (which is its first alias)\"\"\" return cls.get_service_aliases()[0] exposed_get_service_aliases =", "modules.builtins if is_py3k else modules.__builtin__ conn.modules = modules conn.eval =" ]
[ "import core, util from taskmator import context class ManagerTest(TaskmatorTestBase): def", "from taskmator import context class ManagerTest(TaskmatorTestBase): def testManager(self): print (\"Pending\")", "TaskmatorTestBase from taskmator.task import core, util from taskmator import context", "from taskmator.task import core, util from taskmator import context class", "import context class ManagerTest(TaskmatorTestBase): def testManager(self): print (\"Pending\") def main():", "class ManagerTest(TaskmatorTestBase): def testManager(self): print (\"Pending\") def main(): unittest.main() if", "print (\"Pending\") def main(): unittest.main() if __name__ == '__main__': unittest.main()", "def testManager(self): print (\"Pending\") def main(): unittest.main() if __name__ ==", "context class ManagerTest(TaskmatorTestBase): def testManager(self): print (\"Pending\") def main(): unittest.main()", "<filename>tests/task/manager_test.py import unittest from testbase import TaskmatorTestBase from taskmator.task import", "import TaskmatorTestBase from taskmator.task import core, util from taskmator import", "core, util from taskmator import context class ManagerTest(TaskmatorTestBase): def testManager(self):", "unittest from testbase import TaskmatorTestBase from taskmator.task import core, util", "testbase import TaskmatorTestBase from taskmator.task import core, util from taskmator", "testManager(self): print (\"Pending\") def main(): unittest.main() if __name__ == '__main__':", "taskmator import context class ManagerTest(TaskmatorTestBase): def testManager(self): print (\"Pending\") def", "from testbase import TaskmatorTestBase from taskmator.task import core, util from", "ManagerTest(TaskmatorTestBase): def testManager(self): print (\"Pending\") def main(): unittest.main() if __name__", "taskmator.task import core, util from taskmator import context class ManagerTest(TaskmatorTestBase):", "import unittest from testbase import TaskmatorTestBase from taskmator.task import core,", "util from taskmator import context class ManagerTest(TaskmatorTestBase): def testManager(self): print" ]
[ "of entities for device-specific schemas for the Z-Wave JS integration.\"\"\"", "multilevel switch is discovered as a fan.\"\"\" node = ge_12730", "multilevel switch endpoint 2 is discovered as a fan.\"\"\" node", "as a fan.\"\"\" node = inovelli_lzw36 assert node.device_class.specific.label == \"Unused\"", "hass.states.get(\"light.in_wall_smart_fan_control\") assert not state state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async", "\"\"\"Test that an iBlinds v2.0 multilevel switch value is discovered", "as a cover.\"\"\" node = iblinds_v2 assert node.device_class.specific.label == \"Unused\"", "v2.0 multilevel switch is discovered as a fan.\"\"\" node =", "Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\") assert not state state = hass.states.get(\"fan.in_wall_smart_fan_control\")", "state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async def test_inovelli_lzw36(hass, client, inovelli_lzw36,", "def test_ge_12730(hass, client, ge_12730, integration): \"\"\"Test GE 12730 Fan Controller", "= hass.states.get(\"light.family_room_combo\") assert state.state == \"off\" state = hass.states.get(\"fan.family_room_combo_2\") assert", "<filename>tests/components/zwave_js/test_discovery.py \"\"\"Test discovery of entities for device-specific schemas for the", "endpoint 2 is discovered as a fan.\"\"\" node = inovelli_lzw36", "state = hass.states.get(\"light.family_room_combo\") assert state.state == \"off\" state = hass.states.get(\"fan.family_room_combo_2\")", "Fan Controller v2.0 multilevel switch is discovered as a fan.\"\"\"", "state async def test_ge_12730(hass, client, ge_12730, integration): \"\"\"Test GE 12730", "node = ge_12730 assert node.device_class.specific.label == \"Multilevel Power Switch\" state", "ge_12730 assert node.device_class.specific.label == \"Multilevel Power Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\")", "v2.0 multilevel switch value is discovered as a cover.\"\"\" node", "value is discovered as a cover.\"\"\" node = iblinds_v2 assert", "state state = hass.states.get(\"cover.window_blind_controller\") assert state async def test_ge_12730(hass, client,", "client, inovelli_lzw36, integration): \"\"\"Test LZW36 Fan Controller multilevel switch endpoint", "test_ge_12730(hass, client, ge_12730, integration): \"\"\"Test GE 12730 Fan Controller v2.0", "\"Multilevel Power Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\") assert not state state", "schemas for the Z-Wave JS integration.\"\"\" async def test_iblinds_v2(hass, client,", "switch is discovered as a fan.\"\"\" node = ge_12730 assert", "switch endpoint 2 is discovered as a fan.\"\"\" node =", "GE 12730 Fan Controller v2.0 multilevel switch is discovered as", "inovelli_lzw36 assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.family_room_combo\") assert state.state", "is discovered as a fan.\"\"\" node = ge_12730 assert node.device_class.specific.label", "for the Z-Wave JS integration.\"\"\" async def test_iblinds_v2(hass, client, iblinds_v2,", "node = inovelli_lzw36 assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.family_room_combo\")", "Controller multilevel switch endpoint 2 is discovered as a fan.\"\"\"", "hass.states.get(\"cover.window_blind_controller\") assert state async def test_ge_12730(hass, client, ge_12730, integration): \"\"\"Test", "= hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async def test_inovelli_lzw36(hass, client, inovelli_lzw36, integration):", "discovery of entities for device-specific schemas for the Z-Wave JS", "node = iblinds_v2 assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.window_blind_controller\")", "Controller v2.0 multilevel switch is discovered as a fan.\"\"\" node", "for device-specific schemas for the Z-Wave JS integration.\"\"\" async def", "assert state async def test_ge_12730(hass, client, ge_12730, integration): \"\"\"Test GE", "\"Unused\" state = hass.states.get(\"light.window_blind_controller\") assert not state state = hass.states.get(\"cover.window_blind_controller\")", "entities for device-specific schemas for the Z-Wave JS integration.\"\"\" async", "iblinds_v2, integration): \"\"\"Test that an iBlinds v2.0 multilevel switch value", "fan.\"\"\" node = ge_12730 assert node.device_class.specific.label == \"Multilevel Power Switch\"", "LZW36 Fan Controller multilevel switch endpoint 2 is discovered as", "JS integration.\"\"\" async def test_iblinds_v2(hass, client, iblinds_v2, integration): \"\"\"Test that", "client, iblinds_v2, integration): \"\"\"Test that an iBlinds v2.0 multilevel switch", "node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.family_room_combo\") assert state.state == \"off\"", "integration): \"\"\"Test LZW36 Fan Controller multilevel switch endpoint 2 is", "async def test_iblinds_v2(hass, client, iblinds_v2, integration): \"\"\"Test that an iBlinds", "== \"Multilevel Power Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\") assert not state", "= iblinds_v2 assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.window_blind_controller\") assert", "node.device_class.specific.label == \"Multilevel Power Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\") assert not", "state async def test_inovelli_lzw36(hass, client, inovelli_lzw36, integration): \"\"\"Test LZW36 Fan", "multilevel switch value is discovered as a cover.\"\"\" node =", "not state state = hass.states.get(\"cover.window_blind_controller\") assert state async def test_ge_12730(hass,", "is discovered as a fan.\"\"\" node = inovelli_lzw36 assert node.device_class.specific.label", "fan.\"\"\" node = inovelli_lzw36 assert node.device_class.specific.label == \"Unused\" state =", "\"\"\"Test discovery of entities for device-specific schemas for the Z-Wave", "switch value is discovered as a cover.\"\"\" node = iblinds_v2", "hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async def test_inovelli_lzw36(hass, client, inovelli_lzw36, integration): \"\"\"Test", "integration.\"\"\" async def test_iblinds_v2(hass, client, iblinds_v2, integration): \"\"\"Test that an", "integration): \"\"\"Test GE 12730 Fan Controller v2.0 multilevel switch is", "discovered as a fan.\"\"\" node = inovelli_lzw36 assert node.device_class.specific.label ==", "\"\"\"Test LZW36 Fan Controller multilevel switch endpoint 2 is discovered", "that an iBlinds v2.0 multilevel switch value is discovered as", "async def test_inovelli_lzw36(hass, client, inovelli_lzw36, integration): \"\"\"Test LZW36 Fan Controller", "= hass.states.get(\"light.in_wall_smart_fan_control\") assert not state state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert state", "a fan.\"\"\" node = inovelli_lzw36 assert node.device_class.specific.label == \"Unused\" state", "test_inovelli_lzw36(hass, client, inovelli_lzw36, integration): \"\"\"Test LZW36 Fan Controller multilevel switch", "iBlinds v2.0 multilevel switch value is discovered as a cover.\"\"\"", "\"\"\"Test GE 12730 Fan Controller v2.0 multilevel switch is discovered", "Z-Wave JS integration.\"\"\" async def test_iblinds_v2(hass, client, iblinds_v2, integration): \"\"\"Test", "ge_12730, integration): \"\"\"Test GE 12730 Fan Controller v2.0 multilevel switch", "12730 Fan Controller v2.0 multilevel switch is discovered as a", "the Z-Wave JS integration.\"\"\" async def test_iblinds_v2(hass, client, iblinds_v2, integration):", "is discovered as a cover.\"\"\" node = iblinds_v2 assert node.device_class.specific.label", "= inovelli_lzw36 assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.family_room_combo\") assert", "assert not state state = hass.states.get(\"cover.window_blind_controller\") assert state async def", "discovered as a cover.\"\"\" node = iblinds_v2 assert node.device_class.specific.label ==", "not state state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async def test_inovelli_lzw36(hass,", "a fan.\"\"\" node = ge_12730 assert node.device_class.specific.label == \"Multilevel Power", "device-specific schemas for the Z-Wave JS integration.\"\"\" async def test_iblinds_v2(hass,", "= ge_12730 assert node.device_class.specific.label == \"Multilevel Power Switch\" state =", "assert not state state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async def", "integration): \"\"\"Test that an iBlinds v2.0 multilevel switch value is", "assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.family_room_combo\") assert state.state ==", "hass.states.get(\"light.window_blind_controller\") assert not state state = hass.states.get(\"cover.window_blind_controller\") assert state async", "iblinds_v2 assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.window_blind_controller\") assert not", "Power Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\") assert not state state =", "2 is discovered as a fan.\"\"\" node = inovelli_lzw36 assert", "def test_inovelli_lzw36(hass, client, inovelli_lzw36, integration): \"\"\"Test LZW36 Fan Controller multilevel", "assert node.device_class.specific.label == \"Multilevel Power Switch\" state = hass.states.get(\"light.in_wall_smart_fan_control\") assert", "Fan Controller multilevel switch endpoint 2 is discovered as a", "cover.\"\"\" node = iblinds_v2 assert node.device_class.specific.label == \"Unused\" state =", "= hass.states.get(\"light.window_blind_controller\") assert not state state = hass.states.get(\"cover.window_blind_controller\") assert state", "state = hass.states.get(\"light.in_wall_smart_fan_control\") assert not state state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert", "state state = hass.states.get(\"fan.in_wall_smart_fan_control\") assert state async def test_inovelli_lzw36(hass, client,", "= hass.states.get(\"cover.window_blind_controller\") assert state async def test_ge_12730(hass, client, ge_12730, integration):", "== \"Unused\" state = hass.states.get(\"light.family_room_combo\") assert state.state == \"off\" state", "def test_iblinds_v2(hass, client, iblinds_v2, integration): \"\"\"Test that an iBlinds v2.0", "\"Unused\" state = hass.states.get(\"light.family_room_combo\") assert state.state == \"off\" state =", "as a fan.\"\"\" node = ge_12730 assert node.device_class.specific.label == \"Multilevel", "hass.states.get(\"light.family_room_combo\") assert state.state == \"off\" state = hass.states.get(\"fan.family_room_combo_2\") assert state", "client, ge_12730, integration): \"\"\"Test GE 12730 Fan Controller v2.0 multilevel", "assert state async def test_inovelli_lzw36(hass, client, inovelli_lzw36, integration): \"\"\"Test LZW36", "async def test_ge_12730(hass, client, ge_12730, integration): \"\"\"Test GE 12730 Fan", "discovered as a fan.\"\"\" node = ge_12730 assert node.device_class.specific.label ==", "node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.window_blind_controller\") assert not state state", "inovelli_lzw36, integration): \"\"\"Test LZW36 Fan Controller multilevel switch endpoint 2", "assert node.device_class.specific.label == \"Unused\" state = hass.states.get(\"light.window_blind_controller\") assert not state", "a cover.\"\"\" node = iblinds_v2 assert node.device_class.specific.label == \"Unused\" state", "state = hass.states.get(\"cover.window_blind_controller\") assert state async def test_ge_12730(hass, client, ge_12730,", "state = hass.states.get(\"light.window_blind_controller\") assert not state state = hass.states.get(\"cover.window_blind_controller\") assert", "an iBlinds v2.0 multilevel switch value is discovered as a", "test_iblinds_v2(hass, client, iblinds_v2, integration): \"\"\"Test that an iBlinds v2.0 multilevel", "== \"Unused\" state = hass.states.get(\"light.window_blind_controller\") assert not state state =" ]
[ "Dict = None) -> Dict: pass def list_invitations(self, MaxResults: int", "Dict: pass def get_paginator(self, operation_name: str = None) -> Paginator:", "AccountIds: List, DetectorId: str) -> Dict: pass def get_paginator(self, operation_name:", "Dict, Name: str, Action: str = None, ClientToken: str =", "None, NextToken: str = None, OnlyAssociated: str = None) ->", "Activate: bool, DetectorId: str, Format: str, Location: str, Name: str,", "get_findings(self, DetectorId: str, FindingIds: List, SortCriteria: Dict = None) ->", "def get_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def", "pass def get_filter(self, DetectorId: str, FilterName: str) -> Dict: pass", "= None): pass def get_detector(self, DetectorId: str) -> Dict: pass", "pass def can_paginate(self, operation_name: str = None): pass def create_detector(self,", "str, Name: str, ClientToken: str = None) -> Dict: pass", "get_detector(self, DetectorId: str) -> Dict: pass def get_filter(self, DetectorId: str,", "str, Activate: bool = None, Location: str = None, Name:", "int = None, NextToken: str = None, SortCriteria: Dict =", "None, ExpiresIn: int = None, HttpMethod: str = None): pass", "create_sample_findings(self, DetectorId: str, FindingTypes: List = None) -> Dict: pass", "= None) -> Dict: pass def create_members(self, AccountDetails: List, DetectorId:", "Params: Dict = None, ExpiresIn: int = None, HttpMethod: str", "Paginator from botocore.waiter import Waiter from typing import List class", "FindingPublishingFrequency: str = None) -> Dict: pass def create_filter(self, DetectorId:", "FindingIds: List, SortCriteria: Dict = None) -> Dict: pass def", "str = None, FindingPublishingFrequency: str = None) -> Dict: pass", "Dict: pass def disassociate_members(self, AccountIds: List, DetectorId: str) -> Dict:", "get_waiter(self, waiter_name: str = None) -> Waiter: pass def invite_members(self,", "str) -> Dict: pass def delete_members(self, AccountIds: List, DetectorId: str)", "pass def list_findings(self, DetectorId: str, FindingCriteria: Dict = None, MaxResults:", "accept_invitation(self, DetectorId: str, InvitationId: str, MasterId: str) -> Dict: pass", "= None, Description: str = None, FindingCriteria: Dict = None,", "= None, HttpMethod: str = None): pass def get_detector(self, DetectorId:", "def list_ip_sets(self, DetectorId: str, MaxResults: int = None, NextToken: str", "from typing import List class Client(BaseClient): def accept_invitation(self, DetectorId: str,", "None) -> Dict: pass def create_threat_intel_set(self, Activate: bool, DetectorId: str,", "FilterName: str) -> Dict: pass def delete_invitations(self, AccountIds: List) ->", "def get_ip_set(self, DetectorId: str, IpSetId: str) -> Dict: pass def", "import Dict from typing import Union from botocore.paginate import Paginator", "-> Dict: pass def delete_ip_set(self, DetectorId: str, IpSetId: str) ->", "pass def list_invitations(self, MaxResults: int = None, NextToken: str =", "= None) -> Dict: pass def create_filter(self, DetectorId: str, FindingCriteria:", "pass def get_waiter(self, waiter_name: str = None) -> Waiter: pass", "def create_sample_findings(self, DetectorId: str, FindingTypes: List = None) -> Dict:", "NextToken: str = None, SortCriteria: Dict = None) -> Dict:", "pass def update_findings_feedback(self, DetectorId: str, Feedback: str, FindingIds: List, Comments:", "Optional from botocore.client import BaseClient from typing import Dict from", "= None) -> Dict: pass def list_ip_sets(self, DetectorId: str, MaxResults:", "NextToken: str = None) -> Dict: pass def list_filters(self, DetectorId:", "typing import List class Client(BaseClient): def accept_invitation(self, DetectorId: str, InvitationId:", "def create_filter(self, DetectorId: str, FindingCriteria: Dict, Name: str, Action: str", "Activate: bool = None, Location: str = None, Name: str", "str, Format: str, Location: str, Name: str, ClientToken: str =", "ClientMethod: str = None, Params: Dict = None, ExpiresIn: int", "botocore.client import BaseClient from typing import Dict from typing import", "= None, Description: str = None, Rank: int = None)", "def get_waiter(self, waiter_name: str = None) -> Waiter: pass def", "str) -> Dict: pass def delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str)", "operation_name: str = None) -> Paginator: pass def get_threat_intel_set(self, DetectorId:", "ThreatIntelSetId: str) -> Dict: pass def disassociate_from_master_account(self, DetectorId: str) ->", "= None) -> Paginator: pass def get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId:", "= None) -> Dict: pass def list_filters(self, DetectorId: str, MaxResults:", "pass def create_filter(self, DetectorId: str, FindingCriteria: Dict, Name: str, Action:", "Description: str = None, FindingCriteria: Dict = None, Rank: int", "= None, NextToken: str = None) -> Dict: pass def", "FindingCriteria: Dict, Name: str, Action: str = None, ClientToken: str", "List, DetectorId: str) -> Dict: pass def delete_threat_intel_set(self, DetectorId: str,", "DetectorId: str, FindingStatisticTypes: List, FindingCriteria: Dict = None) -> Dict:", "delete_detector(self, DetectorId: str) -> Dict: pass def delete_filter(self, DetectorId: str,", "-> Dict: pass def unarchive_findings(self, DetectorId: str, FindingIds: List) ->", "pass def update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str, Activate: bool =", "= None, ClientToken: str = None, Description: str = None,", "str, FindingCriteria: Dict, Name: str, Action: str = None, ClientToken:", "Message: str = None) -> Dict: pass def list_detectors(self, MaxResults:", "DetectorId: str) -> Dict: pass def delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId:", "List) -> Dict: pass def update_detector(self, DetectorId: str, Enable: bool", "= None) -> Dict: pass def get_invitations_count(self) -> Dict: pass", "-> Dict: pass def create_filter(self, DetectorId: str, FindingCriteria: Dict, Name:", "def get_findings_statistics(self, DetectorId: str, FindingStatisticTypes: List, FindingCriteria: Dict = None)", "str) -> Dict: pass def archive_findings(self, DetectorId: str, FindingIds: List)", "str, FindingIds: List, SortCriteria: Dict = None) -> Dict: pass", "str = None) -> Dict: pass def decline_invitations(self, AccountIds: List)", "update_filter(self, DetectorId: str, FilterName: str, Action: str = None, Description:", "Dict: pass def delete_invitations(self, AccountIds: List) -> Dict: pass def", "-> Dict: pass def decline_invitations(self, AccountIds: List) -> Dict: pass", "None, Params: Dict = None, ExpiresIn: int = None, HttpMethod:", "pass def get_invitations_count(self) -> Dict: pass def get_ip_set(self, DetectorId: str,", "from typing import Union from botocore.paginate import Paginator from botocore.waiter", "AccountIds: List, DetectorId: str) -> Dict: pass def generate_presigned_url(self, ClientMethod:", "pass def create_threat_intel_set(self, Activate: bool, DetectorId: str, Format: str, Location:", "pass def unarchive_findings(self, DetectorId: str, FindingIds: List) -> Dict: pass", "str = None) -> Dict: pass def list_ip_sets(self, DetectorId: str,", "import Paginator from botocore.waiter import Waiter from typing import List", "get_ip_set(self, DetectorId: str, IpSetId: str) -> Dict: pass def get_master_account(self,", "-> Dict: pass def get_paginator(self, operation_name: str = None) ->", "Dict: pass def delete_detector(self, DetectorId: str) -> Dict: pass def", "None, NextToken: str = None) -> Dict: pass def start_monitoring_members(self,", "Dict: pass def generate_presigned_url(self, ClientMethod: str = None, Params: Dict", "create_ip_set(self, Activate: bool, DetectorId: str, Format: str, Location: str, Name:", "Dict: pass def list_threat_intel_sets(self, DetectorId: str, MaxResults: int = None,", "None, FindingPublishingFrequency: str = None) -> Dict: pass def create_filter(self,", "-> Dict: pass def list_detectors(self, MaxResults: int = None, NextToken:", "None) -> Dict: pass def list_findings(self, DetectorId: str, FindingCriteria: Dict", "get_filter(self, DetectorId: str, FilterName: str) -> Dict: pass def get_findings(self,", "None) -> Dict: pass def create_members(self, AccountDetails: List, DetectorId: str)", "Dict: pass def update_detector(self, DetectorId: str, Enable: bool = None,", "Dict: pass def start_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict:", "None, NextToken: str = None, SortCriteria: Dict = None) ->", "str) -> Dict: pass def disassociate_from_master_account(self, DetectorId: str) -> Dict:", "int = None) -> Dict: pass def create_ip_set(self, Activate: bool,", "pass def archive_findings(self, DetectorId: str, FindingIds: List) -> Dict: pass", "DetectorId: str, FindingCriteria: Dict = None, MaxResults: int = None,", "str, FindingIds: List, Comments: str = None) -> Dict: pass", "None, Description: str = None, Rank: int = None) ->", "int = None, HttpMethod: str = None): pass def get_detector(self,", "from botocore.paginate import Paginator from botocore.waiter import Waiter from typing", "List, DetectorId: str) -> Dict: pass def unarchive_findings(self, DetectorId: str,", "None) -> Dict: pass def list_invitations(self, MaxResults: int = None,", "typing import Dict from typing import Union from botocore.paginate import", "str, MaxResults: int = None, NextToken: str = None) ->", "= None, SortCriteria: Dict = None) -> Dict: pass def", "DetectorId: str, MaxResults: int = None, NextToken: str = None)", "FindingIds: List) -> Dict: pass def update_detector(self, DetectorId: str, Enable:", "-> Dict: pass def list_ip_sets(self, DetectorId: str, MaxResults: int =", "BaseClient from typing import Dict from typing import Union from", "List = None) -> Dict: pass def create_threat_intel_set(self, Activate: bool,", "InvitationId: str, MasterId: str) -> Dict: pass def archive_findings(self, DetectorId:", "= None, ExpiresIn: int = None, HttpMethod: str = None):", "get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict: pass def get_waiter(self,", "Paginator: pass def get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict:", "-> Dict: pass def delete_members(self, AccountIds: List, DetectorId: str) ->", "None, FindingCriteria: Dict = None, Rank: int = None) ->", "DetectorId: str) -> Dict: pass def create_sample_findings(self, DetectorId: str, FindingTypes:", "-> Dict: pass def list_threat_intel_sets(self, DetectorId: str, MaxResults: int =", "Union from botocore.paginate import Paginator from botocore.waiter import Waiter from", "None) -> Dict: pass def get_invitations_count(self) -> Dict: pass def", "def unarchive_findings(self, DetectorId: str, FindingIds: List) -> Dict: pass def", "archive_findings(self, DetectorId: str, FindingIds: List) -> Dict: pass def can_paginate(self,", "FindingCriteria: Dict = None) -> Dict: pass def get_invitations_count(self) ->", "DisableEmailNotification: bool = None, Message: str = None) -> Dict:", "FindingTypes: List = None) -> Dict: pass def create_threat_intel_set(self, Activate:", "create_threat_intel_set(self, Activate: bool, DetectorId: str, Format: str, Location: str, Name:", "def delete_ip_set(self, DetectorId: str, IpSetId: str) -> Dict: pass def", "def create_ip_set(self, Activate: bool, DetectorId: str, Format: str, Location: str,", "def update_ip_set(self, DetectorId: str, IpSetId: str, Activate: bool = None,", "create_detector(self, Enable: bool, ClientToken: str = None, FindingPublishingFrequency: str =", "-> Dict: pass def delete_detector(self, DetectorId: str) -> Dict: pass", "list_filters(self, DetectorId: str, MaxResults: int = None, NextToken: str =", "import List class Client(BaseClient): def accept_invitation(self, DetectorId: str, InvitationId: str,", "<filename>boto3_type_annotations/boto3_type_annotations/guardduty/client.py from typing import Optional from botocore.client import BaseClient from", "Dict: pass def list_ip_sets(self, DetectorId: str, MaxResults: int = None,", "def list_members(self, DetectorId: str, MaxResults: int = None, NextToken: str", "from typing import Optional from botocore.client import BaseClient from typing", "None, Description: str = None, FindingCriteria: Dict = None, Rank:", "DetectorId: str, FilterName: str) -> Dict: pass def get_findings(self, DetectorId:", "pass def list_detectors(self, MaxResults: int = None, NextToken: str =", "str) -> Dict: pass def stop_monitoring_members(self, AccountIds: List, DetectorId: str)", "Dict = None, MaxResults: int = None, NextToken: str =", "None) -> Paginator: pass def get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str)", "update_findings_feedback(self, DetectorId: str, Feedback: str, FindingIds: List, Comments: str =", "pass def get_master_account(self, DetectorId: str) -> Dict: pass def get_members(self,", "create_members(self, AccountDetails: List, DetectorId: str) -> Dict: pass def create_sample_findings(self,", "= None) -> Dict: pass def get_findings_statistics(self, DetectorId: str, FindingStatisticTypes:", "get_invitations_count(self) -> Dict: pass def get_ip_set(self, DetectorId: str, IpSetId: str)", "delete_filter(self, DetectorId: str, FilterName: str) -> Dict: pass def delete_invitations(self,", "str, FilterName: str, Action: str = None, Description: str =", "def list_invitations(self, MaxResults: int = None, NextToken: str = None)", "str, MaxResults: int = None, NextToken: str = None, OnlyAssociated:", "List, SortCriteria: Dict = None) -> Dict: pass def get_findings_statistics(self,", "= None, Params: Dict = None, ExpiresIn: int = None,", "List, Comments: str = None) -> Dict: pass def update_ip_set(self,", "None) -> Dict: pass def list_filters(self, DetectorId: str, MaxResults: int", "pass def create_detector(self, Enable: bool, ClientToken: str = None, FindingPublishingFrequency:", "DetectorId: str, Format: str, Location: str, Name: str, ClientToken: str", "Dict: pass def disassociate_from_master_account(self, DetectorId: str) -> Dict: pass def", "Dict: pass def create_threat_intel_set(self, Activate: bool, DetectorId: str, Format: str,", "str, FindingCriteria: Dict = None, MaxResults: int = None, NextToken:", "operation_name: str = None): pass def create_detector(self, Enable: bool, ClientToken:", "None) -> Dict: pass def get_findings_statistics(self, DetectorId: str, FindingStatisticTypes: List,", "from typing import Dict from typing import Union from botocore.paginate", "def delete_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def", "get_paginator(self, operation_name: str = None) -> Paginator: pass def get_threat_intel_set(self,", "unarchive_findings(self, DetectorId: str, FindingIds: List) -> Dict: pass def update_detector(self,", "= None, Name: str = None) -> Dict: pass def", "-> Dict: pass def list_findings(self, DetectorId: str, FindingCriteria: Dict =", "IpSetId: str) -> Dict: pass def delete_members(self, AccountIds: List, DetectorId:", "typing import Optional from botocore.client import BaseClient from typing import", "str, FindingTypes: List = None) -> Dict: pass def create_threat_intel_set(self,", "Dict = None, Rank: int = None) -> Dict: pass", "Dict: pass def get_members(self, AccountIds: List, DetectorId: str) -> Dict:", "Dict: pass def get_ip_set(self, DetectorId: str, IpSetId: str) -> Dict:", "str, DisableEmailNotification: bool = None, Message: str = None) ->", "Format: str, Location: str, Name: str, ClientToken: str = None)", "def can_paginate(self, operation_name: str = None): pass def create_detector(self, Enable:", "def accept_invitation(self, DetectorId: str, InvitationId: str, MasterId: str) -> Dict:", "str, Action: str = None, ClientToken: str = None, Description:", "Dict: pass def get_invitations_count(self) -> Dict: pass def get_ip_set(self, DetectorId:", "pass def get_ip_set(self, DetectorId: str, IpSetId: str) -> Dict: pass", "= None) -> Dict: pass def start_monitoring_members(self, AccountIds: List, DetectorId:", "from botocore.client import BaseClient from typing import Dict from typing", "DetectorId: str, ThreatIntelSetId: str, Activate: bool = None, Location: str", "str) -> Dict: pass def delete_filter(self, DetectorId: str, FilterName: str)", "pass def invite_members(self, AccountIds: List, DetectorId: str, DisableEmailNotification: bool =", "typing import Union from botocore.paginate import Paginator from botocore.waiter import", "pass def get_findings(self, DetectorId: str, FindingIds: List, SortCriteria: Dict =", "bool, ClientToken: str = None, FindingPublishingFrequency: str = None) ->", "def list_threat_intel_sets(self, DetectorId: str, MaxResults: int = None, NextToken: str", "def list_detectors(self, MaxResults: int = None, NextToken: str = None)", "Dict: pass def get_waiter(self, waiter_name: str = None) -> Waiter:", "= None, Location: str = None, Name: str = None)", "str = None) -> Waiter: pass def invite_members(self, AccountIds: List,", "bool = None, FindingPublishingFrequency: str = None) -> Dict: pass", "generate_presigned_url(self, ClientMethod: str = None, Params: Dict = None, ExpiresIn:", "DetectorId: str) -> Dict: pass def disassociate_members(self, AccountIds: List, DetectorId:", "Dict: pass def create_filter(self, DetectorId: str, FindingCriteria: Dict, Name: str,", "str) -> Dict: pass def get_waiter(self, waiter_name: str = None)", "pass def delete_members(self, AccountIds: List, DetectorId: str) -> Dict: pass", "list_ip_sets(self, DetectorId: str, MaxResults: int = None, NextToken: str =", "list_threat_intel_sets(self, DetectorId: str, MaxResults: int = None, NextToken: str =", "update_detector(self, DetectorId: str, Enable: bool = None, FindingPublishingFrequency: str =", "Dict: pass def delete_members(self, AccountIds: List, DetectorId: str) -> Dict:", "None) -> Dict: pass def list_detectors(self, MaxResults: int = None,", "Description: str = None, Rank: int = None) -> Dict:", "DetectorId: str) -> Dict: pass def get_paginator(self, operation_name: str =", "-> Paginator: pass def get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) ->", "List, DetectorId: str, DisableEmailNotification: bool = None, Message: str =", "str = None) -> Dict: pass def start_monitoring_members(self, AccountIds: List,", "-> Dict: pass def update_ip_set(self, DetectorId: str, IpSetId: str, Activate:", "pass def get_members(self, AccountIds: List, DetectorId: str) -> Dict: pass", "str, ThreatIntelSetId: str) -> Dict: pass def get_waiter(self, waiter_name: str", "= None, FindingCriteria: Dict = None, Rank: int = None)", "str = None) -> Dict: pass def create_members(self, AccountDetails: List,", "-> Dict: pass def create_threat_intel_set(self, Activate: bool, DetectorId: str, Format:", "get_master_account(self, DetectorId: str) -> Dict: pass def get_members(self, AccountIds: List,", "FindingCriteria: Dict = None, Rank: int = None) -> Dict:", "str, MasterId: str) -> Dict: pass def archive_findings(self, DetectorId: str,", "stop_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def unarchive_findings(self,", "None, NextToken: str = None) -> Dict: pass def list_members(self,", "-> Dict: pass def generate_presigned_url(self, ClientMethod: str = None, Params:", "def get_paginator(self, operation_name: str = None) -> Paginator: pass def", "from botocore.waiter import Waiter from typing import List class Client(BaseClient):", "None, NextToken: str = None) -> Dict: pass def list_findings(self,", "delete_invitations(self, AccountIds: List) -> Dict: pass def delete_ip_set(self, DetectorId: str,", "def get_findings(self, DetectorId: str, FindingIds: List, SortCriteria: Dict = None)", "IpSetId: str) -> Dict: pass def get_master_account(self, DetectorId: str) ->", "List) -> Dict: pass def delete_detector(self, DetectorId: str) -> Dict:", "SortCriteria: Dict = None) -> Dict: pass def list_invitations(self, MaxResults:", "None) -> Dict: pass def decline_invitations(self, AccountIds: List) -> Dict:", "= None) -> Dict: pass def list_findings(self, DetectorId: str, FindingCriteria:", "List, DetectorId: str) -> Dict: pass def generate_presigned_url(self, ClientMethod: str", "str = None) -> Dict: pass def list_findings(self, DetectorId: str,", "-> Dict: pass def delete_filter(self, DetectorId: str, FilterName: str) ->", "Dict from typing import Union from botocore.paginate import Paginator from", "list_findings(self, DetectorId: str, FindingCriteria: Dict = None, MaxResults: int =", "def update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str, Activate: bool = None,", "= None) -> Waiter: pass def invite_members(self, AccountIds: List, DetectorId:", "Waiter from typing import List class Client(BaseClient): def accept_invitation(self, DetectorId:", "DetectorId: str, FilterName: str, Action: str = None, Description: str", "pass def get_paginator(self, operation_name: str = None) -> Paginator: pass", "def delete_invitations(self, AccountIds: List) -> Dict: pass def delete_ip_set(self, DetectorId:", "None, Message: str = None) -> Dict: pass def list_detectors(self,", "str) -> Dict: pass def unarchive_findings(self, DetectorId: str, FindingIds: List)", "Dict: pass def create_sample_findings(self, DetectorId: str, FindingTypes: List = None)", "def get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict: pass def", "Dict: pass def delete_filter(self, DetectorId: str, FilterName: str) -> Dict:", "def create_members(self, AccountDetails: List, DetectorId: str) -> Dict: pass def", "None) -> Dict: pass def list_members(self, DetectorId: str, MaxResults: int", "= None) -> Dict: pass def list_threat_intel_sets(self, DetectorId: str, MaxResults:", "None) -> Dict: pass def update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str,", "str, ClientToken: str = None) -> Dict: pass def create_members(self,", "str, Enable: bool = None, FindingPublishingFrequency: str = None) ->", "str = None) -> Dict: pass def create_filter(self, DetectorId: str,", "-> Dict: pass def update_detector(self, DetectorId: str, Enable: bool =", "invite_members(self, AccountIds: List, DetectorId: str, DisableEmailNotification: bool = None, Message:", "-> Dict: pass def create_ip_set(self, Activate: bool, DetectorId: str, Format:", "DetectorId: str) -> Dict: pass def stop_monitoring_members(self, AccountIds: List, DetectorId:", "pass def decline_invitations(self, AccountIds: List) -> Dict: pass def delete_detector(self,", "Location: str = None, Name: str = None) -> Dict:", "DetectorId: str) -> Dict: pass def get_filter(self, DetectorId: str, FilterName:", "= None, FindingPublishingFrequency: str = None) -> Dict: pass def", "ClientToken: str = None, Description: str = None, Rank: int", "-> Dict: pass def create_members(self, AccountDetails: List, DetectorId: str) ->", "str, ThreatIntelSetId: str, Activate: bool = None, Location: str =", "-> Dict: pass def delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) ->", "Dict: pass def list_members(self, DetectorId: str, MaxResults: int = None,", "Dict: pass def can_paginate(self, operation_name: str = None): pass def", "List) -> Dict: pass def delete_ip_set(self, DetectorId: str, IpSetId: str)", "DetectorId: str, DisableEmailNotification: bool = None, Message: str = None)", "delete_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def delete_threat_intel_set(self,", "FilterName: str) -> Dict: pass def get_findings(self, DetectorId: str, FindingIds:", "-> Dict: pass def start_monitoring_members(self, AccountIds: List, DetectorId: str) ->", "str = None, Description: str = None, FindingCriteria: Dict =", "list_invitations(self, MaxResults: int = None, NextToken: str = None) ->", "Dict: pass def list_findings(self, DetectorId: str, FindingCriteria: Dict = None,", "DetectorId: str, FindingCriteria: Dict, Name: str, Action: str = None,", "pass def delete_ip_set(self, DetectorId: str, IpSetId: str) -> Dict: pass", "-> Dict: pass def update_filter(self, DetectorId: str, FilterName: str, Action:", "str, FindingStatisticTypes: List, FindingCriteria: Dict = None) -> Dict: pass", "Dict: pass def create_members(self, AccountDetails: List, DetectorId: str) -> Dict:", "None) -> Dict: pass def list_ip_sets(self, DetectorId: str, MaxResults: int", "= None): pass def create_detector(self, Enable: bool, ClientToken: str =", "DetectorId: str, Enable: bool = None, FindingPublishingFrequency: str = None)", "Dict: pass def stop_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict:", "ThreatIntelSetId: str, Activate: bool = None, Location: str = None,", "str, Location: str, Name: str, ClientToken: str = None) ->", "Feedback: str, FindingIds: List, Comments: str = None) -> Dict:", "disassociate_from_master_account(self, DetectorId: str) -> Dict: pass def disassociate_members(self, AccountIds: List,", "= None, OnlyAssociated: str = None) -> Dict: pass def", "AccountIds: List, DetectorId: str) -> Dict: pass def delete_threat_intel_set(self, DetectorId:", "FindingStatisticTypes: List, FindingCriteria: Dict = None) -> Dict: pass def", "str, IpSetId: str) -> Dict: pass def get_master_account(self, DetectorId: str)", "Dict: pass def list_invitations(self, MaxResults: int = None, NextToken: str", "pass def get_findings_statistics(self, DetectorId: str, FindingStatisticTypes: List, FindingCriteria: Dict =", "-> Dict: pass def get_waiter(self, waiter_name: str = None) ->", "= None) -> Dict: pass def list_invitations(self, MaxResults: int =", "FindingPublishingFrequency: str = None) -> Dict: pass def update_filter(self, DetectorId:", "DetectorId: str, ThreatIntelSetId: str) -> Dict: pass def disassociate_from_master_account(self, DetectorId:", "-> Dict: pass def stop_monitoring_members(self, AccountIds: List, DetectorId: str) ->", "-> Dict: pass def get_findings_statistics(self, DetectorId: str, FindingStatisticTypes: List, FindingCriteria:", "Name: str, Action: str = None, ClientToken: str = None,", "NextToken: str = None, OnlyAssociated: str = None) -> Dict:", "None, Location: str = None, Name: str = None) ->", "IpSetId: str, Activate: bool = None, Location: str = None,", "def list_findings(self, DetectorId: str, FindingCriteria: Dict = None, MaxResults: int", "str = None) -> Dict: pass def list_threat_intel_sets(self, DetectorId: str,", "OnlyAssociated: str = None) -> Dict: pass def list_threat_intel_sets(self, DetectorId:", "Dict = None, ExpiresIn: int = None, HttpMethod: str =", "Name: str, ClientToken: str = None) -> Dict: pass def", "DetectorId: str) -> Dict: pass def unarchive_findings(self, DetectorId: str, FindingIds:", "str = None) -> Dict: pass def update_filter(self, DetectorId: str,", "str = None) -> Dict: pass def list_members(self, DetectorId: str,", "import Union from botocore.paginate import Paginator from botocore.waiter import Waiter", "-> Dict: pass def disassociate_from_master_account(self, DetectorId: str) -> Dict: pass", "DetectorId: str, FindingTypes: List = None) -> Dict: pass def", "= None) -> Dict: pass def decline_invitations(self, AccountIds: List) ->", "import Optional from botocore.client import BaseClient from typing import Dict", "-> Dict: pass def get_findings(self, DetectorId: str, FindingIds: List, SortCriteria:", "str) -> Dict: pass def get_master_account(self, DetectorId: str) -> Dict:", "str = None, Rank: int = None) -> Dict: pass", "= None) -> Dict: pass def list_members(self, DetectorId: str, MaxResults:", "DetectorId: str, FindingIds: List, SortCriteria: Dict = None) -> Dict:", "None, FindingPublishingFrequency: str = None) -> Dict: pass def update_filter(self,", "str, ClientToken: str = None) -> Dict: pass def decline_invitations(self,", "Dict: pass def delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict:", "DetectorId: str) -> Dict: pass def get_members(self, AccountIds: List, DetectorId:", "-> Dict: pass def list_filters(self, DetectorId: str, MaxResults: int =", "-> Dict: pass def update_findings_feedback(self, DetectorId: str, Feedback: str, FindingIds:", "str = None, Params: Dict = None, ExpiresIn: int =", "get_findings_statistics(self, DetectorId: str, FindingStatisticTypes: List, FindingCriteria: Dict = None) ->", "None): pass def create_detector(self, Enable: bool, ClientToken: str = None,", "DetectorId: str, InvitationId: str, MasterId: str) -> Dict: pass def", "-> Dict: pass def archive_findings(self, DetectorId: str, FindingIds: List) ->", "def delete_detector(self, DetectorId: str) -> Dict: pass def delete_filter(self, DetectorId:", "import Waiter from typing import List class Client(BaseClient): def accept_invitation(self,", "None, NextToken: str = None) -> Dict: pass def list_filters(self,", "-> Dict: pass def delete_invitations(self, AccountIds: List) -> Dict: pass", "pass def create_ip_set(self, Activate: bool, DetectorId: str, Format: str, Location:", "str, FindingIds: List) -> Dict: pass def update_detector(self, DetectorId: str,", "ThreatIntelSetId: str) -> Dict: pass def get_waiter(self, waiter_name: str =", "MaxResults: int = None, NextToken: str = None, SortCriteria: Dict", "= None, Rank: int = None) -> Dict: pass def", "-> Dict: pass def create_sample_findings(self, DetectorId: str, FindingTypes: List =", "str, IpSetId: str) -> Dict: pass def delete_members(self, AccountIds: List,", "None) -> Dict: pass def list_threat_intel_sets(self, DetectorId: str, MaxResults: int", "List, DetectorId: str) -> Dict: pass def get_paginator(self, operation_name: str", "-> Dict: pass def get_master_account(self, DetectorId: str) -> Dict: pass", "def delete_filter(self, DetectorId: str, FilterName: str) -> Dict: pass def", "-> Dict: pass def list_invitations(self, MaxResults: int = None, NextToken:", "DetectorId: str, MaxResults: int = None, NextToken: str = None,", "= None, NextToken: str = None, SortCriteria: Dict = None)", "None) -> Dict: pass def start_monitoring_members(self, AccountIds: List, DetectorId: str)", "def update_findings_feedback(self, DetectorId: str, Feedback: str, FindingIds: List, Comments: str", "Dict: pass def unarchive_findings(self, DetectorId: str, FindingIds: List) -> Dict:", "int = None, NextToken: str = None) -> Dict: pass", "= None) -> Dict: pass def list_detectors(self, MaxResults: int =", "None, SortCriteria: Dict = None) -> Dict: pass def list_invitations(self,", "def create_threat_intel_set(self, Activate: bool, DetectorId: str, Format: str, Location: str,", "delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict: pass def disassociate_from_master_account(self,", "waiter_name: str = None) -> Waiter: pass def invite_members(self, AccountIds:", "Waiter: pass def invite_members(self, AccountIds: List, DetectorId: str, DisableEmailNotification: bool", "List, DetectorId: str) -> Dict: pass def stop_monitoring_members(self, AccountIds: List,", "-> Dict: pass def list_members(self, DetectorId: str, MaxResults: int =", "SortCriteria: Dict = None) -> Dict: pass def get_findings_statistics(self, DetectorId:", "str, InvitationId: str, MasterId: str) -> Dict: pass def archive_findings(self,", "DetectorId: str, FindingIds: List) -> Dict: pass def update_detector(self, DetectorId:", "None) -> Waiter: pass def invite_members(self, AccountIds: List, DetectorId: str,", "Dict: pass def get_findings(self, DetectorId: str, FindingIds: List, SortCriteria: Dict", "NextToken: str = None) -> Dict: pass def list_members(self, DetectorId:", "update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str, Activate: bool = None, Location:", "str = None, SortCriteria: Dict = None) -> Dict: pass", "bool = None, Location: str = None, Name: str =", "pass def update_filter(self, DetectorId: str, FilterName: str, Action: str =", "Dict: pass def archive_findings(self, DetectorId: str, FindingIds: List) -> Dict:", "AccountDetails: List, DetectorId: str) -> Dict: pass def create_sample_findings(self, DetectorId:", "Rank: int = None) -> Dict: pass def create_ip_set(self, Activate:", "str) -> Dict: pass def generate_presigned_url(self, ClientMethod: str = None,", "List, DetectorId: str) -> Dict: pass def create_sample_findings(self, DetectorId: str,", "= None) -> Dict: pass def update_filter(self, DetectorId: str, FilterName:", "pass def list_threat_intel_sets(self, DetectorId: str, MaxResults: int = None, NextToken:", "Dict: pass def update_ip_set(self, DetectorId: str, IpSetId: str, Activate: bool", "= None) -> Dict: pass def update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId:", "Dict: pass def update_findings_feedback(self, DetectorId: str, Feedback: str, FindingIds: List,", "Dict: pass def decline_invitations(self, AccountIds: List) -> Dict: pass def", "None) -> Dict: pass def update_findings_feedback(self, DetectorId: str, Feedback: str,", "str = None): pass def get_detector(self, DetectorId: str) -> Dict:", "def get_master_account(self, DetectorId: str) -> Dict: pass def get_members(self, AccountIds:", "= None) -> Dict: pass def create_ip_set(self, Activate: bool, DetectorId:", "Name: str = None) -> Dict: pass def update_threat_intel_set(self, DetectorId:", "None, Rank: int = None) -> Dict: pass def create_ip_set(self,", "Dict = None) -> Dict: pass def get_findings_statistics(self, DetectorId: str,", "MaxResults: int = None, NextToken: str = None, OnlyAssociated: str", "int = None) -> Dict: pass def update_findings_feedback(self, DetectorId: str,", "FindingIds: List) -> Dict: pass def can_paginate(self, operation_name: str =", "pass def update_detector(self, DetectorId: str, Enable: bool = None, FindingPublishingFrequency:", "str) -> Dict: pass def delete_invitations(self, AccountIds: List) -> Dict:", "start_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def stop_monitoring_members(self,", "pass def delete_detector(self, DetectorId: str) -> Dict: pass def delete_filter(self,", "str = None, FindingCriteria: Dict = None, Rank: int =", "NextToken: str = None) -> Dict: pass def list_findings(self, DetectorId:", "= None, Message: str = None) -> Dict: pass def", "-> Dict: pass def get_members(self, AccountIds: List, DetectorId: str) ->", "= None) -> Dict: pass def update_ip_set(self, DetectorId: str, IpSetId:", "str = None, ClientToken: str = None, Description: str =", "str) -> Dict: pass def get_paginator(self, operation_name: str = None)", "pass def stop_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict: pass", "str) -> Dict: pass def get_findings(self, DetectorId: str, FindingIds: List,", "AccountIds: List, DetectorId: str) -> Dict: pass def stop_monitoring_members(self, AccountIds:", "def get_detector(self, DetectorId: str) -> Dict: pass def get_filter(self, DetectorId:", "List, FindingCriteria: Dict = None) -> Dict: pass def get_invitations_count(self)", "def disassociate_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def", "Client(BaseClient): def accept_invitation(self, DetectorId: str, InvitationId: str, MasterId: str) ->", "Comments: str = None) -> Dict: pass def update_ip_set(self, DetectorId:", "disassociate_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def generate_presigned_url(self,", "str = None) -> Dict: pass def list_filters(self, DetectorId: str,", "can_paginate(self, operation_name: str = None): pass def create_detector(self, Enable: bool,", "botocore.paginate import Paginator from botocore.waiter import Waiter from typing import", "FindingCriteria: Dict = None, MaxResults: int = None, NextToken: str", "def archive_findings(self, DetectorId: str, FindingIds: List) -> Dict: pass def", "str) -> Dict: pass def get_filter(self, DetectorId: str, FilterName: str)", "AccountIds: List, DetectorId: str, DisableEmailNotification: bool = None, Message: str", "str, ThreatIntelSetId: str) -> Dict: pass def disassociate_from_master_account(self, DetectorId: str)", "list_detectors(self, MaxResults: int = None, NextToken: str = None) ->", "bool, DetectorId: str, Format: str, Location: str, Name: str, ClientToken:", "DetectorId: str, ThreatIntelSetId: str) -> Dict: pass def get_waiter(self, waiter_name:", "list_members(self, DetectorId: str, MaxResults: int = None, NextToken: str =", "delete_ip_set(self, DetectorId: str, IpSetId: str) -> Dict: pass def delete_members(self,", "-> Dict: pass def get_ip_set(self, DetectorId: str, IpSetId: str) ->", "str, Feedback: str, FindingIds: List, Comments: str = None) ->", "def update_detector(self, DetectorId: str, Enable: bool = None, FindingPublishingFrequency: str", "DetectorId: str) -> Dict: pass def delete_filter(self, DetectorId: str, FilterName:", "None, Name: str = None) -> Dict: pass def update_threat_intel_set(self,", "str = None, OnlyAssociated: str = None) -> Dict: pass", "List class Client(BaseClient): def accept_invitation(self, DetectorId: str, InvitationId: str, MasterId:", "ExpiresIn: int = None, HttpMethod: str = None): pass def", "Dict: pass def get_filter(self, DetectorId: str, FilterName: str) -> Dict:", "Rank: int = None) -> Dict: pass def update_findings_feedback(self, DetectorId:", "def get_invitations_count(self) -> Dict: pass def get_ip_set(self, DetectorId: str, IpSetId:", "DetectorId: str, IpSetId: str) -> Dict: pass def get_master_account(self, DetectorId:", "None) -> Dict: pass def update_filter(self, DetectorId: str, FilterName: str,", "FilterName: str, Action: str = None, Description: str = None,", "str = None, Name: str = None) -> Dict: pass", "str, FilterName: str) -> Dict: pass def get_findings(self, DetectorId: str,", "Action: str = None, Description: str = None, FindingCriteria: Dict", "def disassociate_from_master_account(self, DetectorId: str) -> Dict: pass def disassociate_members(self, AccountIds:", "str, Action: str = None, Description: str = None, FindingCriteria:", "AccountIds: List) -> Dict: pass def delete_ip_set(self, DetectorId: str, IpSetId:", "ClientToken: str = None, FindingPublishingFrequency: str = None) -> Dict:", "create_filter(self, DetectorId: str, FindingCriteria: Dict, Name: str, Action: str =", "None) -> Dict: pass def update_ip_set(self, DetectorId: str, IpSetId: str,", "None) -> Dict: pass def create_ip_set(self, Activate: bool, DetectorId: str,", "MasterId: str) -> Dict: pass def archive_findings(self, DetectorId: str, FindingIds:", "None): pass def get_detector(self, DetectorId: str) -> Dict: pass def", "None, OnlyAssociated: str = None) -> Dict: pass def list_threat_intel_sets(self,", "Enable: bool = None, FindingPublishingFrequency: str = None) -> Dict:", "ClientToken: str = None) -> Dict: pass def decline_invitations(self, AccountIds:", "str) -> Dict: pass def get_members(self, AccountIds: List, DetectorId: str)", "None) -> Dict: pass def create_filter(self, DetectorId: str, FindingCriteria: Dict,", "def decline_invitations(self, AccountIds: List) -> Dict: pass def delete_detector(self, DetectorId:", "get_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def get_paginator(self,", "None, ClientToken: str = None, Description: str = None, Rank:", "Dict = None) -> Dict: pass def get_invitations_count(self) -> Dict:", "Dict: pass def get_master_account(self, DetectorId: str) -> Dict: pass def", "bool = None, Message: str = None) -> Dict: pass", "str = None) -> Paginator: pass def get_threat_intel_set(self, DetectorId: str,", "str = None) -> Dict: pass def list_detectors(self, MaxResults: int", "Dict: pass def list_filters(self, DetectorId: str, MaxResults: int = None,", "str, FilterName: str) -> Dict: pass def delete_invitations(self, AccountIds: List)", "HttpMethod: str = None): pass def get_detector(self, DetectorId: str) ->", "def create_detector(self, Enable: bool, ClientToken: str = None, FindingPublishingFrequency: str", "pass def delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict: pass", "int = None, NextToken: str = None, OnlyAssociated: str =", "pass def update_ip_set(self, DetectorId: str, IpSetId: str, Activate: bool =", "str) -> Dict: pass def create_sample_findings(self, DetectorId: str, FindingTypes: List", "-> Dict: pass def disassociate_members(self, AccountIds: List, DetectorId: str) ->", "Location: str, Name: str, ClientToken: str = None) -> Dict:", "Dict: pass def list_detectors(self, MaxResults: int = None, NextToken: str", "Action: str = None, ClientToken: str = None, Description: str", "None, NextToken: str = None) -> Dict: pass def list_ip_sets(self,", "NextToken: str = None) -> Dict: pass def list_ip_sets(self, DetectorId:", "Enable: bool, ClientToken: str = None, FindingPublishingFrequency: str = None)", "botocore.waiter import Waiter from typing import List class Client(BaseClient): def", "-> Waiter: pass def invite_members(self, AccountIds: List, DetectorId: str, DisableEmailNotification:", "NextToken: str = None) -> Dict: pass def start_monitoring_members(self, AccountIds:", "List) -> Dict: pass def can_paginate(self, operation_name: str = None):", "DetectorId: str, IpSetId: str) -> Dict: pass def delete_members(self, AccountIds:", "AccountIds: List, DetectorId: str) -> Dict: pass def unarchive_findings(self, DetectorId:", "pass def disassociate_from_master_account(self, DetectorId: str) -> Dict: pass def disassociate_members(self,", "-> Dict: pass def get_invitations_count(self) -> Dict: pass def get_ip_set(self,", "pass def delete_invitations(self, AccountIds: List) -> Dict: pass def delete_ip_set(self,", "= None) -> Dict: pass def create_threat_intel_set(self, Activate: bool, DetectorId:", "-> Dict: pass def can_paginate(self, operation_name: str = None): pass", "MaxResults: int = None, NextToken: str = None) -> Dict:", "= None, NextToken: str = None, OnlyAssociated: str = None)", "FindingIds: List, Comments: str = None) -> Dict: pass def", "pass def create_sample_findings(self, DetectorId: str, FindingTypes: List = None) ->", "pass def start_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict: pass", "str, IpSetId: str, Activate: bool = None, Location: str =", "Dict: pass def update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str, Activate: bool", "str) -> Dict: pass def disassociate_members(self, AccountIds: List, DetectorId: str)", "pass def get_detector(self, DetectorId: str) -> Dict: pass def get_filter(self,", "pass def disassociate_members(self, AccountIds: List, DetectorId: str) -> Dict: pass", "def invite_members(self, AccountIds: List, DetectorId: str, DisableEmailNotification: bool = None,", "pass def generate_presigned_url(self, ClientMethod: str = None, Params: Dict =", "pass def list_members(self, DetectorId: str, MaxResults: int = None, NextToken:", "DetectorId: str, IpSetId: str, Activate: bool = None, Location: str", "pass def get_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict: pass", "Dict: pass def delete_ip_set(self, DetectorId: str, IpSetId: str) -> Dict:", "-> Dict: pass def get_filter(self, DetectorId: str, FilterName: str) ->", "pass def list_filters(self, DetectorId: str, MaxResults: int = None, NextToken:", "class Client(BaseClient): def accept_invitation(self, DetectorId: str, InvitationId: str, MasterId: str)", "ClientToken: str = None) -> Dict: pass def create_members(self, AccountDetails:", "def get_filter(self, DetectorId: str, FilterName: str) -> Dict: pass def", "DetectorId: str) -> Dict: pass def generate_presigned_url(self, ClientMethod: str =", "str, FindingIds: List) -> Dict: pass def can_paginate(self, operation_name: str", "def generate_presigned_url(self, ClientMethod: str = None, Params: Dict = None,", "Dict: pass def update_filter(self, DetectorId: str, FilterName: str, Action: str", "def stop_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def", "def delete_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str) -> Dict: pass def", "None, MaxResults: int = None, NextToken: str = None, SortCriteria:", "def start_monitoring_members(self, AccountIds: List, DetectorId: str) -> Dict: pass def", "None, Rank: int = None) -> Dict: pass def update_findings_feedback(self,", "str = None) -> Dict: pass def update_threat_intel_set(self, DetectorId: str,", "AccountIds: List) -> Dict: pass def delete_detector(self, DetectorId: str) ->", "update_ip_set(self, DetectorId: str, IpSetId: str, Activate: bool = None, Location:", "= None, MaxResults: int = None, NextToken: str = None,", "-> Dict: pass def update_threat_intel_set(self, DetectorId: str, ThreatIntelSetId: str, Activate:", "str = None): pass def create_detector(self, Enable: bool, ClientToken: str", "decline_invitations(self, AccountIds: List) -> Dict: pass def delete_detector(self, DetectorId: str)", "str = None, Description: str = None, Rank: int =", "Dict: pass def get_findings_statistics(self, DetectorId: str, FindingStatisticTypes: List, FindingCriteria: Dict", "str = None) -> Dict: pass def update_ip_set(self, DetectorId: str,", "DetectorId: str, FilterName: str) -> Dict: pass def delete_invitations(self, AccountIds:", "DetectorId: str, FindingIds: List) -> Dict: pass def can_paginate(self, operation_name:", "Dict: pass def create_ip_set(self, Activate: bool, DetectorId: str, Format: str,", "= None) -> Dict: pass def update_findings_feedback(self, DetectorId: str, Feedback:", "pass def list_ip_sets(self, DetectorId: str, MaxResults: int = None, NextToken:", "def update_filter(self, DetectorId: str, FilterName: str, Action: str = None,", "import BaseClient from typing import Dict from typing import Union", "pass def create_members(self, AccountDetails: List, DetectorId: str) -> Dict: pass", "DetectorId: str, Feedback: str, FindingIds: List, Comments: str = None)", "def list_filters(self, DetectorId: str, MaxResults: int = None, NextToken: str", "None, HttpMethod: str = None): pass def get_detector(self, DetectorId: str)", "pass def delete_filter(self, DetectorId: str, FilterName: str) -> Dict: pass" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "Raven Authors. All rights reserved. # # Licensed under the", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "distributed under the License is distributed on an \"AS IS\"", "from queue import Queue from threading import Thread from benchmark.workload.tpch", "under the License. from queue import Queue from threading import", "permissions and # limitations under the License. from queue import", "the specific language governing permissions and # limitations under the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "True: query = queue.get() print(query) if __name__ == '__main__': workload", "queue.get() print(query) if __name__ == '__main__': workload = TpchLoopWorkload() print(workload)", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= Queue() generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start()", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread =", "not use this file except in compliance with the License.", "= Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread = Thread(", "rights reserved. # # Licensed under the Apache License, Version", "queue = Queue() generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' )", "and # limitations under the License. from queue import Queue", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "__name__ == '__main__': workload = TpchLoopWorkload() print(workload) queue = Queue()", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "language governing permissions and # limitations under the License. from", "# limitations under the License. from queue import Queue from", "Thread from benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue: Queue): while True:", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "threading import Thread from benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue: Queue):", "reserved. # # Licensed under the Apache License, Version 2.0", "CONDITIONS OF ANY KIND, either express or implied. # See", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "governing permissions and # limitations under the License. from queue", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "print_queries(queue: Queue): while True: query = queue.get() print(query) if __name__", "under the License is distributed on an \"AS IS\" BASIS,", "print(workload) queue = Queue() generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator'", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "<gh_stars>1-10 # Copyright 2021 Raven Authors. All rights reserved. #", "name='QueryGenerator' ) generate_thread.start() print_thread = Thread( target=print_queries, args=(queue,), name='QueryPrinter' )", "the License for the specific language governing permissions and #", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "import TpchLoopWorkload def print_queries(queue: Queue): while True: query = queue.get()", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "the License is distributed on an \"AS IS\" BASIS, #", "benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue: Queue): while True: query =", "== '__main__': workload = TpchLoopWorkload() print(workload) queue = Queue() generate_thread", "in compliance with the License. # You may obtain a", "'__main__': workload = TpchLoopWorkload() print(workload) queue = Queue() generate_thread =", "software # distributed under the License is distributed on an", "the License. from queue import Queue from threading import Thread", "TpchLoopWorkload def print_queries(queue: Queue): while True: query = queue.get() print(query)", "# # Unless required by applicable law or agreed to", "args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread = Thread( target=print_queries, args=(queue,), name='QueryPrinter'", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "= TpchLoopWorkload() print(workload) queue = Queue() generate_thread = Thread( target=workload.generate_one_loop_queries,", "License. from queue import Queue from threading import Thread from", "workload = TpchLoopWorkload() print(workload) queue = Queue() generate_thread = Thread(", "Version 2.0 (the \"License\"); # you may not use this", "Queue() generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread", "# Copyright 2021 Raven Authors. All rights reserved. # #", "target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread = Thread( target=print_queries, args=(queue,),", "law or agreed to in writing, software # distributed under", ") generate_thread.start() print_thread = Thread( target=print_queries, args=(queue,), name='QueryPrinter' ) print_thread.start()", "queue import Queue from threading import Thread from benchmark.workload.tpch import", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"License\"); # you may not use this file except in", "TpchLoopWorkload() print(workload) queue = Queue() generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,),", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "query = queue.get() print(query) if __name__ == '__main__': workload =", "All rights reserved. # # Licensed under the Apache License,", "2021 Raven Authors. All rights reserved. # # Licensed under", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "Queue): while True: query = queue.get() print(query) if __name__ ==", "= queue.get() print(query) if __name__ == '__main__': workload = TpchLoopWorkload()", "Copyright 2021 Raven Authors. All rights reserved. # # Licensed", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "import Thread from benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue: Queue): while", "if __name__ == '__main__': workload = TpchLoopWorkload() print(workload) queue =", "while True: query = queue.get() print(query) if __name__ == '__main__':", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread = Thread( target=print_queries,", "from threading import Thread from benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue:", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "You may obtain a copy of the License at #", "print(query) if __name__ == '__main__': workload = TpchLoopWorkload() print(workload) queue", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "from benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue: Queue): while True: query", "required by applicable law or agreed to in writing, software", "Authors. All rights reserved. # # Licensed under the Apache", "def print_queries(queue: Queue): while True: query = queue.get() print(query) if", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "limitations under the License. from queue import Queue from threading", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "Queue from threading import Thread from benchmark.workload.tpch import TpchLoopWorkload def", "import Queue from threading import Thread from benchmark.workload.tpch import TpchLoopWorkload" ]
[ "class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ('collectionID',", "Meta: model = User fields = ('id', 'username', 'email', 'password',", "{'<PASSWORD>} } def create(self, validated_data): password = validated_data.pop('password', None) instance", "model = Own fields = ('ownID', 'user', 'art', 'duplicates') class", "serializers from .models import * class CollectionSerializer(serializers.ModelSerializer): class Meta: model", "= { 'password': {'<PASSWORD>} } def create(self, validated_data): password =", "= ('collectionID', 'name', 'display_name', 'description', 'img_url') class ArtSerializer(serializers.ModelSerializer): img_url =", "'thumb_url') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields =", "class OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField() class Meta: model = Own", "instance.set_password(password) instance.save() return instance class OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField() class", "validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password", "None: instance.set_password(password) instance.save() return instance class OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField()", "('ownID', 'user', 'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer): class Meta: model =", "'user', 'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale", "serializers.ReadOnlyField() class Meta: model = Art fields = ('artID', 'title',", "import serializers from .models import * class CollectionSerializer(serializers.ModelSerializer): class Meta:", "'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields", "Sale fields = ('saleID', 'seller', 'buyer', 'ownership', 'art', 'price', 'available',", "= Collection fields = ('collectionID', 'name', 'display_name', 'description', 'img_url') class", "class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id',", "= ('saleID', 'seller', 'buyer', 'ownership', 'art', 'price', 'available', 'sold', 'postDate',", "Meta: model = Art fields = ('artID', 'title', 'filename', 'rarity',", "model = User fields = ('id', 'username', 'email', 'password', 'coins',", "('saleID', 'seller', 'buyer', 'ownership', 'art', 'price', 'available', 'sold', 'postDate', 'purchaseDate')", "instance.save() return instance class OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField() class Meta:", "fields = ('artID', 'title', 'filename', 'rarity', 'collection', 'img_url', 'thumb_url') class", "UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username',", "Own fields = ('ownID', 'user', 'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer): class", "class Meta: model = Collection fields = ('collectionID', 'name', 'display_name',", "= Own fields = ('ownID', 'user', 'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer):", "password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is", "fields = ('id', 'username', 'email', 'password', 'coins', 'art') extra_kwargs =", "def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data)", "class Meta: model = Sale fields = ('saleID', 'seller', 'buyer',", "rest_framework import serializers from .models import * class CollectionSerializer(serializers.ModelSerializer): class", "duplicates = serializers.ReadOnlyField() class Meta: model = Own fields =", "return instance class OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField() class Meta: model", "fields = ('saleID', 'seller', 'buyer', 'ownership', 'art', 'price', 'available', 'sold',", "'password': {'<PASSWORD>} } def create(self, validated_data): password = validated_data.pop('password', None)", "serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField() class Meta: model = Art fields", "SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields = ('saleID', 'seller',", "instance class OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField() class Meta: model =", "model = Sale fields = ('saleID', 'seller', 'buyer', 'ownership', 'art',", "= self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return", "CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ('collectionID', 'name',", "('id', 'username', 'email', 'password', 'coins', 'art') extra_kwargs = { 'password':", "class Meta: model = Art fields = ('artID', 'title', 'filename',", "'username', 'email', 'password', 'coins', 'art') extra_kwargs = { 'password': {'<PASSWORD>}", "Collection fields = ('collectionID', 'name', 'display_name', 'description', 'img_url') class ArtSerializer(serializers.ModelSerializer):", "class ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField() class Meta:", "Art fields = ('artID', 'title', 'filename', 'rarity', 'collection', 'img_url', 'thumb_url')", "'email', 'password', 'coins', 'art') extra_kwargs = { 'password': {'<PASSWORD>} }", "= ('ownID', 'user', 'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer): class Meta: model", "Meta: model = Sale fields = ('saleID', 'seller', 'buyer', 'ownership',", "('artID', 'title', 'filename', 'rarity', 'collection', 'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer): class", "ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField() class Meta: model", "'duplicates') class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields =", "model = Art fields = ('artID', 'title', 'filename', 'rarity', 'collection',", "'name', 'display_name', 'description', 'img_url') class ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField() thumb_url", "'description', 'img_url') class ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField()", "create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if", "Meta: model = Collection fields = ('collectionID', 'name', 'display_name', 'description',", ".models import * class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection", "self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance", "= serializers.ReadOnlyField() class Meta: model = Art fields = ('artID',", "* class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields =", "{ 'password': {'<PASSWORD>} } def create(self, validated_data): password = validated_data.pop('password',", "'art') extra_kwargs = { 'password': {'<PASSWORD>} } def create(self, validated_data):", "validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None:", "img_url = serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField() class Meta: model =", "= serializers.ReadOnlyField() class Meta: model = Own fields = ('ownID',", "instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save()", "None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password)", "'img_url') class ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField() class", "= ('artID', 'title', 'filename', 'rarity', 'collection', 'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer):", "'title', 'filename', 'rarity', 'collection', 'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer): class Meta:", "password is not None: instance.set_password(password) instance.save() return instance class OwnSerializer(serializers.ModelSerializer):", "= Sale fields = ('saleID', 'seller', 'buyer', 'ownership', 'art', 'price',", "from .models import * class CollectionSerializer(serializers.ModelSerializer): class Meta: model =", "thumb_url = serializers.ReadOnlyField() class Meta: model = Art fields =", "} def create(self, validated_data): password = validated_data.pop('password', None) instance =", "User fields = ('id', 'username', 'email', 'password', 'coins', 'art') extra_kwargs", "'collection', 'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer): class Meta: model = User", "import * class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields", "'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields", "'display_name', 'description', 'img_url') class ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField() thumb_url =", "'password', 'coins', 'art') extra_kwargs = { 'password': {'<PASSWORD>} } def", "= User fields = ('id', 'username', 'email', 'password', 'coins', 'art')", "serializers.ReadOnlyField() class Meta: model = Own fields = ('ownID', 'user',", "class Meta: model = User fields = ('id', 'username', 'email',", "fields = ('collectionID', 'name', 'display_name', 'description', 'img_url') class ArtSerializer(serializers.ModelSerializer): img_url", "= Art fields = ('artID', 'title', 'filename', 'rarity', 'collection', 'img_url',", "class Meta: model = Own fields = ('ownID', 'user', 'art',", "not None: instance.set_password(password) instance.save() return instance class OwnSerializer(serializers.ModelSerializer): duplicates =", "model = Collection fields = ('collectionID', 'name', 'display_name', 'description', 'img_url')", "'filename', 'rarity', 'collection', 'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer): class Meta: model", "class SaleSerializer(serializers.ModelSerializer): class Meta: model = Sale fields = ('saleID',", "'rarity', 'collection', 'img_url', 'thumb_url') class UserSerializer(serializers.ModelSerializer): class Meta: model =", "= validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not", "= ('id', 'username', 'email', 'password', 'coins', 'art') extra_kwargs = {", "extra_kwargs = { 'password': {'<PASSWORD>} } def create(self, validated_data): password", "OwnSerializer(serializers.ModelSerializer): duplicates = serializers.ReadOnlyField() class Meta: model = Own fields", "if password is not None: instance.set_password(password) instance.save() return instance class", "'coins', 'art') extra_kwargs = { 'password': {'<PASSWORD>} } def create(self,", "is not None: instance.set_password(password) instance.save() return instance class OwnSerializer(serializers.ModelSerializer): duplicates", "from rest_framework import serializers from .models import * class CollectionSerializer(serializers.ModelSerializer):", "= serializers.ReadOnlyField() thumb_url = serializers.ReadOnlyField() class Meta: model = Art", "fields = ('ownID', 'user', 'art', 'duplicates') class SaleSerializer(serializers.ModelSerializer): class Meta:", "Meta: model = Own fields = ('ownID', 'user', 'art', 'duplicates')", "('collectionID', 'name', 'display_name', 'description', 'img_url') class ArtSerializer(serializers.ModelSerializer): img_url = serializers.ReadOnlyField()" ]
[ "<filename>google/cloud/google_cloud_cpp_common_unit_tests.bzl # Copyright 2018 Google LLC # # Licensed under", "obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0", "LLC # # Licensed under the Apache License, Version 2.0", "the License. # # DO NOT EDIT -- GENERATED BY", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "\"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\",", "the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\", \"status_or_test.cc\", \"status_test.cc\", \"stream_range_test.cc\",", "distributed under the License is distributed on an \"AS IS\"", "\"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\", \"status_or_test.cc\", \"status_test.cc\", \"stream_range_test.cc\", \"terminate_handler_test.cc\", \"tracing_options_test.cc\", ]", "permissions and # limitations under the License. # # DO", "the specific language governing permissions and # limitations under the", "\"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\",", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 #", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "\"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\",", "CMakeLists.txt file if needed \"\"\"Automatically generated unit tests list -", "\"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\",", "\"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\",", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "if needed \"\"\"Automatically generated unit tests list - DO NOT", "= [ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\",", "\"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\",", "copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # #", "Google LLC # # Licensed under the Apache License, Version", "\"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\",", "DO NOT EDIT -- GENERATED BY CMake -- Change the", "unit tests list - DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [", "DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\",", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "governing permissions and # limitations under the License. # #", "you may not use this file except in compliance with", "tests list - DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\",", "\"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\",", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "\"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\", \"status_or_test.cc\", \"status_test.cc\", \"stream_range_test.cc\", \"terminate_handler_test.cc\",", "\"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\",", "Copyright 2018 Google LLC # # Licensed under the Apache", "use this file except in compliance with the License. #", "limitations under the License. # # DO NOT EDIT --", "Change the CMakeLists.txt file if needed \"\"\"Automatically generated unit tests", "CONDITIONS OF ANY KIND, either express or implied. # See", "# limitations under the License. # # DO NOT EDIT", "\"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\",", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "under the License is distributed on an \"AS IS\" BASIS,", "\"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\", \"status_or_test.cc\", \"status_test.cc\", \"stream_range_test.cc\", \"terminate_handler_test.cc\", \"tracing_options_test.cc\",", "License for the specific language governing permissions and # limitations", "and # limitations under the License. # # DO NOT", "License. # # DO NOT EDIT -- GENERATED BY CMake", "generated unit tests list - DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests =", "\"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\", \"status_or_test.cc\", \"status_test.cc\",", "\"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\",", "the License for the specific language governing permissions and #", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "GENERATED BY CMake -- Change the CMakeLists.txt file if needed", "either express or implied. # See the License for the", "google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\",", "License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "\"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\",", "OR CONDITIONS OF ANY KIND, either express or implied. #", "\"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\",", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "the CMakeLists.txt file if needed \"\"\"Automatically generated unit tests list", "software # distributed under the License is distributed on an", "\"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\",", "NOT EDIT -- GENERATED BY CMake -- Change the CMakeLists.txt", "\"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\",", "# # Unless required by applicable law or agreed to", "\"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\",", "file if needed \"\"\"Automatically generated unit tests list - DO", "\"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\",", "\"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\", \"internal/base64_transforms_test.cc\", \"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\",", "\"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\",", "EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\",", "-- Change the CMakeLists.txt file if needed \"\"\"Automatically generated unit", "\"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\",", "Version 2.0 (the \"License\"); # you may not use this", "law or agreed to in writing, software # distributed under", "\"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\",", "EDIT -- GENERATED BY CMake -- Change the CMakeLists.txt file", "\"\"\"Automatically generated unit tests list - DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests", "\"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\", \"project_test.cc\", \"status_or_test.cc\",", "# Copyright 2018 Google LLC # # Licensed under the", "\"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\", \"polling_policy_test.cc\",", "implied. # See the License for the specific language governing", "# DO NOT EDIT -- GENERATED BY CMake -- Change", "under the Apache License, Version 2.0 (the \"License\"); # you", "NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\",", "\"License\"); # you may not use this file except in", "under the License. # # DO NOT EDIT -- GENERATED", "- DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\",", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "\"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\",", "# # DO NOT EDIT -- GENERATED BY CMake --", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "[ \"common_options_test.cc\", \"future_generic_test.cc\", \"future_generic_then_test.cc\", \"future_void_test.cc\", \"future_void_then_test.cc\", \"iam_bindings_test.cc\", \"internal/algorithm_test.cc\", \"internal/api_client_header_test.cc\", \"internal/backoff_policy_test.cc\",", "list - DO NOT EDIT.\"\"\" google_cloud_cpp_common_unit_tests = [ \"common_options_test.cc\", \"future_generic_test.cc\",", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "\"internal/big_endian_test.cc\", \"internal/compiler_info_test.cc\", \"internal/credentials_impl_test.cc\", \"internal/env_test.cc\", \"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\",", "at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "CMake -- Change the CMakeLists.txt file if needed \"\"\"Automatically generated", "BY CMake -- Change the CMakeLists.txt file if needed \"\"\"Automatically", "You may obtain a copy of the License at #", "language governing permissions and # limitations under the License. #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "\"internal/filesystem_test.cc\", \"internal/format_time_point_test.cc\", \"internal/future_impl_test.cc\", \"internal/invoke_result_test.cc\", \"internal/log_impl_test.cc\", \"internal/pagination_range_test.cc\", \"internal/parse_rfc3339_test.cc\", \"internal/random_test.cc\", \"internal/retry_policy_test.cc\", \"internal/status_payload_keys_test.cc\",", "\"internal/status_payload_keys_test.cc\", \"internal/strerror_test.cc\", \"internal/throw_delegate_test.cc\", \"internal/tuple_test.cc\", \"internal/type_list_test.cc\", \"internal/user_agent_prefix_test.cc\", \"internal/utility_test.cc\", \"kms_key_name_test.cc\", \"log_test.cc\", \"options_test.cc\",", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "-- GENERATED BY CMake -- Change the CMakeLists.txt file if", "needed \"\"\"Automatically generated unit tests list - DO NOT EDIT.\"\"\"", "2018 Google LLC # # Licensed under the Apache License,", "https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed" ]
[ "setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.item_list = []", "= self.app.test_client() self.item_list = [] # deconstructs test elements def", "super class for api ver 1 tests\"\"\" # setup testing", "tests\"\"\" # setup testing def setUp(self): self.app = create_app('testing') self.client", "1 tests\"\"\" # setup testing def setUp(self): self.app = create_app('testing')", "self.app.test_client() self.item_list = [] # deconstructs test elements def tearDown(self):", "\"\"\"Default super class for api ver 1 tests\"\"\" # setup", "create_app class TestBase(unittest.TestCase): \"\"\"Default super class for api ver 1", "api ver 1 tests\"\"\" # setup testing def setUp(self): self.app", "import create_app class TestBase(unittest.TestCase): \"\"\"Default super class for api ver", "unittest from api import create_app class TestBase(unittest.TestCase): \"\"\"Default super class", "testing def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.item_list", "for api ver 1 tests\"\"\" # setup testing def setUp(self):", "import unittest from api import create_app class TestBase(unittest.TestCase): \"\"\"Default super", "self.app = create_app('testing') self.client = self.app.test_client() self.item_list = [] #", "from api import create_app class TestBase(unittest.TestCase): \"\"\"Default super class for", "create_app('testing') self.client = self.app.test_client() self.item_list = [] # deconstructs test", "ver 1 tests\"\"\" # setup testing def setUp(self): self.app =", "<filename>api/tests/ver1/test_base.py import unittest from api import create_app class TestBase(unittest.TestCase): \"\"\"Default", "# deconstructs test elements def tearDown(self): self.app = None self.item_list.clear()", "class for api ver 1 tests\"\"\" # setup testing def", "setup testing def setUp(self): self.app = create_app('testing') self.client = self.app.test_client()", "= [] # deconstructs test elements def tearDown(self): self.app =", "[] # deconstructs test elements def tearDown(self): self.app = None", "self.client = self.app.test_client() self.item_list = [] # deconstructs test elements", "self.item_list = [] # deconstructs test elements def tearDown(self): self.app", "= create_app('testing') self.client = self.app.test_client() self.item_list = [] # deconstructs", "class TestBase(unittest.TestCase): \"\"\"Default super class for api ver 1 tests\"\"\"", "api import create_app class TestBase(unittest.TestCase): \"\"\"Default super class for api", "TestBase(unittest.TestCase): \"\"\"Default super class for api ver 1 tests\"\"\" #", "def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.item_list =", "# setup testing def setUp(self): self.app = create_app('testing') self.client =" ]
[ "stringfilter from django.utils.safestring import SafeString import markdown import urllib register", "value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value): return", "urllib.parse.quote(value) @register.filter def get_post_id(url): \"\"\" gets the post id from", "return value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value):", "get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value): return urllib.parse.quote(value) @register.filter def", "import markdown import urllib register = template.Library() @register.filter def strip_space(value):", "is str: return value return value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value): return", "return value return value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\")", "django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import", "return value.replace(' ', '') @register.filter @stringfilter def commonmark(value): return markdown.Markdown().convert(value)", "value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value): return urllib.parse.quote(value) @register.filter def get_post_id(url): \"\"\"", "register = template.Library() @register.filter def strip_space(value): return value.replace(' ', '')", "from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring", "from django.template.defaultfilters import stringfilter from django.utils.safestring import SafeString import markdown", "not type(value) is str: return value return value.split('/')[-1] @register.filter(name=\"getNav\") def", "= template.Library() @register.filter def strip_space(value): return value.replace(' ', '') @register.filter", "get_post_id(url): \"\"\" gets the post id from the comment page", "return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value): if not type(value) is str:", "'') @register.filter @stringfilter def commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value):", "@stringfilter def commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value): if not", "django.template.defaultfilters import stringfilter from django.utils.safestring import SafeString import markdown import", "value.replace(' ', '') @register.filter @stringfilter def commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\")", "@register.filter(name=\"getNav\") def get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value): return urllib.parse.quote(value)", "return value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value): return urllib.parse.quote(value) @register.filter def get_post_id(url):", "encode_url(value): return urllib.parse.quote(value) @register.filter def get_post_id(url): \"\"\" gets the post", "id from the comment page url \"\"\" return urllib.parse.urlparse(url.get_full_path()).path.rsplit('/', 1)[0]", "commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value): if not type(value) is", "gets the post id from the comment page url \"\"\"", "@register.filter @stringfilter def commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value): if", "@register.filter(name=\"encode_url\") def encode_url(value): return urllib.parse.quote(value) @register.filter def get_post_id(url): \"\"\" gets", "type(value) is str: return value return value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value):", "def encode_url(value): return urllib.parse.quote(value) @register.filter def get_post_id(url): \"\"\" gets the", "def get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\") def encode_url(value): return urllib.parse.quote(value) @register.filter", "post id from the comment page url \"\"\" return urllib.parse.urlparse(url.get_full_path()).path.rsplit('/',", "import stringfilter from django.utils.safestring import SafeString import markdown import urllib", "', '') @register.filter @stringfilter def commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def", "from django.utils.safestring import SafeString import markdown import urllib register =", "import template from django.template.defaultfilters import stringfilter from django.utils.safestring import SafeString", "SafeString import markdown import urllib register = template.Library() @register.filter def", "urllib register = template.Library() @register.filter def strip_space(value): return value.replace(' ',", "template from django.template.defaultfilters import stringfilter from django.utils.safestring import SafeString import", "markdown import urllib register = template.Library() @register.filter def strip_space(value): return", "template.Library() @register.filter def strip_space(value): return value.replace(' ', '') @register.filter @stringfilter", "markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value): if not type(value) is str: return", "if not type(value) is str: return value return value.split('/')[-1] @register.filter(name=\"getNav\")", "@register.filter def get_post_id(url): \"\"\" gets the post id from the", "the post id from the comment page url \"\"\" return", "def get_ID(value): if not type(value) is str: return value return", "\"\"\" gets the post id from the comment page url", "strip_space(value): return value.replace(' ', '') @register.filter @stringfilter def commonmark(value): return", "value return value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value): return value.split('/')[-2] @register.filter(name=\"encode_url\") def", "@register.filter def strip_space(value): return value.replace(' ', '') @register.filter @stringfilter def", "django.utils.safestring import SafeString import markdown import urllib register = template.Library()", "@register.filter(name=\"getID\") def get_ID(value): if not type(value) is str: return value", "import SafeString import markdown import urllib register = template.Library() @register.filter", "str: return value return value.split('/')[-1] @register.filter(name=\"getNav\") def get_nav(value): return value.split('/')[-2]", "def strip_space(value): return value.replace(' ', '') @register.filter @stringfilter def commonmark(value):", "def commonmark(value): return markdown.Markdown().convert(value) @register.filter(name=\"getID\") def get_ID(value): if not type(value)", "get_ID(value): if not type(value) is str: return value return value.split('/')[-1]", "def get_post_id(url): \"\"\" gets the post id from the comment", "import urllib register = template.Library() @register.filter def strip_space(value): return value.replace('", "return urllib.parse.quote(value) @register.filter def get_post_id(url): \"\"\" gets the post id" ]
[ "params['time'] = self.time if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] =", "import CloudbusUserInfo class MetroOdItem(object): def __init__(self): self._dest_geo = None self._od", "value): self._od = value @property def time(self): return self._time @time.setter", "self._time = value @property def user_info(self): return self._user_info @user_info.setter def", "alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object): def", "d: o.time = d['time'] if 'user_info' in d: o.user_info =", "time(self, value): self._time = value @property def user_info(self): return self._user_info", "hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od return", "in d: o.od = d['od'] if 'time' in d: o.time", "self._time = None self._user_info = None self._week_od = None self._work_od", "return self._od @od.setter def od(self, value): self._od = value @property", "self.dest_geo if self.od: if hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else:", "= self.dest_geo if self.od: if hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict()", "'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od if self.work_od:", "params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od if self.work_od: if", "def work_od(self): return self._work_od @work_od.setter def work_od(self, value): self._work_od =", "= self.od if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict()", "def time(self, value): self._time = value @property def user_info(self): return", "MetroOdItem(object): def __init__(self): self._dest_geo = None self._od = None self._time", "o.user_info = d['user_info'] if 'week_od' in d: o.week_od = d['week_od']", "def dest_geo(self): return self._dest_geo @dest_geo.setter def dest_geo(self, value): self._dest_geo =", "self.od if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else:", "def od(self, value): self._od = value @property def time(self): return", "-*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import *", "'time' in d: o.time = d['time'] if 'user_info' in d:", "'user_info' in d: o.user_info = d['user_info'] if 'week_od' in d:", "self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo'] =", "-*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo import", "d['week_od'] if 'work_od' in d: o.work_od = d['work_od'] return o", "params['od'] = self.od.to_alipay_dict() else: params['od'] = self.od if self.time: if", "self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'):", "return self._dest_geo @dest_geo.setter def dest_geo(self, value): self._dest_geo = value @property", "= value def to_alipay_dict(self): params = dict() if self.dest_geo: if", "if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od", "= d['od'] if 'time' in d: o.time = d['time'] if", "self._week_od = value @property def work_od(self): return self._work_od @work_od.setter def", "def week_od(self, value): self._week_od = value @property def work_od(self): return", "hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time'] = self.time if", "= self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info if self.week_od: if hasattr(self.week_od,", "self._user_info @user_info.setter def user_info(self, value): if isinstance(value, CloudbusUserInfo): self._user_info =", "in d: o.user_info = d['user_info'] if 'week_od' in d: o.week_od", "work_od(self, value): self._work_od = value def to_alipay_dict(self): params = dict()", "if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time'] = self.time", "alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object): def __init__(self): self._dest_geo = None", "def from_alipay_dict(d): if not d: return None o = MetroOdItem()", "d['user_info'] if 'week_od' in d: o.week_od = d['week_od'] if 'work_od'", "'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od return params", "o.week_od = d['week_od'] if 'work_od' in d: o.work_od = d['work_od']", "= self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od if self.work_od: if hasattr(self.work_od,", "= MetroOdItem() if 'dest_geo' in d: o.dest_geo = d['dest_geo'] if", "def __init__(self): self._dest_geo = None self._od = None self._time =", "hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info if", "return params @staticmethod def from_alipay_dict(d): if not d: return None", "in d: o.dest_geo = d['dest_geo'] if 'od' in d: o.od", "= self.time if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict()", "self.work_od return params @staticmethod def from_alipay_dict(d): if not d: return", "params @staticmethod def from_alipay_dict(d): if not d: return None o", "params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info if self.week_od: if", "@property def user_info(self): return self._user_info @user_info.setter def user_info(self, value): if", "self.time.to_alipay_dict() else: params['time'] = self.time if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'):", "coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from", "return self._user_info @user_info.setter def user_info(self, value): if isinstance(value, CloudbusUserInfo): self._user_info", "@week_od.setter def week_od(self, value): self._week_od = value @property def work_od(self):", "self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo if self.od: if hasattr(self.od, 'to_alipay_dict'):", "params['week_od'] = self.week_od if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] =", "if 'dest_geo' in d: o.dest_geo = d['dest_geo'] if 'od' in", "= value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return", "self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return self._week_od @week_od.setter def", "self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'):", "None self._time = None self._user_info = None self._week_od = None", "if self.od: if hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else: params['od']", "hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od if", "json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class", "= None self._week_od = None self._work_od = None @property def", "o.time = d['time'] if 'user_info' in d: o.user_info = d['user_info']", "= d['time'] if 'user_info' in d: o.user_info = d['user_info'] if", "@od.setter def od(self, value): self._od = value @property def time(self):", "* from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object): def __init__(self): self._dest_geo", "self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od return params @staticmethod def from_alipay_dict(d):", "self._od = None self._time = None self._user_info = None self._week_od", "self._user_info = value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self):", "params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo if self.od: if", "CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return self._week_od @week_od.setter def week_od(self, value):", "week_od(self, value): self._week_od = value @property def work_od(self): return self._work_od", "self._dest_geo @dest_geo.setter def dest_geo(self, value): self._dest_geo = value @property def", "o.od = d['od'] if 'time' in d: o.time = d['time']", "if not d: return None o = MetroOdItem() if 'dest_geo'", "if 'user_info' in d: o.user_info = d['user_info'] if 'week_od' in", "= None self._user_info = None self._week_od = None self._work_od =", "if isinstance(value, CloudbusUserInfo): self._user_info = value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value)", "self._dest_geo = None self._od = None self._time = None self._user_info", "@time.setter def time(self, value): self._time = value @property def user_info(self):", "self.user_info if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else:", "params['od'] = self.od if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] =", "@user_info.setter def user_info(self, value): if isinstance(value, CloudbusUserInfo): self._user_info = value", "None self._week_od = None self._work_od = None @property def dest_geo(self):", "d['od'] if 'time' in d: o.time = d['time'] if 'user_info'", "params['time'] = self.time.to_alipay_dict() else: params['time'] = self.time if self.user_info: if", "python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants", "= value @property def user_info(self): return self._user_info @user_info.setter def user_info(self,", "if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od']", "= self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo if self.od: if hasattr(self.od,", "#!/usr/bin/env python # -*- coding: utf-8 -*- import json from", "= value @property def time(self): return self._time @time.setter def time(self,", "@property def dest_geo(self): return self._dest_geo @dest_geo.setter def dest_geo(self, value): self._dest_geo", "else: params['dest_geo'] = self.dest_geo if self.od: if hasattr(self.od, 'to_alipay_dict'): params['od']", "work_od(self): return self._work_od @work_od.setter def work_od(self, value): self._work_od = value", "od(self): return self._od @od.setter def od(self, value): self._od = value", "if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od", "@property def time(self): return self._time @time.setter def time(self, value): self._time", "= None self._od = None self._time = None self._user_info =", "self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info'] =", "def work_od(self, value): self._work_od = value def to_alipay_dict(self): params =", "class MetroOdItem(object): def __init__(self): self._dest_geo = None self._od = None", "@property def od(self): return self._od @od.setter def od(self, value): self._od", "self._work_od @work_od.setter def work_od(self, value): self._work_od = value def to_alipay_dict(self):", "= self.work_od return params @staticmethod def from_alipay_dict(d): if not d:", "def week_od(self): return self._week_od @week_od.setter def week_od(self, value): self._week_od =", "self._work_od = value def to_alipay_dict(self): params = dict() if self.dest_geo:", "self.time if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else:", "params['dest_geo'] = self.dest_geo if self.od: if hasattr(self.od, 'to_alipay_dict'): params['od'] =", "def to_alipay_dict(self): params = dict() if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'):", "= CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return self._week_od @week_od.setter def week_od(self,", "value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return self._week_od", "from_alipay_dict(d): if not d: return None o = MetroOdItem() if", "in d: o.time = d['time'] if 'user_info' in d: o.user_info", "else: params['week_od'] = self.week_od if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od']", "if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od']", "self._work_od = None @property def dest_geo(self): return self._dest_geo @dest_geo.setter def", "self._od @od.setter def od(self, value): self._od = value @property def", "= d['dest_geo'] if 'od' in d: o.od = d['od'] if", "not d: return None o = MetroOdItem() if 'dest_geo' in", "to_alipay_dict(self): params = dict() if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo']", "def user_info(self): return self._user_info @user_info.setter def user_info(self, value): if isinstance(value,", "if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo", "def user_info(self, value): if isinstance(value, CloudbusUserInfo): self._user_info = value else:", "else: params['time'] = self.time if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info']", "CloudbusUserInfo class MetroOdItem(object): def __init__(self): self._dest_geo = None self._od =", "'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info if self.week_od:", "return None o = MetroOdItem() if 'dest_geo' in d: o.dest_geo", "o.dest_geo = d['dest_geo'] if 'od' in d: o.od = d['od']", "if 'time' in d: o.time = d['time'] if 'user_info' in", "None @property def dest_geo(self): return self._dest_geo @dest_geo.setter def dest_geo(self, value):", "value def to_alipay_dict(self): params = dict() if self.dest_geo: if hasattr(self.dest_geo,", "def dest_geo(self, value): self._dest_geo = value @property def od(self): return", "dest_geo(self, value): self._dest_geo = value @property def od(self): return self._od", "= value @property def od(self): return self._od @od.setter def od(self,", "'od' in d: o.od = d['od'] if 'time' in d:", "value): if isinstance(value, CloudbusUserInfo): self._user_info = value else: self._user_info =", "else: params['od'] = self.od if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time']", "params['work_od'] = self.work_od return params @staticmethod def from_alipay_dict(d): if not", "params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od return params @staticmethod", "self._week_od = None self._work_od = None @property def dest_geo(self): return", "= self.od.to_alipay_dict() else: params['od'] = self.od if self.time: if hasattr(self.time,", "if 'week_od' in d: o.week_od = d['week_od'] if 'work_od' in", "self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od'] =", "CloudbusUserInfo): self._user_info = value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def", "= self.user_info if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict()", "@dest_geo.setter def dest_geo(self, value): self._dest_geo = value @property def od(self):", "None self._work_od = None @property def dest_geo(self): return self._dest_geo @dest_geo.setter", "None o = MetroOdItem() if 'dest_geo' in d: o.dest_geo =", "in d: o.week_od = d['week_od'] if 'work_od' in d: o.work_od", "params['user_info'] = self.user_info if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] =", "utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo", "user_info(self, value): if isinstance(value, CloudbusUserInfo): self._user_info = value else: self._user_info", "'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo if self.od:", "= None @property def dest_geo(self): return self._dest_geo @dest_geo.setter def dest_geo(self,", "@staticmethod def from_alipay_dict(d): if not d: return None o =", "MetroOdItem() if 'dest_geo' in d: o.dest_geo = d['dest_geo'] if 'od'", "value @property def time(self): return self._time @time.setter def time(self, value):", "= dict() if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict()", "dest_geo(self): return self._dest_geo @dest_geo.setter def dest_geo(self, value): self._dest_geo = value", "value): self._dest_geo = value @property def od(self): return self._od @od.setter", "return self._work_od @work_od.setter def work_od(self, value): self._work_od = value def", "self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time'] =", "= d['week_od'] if 'work_od' in d: o.work_od = d['work_od'] return", "value): self._time = value @property def user_info(self): return self._user_info @user_info.setter", "= None self._time = None self._user_info = None self._week_od =", "@property def work_od(self): return self._work_od @work_od.setter def work_od(self, value): self._work_od", "self.od.to_alipay_dict() else: params['od'] = self.od if self.time: if hasattr(self.time, 'to_alipay_dict'):", "'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time'] = self.time if self.user_info:", "= None self._work_od = None @property def dest_geo(self): return self._dest_geo", "self.week_od if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else:", "# -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import", "else: params['user_info'] = self.user_info if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od']", "if hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else: params['od'] = self.od", "__init__(self): self._dest_geo = None self._od = None self._time = None", "week_od(self): return self._week_od @week_od.setter def week_od(self, value): self._week_od = value", "isinstance(value, CloudbusUserInfo): self._user_info = value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property", "= self.time.to_alipay_dict() else: params['time'] = self.time if self.user_info: if hasattr(self.user_info,", "d: return None o = MetroOdItem() if 'dest_geo' in d:", "time(self): return self._time @time.setter def time(self, value): self._time = value", "else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return self._week_od @week_od.setter", "@work_od.setter def work_od(self, value): self._work_od = value def to_alipay_dict(self): params", "if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info']", "return self._week_od @week_od.setter def week_od(self, value): self._week_od = value @property", "d: o.od = d['od'] if 'time' in d: o.time =", "self._od = value @property def time(self): return self._time @time.setter def", "if 'od' in d: o.od = d['od'] if 'time' in", "= d['user_info'] if 'week_od' in d: o.week_od = d['week_od'] if", "= value @property def work_od(self): return self._work_od @work_od.setter def work_od(self,", "def od(self): return self._od @od.setter def od(self, value): self._od =", "'week_od' in d: o.week_od = d['week_od'] if 'work_od' in d:", "self.od: if hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else: params['od'] =", "value @property def work_od(self): return self._work_od @work_od.setter def work_od(self, value):", "self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od'] =", "if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time']", "d['time'] if 'user_info' in d: o.user_info = d['user_info'] if 'week_od'", "import * from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object): def __init__(self):", "value): self._work_od = value def to_alipay_dict(self): params = dict() if", "self._user_info = None self._week_od = None self._work_od = None @property", "od(self, value): self._od = value @property def time(self): return self._time", "else: params['work_od'] = self.work_od return params @staticmethod def from_alipay_dict(d): if", "d: o.user_info = d['user_info'] if 'week_od' in d: o.week_od =", "o = MetroOdItem() if 'dest_geo' in d: o.dest_geo = d['dest_geo']", "value @property def user_info(self): return self._user_info @user_info.setter def user_info(self, value):", "if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info", "self._week_od @week_od.setter def week_od(self, value): self._week_od = value @property def", "= self.week_od if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict()", "value @property def od(self): return self._od @od.setter def od(self, value):", "params = dict() if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] =", "return self._time @time.setter def time(self, value): self._time = value @property", "value): self._week_od = value @property def work_od(self): return self._work_od @work_od.setter", "'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else: params['od'] = self.od if self.time:", "import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo", "None self._od = None self._time = None self._user_info = None", "from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object):", "d: o.week_od = d['week_od'] if 'work_od' in d: o.work_od =", "'dest_geo' in d: o.dest_geo = d['dest_geo'] if 'od' in d:", "hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else: params['od'] = self.od if", "d: o.dest_geo = d['dest_geo'] if 'od' in d: o.od =", "dict() if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else:", "hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo if", "user_info(self): return self._user_info @user_info.setter def user_info(self, value): if isinstance(value, CloudbusUserInfo):", "d['dest_geo'] if 'od' in d: o.od = d['od'] if 'time'", "self._dest_geo = value @property def od(self): return self._od @od.setter def", "self._time @time.setter def time(self, value): self._time = value @property def", "@property def week_od(self): return self._week_od @week_od.setter def week_od(self, value): self._week_od", "if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo']", "def time(self): return self._time @time.setter def time(self, value): self._time =", "None self._user_info = None self._week_od = None self._work_od = None", "= self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od return params @staticmethod def", "from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object): def __init__(self): self._dest_geo =" ]
[ "pages starting with the given string will be redirected to", "2019-08-10 08:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "operations = [ migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected all", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djangocms_redirect',", "all the pages starting with the given string will be", "subpath with the provided redirect path.', verbose_name='Subpath match'), ), ]", "model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected all the pages starting with", "given redirect path', verbose_name='Catchall redirect'), ), migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False,", "class Migration(migrations.Migration): dependencies = [ ('djangocms_redirect', '0002_auto_20170321_1807'), ] operations =", "Django 2.2.4 on 2019-08-10 08:09 from django.db import migrations, models", "Generated by Django 2.2.4 on 2019-08-10 08:09 from django.db import", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('djangocms_redirect', '0002_auto_20170321_1807'),", "migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected all the pages starting", "redirected by replacing the matching subpath with the provided redirect", "matching subpath with the provided redirect path.', verbose_name='Subpath match'), ),", "with the given string will be redirected to the given", "Migration(migrations.Migration): dependencies = [ ('djangocms_redirect', '0002_auto_20170321_1807'), ] operations = [", "migrations, models class Migration(migrations.Migration): dependencies = [ ('djangocms_redirect', '0002_auto_20170321_1807'), ]", "string will be redirected by replacing the matching subpath with", "path', verbose_name='Catchall redirect'), ), migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If selected", "= [ ('djangocms_redirect', '0002_auto_20170321_1807'), ] operations = [ migrations.AddField( model_name='redirect',", "name='subpath_match', field=models.BooleanField(default=False, help_text='If selected all the pages starting with the", "[ migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected all the pages", "the matching subpath with the provided redirect path.', verbose_name='Subpath match'),", "name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected all the pages starting with the", "verbose_name='Catchall redirect'), ), migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If selected all", "given string will be redirected to the given redirect path',", "the pages starting with the given string will be redirected", "string will be redirected to the given redirect path', verbose_name='Catchall", "the given string will be redirected by replacing the matching", "be redirected by replacing the matching subpath with the provided", "<reponame>vsalat/djangocms-redirect # Generated by Django 2.2.4 on 2019-08-10 08:09 from", "by replacing the matching subpath with the provided redirect path.',", "= [ migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected all the", "will be redirected to the given redirect path', verbose_name='Catchall redirect'),", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "] operations = [ migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If selected", "redirect path', verbose_name='Catchall redirect'), ), migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If", "), migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If selected all the pages", "08:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "models class Migration(migrations.Migration): dependencies = [ ('djangocms_redirect', '0002_auto_20170321_1807'), ] operations", "redirected to the given redirect path', verbose_name='Catchall redirect'), ), migrations.AddField(", "field=models.BooleanField(default=False, help_text='If selected all the pages starting with the given", "the given redirect path', verbose_name='Catchall redirect'), ), migrations.AddField( model_name='redirect', name='subpath_match',", "replacing the matching subpath with the provided redirect path.', verbose_name='Subpath", "the given string will be redirected to the given redirect", "on 2019-08-10 08:09 from django.db import migrations, models class Migration(migrations.Migration):", "starting with the given string will be redirected to the", "starting with the given string will be redirected by replacing", "'0002_auto_20170321_1807'), ] operations = [ migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False, help_text='If", "be redirected to the given redirect path', verbose_name='Catchall redirect'), ),", "selected all the pages starting with the given string will", "2.2.4 on 2019-08-10 08:09 from django.db import migrations, models class", "model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If selected all the pages starting with", "given string will be redirected by replacing the matching subpath", "dependencies = [ ('djangocms_redirect', '0002_auto_20170321_1807'), ] operations = [ migrations.AddField(", "# Generated by Django 2.2.4 on 2019-08-10 08:09 from django.db", "pages starting with the given string will be redirected by", "[ ('djangocms_redirect', '0002_auto_20170321_1807'), ] operations = [ migrations.AddField( model_name='redirect', name='catchall_redirect',", "('djangocms_redirect', '0002_auto_20170321_1807'), ] operations = [ migrations.AddField( model_name='redirect', name='catchall_redirect', field=models.BooleanField(default=False,", "help_text='If selected all the pages starting with the given string", "by Django 2.2.4 on 2019-08-10 08:09 from django.db import migrations,", "to the given redirect path', verbose_name='Catchall redirect'), ), migrations.AddField( model_name='redirect',", "with the given string will be redirected by replacing the", "will be redirected by replacing the matching subpath with the", "redirect'), ), migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If selected all the", "migrations.AddField( model_name='redirect', name='subpath_match', field=models.BooleanField(default=False, help_text='If selected all the pages starting" ]
[ "Part in the SearchResult print (\"[info] %s_%s...\" % (part['brand']['name'].replace(\" \",", "HTTP Requests/second print(\"DONE\") print(\"[info] %s Parts Completed.\" % MAX_RESULTS) print(\"[info]", "# print number of hits print \"[info] Search Response Hits:", "number of hits that correspond to the search query. \"\"\"", "Grab the SearchResponse # Iterate through the SearchResults in the", "search query. \"\"\" url = \"http://octopart.com/api/v3/categories/\" # NOTE: Use your", "datasheets for the query were downloaded.\" % counter) def parse_args():", "time.sleep(0.4) # Limit ourselves to 3 HTTP Requests/second print(\"DONE\") print(\"[info]", "commandline arguments can be accepted parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords", "the counter of files downloaded # NOTE: Not sure if", "= time.time() print '[info] Took', finish_time - start_time, 'sec total.'", "%s Parts Completed.\" % MAX_RESULTS) print(\"[info] COMPLETED: %s datasheets for", "datasheet['url'] if pdflink is not None: # Download the PDF", "given set of search keywords. \"\"\" MAX_RESULTS = 100 counter", "query in quotes (required)\") parser.add_argument('--version', action='version', version='%(prog)s 0.1.0') args =", "= parser.parse_args() return args.query # Main Function if __name__ ==", "search_response['hits'] def download_datasheets(search_query): \"\"\" Function: download_datasheets -------------------- Uses the OctoPart", "arguments for the Octopart Datasheet Scraper \"\"\" # Define what", "re # Category ID for Discrete Semiconductors > Transistors >", "ourselves to 3 HTTP Requests/second print(\"DONE\") print(\"[info] %s Parts Completed.\"", "open(\"../datasheets/%s.pdf\" % filename, 'w') file.write(response.read()) file.close() counter += 1 #", "can be accepted parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query", "('start', 0), ('limit', 1), #change to increase number of datasheets", "the Part in the SearchResult print (\"[info] %s_%s...\" % (part['brand']['name'].replace(\"", "of hits return search_response['hits'] def download_datasheets(search_query): \"\"\" Function: download_datasheets --------------------", "BJTs TRANSISTOR_ID = b814751e89ff63d3 def find_total_hits(search_query): \"\"\" Function: find_total_hits --------------------", "number of datasheets ('include[]','datasheets') ] url += '&' + urllib.urlencode(args)", "for %s\" % search_query download_datasheets(search_query) finish_time = time.time() print '[info]", "NOTE: Use your API key here (https://octopart.com/api/register) url += \"?apikey=<KEY>\"", "SearchRequest search_response = json.loads(data) # Grab the SearchResponse # return", "args = parser.parse_args() return args.query # Main Function if __name__", "Use your API key here (https://octopart.com/api/register) url += \"?apikey=09b32c6c\" args", "download all datasheets associated with a given set of search", "Datasheet Scraper \"\"\" # Define what commandline arguments can be", "of hits that correspond to the search query. \"\"\" url", "of search keywords. \"\"\" MAX_RESULTS = 100 counter = 0", "in the SearchResult print (\"[info] %s_%s...\" % (part['brand']['name'].replace(\" \", \"\"),", "OctoPart API to download all datasheets associated with a given", "('q', search_query), ('start', 0), ('limit', 1), #change to increase number", "to next datasheet rather than crashing file = open(\"../datasheets/%s.pdf\" %", "#! /usr/bin/env python import sys import json import urllib import", "crashing try: filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError: continue; #", "query were downloaded.\" % counter) def parse_args(): \"\"\" Function: parse_args", "downloaded # NOTE: Not sure if this is necessary. Just", "args.query # Main Function if __name__ == \"__main__\": reload(sys) sys.setdefaultencoding('utf-8')", "accepted parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query in quotes", "('q', search_query), ('start', (i * MAX_RESULTS)), ('limit', MAX_RESULTS), # change", "the SearchResponse if not search_response.get('results'): print \"[error] no results returned", "% counter) def parse_args(): \"\"\" Function: parse_args -------------------- Parse the", "through list of datasheets for the given part for datasheet", "elif err.code == 403: print \"[error] Access Denied!...\", else: print", "\"\"\" url = \"http://octopart.com/api/v3/categories/\" # NOTE: Use your API key", "403: print \"[error] Access Denied!...\", else: print \"[error] HTTP Error", "outer loop: \" + str(i) continue for result in search_response['results']:", "] url += '&' + urllib.urlencode(args) data = urllib.urlopen(url).read() #", "url = \"http://octopart.com/api/v3/categories/\" # NOTE: Use your API key here", "to the search query. \"\"\" url = \"http://octopart.com/api/v3/categories/\" # NOTE:", "# Iterate through list of datasheets for the given part", "datasheet rather than crashing file = open(\"../datasheets/%s.pdf\" % filename, 'w')", "HTTP Error code \", err.code, continue; # advance to next", "'w') file.write(response.read()) file.close() counter += 1 # Increment the counter", "hits print \"[info] Search Response Hits: %s\" % (total_hits) #", "in quotes (required)\") parser.add_argument('--version', action='version', version='%(prog)s 0.1.0') args = parser.parse_args()", "json import urllib import urllib2 import time import argparse import", "# NOTE: Use your API key here (https://octopart.com/api/register) url +=", "\"\"\" MAX_RESULTS = 100 counter = 0 total_hits = find_total_hits(search_query)", "-------------------- Uses the OctoPart API to download all datasheets associated", "find_total_hits(search_query) # print number of hits print \"[info] Search Response", "Function: find_total_hits -------------------- Returns the number of hits that correspond", "sure if this is necessary. Just a precaution. time.sleep(0.4) #", "args = [ ('q', search_query), ('start', 0), ('limit', 1), #change", "data = urllib.urlopen(url).read() # perform a SearchRequest search_response = json.loads(data)", "loop: \" + str(i) continue for result in search_response['results']: part", "files downloaded # NOTE: Not sure if this is necessary.", "Semiconductors > Transistors > BJTs TRANSISTOR_ID = b814751e89ff63d3 def find_total_hits(search_query):", "datasheet in part['datasheets']: # Grab the Datasheet URL pdflink =", "of hits there are num_hundreds = total_hits / MAX_RESULTS print", "= datasheet['url'] if pdflink is not None: # Download the", "to query in quotes (required)\") parser.add_argument('--version', action='version', version='%(prog)s 0.1.0') args", "= 0 total_hits = find_total_hits(search_query) # print number of hits", "no results returned in outer loop: \" + str(i) continue", "print \"[info] Search Response Hits: %s\" % (total_hits) # Calculate", "SearchResponse if not search_response.get('results'): print \"[error] no results returned in", "sys import json import urllib import urllib2 import time import", "# Grab the Datasheet URL pdflink = datasheet['url'] if pdflink", "% (num_hundreds, MAX_RESULTS) for i in range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\"", "(part['brand']['name'].replace(\" \", \"\"), part['mpn'])), sys.stdout.flush() # Iterate through list of", "download_datasheets -------------------- Uses the OctoPart API to download all datasheets", "downloaded.\" % counter) def parse_args(): \"\"\" Function: parse_args -------------------- Parse", "[ ('q', search_query), ('start', (i * MAX_RESULTS)), ('limit', MAX_RESULTS), #", "code \", err.code, continue; # advance to next datasheet rather", "# Parse commandline arguments start_time = time.time() print \"[info] Download", "try: filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError: continue; # skip", "of files downloaded # NOTE: Not sure if this is", "rather than crashing file = open(\"../datasheets/%s.pdf\" % filename, 'w') file.write(response.read())", "import time import argparse import re # Category ID for", "/ MAX_RESULTS print \"[info] Performing %s iterations of %s results.\"", "not search_response.get('results'): print \"[error] no results returned in outer loop:", "(https://octopart.com/api/register) url += \"?apikey=09b32c6c\" args = [ ('q', search_query), ('start',", "# Grab the Part in the SearchResult print (\"[info] %s_%s...\"", "keywords. \"\"\" MAX_RESULTS = 100 counter = 0 total_hits =", "search_response = json.loads(data) # Grab the SearchResponse # return number", "Increment the counter of files downloaded # NOTE: Not sure", "API key here (https://octopart.com/api/register) url += \"?apikey=09b32c6c\" args = [", "to increase number of datasheets ('include[]','datasheets') ] url += '&'", "return search_response['hits'] def download_datasheets(search_query): \"\"\" Function: download_datasheets -------------------- Uses the", "print(\"[info] COMPLETED: %s datasheets for the query were downloaded.\" %", "except AttributeError: continue; # skip to next datasheet rather than", "SearchResponse # return number of hits return search_response['hits'] def download_datasheets(search_query):", "= [ ('q', search_query), ('start', 0), ('limit', 1), #change to", "that correspond to the search query. \"\"\" url = \"http://octopart.com/api/v3/categories/\"", "# ('include[]','descriptions') ] url += '&' + urllib.urlencode(args) data =", "NOTE: Not sure if this is necessary. Just a precaution.", "Uses the OctoPart API to download all datasheets associated with", "= result['item'] # Grab the Part in the SearchResult print", "counter) def parse_args(): \"\"\" Function: parse_args -------------------- Parse the arguments", "hits return search_response['hits'] def download_datasheets(search_query): \"\"\" Function: download_datasheets -------------------- Uses", "find_total_hits(search_query): \"\"\" Function: find_total_hits -------------------- Returns the number of hits", "search keywords. \"\"\" MAX_RESULTS = 100 counter = 0 total_hits", "counter of files downloaded # NOTE: Not sure if this", "Download datasheets for %s\" % search_query download_datasheets(search_query) finish_time = time.time()", "SearchResult print (\"[info] %s_%s...\" % (part['brand']['name'].replace(\" \", \"\"), part['mpn'])), sys.stdout.flush()", "in search_response['results']: part = result['item'] # Grab the Part in", "+= \"?apikey=<KEY>\" args = [ ('q', search_query), ('start', 0), ('limit',", "in outer loop: \" + str(i) continue for result in", "== \"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query = parse_args() # Parse commandline", "Limit ourselves to 3 HTTP Requests/second print(\"DONE\") print(\"[info] %s Parts", "sys.setdefaultencoding('utf-8') search_query = parse_args() # Parse commandline arguments start_time =", "\", err.code, continue; # advance to next datasheet rather than", "the SearchResponse # Iterate through the SearchResults in the SearchResponse", "\", \"\"), part['mpn'])), sys.stdout.flush() # Iterate through list of datasheets", "API to download all datasheets associated with a given set", "> Transistors > BJTs TRANSISTOR_ID = b814751e89ff63d3 def find_total_hits(search_query): \"\"\"", "Function if __name__ == \"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query = parse_args()", "datasheets ('include[]','datasheets') ] url += '&' + urllib.urlencode(args) data =", "many multiples of 100s of hits there are num_hundreds =", "Parse commandline arguments start_time = time.time() print \"[info] Download datasheets", "Discrete Semiconductors > Transistors > BJTs TRANSISTOR_ID = b814751e89ff63d3 def", "parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query in quotes (required)\") parser.add_argument('--version', action='version', version='%(prog)s", "= re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError: continue; # skip to next", "print (\"[info] %s_%s...\" % (part['brand']['name'].replace(\" \", \"\"), part['mpn'])), sys.stdout.flush() #", "here (https://octopart.com/api/register) url += \"?apikey=<KEY>\" args = [ ('q', search_query),", "list of datasheets for the given part for datasheet in", "precaution. time.sleep(0.4) # Limit ourselves to 3 HTTP Requests/second print(\"DONE\")", "time import argparse import re # Category ID for Discrete", "quotes (required)\") parser.add_argument('--version', action='version', version='%(prog)s 0.1.0') args = parser.parse_args() return", "Access Denied!...\", else: print \"[error] HTTP Error code \", err.code,", "of datasheets for the given part for datasheet in part['datasheets']:", "start_time = time.time() print \"[info] Download datasheets for %s\" %", "err.code == 404: print \"[error] Page not found!...\", elif err.code", "MAX_RESULTS print \"[info] Performing %s iterations of %s results.\" %", "be accepted parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query in", "continue; # skip to next datasheet rather than crashing file", "100 counter = 0 total_hits = find_total_hits(search_query) # print number", "else: print \"[error] HTTP Error code \", err.code, continue; #", "# Category ID for Discrete Semiconductors > Transistors > BJTs", "search_response.get('results'): print \"[error] no results returned in outer loop: \"", "print \"[error] Page not found!...\", elif err.code == 403: print", "(total_hits) # Calculate how many multiples of 100s of hits", "Scraper \"\"\" # Define what commandline arguments can be accepted", "for the query were downloaded.\" % counter) def parse_args(): \"\"\"", "key here (https://octopart.com/api/register) url += \"?apikey=09b32c6c\" args = [ ('q',", "% (part['brand']['name'].replace(\" \", \"\"), part['mpn'])), sys.stdout.flush() # Iterate through list", "COMPLETED: %s datasheets for the query were downloaded.\" % counter)", "None: # Download the PDF try: response = urllib2.urlopen(pdflink) except", "url += \"?apikey=<KEY>\" args = [ ('q', search_query), ('start', 0),", "urllib.urlencode(args) data = urllib.urlopen(url).read() # perform a SearchRequest search_response =", "given part for datasheet in part['datasheets']: # Grab the Datasheet", "Parts Completed.\" % MAX_RESULTS) print(\"[info] COMPLETED: %s datasheets for the", "Octopart Datasheet Scraper \"\"\" # Define what commandline arguments can", "\"?apikey=09b32c6c\" args = [ ('q', search_query), ('start', (i * MAX_RESULTS)),", "there are num_hundreds = total_hits / MAX_RESULTS print \"[info] Performing", "MAX_RESULTS = 100 counter = 0 total_hits = find_total_hits(search_query) #", "parse_args(): \"\"\" Function: parse_args -------------------- Parse the arguments for the", "urllib2.urlopen(pdflink) except urllib2.HTTPError, err: if err.code == 404: print \"[error]", "datasheets ('include[]','datasheets') # ('include[]','specs'), # ('include[]','descriptions') ] url += '&'", "MAX_RESULTS)), ('limit', MAX_RESULTS), # change to edit number of datasheets", "Grab the Datasheet URL pdflink = datasheet['url'] if pdflink is", "action='version', version='%(prog)s 0.1.0') args = parser.parse_args() return args.query # Main", "Grab the SearchResponse # return number of hits return search_response['hits']", "\"[error] HTTP Error code \", err.code, continue; # advance to", "counter += 1 # Increment the counter of files downloaded", "print \"[error] Access Denied!...\", else: print \"[error] HTTP Error code", "parser.add_argument('--version', action='version', version='%(prog)s 0.1.0') args = parser.parse_args() return args.query #", "datasheets associated with a given set of search keywords. \"\"\"", "%s\" % (total_hits) # Calculate how many multiples of 100s", "('include[]','descriptions') ] url += '&' + urllib.urlencode(args) data = urllib.urlopen(url).read()", "= parse_args() # Parse commandline arguments start_time = time.time() print", "# Download the PDF try: response = urllib2.urlopen(pdflink) except urllib2.HTTPError,", "= find_total_hits(search_query) # print number of hits print \"[info] Search", "Page not found!...\", elif err.code == 403: print \"[error] Access", "-------------------- Returns the number of hits that correspond to the", "err.code, continue; # advance to next datasheet rather than crashing", "result['item'] # Grab the Part in the SearchResult print (\"[info]", "datasheet['url']).group(1) except AttributeError: continue; # skip to next datasheet rather", "urllib2.HTTPError, err: if err.code == 404: print \"[error] Page not", "than crashing try: filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError: continue;", "urllib.urlopen(url).read() # perform a SearchRequest search_response = json.loads(data) # Grab", "to next datasheet rather than crashing try: filename = re.search('([^/]*)\\.[^.]*$',", "print \"[info] Performing %s iterations of %s results.\" % (num_hundreds,", "= urllib2.urlopen(pdflink) except urllib2.HTTPError, err: if err.code == 404: print", "iterations of %s results.\" % (num_hundreds, MAX_RESULTS) for i in", "Search Response Hits: %s\" % (total_hits) # Calculate how many", "('include[]','datasheets') # ('include[]','specs'), # ('include[]','descriptions') ] url += '&' +", "SearchResponse # Iterate through the SearchResults in the SearchResponse if", "change to edit number of datasheets ('include[]','datasheets') # ('include[]','specs'), #", "== 404: print \"[error] Page not found!...\", elif err.code ==", "NOTE: Use your API key here (https://octopart.com/api/register) url += \"?apikey=09b32c6c\"", "range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\" # NOTE: Use your API key", "arguments can be accepted parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to", "Iterate through list of datasheets for the given part for", "\"?apikey=<KEY>\" args = [ ('q', search_query), ('start', 0), ('limit', 1),", "Requests/second print(\"DONE\") print(\"[info] %s Parts Completed.\" % MAX_RESULTS) print(\"[info] COMPLETED:", "import json import urllib import urllib2 import time import argparse", "time.time() print \"[info] Download datasheets for %s\" % search_query download_datasheets(search_query)", "filename, 'w') file.write(response.read()) file.close() counter += 1 # Increment the", "+= \"?apikey=09b32c6c\" args = [ ('q', search_query), ('start', (i *", "a given set of search keywords. \"\"\" MAX_RESULTS = 100", "+= 1 # Increment the counter of files downloaded #", "the search query. \"\"\" url = \"http://octopart.com/api/v3/categories/\" # NOTE: Use", "key here (https://octopart.com/api/register) url += \"?apikey=<KEY>\" args = [ ('q',", "# return number of hits return search_response['hits'] def download_datasheets(search_query): \"\"\"", "not found!...\", elif err.code == 403: print \"[error] Access Denied!...\",", "except urllib2.HTTPError, err: if err.code == 404: print \"[error] Page", "correspond to the search query. \"\"\" url = \"http://octopart.com/api/v3/categories/\" #", "err: if err.code == 404: print \"[error] Page not found!...\",", "version='%(prog)s 0.1.0') args = parser.parse_args() return args.query # Main Function", "next datasheet rather than crashing try: filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1)", "search_query download_datasheets(search_query) finish_time = time.time() print '[info] Took', finish_time -", "# NOTE: Not sure if this is necessary. Just a", "if this is necessary. Just a precaution. time.sleep(0.4) # Limit", "the SearchResult print (\"[info] %s_%s...\" % (part['brand']['name'].replace(\" \", \"\"), part['mpn'])),", "Denied!...\", else: print \"[error] HTTP Error code \", err.code, continue;", "search_query), ('start', (i * MAX_RESULTS)), ('limit', MAX_RESULTS), # change to", "Not sure if this is necessary. Just a precaution. time.sleep(0.4)", "MAX_RESULTS), # change to edit number of datasheets ('include[]','datasheets') #", "import argparse import re # Category ID for Discrete Semiconductors", "how many multiples of 100s of hits there are num_hundreds", "reload(sys) sys.setdefaultencoding('utf-8') search_query = parse_args() # Parse commandline arguments start_time", "are num_hundreds = total_hits / MAX_RESULTS print \"[info] Performing %s", "+ urllib.urlencode(args) data = urllib.urlopen(url).read() # perform a SearchRequest search_response", "next datasheet rather than crashing file = open(\"../datasheets/%s.pdf\" % filename,", "the arguments for the Octopart Datasheet Scraper \"\"\" # Define", "pdflink = datasheet['url'] if pdflink is not None: # Download", "a precaution. time.sleep(0.4) # Limit ourselves to 3 HTTP Requests/second", "total_hits = find_total_hits(search_query) # print number of hits print \"[info]", "SearchRequest search_response = json.loads(data) # Grab the SearchResponse # Iterate", "datasheet rather than crashing try: filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except", "Use your API key here (https://octopart.com/api/register) url += \"?apikey=<KEY>\" args", "if not search_response.get('results'): print \"[error] no results returned in outer", "filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError: continue; # skip to", "re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError: continue; # skip to next datasheet", "skip to next datasheet rather than crashing file = open(\"../datasheets/%s.pdf\"", "b814751e89ff63d3 def find_total_hits(search_query): \"\"\" Function: find_total_hits -------------------- Returns the number", "response = urllib2.urlopen(pdflink) except urllib2.HTTPError, err: if err.code == 404:", "were downloaded.\" % counter) def parse_args(): \"\"\" Function: parse_args --------------------", "ID for Discrete Semiconductors > Transistors > BJTs TRANSISTOR_ID =", "= time.time() print \"[info] Download datasheets for %s\" % search_query", "continue; # advance to next datasheet rather than crashing try:", "Define what commandline arguments can be accepted parser = argparse.ArgumentParser()", "Function: download_datasheets -------------------- Uses the OctoPart API to download all", "# change to edit number of datasheets ('include[]','datasheets') # ('include[]','specs'),", "of datasheets ('include[]','datasheets') ] url += '&' + urllib.urlencode(args) data", "= urllib.urlopen(url).read() # perform a SearchRequest search_response = json.loads(data) #", "results.\" % (num_hundreds, MAX_RESULTS) for i in range(num_hundreds+1): url =", "with a given set of search keywords. \"\"\" MAX_RESULTS =", "part for datasheet in part['datasheets']: # Grab the Datasheet URL", "increase number of datasheets ('include[]','datasheets') ] url += '&' +", "API key here (https://octopart.com/api/register) url += \"?apikey=<KEY>\" args = [", "the number of hits that correspond to the search query.", "search_response['results']: part = result['item'] # Grab the Part in the", "def find_total_hits(search_query): \"\"\" Function: find_total_hits -------------------- Returns the number of", "to download all datasheets associated with a given set of", "of hits print \"[info] Search Response Hits: %s\" % (total_hits)", "your API key here (https://octopart.com/api/register) url += \"?apikey=09b32c6c\" args =", "result in search_response['results']: part = result['item'] # Grab the Part", "-------------------- Parse the arguments for the Octopart Datasheet Scraper \"\"\"", "def download_datasheets(search_query): \"\"\" Function: download_datasheets -------------------- Uses the OctoPart API", "if __name__ == \"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query = parse_args() #", "(i * MAX_RESULTS)), ('limit', MAX_RESULTS), # change to edit number", "('include[]','datasheets') ] url += '&' + urllib.urlencode(args) data = urllib.urlopen(url).read()", "file = open(\"../datasheets/%s.pdf\" % filename, 'w') file.write(response.read()) file.close() counter +=", "Grab the Part in the SearchResult print (\"[info] %s_%s...\" %", "str(i) continue for result in search_response['results']: part = result['item'] #", "download_datasheets(search_query): \"\"\" Function: download_datasheets -------------------- Uses the OctoPart API to", "Datasheet URL pdflink = datasheet['url'] if pdflink is not None:", "(https://octopart.com/api/register) url += \"?apikey=<KEY>\" args = [ ('q', search_query), ('start',", "search_query = parse_args() # Parse commandline arguments start_time = time.time()", "# Limit ourselves to 3 HTTP Requests/second print(\"DONE\") print(\"[info] %s", "(\"[info] %s_%s...\" % (part['brand']['name'].replace(\" \", \"\"), part['mpn'])), sys.stdout.flush() # Iterate", "rather than crashing try: filename = re.search('([^/]*)\\.[^.]*$', datasheet['url']).group(1) except AttributeError:", "== 403: print \"[error] Access Denied!...\", else: print \"[error] HTTP", "parse_args() # Parse commandline arguments start_time = time.time() print \"[info]", "to edit number of datasheets ('include[]','datasheets') # ('include[]','specs'), # ('include[]','descriptions')", "parser.parse_args() return args.query # Main Function if __name__ == \"__main__\":", "in range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\" # NOTE: Use your API", "arguments start_time = time.time() print \"[info] Download datasheets for %s\"", "the Octopart Datasheet Scraper \"\"\" # Define what commandline arguments", "Performing %s iterations of %s results.\" % (num_hundreds, MAX_RESULTS) for", "\"[error] no results returned in outer loop: \" + str(i)", "sys.stdout.flush() # Iterate through list of datasheets for the given", "(required)\") parser.add_argument('--version', action='version', version='%(prog)s 0.1.0') args = parser.parse_args() return args.query", "%s iterations of %s results.\" % (num_hundreds, MAX_RESULTS) for i", "number of hits return search_response['hits'] def download_datasheets(search_query): \"\"\" Function: download_datasheets", "counter = 0 total_hits = find_total_hits(search_query) # print number of", "= json.loads(data) # Grab the SearchResponse # return number of", "= json.loads(data) # Grab the SearchResponse # Iterate through the", "multiples of 100s of hits there are num_hundreds = total_hits", "0.1.0') args = parser.parse_args() return args.query # Main Function if", "= total_hits / MAX_RESULTS print \"[info] Performing %s iterations of", "in the SearchResponse if not search_response.get('results'): print \"[error] no results", "= \"http://octopart.com/api/v3/categories/\" # NOTE: Use your API key here (https://octopart.com/api/register)", "number of hits print \"[info] Search Response Hits: %s\" %", "# ('include[]','specs'), # ('include[]','descriptions') ] url += '&' + urllib.urlencode(args)", "print \"[info] Download datasheets for %s\" % search_query download_datasheets(search_query) finish_time", "import urllib2 import time import argparse import re # Category", "Returns the number of hits that correspond to the search", "% (total_hits) # Calculate how many multiples of 100s of", "+= '&' + urllib.urlencode(args) data = urllib.urlopen(url).read() # perform a", "a SearchRequest search_response = json.loads(data) # Grab the SearchResponse #", "= 100 counter = 0 total_hits = find_total_hits(search_query) # print", "\"[info] Search Response Hits: %s\" % (total_hits) # Calculate how", "# skip to next datasheet rather than crashing file =", "through the SearchResults in the SearchResponse if not search_response.get('results'): print", "> BJTs TRANSISTOR_ID = b814751e89ff63d3 def find_total_hits(search_query): \"\"\" Function: find_total_hits", "search_response = json.loads(data) # Grab the SearchResponse # Iterate through", "(num_hundreds, MAX_RESULTS) for i in range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\" #", "[ ('q', search_query), ('start', 0), ('limit', 1), #change to increase", "part['datasheets']: # Grab the Datasheet URL pdflink = datasheet['url'] if", "%s\" % search_query download_datasheets(search_query) finish_time = time.time() print '[info] Took',", "\"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query = parse_args() # Parse commandline arguments", "print number of hits print \"[info] Search Response Hits: %s\"", "url = \"http://octopart.com/api/v3/parts/search\" # NOTE: Use your API key here", "of datasheets ('include[]','datasheets') # ('include[]','specs'), # ('include[]','descriptions') ] url +=", "import urllib import urllib2 import time import argparse import re", "for the Octopart Datasheet Scraper \"\"\" # Define what commandline", "all datasheets associated with a given set of search keywords.", "SearchResults in the SearchResponse if not search_response.get('results'): print \"[error] no", "print(\"DONE\") print(\"[info] %s Parts Completed.\" % MAX_RESULTS) print(\"[info] COMPLETED: %s", "('limit', 1), #change to increase number of datasheets ('include[]','datasheets') ]", "1), #change to increase number of datasheets ('include[]','datasheets') ] url", "for datasheet in part['datasheets']: # Grab the Datasheet URL pdflink", "\"\"\" # Define what commandline arguments can be accepted parser", "= open(\"../datasheets/%s.pdf\" % filename, 'w') file.write(response.read()) file.close() counter += 1", "try: response = urllib2.urlopen(pdflink) except urllib2.HTTPError, err: if err.code ==", "for Discrete Semiconductors > Transistors > BJTs TRANSISTOR_ID = b814751e89ff63d3", "python import sys import json import urllib import urllib2 import", "i in range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\" # NOTE: Use your", "crashing file = open(\"../datasheets/%s.pdf\" % filename, 'w') file.write(response.read()) file.close() counter", "total_hits / MAX_RESULTS print \"[info] Performing %s iterations of %s", "Category ID for Discrete Semiconductors > Transistors > BJTs TRANSISTOR_ID", "Calculate how many multiples of 100s of hits there are", "advance to next datasheet rather than crashing try: filename =", "print(\"[info] %s Parts Completed.\" % MAX_RESULTS) print(\"[info] COMPLETED: %s datasheets", "part['mpn'])), sys.stdout.flush() # Iterate through list of datasheets for the", "returned in outer loop: \" + str(i) continue for result", "print \"[error] HTTP Error code \", err.code, continue; # advance", "the OctoPart API to download all datasheets associated with a", "0 total_hits = find_total_hits(search_query) # print number of hits print", "args = [ ('q', search_query), ('start', (i * MAX_RESULTS)), ('limit',", "for the given part for datasheet in part['datasheets']: # Grab", "number of datasheets ('include[]','datasheets') # ('include[]','specs'), # ('include[]','descriptions') ] url", "if pdflink is not None: # Download the PDF try:", "# perform a SearchRequest search_response = json.loads(data) # Grab the", "urllib import urllib2 import time import argparse import re #", "\"[error] Page not found!...\", elif err.code == 403: print \"[error]", "Main Function if __name__ == \"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query =", "of 100s of hits there are num_hundreds = total_hits /", "to 3 HTTP Requests/second print(\"DONE\") print(\"[info] %s Parts Completed.\" %", "\"\"\" Function: find_total_hits -------------------- Returns the number of hits that", "part = result['item'] # Grab the Part in the SearchResult", "the given part for datasheet in part['datasheets']: # Grab the", "search_query), ('start', 0), ('limit', 1), #change to increase number of", "in part['datasheets']: # Grab the Datasheet URL pdflink = datasheet['url']", "parse_args -------------------- Parse the arguments for the Octopart Datasheet Scraper", "argparse import re # Category ID for Discrete Semiconductors >", "edit number of datasheets ('include[]','datasheets') # ('include[]','specs'), # ('include[]','descriptions') ]", "find_total_hits -------------------- Returns the number of hits that correspond to", "url += \"?apikey=09b32c6c\" args = [ ('q', search_query), ('start', (i", "3 HTTP Requests/second print(\"DONE\") print(\"[info] %s Parts Completed.\" % MAX_RESULTS)", "json.loads(data) # Grab the SearchResponse # Iterate through the SearchResults", "download_datasheets(search_query) finish_time = time.time() print '[info] Took', finish_time - start_time,", "= b814751e89ff63d3 def find_total_hits(search_query): \"\"\" Function: find_total_hits -------------------- Returns the", "\"\"), part['mpn'])), sys.stdout.flush() # Iterate through list of datasheets for", "urllib2 import time import argparse import re # Category ID", "%s results.\" % (num_hundreds, MAX_RESULTS) for i in range(num_hundreds+1): url", "\"[info] Performing %s iterations of %s results.\" % (num_hundreds, MAX_RESULTS)", "% MAX_RESULTS) print(\"[info] COMPLETED: %s datasheets for the query were", "set of search keywords. \"\"\" MAX_RESULTS = 100 counter =", "# Main Function if __name__ == \"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query", "% filename, 'w') file.write(response.read()) file.close() counter += 1 # Increment", "not None: # Download the PDF try: response = urllib2.urlopen(pdflink)", "hits there are num_hundreds = total_hits / MAX_RESULTS print \"[info]", "json.loads(data) # Grab the SearchResponse # return number of hits", "Iterate through the SearchResults in the SearchResponse if not search_response.get('results'):", "err.code == 403: print \"[error] Access Denied!...\", else: print \"[error]", "\"http://octopart.com/api/v3/parts/search\" # NOTE: Use your API key here (https://octopart.com/api/register) url", "Transistors > BJTs TRANSISTOR_ID = b814751e89ff63d3 def find_total_hits(search_query): \"\"\" Function:", "# Increment the counter of files downloaded # NOTE: Not", "# Grab the SearchResponse # return number of hits return", "if err.code == 404: print \"[error] Page not found!...\", elif", "is not None: # Download the PDF try: response =", "# advance to next datasheet rather than crashing try: filename", "parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query in quotes (required)\")", "* MAX_RESULTS)), ('limit', MAX_RESULTS), # change to edit number of", "100s of hits there are num_hundreds = total_hits / MAX_RESULTS", "perform a SearchRequest search_response = json.loads(data) # Grab the SearchResponse", "query. \"\"\" url = \"http://octopart.com/api/v3/categories/\" # NOTE: Use your API", "url += '&' + urllib.urlencode(args) data = urllib.urlopen(url).read() # perform", "Completed.\" % MAX_RESULTS) print(\"[info] COMPLETED: %s datasheets for the query", "file.write(response.read()) file.close() counter += 1 # Increment the counter of", "('limit', MAX_RESULTS), # change to edit number of datasheets ('include[]','datasheets')", "# Iterate through the SearchResults in the SearchResponse if not", "pdflink is not None: # Download the PDF try: response", "= [ ('q', search_query), ('start', (i * MAX_RESULTS)), ('limit', MAX_RESULTS),", "for result in search_response['results']: part = result['item'] # Grab the", "#change to increase number of datasheets ('include[]','datasheets') ] url +=", "hits that correspond to the search query. \"\"\" url =", "associated with a given set of search keywords. \"\"\" MAX_RESULTS", "\"http://octopart.com/api/v3/categories/\" # NOTE: Use your API key here (https://octopart.com/api/register) url", "MAX_RESULTS) for i in range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\" # NOTE:", "% search_query download_datasheets(search_query) finish_time = time.time() print '[info] Took', finish_time", "the SearchResults in the SearchResponse if not search_response.get('results'): print \"[error]", "%s_%s...\" % (part['brand']['name'].replace(\" \", \"\"), part['mpn'])), sys.stdout.flush() # Iterate through", "TRANSISTOR_ID = b814751e89ff63d3 def find_total_hits(search_query): \"\"\" Function: find_total_hits -------------------- Returns", "1 # Increment the counter of files downloaded # NOTE:", "Function: parse_args -------------------- Parse the arguments for the Octopart Datasheet", "# Grab the SearchResponse # Iterate through the SearchResults in", "here (https://octopart.com/api/register) url += \"?apikey=09b32c6c\" args = [ ('q', search_query),", "the PDF try: response = urllib2.urlopen(pdflink) except urllib2.HTTPError, err: if", "\"[error] Access Denied!...\", else: print \"[error] HTTP Error code \",", "your API key here (https://octopart.com/api/register) url += \"?apikey=<KEY>\" args =", "the SearchResponse # return number of hits return search_response['hits'] def", "def parse_args(): \"\"\" Function: parse_args -------------------- Parse the arguments for", "0), ('limit', 1), #change to increase number of datasheets ('include[]','datasheets')", "= argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query in quotes (required)\") parser.add_argument('--version',", "+ str(i) continue for result in search_response['results']: part = result['item']", "file.close() counter += 1 # Increment the counter of files", "argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\", help=\"keywords to query in quotes (required)\") parser.add_argument('--version', action='version',", "# Define what commandline arguments can be accepted parser =", "URL pdflink = datasheet['url'] if pdflink is not None: #", "404: print \"[error] Page not found!...\", elif err.code == 403:", "finish_time = time.time() print '[info] Took', finish_time - start_time, 'sec", "\" + str(i) continue for result in search_response['results']: part =", "import re # Category ID for Discrete Semiconductors > Transistors", "PDF try: response = urllib2.urlopen(pdflink) except urllib2.HTTPError, err: if err.code", "MAX_RESULTS) print(\"[info] COMPLETED: %s datasheets for the query were downloaded.\"", "commandline arguments start_time = time.time() print \"[info] Download datasheets for", "datasheets for %s\" % search_query download_datasheets(search_query) finish_time = time.time() print", "\"\"\" Function: download_datasheets -------------------- Uses the OctoPart API to download", "return number of hits return search_response['hits'] def download_datasheets(search_query): \"\"\" Function:", "__name__ == \"__main__\": reload(sys) sys.setdefaultencoding('utf-8') search_query = parse_args() # Parse", "found!...\", elif err.code == 403: print \"[error] Access Denied!...\", else:", "help=\"keywords to query in quotes (required)\") parser.add_argument('--version', action='version', version='%(prog)s 0.1.0')", "for i in range(num_hundreds+1): url = \"http://octopart.com/api/v3/parts/search\" # NOTE: Use", "/usr/bin/env python import sys import json import urllib import urllib2", "datasheets for the given part for datasheet in part['datasheets']: #", "the Datasheet URL pdflink = datasheet['url'] if pdflink is not", "continue for result in search_response['results']: part = result['item'] # Grab", "necessary. Just a precaution. time.sleep(0.4) # Limit ourselves to 3", "return args.query # Main Function if __name__ == \"__main__\": reload(sys)", "this is necessary. Just a precaution. time.sleep(0.4) # Limit ourselves", "print \"[error] no results returned in outer loop: \" +", "AttributeError: continue; # skip to next datasheet rather than crashing", "%s datasheets for the query were downloaded.\" % counter) def", "\"\"\" Function: parse_args -------------------- Parse the arguments for the Octopart", "than crashing file = open(\"../datasheets/%s.pdf\" % filename, 'w') file.write(response.read()) file.close()", "('start', (i * MAX_RESULTS)), ('limit', MAX_RESULTS), # change to edit", "num_hundreds = total_hits / MAX_RESULTS print \"[info] Performing %s iterations", "Hits: %s\" % (total_hits) # Calculate how many multiples of", "import sys import json import urllib import urllib2 import time", "('include[]','specs'), # ('include[]','descriptions') ] url += '&' + urllib.urlencode(args) data", "the query were downloaded.\" % counter) def parse_args(): \"\"\" Function:", "'&' + urllib.urlencode(args) data = urllib.urlopen(url).read() # perform a SearchRequest", "of %s results.\" % (num_hundreds, MAX_RESULTS) for i in range(num_hundreds+1):", "= \"http://octopart.com/api/v3/parts/search\" # NOTE: Use your API key here (https://octopart.com/api/register)", "\"[info] Download datasheets for %s\" % search_query download_datasheets(search_query) finish_time =", "Download the PDF try: response = urllib2.urlopen(pdflink) except urllib2.HTTPError, err:", "Parse the arguments for the Octopart Datasheet Scraper \"\"\" #", "is necessary. Just a precaution. time.sleep(0.4) # Limit ourselves to", "what commandline arguments can be accepted parser = argparse.ArgumentParser() parser.add_argument('query',metavar=\"\\\"SEARCH_KEYWORDS\\\"\",", "Error code \", err.code, continue; # advance to next datasheet", "results returned in outer loop: \" + str(i) continue for", "Just a precaution. time.sleep(0.4) # Limit ourselves to 3 HTTP", "Response Hits: %s\" % (total_hits) # Calculate how many multiples", "# Calculate how many multiples of 100s of hits there" ]
[ "stat += (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate)))", "help='The number of iterations of the test (default: 1)') parser.add_argument('-O',", "-O --occurrences The number of occurrences of the template (default:", "{ \"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI sensorTag/pressure\", \"sensor_values\" :", "help='The type of statistics to collect ' '(default: total)') namespace", "= os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval,", "payload ' 'and protocol (default: coap)') parser.add_argument('-I', '--iterations', help='The number", "str_res[:4] # or str_res.split()[0] if status_code == \"4.00\" or status_code", "a Python script used to test FogLAMP. The objective is", "Pre-calculate the messages and size msg_transferred_itr = 0 # Messages", "file name specified with -o * Read those objects *", ": \"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI sensorTag/pressure\", \"sensor_values\" : { \"pressure\"", "of FogLAMP southbound services. fogbench [IN] -h --help Print this", ": \"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI sensorTag/magnetometer\", \"sensor_values\" : { \"x\"", ": { \"pressure\" : 1021.2 } } { \"timestamp\" :", "requests against one or more FogLAMP instances. This version of", "Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port = arg_port request.opt.uri_path =", "itr in range(_num_iterated): time_taken = _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr]", "this help -i --interval The interval in seconds between each", "InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min and Max values must be defined", "sensorTag/accelerometer\", \"sensor_values\" : { \"x\" : 1.2, \"y\" : 0.0,", "_template_file) with open(_template_file) as data_file: data = json.load(data_file) supported_format_types =", "_keep: os.remove(_file) async def send_to_coap(payload): \"\"\" POST request to: localhost", "- _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin messages/second:", "messages/second: {}\".format(max(_msg_rate))) stat += (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin", "sample (default: no) [IN] -o --output Set the output file", "\"sensor_values\" : { \"x\" : 1.2, \"y\" : 0.0, \"z\"", "= int(namespace.occurrences) if namespace.occurrences else 1 # interval between each", "import os import random import json from datetime import datetime,", "'http'], help='Type of payload ' 'and protocol (default: coap)') parser.add_argument('-I',", "template file, json extension') parser.add_argument('-o', '--output', default=None, help='Set the statistics", "the running sample (default: no)') parser.add_argument('-t', '--template', required=True, help='Set the", "_start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time of every iteration _tot_msgs_transferred.append(msg_transferred_itr)", "reading # print(d[\"name\"]) sensor_value_object = dict() sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"]", "# print(min_val) # print(max_val) reading = round(random.uniform(min_val, max_val), precision) elif", "} } { \"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI sensorTag/temperature\",", "\"asset\" : \"TI sensorTag/humidity\", \"sensor_values\" : { \"humidity\" : 71.2,", "[IN] -S --statistic The type of statistics to collect Example:", "# print(u\"Iteration {} completed, waiting for {} seconds\".format(_iterations, _interval)) time.sleep(_interval)", "_start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin messages/second: {}\".format(min(_msg_rate)))", "def local_timestamp(): \"\"\" :return: str - current time stamp with", "each iteration (default: 0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The type", "the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings = [] for d in", "on specific host and port .. todo:: * Try generators", "send_to='coap'): global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global", "{}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\")))", "(official IANA assigned CoAP port), URI \"/other/sensor-values\". \"\"\" from aiocoap", "(time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat += (u\"\\nMax messages/second:", "\"asset\" : \"TI sensorTag/accelerometer\", \"sensor_values\" : { \"x\" : 1.2,", "stamp with microseconds and machine timezone info :example '2018-05-08 14:06:40.517313+05:30'", "to collect ' '(default: total)') namespace = parser.parse_args(sys.argv[1:]) infile =", "for statistics [IN] -p --payload Type of payload and protocol", "stat += (u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal Bytes", "and port .. todo:: * Try generators \"\"\" import sys", "\"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI sensorTag/luxometer\", \"sensor_values\" : { \"lux\" :", "# print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] = reading # print(d[\"name\"]) sensor_value_object =", "diff? end_time - start_time def check_server(payload_type='coap'): template_str = \">>> Make", "pprint import pprint import time # _file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile))", "# print(max_val) reading = round(random.uniform(min_val, max_val), precision) elif fmt[\"type\"] ==", "(u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred)))", "= 0 \"\"\"Statistics to be collected\"\"\" # _logger = logger.setup(__name__)", "open(_out_file, 'w') as f: f.write(stat) else: print(stat) # should we", "of %(prog)s is meant to test the south plugin interface", "\"asset\" : \"TI sensorTag/luxometer\", \"sensor_values\" : { \"lux\" : 49", "print(d[\"name\"]) sensor_value_object = dict() sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"] = x_sensor_values", "between each iteration arg_interval = int(namespace.interval) if namespace.interval else 0", "code:{}, reason: {}\".format(status_code, resp.reason)) return False if status_code in range(500,", "parser.add_argument('-I', '--iterations', help='The number of iterations of the test (default:", ": 0.0, \"z\" : -0.6 } } { \"timestamp\" :", "of ' \\ 'FogLAMP using CoAP or HTTP' parser.add_argument('-v', '--version',", ": 49 } } { \"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\" :", "'coap': print(template_str.format(\"CoAP\")) elif payload_type == 'http': print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench')", "argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s -- a Python script used to", "templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file = os.path.join(os.path.dirname(__file__), \"templates/\"", "iteration for r in readings_list: msg_transferred_itr += 1 byte_transferred_itr +=", ": \"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI sensorTag/temperature\", \"sensor_values\" : { \"object\"", "random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] = reading # print(d[\"name\"]) sensor_value_object", "'yes', 'n', 'no'], help='Do not delete the running sample (default:", "* Create reading objects from given template, as per the", ":example '2018-05-08 14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates =", "used to test FogLAMP. The objective is to simulate payloads", "r in readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r): with open(to_file,", "print(\"Server error | code:{}, reason: {}\".format(status_code, resp.reason)) return False return", "session: async with session.post(url, data=json.dumps(payload), headers=headers) as resp: await resp.text()", "\"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI sensorTag/luxometer\", \"sensor_values\" : {", "for each iteration (default: 0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The", "= \"Apache 2.0\" __version__ = \"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\" _start_time", "not delete (keep) the running sample (default: no) [IN] -o", "import datetime, timezone import argparse import collections import asyncio import", "'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession() as session:", "1021.2 } } { \"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI", "-k --keep Do not delete (keep) the running sample (default:", "The objective is to simulate payloads for input, REST and", "_num_iterated # from pprint import pprint import time # _file", "stat += (u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal Iterations:", "int(namespace.interval) if namespace.interval else 0 arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics", "= u\"0.1.1\" _start_time = [] _end_time = [] _tot_msgs_transferred =", "plugin port), uri sensor-reading \"\"\" headers = {'content-type': 'application/json'} url", "sensorTag/gyroscope\", \"sensor_values\" : { \"x\" : 101.2, \"y\" : 46.2,", "# _logger = logger.setup(__name__) def local_timestamp(): \"\"\" :return: str -", "Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat", "those objects to the file, as per the file name", "the template (default: 1)') parser.add_argument('-H', '--host', help='Server host address (default:", "for input, REST and other requests against one or more", "__copyright__ = \"Copyright (c) 2017 OSIsoft, LLC\" __license__ = \"Apache", "Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file, 'w') as f: f.write(stat)", "per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate = [] for", "else 0 arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics else 'total' if", "FogLAMP southbound services. fogbench [IN] -h --help Print this help", "the messages and size msg_transferred_itr = 0 # Messages transferred", "from aiocoap.numbers.codes import Code from cbor2 import dumps context =", "+= (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file, 'w') as", "= \"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\" _start_time = [] _end_time =", "not parse type {}\".format(fmt[\"type\"])) if fmt[\"type\"] == \"number\": # check", "as per the json file name specified with -t *", "fmt in _sensor_value_object_formats: if fmt[\"type\"] not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid", "version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes', 'n', 'no'], help='Do", "False return True async def send_to_http(payload): \"\"\" POST request to:", "int(namespace.iterations) if namespace.iterations else 1 arg_occurrences = int(namespace.occurrences) if namespace.occurrences", "parser.add_argument('-P', '--port', help='The FogLAMP port. (default: 5683)') parser.add_argument('-i', '--interval', default=0,", "Bytes/second: {}\".format(max(_byte_rate))) stat += (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with", "True def get_statistics(_stats_type=None, _out_file=None): stat = '' global _start_time global", "_out_file: with open(_out_file, 'w') as f: f.write(stat) else: print(stat) #", "resp.reason)) return False return True def get_statistics(_stats_type=None, _out_file=None): stat =", "= fmt.get(\"min\", None) max_val = fmt.get(\"max\", None) if min_val is", "interval in seconds for each iteration (default: 0)') parser.add_argument('-S', '--statistics',", "check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file,", "u\"0.1.1\" _start_time = [] _end_time = [] _tot_msgs_transferred = []", "in readings_list: msg_transferred_itr += 1 byte_transferred_itr += sys.getsizeof(r) if send_to", "Iterations: {}\".format(_num_iterated)) stat += (u\"\\nTotal Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat", "_start_time.append(datetime.now()) for r in readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if not", "0.0, \"z\" : -0.6 } } { \"timestamp\" : \"2017-08-04T07:00:01.863Z\",", "--help Print this help -i --interval The interval in seconds", "parser.add_argument('-i', '--interval', default=0, help='The interval in seconds for each iteration", "{} plugin service is running \\n & listening on specified", "__author__ = \"<NAME>\" __copyright__ = \"Copyright (c) 2017 OSIsoft, LLC\"", "r in readings_list: msg_transferred_itr += 1 byte_transferred_itr += sys.getsizeof(r) if", "1)') parser.add_argument('-H', '--host', help='Server host address (default: localhost)') parser.add_argument('-P', '--port',", "[IN] -P --port The FogLAMP port. Default depends on payload", "in data: x_sensor_values = dict() _sensor_value_object_formats = d[\"sensor_values\"] for fmt", "global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated if _stats_type == 'total':", "assigned CoAP port), URI \"/other/sensor-values\". \"\"\" from aiocoap import Context,", "InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can not parse type {}\".format(fmt[\"type\"])) if fmt[\"type\"]", "must be defined for type number.\") # print(precision) # print(min_val)", "the template to use [IN] -v --version Display the version", "collect Example: $ cd $FOGLAMP_ROOT/bin $ ./fogbench Help: $ ./fogbench", "\"mouse\", \"sensor_values\" : { \"button\" : \"down\" } } {", "print(min_val) # print(max_val) reading = round(random.uniform(min_val, max_val), precision) elif fmt[\"type\"]", "[IN] -o --output Set the output file for statistics [IN]", "import * __author__ = \"<NAME>\" __copyright__ = \"Copyright (c) 2017", "\">>> Make sure south {} plugin service is running \\n", "in seconds for each iteration (default: 0)') parser.add_argument('-S', '--statistics', default='total',", "} { \"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI sensorTag/humidity\", \"sensor_values\"", "True async def send_to_http(payload): \"\"\" POST request to: host localhost", "listening on specified host and port \\n\" if payload_type ==", "msg_transferred_itr += 1 byte_transferred_itr += sys.getsizeof(r) if send_to == 'coap':", "status_code == \"4.00\" or status_code == \"5.00\": print(\"Error: \", str_res)", "not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can not parse", "reading objects from given template, as per the json file", "check float precision if any precision = fmt.get(\"precision\", None) min_val", "The interval in seconds between each iteration (default: 0) [IN]", "global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated if _stats_type", "Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal Bytes per Iteration:", "\"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type,", "-P --port The FogLAMP port. Default depends on payload and", "\"z\" : -0.6 } } { \"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\"", "stat += (u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat += (u\"\\nMax messages/second: {}\".format(max(_msg_rate)))", "arg_interval = int(namespace.interval) if namespace.interval else 0 arg_stats_type = '{0}'.format(namespace.statistics)", "iterations of the test (default: 1) [IN] -O --occurrences The", "= '{0}'.format(namespace.statistics) if namespace.statistics else 'total' if namespace.payload: arg_payload_protocol =", ": \"TI sensorTag/accelerometer\", \"sensor_values\" : { \"x\" : 1.2, \"y\"", "{}\".format(max(_msg_rate))) stat += (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin Bytes/second:", "if namespace.port else default_port check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile,", "_sensor_value_object_formats: if fmt[\"type\"] not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \"", "# -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/", "delete (keep) the running sample (default: no) [IN] -o --output", "infile = '{0}'.format(namespace.template if namespace.template else '') statistics_file = os.path.join(os.path.dirname(__file__),", "(default: no)') parser.add_argument('-t', '--template', required=True, help='Set the template file, json", "from .exceptions import * __author__ = \"<NAME>\" __copyright__ = \"Copyright", "See: http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\" fogbench -- a Python script", "code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port = arg_port request.opt.uri_path = (\"other\",", "and port \\n\" if payload_type == 'coap': print(template_str.format(\"CoAP\")) elif payload_type", "as f: f.write(stat) else: print(stat) # should we also show", "_end_time.append(datetime.now()) # End time of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations", ": -12.6 } } { \"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\" :", "Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port =", "min_val = fmt.get(\"min\", None) max_val = fmt.get(\"max\", None) if min_val", "return True def get_statistics(_stats_type=None, _out_file=None): stat = '' global _start_time", "sure south {} plugin service is running \\n & listening", "{ \"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI sensorTag/temperature\", \"sensor_values\" :", "{}\".format(min(_msg_rate))) stat += (u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat += (u\"\\nAvg messages/second:", "number of iterations of the test (default: 1)') parser.add_argument('-O', '--occurrences',", "-h * Create reading objects from given template, as per", "readings def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'): global _start_time global", "18.6 } } { \"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI", "# print(d[\"name\"]) sensor_value_object = dict() sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"] =", "'no'], help='Do not delete the running sample (default: no)') parser.add_argument('-t',", "depends on payload and protocol [IN] -S --statistic The type", "def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'): global _start_time global _end_time", "-*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ #", "= await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host", "defined for type number.\") # print(precision) # print(min_val) # print(max_val)", "await resp.text() status_code = resp.status if status_code in range(400, 500):", "--keep Do not delete (keep) the running sample (default: no)", "500): print(\"Bad request error | code:{}, reason: {}\".format(status_code, resp.reason)) return", "_FOGBENCH_VERSION = u\"0.1.1\" _start_time = [] _end_time = [] _tot_msgs_transferred", "== \"5.00\": print(\"Error: \", str_res) return False return True async", "fogbench [IN] -h --help Print this help -i --interval The", "print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s -- a Python", "as f: readings_list = [json.loads(line) for line in f] loop", "print(stat) # should we also show total time diff? end_time", "for {} seconds\".format(_iterations, _interval)) time.sleep(_interval) if not _keep: os.remove(_file) async", "of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated +=", "'localhost' default_port = 6683 if arg_payload_protocol == 'http' else 5683", "FogLAMP (simulate payloads)' parser.epilog = 'The initial version of %(prog)s", "return True async def send_to_http(payload): \"\"\" POST request to: host", ": 46.2, \"z\" : -12.6 } } { \"timestamp\" :", "return False return True async def send_to_http(payload): \"\"\" POST request", "protocol (default: coap) [IN] -t --template Set the template to", "parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes',", "None keep_the_file = True if namespace.keep in ['y', 'yes'] else", "= _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat +=", "\"asset\" : \"TI sensorTag/temperature\", \"sensor_values\" : { \"object\" : 18.2,", "is_sent: break elif send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) #", "request to: host localhost port 6683 (default HTTP south plugin", "--occurrences The number of occurrences of the template (default: 1)", "'{0}'.format(namespace.statistics) if namespace.statistics else 'total' if namespace.payload: arg_payload_protocol = namespace.payload", "response = await context.request(request).response str_res = str(response.code) status_code = str_res[:4]", "with session.post(url, data=json.dumps(payload), headers=headers) as resp: await resp.text() status_code =", "FOGLAMP_END \"\"\" fogbench -- a Python script used to test", "file name specified with -t * Save those objects to", "per the file name specified with -o * Read those", "_prepare_sensor_reading(data, supported_format_types) for r in readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file,", "Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate", "\"\"\" from aiocoap import Context, Message from aiocoap.numbers.codes import Code", "def send_to_http(payload): \"\"\" POST request to: host localhost port 6683", "_stats_type == 'total': stat += u\"Total Statistics:\\n\" stat += (u\"\\nStart", "(default: 5683)') parser.add_argument('-i', '--interval', default=0, help='The interval in seconds for", "\"sensor_values\" : { \"object\" : 18.2, \"ambient\" : 21.6 }", "= d[\"sensor_values\"] for fmt in _sensor_value_object_formats: if fmt[\"type\"] not in", "HTTP south plugin port), uri sensor-reading \"\"\" headers = {'content-type':", "for line in f] loop = asyncio.get_event_loop() while _iterations >", "request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port = arg_port", "or max_val is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min and", "'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession() as session: async with session.post(url,", "+= 1 if _iterations != 0: # print(u\"Iteration {} completed,", "_byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat +=", "payloads)' parser.epilog = 'The initial version of %(prog)s is meant", "if send_to == 'coap': _start_time.append(datetime.now()) for r in readings_list: is_sent", "REST and other requests against one or more FogLAMP instances.", "FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\" fogbench -- a", "in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can not parse type", "def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file = os.path.join(os.path.dirname(__file__), \"templates/\" +", "+= (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nEnd Time:", "'w') as f: f.write(stat) else: print(stat) # should we also", "parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if namespace.template else '') statistics_file =", "resp.text() status_code = resp.status if status_code in range(400, 500): print(\"Bad", "{ \"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI sensorTag/humidity\", \"sensor_values\" :", "\"TI sensorTag/humidity\", \"sensor_values\" : { \"humidity\" : 71.2, \"temperature\" :", "iteration (default: 0) [IN] -k --keep Do not delete (keep)", "microseconds and machine timezone info :example '2018-05-08 14:06:40.517313+05:30' \"\"\" return", "+= (u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal Bytes Transferred:", "\"x\" : 101.2, \"y\" : 46.2, \"z\" : -12.6 }", "= reading # print(d[\"name\"]) sensor_value_object = dict() sensor_value_object[\"asset\"] = d['name']", "stat += (u\"\\nTotal Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = []", "iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated += 1 if", "show total time diff? end_time - start_time def check_server(payload_type='coap'): template_str", "protocol [IN] -S --statistic The type of statistics to collect", "default_port = 6683 if arg_payload_protocol == 'http' else 5683 arg_port", "['y', 'yes'] else False # iterations and occurrences arg_iterations =", "json.load(data_file) supported_format_types = [\"number\", \"enum\"] for _ in range(_occurrences): readings_", "between each iteration (default: 0) [IN] -k --keep Do not", "global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated # from", "= arg_port request.opt.uri_path = (\"other\", \"sensor-values\") response = await context.request(request).response", "send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time of", "for type number.\") # print(precision) # print(min_val) # print(max_val) reading", "port .. todo:: * Try generators \"\"\" import sys import", "open(_file) as f: readings_list = [json.loads(line) for line in f]", "of occurrences of the template (default: 1)') parser.add_argument('-H', '--host', help='Server", "= [] for d in data: x_sensor_values = dict() _sensor_value_object_formats", "Statistics:\\n\" stat += (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat +=", "of iterations of the test (default: 1) [IN] -O --occurrences", "} { \"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI sensorTag/magnetometer\", \"sensor_values\"", "in f] loop = asyncio.get_event_loop() while _iterations > 0: #", "1 arg_occurrences = int(namespace.occurrences) if namespace.occurrences else 1 # interval", "max_val), precision) elif fmt[\"type\"] == \"enum\": reading = random.choice(fmt[\"list\"]) #", "sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict =", "to test the south plugin interface of ' \\ 'FogLAMP", "async with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(payload), headers=headers)", "port 5683 (official IANA assigned CoAP port), URI \"/other/sensor-values\". \"\"\"", "= arg_host request.opt.uri_port = arg_port request.opt.uri_path = (\"other\", \"sensor-values\") response", "in range(500, 600): print(\"Server error | code:{}, reason: {}\".format(status_code, resp.reason))", "readings_list: msg_transferred_itr += 1 byte_transferred_itr += sys.getsizeof(r) if send_to ==", "+= (u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat += (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat", "-o * Read those objects * Send those to CoAP", "exit [IN] -H --host The FogLAMP host (default: localhost) -I", "= 6683 if arg_payload_protocol == 'http' else 5683 arg_port =", "_write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r): with open(to_file, 'a') as the_file:", "as data_file: data = json.load(data_file) supported_format_types = [\"number\", \"enum\"] for", "\"\"\" Expected output from given template { \"timestamp\" : \"2017-08-04T06:59:57.503Z\",", "total)') namespace = parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if namespace.template else", "} { \"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI sensorTag/pressure\", \"sensor_values\"", "'n', 'no'], help='Do not delete the running sample (default: no)')", "url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession() as session: async", "coap)') parser.add_argument('-I', '--iterations', help='The number of iterations of the test", "datetime, timezone import argparse import collections import asyncio import aiohttp", ": \"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI sensorTag/luxometer\", \"sensor_values\" : { \"lux\"", "5683 arg_port = int(namespace.port) if namespace.port else default_port check_server(arg_payload_protocol) sample_file", "resp.status if status_code in range(400, 500): print(\"Bad request error |", "else default_port check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences)", "== \"number\": # check float precision if any precision =", "no) [IN] -o --output Set the output file for statistics", "(u\"\\nTotal Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal Bytes per", "argparse import collections import asyncio import aiohttp from .exceptions import", "f.write(stat) else: print(stat) # should we also show total time", "\"\"\" :return: str - current time stamp with microseconds and", "if namespace.host else 'localhost' default_port = 6683 if arg_payload_protocol ==", "template, as per the json file name specified with -t", "to simulate payloads for input, REST and other requests against", "cd $FOGLAMP_ROOT/bin $ ./fogbench Help: $ ./fogbench -h * Create", "else 'total' if namespace.payload: arg_payload_protocol = namespace.payload arg_host = '{0}'.format(namespace.host)", "= \"<NAME>\" __copyright__ = \"Copyright (c) 2017 OSIsoft, LLC\" __license__", "\"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI sensorTag/pressure\", \"sensor_values\" : {", "seconds for each iteration (default: 0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'],", "global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated # from pprint import", "-h --help Print this help -i --interval The interval in", "fmt[\"type\"] == \"enum\": reading = random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]]", "\"asset\" : \"TI sensorTag/pressure\", \"sensor_values\" : { \"pressure\" : 1021.2", "\"asset\" : \"TI sensorTag/gyroscope\", \"sensor_values\" : { \"x\" : 101.2,", "[IN] -H --host The FogLAMP host (default: localhost) -I --iterations", "transferred in every iteration byte_transferred_itr = 0 # Bytes transferred", "in ['y', 'yes'] else False # iterations and occurrences arg_iterations", "_write_readings_to_file(to_file, r): with open(to_file, 'a') as the_file: json.dump(r, the_file) the_file.write(os.linesep)", "sensorTag/luxometer\", \"sensor_values\" : { \"lux\" : 49 } } {", "the test (default: 1) [IN] -O --occurrences The number of", "readings.append(ord_dict) return readings def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'): global", "version of %(prog)s is meant to test the south plugin", "2017 OSIsoft, LLC\" __license__ = \"Apache 2.0\" __version__ = \"${VERSION}\"", "json extension') parser.add_argument('-o', '--output', default=None, help='Set the statistics output file')", "FogLAMP. The objective is to simulate payloads for input, REST", "# interval between each iteration arg_interval = int(namespace.interval) if namespace.interval", ": \"TI sensorTag/gyroscope\", \"sensor_values\" : { \"x\" : 101.2, \"y\"", "r): with open(to_file, 'a') as the_file: json.dump(r, the_file) the_file.write(os.linesep) def", "Python script used to test FogLAMP. The objective is to", "_msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat", "else 'localhost' default_port = 6683 if arg_payload_protocol == 'http' else", "_occurrences=1): # template_file = os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file) with open(_template_file)", "help='The number of occurrences of the template (default: 1)') parser.add_argument('-H',", "return readings def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'): global _start_time", "running \\n & listening on specified host and port \\n\"", "import asyncio import aiohttp from .exceptions import * __author__ =", "per local_timestamp() values \"\"\" Expected output from given template {", "values must be defined for type number.\") # print(precision) #", "print(max_val) reading = round(random.uniform(min_val, max_val), precision) elif fmt[\"type\"] == \"enum\":", "\"\"\" fogbench -- a Python script used to test FogLAMP.", "arg_occurrences = int(namespace.occurrences) if namespace.occurrences else 1 # interval between", "type number.\") # print(precision) # print(min_val) # print(max_val) reading =", "time of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated", "'--statistics', default='total', choices=['total'], help='The type of statistics to collect '", "global _num_iterated if _stats_type == 'total': stat += u\"Total Statistics:\\n\"", "= fmt.get(\"max\", None) if min_val is None or max_val is", "of the template (default: 1) [IN] -P --port The FogLAMP", "else False # iterations and occurrences arg_iterations = int(namespace.iterations) if", "initial version of %(prog)s is meant to test the south", "resp: await resp.text() status_code = resp.status if status_code in range(400,", "None) max_val = fmt.get(\"max\", None) if min_val is None or", "the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings = [] for d", "the file name specified with -o * Read those objects", "statistics output file') parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'], help='Type of", "-*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\" fogbench", "= fmt.get(\"precision\", None) min_val = fmt.get(\"min\", None) max_val = fmt.get(\"max\",", "reason: {}\".format(status_code, resp.reason)) return False return True def get_statistics(_stats_type=None, _out_file=None):", "= [] _end_time = [] _tot_msgs_transferred = [] _tot_byte_transferred =", "Message from aiocoap.numbers.codes import Code from cbor2 import dumps context", "} } { \"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI sensorTag/pressure\",", "%H:%M:%S.%f\"))) stat += (u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal", "fmt.get(\"precision\", None) min_val = fmt.get(\"min\", None) max_val = fmt.get(\"max\", None)", "if namespace.template else '') statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output", "max_val is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min and Max", "HTTP plugins interface of FogLAMP southbound services. fogbench [IN] -h", "= random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] = reading # print(d[\"name\"])", "of the test (default: 1)') parser.add_argument('-O', '--occurrences', help='The number of", "LLC\" __license__ = \"Apache 2.0\" __version__ = \"${VERSION}\" _FOGBENCH_VERSION =", "the running sample (default: no) [IN] -o --output Set the", "= parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if namespace.template else '') statistics_file", "fmt.get(\"min\", None) max_val = fmt.get(\"max\", None) if min_val is None", "open(_template_file) as data_file: data = json.load(data_file) supported_format_types = [\"number\", \"enum\"]", "__license__ = \"Apache 2.0\" __version__ = \"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\"", "\"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI sensorTag/humidity\", \"sensor_values\" : { \"humidity\" :", "import random import json from datetime import datetime, timezone import", "def send_to_coap(payload): \"\"\" POST request to: localhost port 5683 (official", "(u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1],", "interval in seconds between each iteration (default: 0) [IN] -k", "_tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated += 1 if _iterations", "break elif send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End", "\"/other/sensor-values\". \"\"\" from aiocoap import Context, Message from aiocoap.numbers.codes import", "IANA assigned CoAP port), URI \"/other/sensor-values\". \"\"\" from aiocoap import", "required=True, help='Set the template file, json extension') parser.add_argument('-o', '--output', default=None,", "if status_code in range(400, 500): print(\"Bad request error | code:{},", "1.2, \"y\" : 0.0, \"z\" : -0.6 } } {", "_iterations != 0: # print(u\"Iteration {} completed, waiting for {}", "parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The type of statistics to collect", "0: # Pre-calculate the messages and size msg_transferred_itr = 0", "collected\"\"\" # _logger = logger.setup(__name__) def local_timestamp(): \"\"\" :return: str", "End time of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1", "POST request to: localhost port 5683 (official IANA assigned CoAP", "of statistics to collect ' '(default: total)') namespace = parser.parse_args(sys.argv[1:])", "%(prog)s is meant to test the south plugin interface of", "u\"Total Statistics:\\n\" stat += (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat", "the version and exit [IN] -H --host The FogLAMP host", "= dict() _sensor_value_object_formats = d[\"sensor_values\"] for fmt in _sensor_value_object_formats: if", "_interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change below per local_timestamp()", "file, as per the file name specified with -o *", "-t --template Set the template to use [IN] -v --version", "OSIsoft, LLC\" __license__ = \"Apache 2.0\" __version__ = \"${VERSION}\" _FOGBENCH_VERSION", "action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes', 'n', 'no'],", "collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'):", "= [] return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file", "{'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession() as", "-- a Python script used to test FogLAMP. The objective", "every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated += 1", "\"humidity\" : 71.2, \"temperature\" : 18.6 } } { \"timestamp\"", "--iterations The number of iterations of the test (default: 1)", "== 'coap': print(template_str.format(\"CoAP\")) elif payload_type == 'http': print(template_str.format(\"HTTP\")) parser =", "service is running \\n & listening on specified host and", "= namespace.payload arg_host = '{0}'.format(namespace.host) if namespace.host else 'localhost' default_port", "+ _template_file) with open(_template_file) as data_file: data = json.load(data_file) supported_format_types", "_out_file=statistics_file) # TODO: Change below per local_timestamp() values \"\"\" Expected", "_tot_msgs_transferred global _tot_byte_transferred global _num_iterated # from pprint import pprint", "reading = round(random.uniform(min_val, max_val), precision) elif fmt[\"type\"] == \"enum\": reading", "# print(precision) # print(min_val) # print(max_val) reading = round(random.uniform(min_val, max_val),", "reading = random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] = reading #", "and other requests against one or more FogLAMP instances. This", "stat += (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat += (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate)))", "namespace.payload arg_host = '{0}'.format(namespace.host) if namespace.host else 'localhost' default_port =", "\"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\" _start_time = [] _end_time = []", "\"<NAME>\" __copyright__ = \"Copyright (c) 2017 OSIsoft, LLC\" __license__ =", "aiohttp from .exceptions import * __author__ = \"<NAME>\" __copyright__ =", "from given template { \"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI", "return False return True def get_statistics(_stats_type=None, _out_file=None): stat = ''", "with microseconds and machine timezone info :example '2018-05-08 14:06:40.517313+05:30' \"\"\"", "timezone info :example '2018-05-08 14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone()) def read_templates():", "sensorTag/magnetometer\", \"sensor_values\" : { \"x\" : 101.2, \"y\" : 46.2,", "Make sure south {} plugin service is running \\n &", "(default: 1)') parser.add_argument('-O', '--occurrences', help='The number of occurrences of the", "14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates = [] return", "-- a Python script used to test FogLAMP (simulate payloads)'", "choices=['total'], help='The type of statistics to collect ' '(default: total)')", "those objects * Send those to CoAP or HTTP south", "collect ' '(default: total)') namespace = parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template", ": \"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI sensorTag/gyroscope\", \"sensor_values\" : { \"x\"", "(u\"\\nTotal Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate =", "help -i --interval The interval in seconds between each iteration", "number of iterations of the test (default: 1) [IN] -O", "if namespace.payload: arg_payload_protocol = namespace.payload arg_host = '{0}'.format(namespace.host) if namespace.host", "./fogbench -h * Create reading objects from given template, as", "iteration arg_interval = int(namespace.interval) if namespace.interval else 0 arg_stats_type =", "2.0\" __version__ = \"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\" _start_time = []", "& listening on specified host and port \\n\" if payload_type", "script used to test FogLAMP. The objective is to simulate", "status_code in range(500, 600): print(\"Server error | code:{}, reason: {}\".format(status_code,", "host and port .. todo:: * Try generators \"\"\" import", "0) [IN] -k --keep Do not delete (keep) the running", "in range(_num_iterated): time_taken = _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] /", "request.opt.uri_port = arg_port request.opt.uri_path = (\"other\", \"sensor-values\") response = await", "_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file) as f: readings_list =", "6683 if arg_payload_protocol == 'http' else 5683 arg_port = int(namespace.port)", "else None keep_the_file = True if namespace.keep in ['y', 'yes']", "[] for itr in range(_num_iterated): time_taken = _end_time[itr] - _start_time[itr]", "if payload_type == 'coap': print(template_str.format(\"CoAP\")) elif payload_type == 'http': print(template_str.format(\"HTTP\"))", "\"\"\" POST request to: localhost port 5683 (official IANA assigned", "+= (u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal Iterations: {}\".format(_num_iterated))", "sensorTag/humidity\", \"sensor_values\" : { \"humidity\" : 71.2, \"temperature\" : 18.6", "time stamp with microseconds and machine timezone info :example '2018-05-08", "(u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat += (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file:", "\"sensor-values\") response = await context.request(request).response str_res = str(response.code) status_code =", "= 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession() as session: async with", "\"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\", \"sensor_values\" : { \"button\" : \"down\"", "\"down\" } } { \"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall", "if fmt[\"type\"] not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can", "of fogbench is meant to test the CoAP and HTTP", "} } { \"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall clock\",", "[] for d in data: x_sensor_values = dict() _sensor_value_object_formats =", "asyncio import aiohttp from .exceptions import * __author__ = \"<NAME>\"", "== 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time of every", "Send those to CoAP or HTTP south plugin server, on", "of payload ' 'and protocol (default: coap)') parser.add_argument('-I', '--iterations', help='The", "objects * Send those to CoAP or HTTP south plugin", "is_sent = loop.run_until_complete(send_to_coap(r)) if not is_sent: break elif send_to ==", "{ \"humidity\" : 71.2, \"temperature\" : 18.6 } } {", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- # FOGLAMP_BEGIN #", "--statistic The type of statistics to collect Example: $ cd", "\"\"\" import sys import os import random import json from", "\"5.00\": print(\"Error: \", str_res) return False return True async def", "+= (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat", "--version Display the version and exit [IN] -H --host The", "for r in readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r): with", "1) [IN] -P --port The FogLAMP port. Default depends on", "* Try generators \"\"\" import sys import os import random", "import Code from cbor2 import dumps context = await Context.create_client_context()", ": \"TI sensorTag/magnetometer\", \"sensor_values\" : { \"x\" : 101.2, \"y\"", "\"y\" : 0.0, \"z\" : -0.6 } } { \"timestamp\"", "\"asset\" : \"mouse\", \"sensor_values\" : { \"button\" : \"down\" }", "_num_iterated += 1 if _iterations != 0: # print(u\"Iteration {}", "sensorTag/pressure\", \"sensor_values\" : { \"pressure\" : 1021.2 } } {", "# print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def read_out_file(_file=None,", "101.2, \"y\" : 46.2, \"z\" : -12.6 } } {", "(u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nTotal Messages Transferred:", "_start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated #", "to use [IN] -v --version Display the version and exit", "stat += (u\"\\nTotal Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal", "\\ 'FogLAMP using CoAP or HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s", "= os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output else None keep_the_file = True", "messages and size msg_transferred_itr = 0 # Messages transferred in", "with -t * Save those objects to the file, as", "server, on specific host and port .. todo:: * Try", "46.2, \"z\" : -12.6 } } { \"timestamp\" : \"2017-08-04T07:00:03.863Z\",", "_sensor_value_object_formats = d[\"sensor_values\"] for fmt in _sensor_value_object_formats: if fmt[\"type\"] not", "} } { \"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI sensorTag/magnetometer\",", "occurrences arg_iterations = int(namespace.iterations) if namespace.iterations else 1 arg_occurrences =", "help='The FogLAMP port. (default: 5683)') parser.add_argument('-i', '--interval', default=0, help='The interval", "-S --statistic The type of statistics to collect Example: $", "iteration byte_transferred_itr = 0 # Bytes transferred in every iteration", "[IN] -v --version Display the version and exit [IN] -H", "float precision if any precision = fmt.get(\"precision\", None) min_val =", "The number of iterations of the test (default: 1) [IN]", "HTTP south plugin server, on specific host and port ..", "status_code in range(400, 500): print(\"Bad request error | code:{}, reason:", "{ \"button\" : \"down\" } } { \"timestamp\" : \"2017-08-04T07:00:04.863Z\",", "= 0 # Bytes transferred in every iteration for r", "name specified with -o * Read those objects * Send", "be defined for type number.\") # print(precision) # print(min_val) #", "payload and protocol (default: coap) [IN] -t --template Set the", "is None or max_val is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \"", "--payload Type of payload and protocol (default: coap) [IN] -t", "_write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) #", "_interval)) time.sleep(_interval) if not _keep: os.remove(_file) async def send_to_coap(payload): \"\"\"", "request.opt.uri_path = (\"other\", \"sensor-values\") response = await context.request(request).response str_res =", "south plugin server, on specific host and port .. todo::", ": \"mouse\", \"sensor_values\" : { \"button\" : \"down\" } }", "reason: {}\".format(status_code, resp.reason)) return False if status_code in range(500, 600):", "_keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change below", "-v --version Display the version and exit [IN] -H --host", "-12.6 } } { \"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\",", "if _stats_type == 'total': stat += u\"Total Statistics:\\n\" stat +=", "specified with -t * Save those objects to the file,", "Code from cbor2 import dumps context = await Context.create_client_context() request", "localhost port 6683 (default HTTP south plugin port), uri sensor-reading", "template (default: 1)') parser.add_argument('-H', '--host', help='Server host address (default: localhost)')", "FogLAMP port. (default: 5683)') parser.add_argument('-i', '--interval', default=0, help='The interval in", "-i --interval The interval in seconds between each iteration (default:", "namespace = parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if namespace.template else '')", "instances. This version of fogbench is meant to test the", "- start_time def check_server(payload_type='coap'): template_str = \">>> Make sure south", "in range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types) for r in readings_:", "\"templates/\" + _template_file) with open(_template_file) as data_file: data = json.load(data_file)", "= int(namespace.iterations) if namespace.iterations else 1 arg_occurrences = int(namespace.occurrences) if", "the output file for statistics [IN] -p --payload Type of", "\" u\"Min and Max values must be defined for type", "= \"Copyright (c) 2017 OSIsoft, LLC\" __license__ = \"Apache 2.0\"", "the test (default: 1)') parser.add_argument('-O', '--occurrences', help='The number of occurrences", "send_to_http(payload): \"\"\" POST request to: host localhost port 6683 (default", "CoAP and HTTP plugins interface of FogLAMP southbound services. fogbench", "supported_format_types = [\"number\", \"enum\"] for _ in range(_occurrences): readings_ =", "objects to the file, as per the file name specified", "error | code:{}, reason: {}\".format(status_code, resp.reason)) return False if status_code", "'--interval', default=0, help='The interval in seconds for each iteration (default:", "arg_iterations = int(namespace.iterations) if namespace.iterations else 1 arg_occurrences = int(namespace.occurrences)", "[IN] -k --keep Do not delete (keep) the running sample", "stat += (u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat += (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated))", "-I --iterations The number of iterations of the test (default:", "fogbench is meant to test the CoAP and HTTP plugins", "Do not delete (keep) the running sample (default: no) [IN]", "read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change", "context = await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host =", "reading) x_sensor_values[fmt[\"name\"]] = reading # print(d[\"name\"]) sensor_value_object = dict() sensor_value_object[\"asset\"]", "import pprint import time # _file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with", "# check float precision if any precision = fmt.get(\"precision\", None)", "not delete the running sample (default: no)') parser.add_argument('-t', '--template', required=True,", "0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The type of statistics to", "pprint import time # _file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file)", "in seconds between each iteration (default: 0) [IN] -k --keep", "async with session.post(url, data=json.dumps(payload), headers=headers) as resp: await resp.text() status_code", "\"temperature\" : 18.6 } } { \"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\"", "parser.epilog = 'The initial version of %(prog)s is meant to", "sys import os import random import json from datetime import", "open(to_file, 'a') as the_file: json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types):", "payload_type == 'coap': print(template_str.format(\"CoAP\")) elif payload_type == 'http': print(template_str.format(\"HTTP\")) parser", "0 # Messages transferred in every iteration byte_transferred_itr = 0", "python3 # -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See:", "_iterations -= 1 _num_iterated += 1 if _iterations != 0:", "resp.reason)) return False if status_code in range(500, 600): print(\"Server error", "5683)') parser.add_argument('-i', '--interval', default=0, help='The interval in seconds for each", "# iterations and occurrences arg_iterations = int(namespace.iterations) if namespace.iterations else", "template (default: 1) [IN] -P --port The FogLAMP port. Default", "file for statistics [IN] -p --payload Type of payload and", "namespace.keep in ['y', 'yes'] else False # iterations and occurrences", "import time # _file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file) as", "(keep) the running sample (default: no) [IN] -o --output Set", "'%(prog)s -- a Python script used to test FogLAMP (simulate", "occurrences of the template (default: 1)') parser.add_argument('-H', '--host', help='Server host", "return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates = [] return templates def", "Change below per local_timestamp() values \"\"\" Expected output from given", "with -o * Read those objects * Send those to", "f: f.write(stat) else: print(stat) # should we also show total", "of the test (default: 1) [IN] -O --occurrences The number", "'FogLAMP using CoAP or HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION))", "Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d", "Save those objects to the file, as per the file", "= \">>> Make sure south {} plugin service is running", "'{0}'.format(namespace.host) if namespace.host else 'localhost' default_port = 6683 if arg_payload_protocol", "} { \"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI sensorTag/accelerometer\", \"sensor_values\"", "test the CoAP and HTTP plugins interface of FogLAMP southbound", "supported_format_types): readings = [] for d in data: x_sensor_values =", "{} seconds\".format(_iterations, _interval)) time.sleep(_interval) if not _keep: os.remove(_file) async def", "Type of payload and protocol (default: coap) [IN] -t --template", "POST request to: host localhost port 6683 (default HTTP south", "aiocoap.numbers.codes import Code from cbor2 import dumps context = await", "_end_time = [] _tot_msgs_transferred = [] _tot_byte_transferred = [] _num_iterated", "str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates = [] return templates def parse_template_and_prepare_json(_template_file,", "data = json.load(data_file) supported_format_types = [\"number\", \"enum\"] for _ in", "import argparse import collections import asyncio import aiohttp from .exceptions", "supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can not parse type {}\".format(fmt[\"type\"]))", "payload and protocol [IN] -S --statistic The type of statistics", "{}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat += (u\"\\nMax Bytes/second:", "= asyncio.get_event_loop() while _iterations > 0: # Pre-calculate the messages", "is meant to test the south plugin interface of '", "port), uri sensor-reading \"\"\" headers = {'content-type': 'application/json'} url =", "format, \" u\"Min and Max values must be defined for", "parser = argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s -- a Python script", "fmt[\"type\"] not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can not", "{ \"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI sensorTag/magnetometer\", \"sensor_values\" :", ": { \"object\" : 18.2, \"ambient\" : 21.6 } }", "# FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\" fogbench --", "fmt[\"type\"] == \"number\": # check float precision if any precision", "\"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI sensorTag/accelerometer\", \"sensor_values\" : {", "and HTTP plugins interface of FogLAMP southbound services. fogbench [IN]", "1 byte_transferred_itr += sys.getsizeof(r) if send_to == 'coap': _start_time.append(datetime.now()) for", "namespace.iterations else 1 arg_occurrences = int(namespace.occurrences) if namespace.occurrences else 1", "'coap': _start_time.append(datetime.now()) for r in readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if", "import Context, Message from aiocoap.numbers.codes import Code from cbor2 import", "specified with -o * Read those objects * Send those", "\"z\" : -12.6 } } { \"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\"", "with open(_file) as f: readings_list = [json.loads(line) for line in", "async def send_to_coap(payload): \"\"\" POST request to: localhost port 5683", "msg_transferred_itr = 0 # Messages transferred in every iteration byte_transferred_itr", "print(\"Error: \", str_res) return False return True async def send_to_http(payload):", "(default: 1)') parser.add_argument('-H', '--host', help='Server host address (default: localhost)') parser.add_argument('-P',", "0: # print(u\"Iteration {} completed, waiting for {} seconds\".format(_iterations, _interval))", "' 'and protocol (default: coap)') parser.add_argument('-I', '--iterations', help='The number of", "u\"Min and Max values must be defined for type number.\")", "for r in readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if not is_sent:", "seconds\".format(_iterations, _interval)) time.sleep(_interval) if not _keep: os.remove(_file) async def send_to_coap(payload):", "json file name specified with -t * Save those objects", "(default: localhost)') parser.add_argument('-P', '--port', help='The FogLAMP port. (default: 5683)') parser.add_argument('-i',", "templates = [] return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): #", "# or str_res.split()[0] if status_code == \"4.00\" or status_code ==", "Bytes/second: {}\".format(min(_byte_rate))) stat += (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat += (u\"\\nAvg", "_tot_byte_transferred global _num_iterated if _stats_type == 'total': stat += u\"Total", "request to: localhost port 5683 (official IANA assigned CoAP port),", "number of occurrences of the template (default: 1) [IN] -P", "= json.load(data_file) supported_format_types = [\"number\", \"enum\"] for _ in range(_occurrences):", "port. Default depends on payload and protocol [IN] -S --statistic", "= [] _tot_byte_transferred = [] _num_iterated = 0 \"\"\"Statistics to", "host (default: localhost) -I --iterations The number of iterations of", "d['name'] sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict", "u\"Can not parse type {}\".format(fmt[\"type\"])) if fmt[\"type\"] == \"number\": #", "x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict)", "json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings = [] for", "no)') parser.add_argument('-t', '--template', required=True, help='Set the template file, json extension')", "\"lux\" : 49 } } { \"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\"", "south {} plugin service is running \\n & listening on", "dict() sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp())", "output file') parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'], help='Type of payload", "{}\".format(fmt[\"type\"])) if fmt[\"type\"] == \"number\": # check float precision if", "1 if _iterations != 0: # print(u\"Iteration {} completed, waiting", "} } { \"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI sensorTag/accelerometer\",", "or HTTP south plugin server, on specific host and port", "-H --host The FogLAMP host (default: localhost) -I --iterations The", "+= 1 byte_transferred_itr += sys.getsizeof(r) if send_to == 'coap': _start_time.append(datetime.now())", "help='Do not delete the running sample (default: no)') parser.add_argument('-t', '--template',", "as per the file name specified with -o * Read", "\"enum\": reading = random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] = reading", "\"TI sensorTag/pressure\", \"sensor_values\" : { \"pressure\" : 1021.2 } }", "1) [IN] -O --occurrences The number of occurrences of the", "CoAP or HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep',", "if namespace.output else None keep_the_file = True if namespace.keep in", "template to use [IN] -v --version Display the version and", "1 # interval between each iteration arg_interval = int(namespace.interval) if", "output file for statistics [IN] -p --payload Type of payload", "= os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file) with open(_template_file) as data_file: data", "file') parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'], help='Type of payload '", "\"asset\" : \"TI sensorTag/magnetometer\", \"sensor_values\" : { \"x\" : 101.2,", "Transferred: {}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat +=", "= dict() sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"] =", "namespace.output else None keep_the_file = True if namespace.keep in ['y',", "x_sensor_values = dict() _sensor_value_object_formats = d[\"sensor_values\"] for fmt in _sensor_value_object_formats:", "if status_code in range(500, 600): print(\"Server error | code:{}, reason:", "+= sys.getsizeof(r) if send_to == 'coap': _start_time.append(datetime.now()) for r in", "\"sensor_values\" : { \"humidity\" : 71.2, \"temperature\" : 18.6 }", "random import json from datetime import datetime, timezone import argparse", "data=json.dumps(payload), headers=headers) as resp: await resp.text() status_code = resp.status if", "context.request(request).response str_res = str(response.code) status_code = str_res[:4] # or str_res.split()[0]", ".. todo:: * Try generators \"\"\" import sys import os", "headers=headers) as resp: await resp.text() status_code = resp.status if status_code", "number.\") # print(precision) # print(min_val) # print(max_val) reading = round(random.uniform(min_val,", "with open(to_file, 'a') as the_file: json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data,", "sys.getsizeof(r) if send_to == 'coap': _start_time.append(datetime.now()) for r in readings_list:", "# _file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file) as f: readings_list", "Messages transferred in every iteration byte_transferred_itr = 0 # Bytes", "_end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin", "> 0: # Pre-calculate the messages and size msg_transferred_itr =", "sample (default: no)') parser.add_argument('-t', '--template', required=True, help='Set the template file,", "round(random.uniform(min_val, max_val), precision) elif fmt[\"type\"] == \"enum\": reading = random.choice(fmt[\"list\"])", "those to CoAP or HTTP south plugin server, on specific", "end_time - start_time def check_server(payload_type='coap'): template_str = \">>> Make sure", "TODO: Change below per local_timestamp() values \"\"\" Expected output from", "== \"4.00\" or status_code == \"5.00\": print(\"Error: \", str_res) return", "print(\"Bad request error | code:{}, reason: {}\".format(status_code, resp.reason)) return False", "\", str_res) return False return True async def send_to_http(payload): \"\"\"", "global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated", "_start_time = [] _end_time = [] _tot_msgs_transferred = [] _tot_byte_transferred", "aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(payload), headers=headers) as resp:", "%H:%M:%S.%f\"))) stat += (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat +=", "' \\ 'FogLAMP using CoAP or HTTP' parser.add_argument('-v', '--version', action='version',", "Set the template to use [IN] -v --version Display the", "{}\".format(status_code, resp.reason)) return False return True def get_statistics(_stats_type=None, _out_file=None): stat", "script used to test FogLAMP (simulate payloads)' parser.epilog = 'The", "if status_code == \"4.00\" or status_code == \"5.00\": print(\"Error: \",", "\"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI sensorTag/pressure\", \"sensor_values\" : { \"pressure\" :", "= x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items()))", "= (\"other\", \"sensor-values\") response = await context.request(request).response str_res = str(response.code)", "range(500, 600): print(\"Server error | code:{}, reason: {}\".format(status_code, resp.reason)) return", "[] _byte_rate = [] for itr in range(_num_iterated): time_taken =", "The number of occurrences of the template (default: 1) [IN]", "= collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0,", "$ cd $FOGLAMP_ROOT/bin $ ./fogbench Help: $ ./fogbench -h *", "_end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated # from pprint", "* Send those to CoAP or HTTP south plugin server,", "[] _end_time = [] _tot_msgs_transferred = [] _tot_byte_transferred = []", "stat += (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nTotal", "-12.6 } } { \"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI", "(u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat += (u\"\\nTotal Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated))", "_tot_msgs_transferred global _tot_byte_transferred global _num_iterated if _stats_type == 'total': stat", "FogLAMP instances. This version of fogbench is meant to test", "== 'total': stat += u\"Total Statistics:\\n\" stat += (u\"\\nStart Time:", "parser.add_argument('-O', '--occurrences', help='The number of occurrences of the template (default:", ": \"TI sensorTag/pressure\", \"sensor_values\" : { \"pressure\" : 1021.2 }", "_occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO:", "help='Set the template file, json extension') parser.add_argument('-o', '--output', default=None, help='Set", "stat += (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file, 'w')", "\"timestamp\" : \"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI sensorTag/magnetometer\", \"sensor_values\" : {", "str(response.code) status_code = str_res[:4] # or str_res.split()[0] if status_code ==", "for itr in range(_num_iterated): time_taken = _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6))", "'and protocol (default: coap)') parser.add_argument('-I', '--iterations', help='The number of iterations", "f: readings_list = [json.loads(line) for line in f] loop =", "plugins interface of FogLAMP southbound services. fogbench [IN] -h --help", "'--iterations', help='The number of iterations of the test (default: 1)')", "= Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port = arg_port request.opt.uri_path", "default_port check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file,", "fogbench -- a Python script used to test FogLAMP. The", "True if namespace.keep in ['y', 'yes'] else False # iterations", "$FOGLAMP_ROOT/bin $ ./fogbench Help: $ ./fogbench -h * Create reading", "and machine timezone info :example '2018-05-08 14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone())", "= [] _num_iterated = 0 \"\"\"Statistics to be collected\"\"\" #", "{}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file, 'w') as f: f.write(stat) else:", "'' global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global", "localhost port 5683 (official IANA assigned CoAP port), URI \"/other/sensor-values\".", "None) if min_val is None or max_val is None: raise", "loop.run_until_complete(send_to_coap(r)) if not is_sent: break elif send_to == 'http': _start_time.append(datetime.now())", "in readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if not is_sent: break elif", "in every iteration byte_transferred_itr = 0 # Bytes transferred in", "payload_type == 'http': print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s", "'') statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output else None keep_the_file", "from datetime import datetime, timezone import argparse import collections import", "messages/second: {}\".format(min(_msg_rate))) stat += (u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat += (u\"\\nAvg", "specific host and port .. todo:: * Try generators \"\"\"", "arg_host request.opt.uri_port = arg_port request.opt.uri_path = (\"other\", \"sensor-values\") response =", "sensor_value_object = dict() sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"]", "of payload and protocol (default: coap) [IN] -t --template Set", "{ \"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\", \"sensor_values\" : {", "def get_statistics(_stats_type=None, _out_file=None): stat = '' global _start_time global _end_time", "'(default: total)') namespace = parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if namespace.template", "} } { \"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI sensorTag/gyroscope\",", "\"out/{}\".format(namespace.output)) if namespace.output else None keep_the_file = True if namespace.keep", "precision) elif fmt[\"type\"] == \"enum\": reading = random.choice(fmt[\"list\"]) # print(fmt[\"name\"],", "\"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall clock\", \"sensor_values\" : { \"tick\" :", "localhost) -I --iterations The number of iterations of the test", "precision = fmt.get(\"precision\", None) min_val = fmt.get(\"min\", None) max_val =", "default=0, help='The interval in seconds for each iteration (default: 0)')", "elif payload_type == 'http': print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench') parser.description =", "{ \"lux\" : 49 } } { \"timestamp\" : \"2017-08-04T06:59:57.863Z\",", "parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes', 'n', 'no'], help='Do not delete", "+= u\"Total Statistics:\\n\" stat += (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\")))", "to test FogLAMP (simulate payloads)' parser.epilog = 'The initial version", "number of occurrences of the template (default: 1)') parser.add_argument('-H', '--host',", "_tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated += 1 if _iterations !=", "False # iterations and occurrences arg_iterations = int(namespace.iterations) if namespace.iterations", "\\n\" if payload_type == 'coap': print(template_str.format(\"CoAP\")) elif payload_type == 'http':", "if arg_payload_protocol == 'http' else 5683 arg_port = int(namespace.port) if", "--interval The interval in seconds between each iteration (default: 0)", "for _ in range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types) for r", "the template (default: 1) [IN] -P --port The FogLAMP port.", "status_code == \"5.00\": print(\"Error: \", str_res) return False return True", "arg_port request.opt.uri_path = (\"other\", \"sensor-values\") response = await context.request(request).response str_res", "await context.request(request).response str_res = str(response.code) status_code = str_res[:4] # or", "print(precision) # print(min_val) # print(max_val) reading = round(random.uniform(min_val, max_val), precision)", "= loop.run_until_complete(send_to_coap(r)) if not is_sent: break elif send_to == 'http':", "iterations of the test (default: 1)') parser.add_argument('-O', '--occurrences', help='The number", "help='Set the statistics output file') parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'],", "--output Set the output file for statistics [IN] -p --payload", "cbor2 import dumps context = await Context.create_client_context() request = Message(payload=dumps(payload),", "namespace.port else default_port check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file,", "} { \"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI sensorTag/gyroscope\", \"sensor_values\"", "readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r): with open(to_file, 'a') as", "delete the running sample (default: no)') parser.add_argument('-t', '--template', required=True, help='Set", "else 5683 arg_port = int(namespace.port) if namespace.port else default_port check_server(arg_payload_protocol)", "datetime import datetime, timezone import argparse import collections import asyncio", "arg_host = '{0}'.format(namespace.host) if namespace.host else 'localhost' default_port = 6683", "Expected output from given template { \"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\"", "(default: 0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The type of statistics", "localhost)') parser.add_argument('-P', '--port', help='The FogLAMP port. (default: 5683)') parser.add_argument('-i', '--interval',", "'2018-05-08 14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates = []", "protocol (default: coap)') parser.add_argument('-I', '--iterations', help='The number of iterations of", "local_timestamp(): \"\"\" :return: str - current time stamp with microseconds", "stat += (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nEnd", "\"Copyright (c) 2017 OSIsoft, LLC\" __license__ = \"Apache 2.0\" __version__", "completed, waiting for {} seconds\".format(_iterations, _interval)) time.sleep(_interval) if not _keep:", "help='The interval in seconds for each iteration (default: 0)') parser.add_argument('-S',", "readings_list = [json.loads(line) for line in f] loop = asyncio.get_event_loop()", "stat += (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat += (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated))", "[IN] -O --occurrences The number of occurrences of the template", "x_sensor_values[fmt[\"name\"]] = reading # print(d[\"name\"]) sensor_value_object = dict() sensor_value_object[\"asset\"] =", "\"out/{}\".format(outfile)) with open(_file) as f: readings_list = [json.loads(line) for line", ": 101.2, \"y\" : 46.2, \"z\" : -12.6 } }", "iteration (default: 0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The type of", "Set the output file for statistics [IN] -p --payload Type", "if not is_sent: break elif send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list))", "status_code = str_res[:4] # or str_res.split()[0] if status_code == \"4.00\"", "port 6683 (default HTTP south plugin port), uri sensor-reading \"\"\"", "collections import asyncio import aiohttp from .exceptions import * __author__", "(simulate payloads)' parser.epilog = 'The initial version of %(prog)s is", "info :example '2018-05-08 14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates", "The type of statistics to collect Example: $ cd $FOGLAMP_ROOT/bin", "# template_file = os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file) with open(_template_file) as", "_logger = logger.setup(__name__) def local_timestamp(): \"\"\" :return: str - current", "os.remove(_file) async def send_to_coap(payload): \"\"\" POST request to: localhost port", "a Python script used to test FogLAMP (simulate payloads)' parser.epilog", "timezone import argparse import collections import asyncio import aiohttp from", ": { \"x\" : 101.2, \"y\" : 46.2, \"z\" :", "= 'The initial version of %(prog)s is meant to test", "= resp.status if status_code in range(400, 500): print(\"Bad request error", ": \"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI sensorTag/accelerometer\", \"sensor_values\" : { \"x\"", "values \"\"\" Expected output from given template { \"timestamp\" :", "every iteration byte_transferred_itr = 0 # Bytes transferred in every", ": \"down\" } } { \"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\" :", "Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat +=", "range(_num_iterated): time_taken = _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6))", "using CoAP or HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k',", "time diff? end_time - start_time def check_server(payload_type='coap'): template_str = \">>>", "request error | code:{}, reason: {}\".format(status_code, resp.reason)) return False if", "- current time stamp with microseconds and machine timezone info", "parser.add_argument('-t', '--template', required=True, help='Set the template file, json extension') parser.add_argument('-o',", "payloads for input, REST and other requests against one or", "[IN] -h --help Print this help -i --interval The interval", "_msg_rate = [] _byte_rate = [] for itr in range(_num_iterated):", "clock\", \"sensor_values\" : { \"tick\" : \"tock\" } } \"\"\"", "default='total', choices=['total'], help='The type of statistics to collect ' '(default:", "per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated))", "await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port", "for d in data: x_sensor_values = dict() _sensor_value_object_formats = d[\"sensor_values\"]", "1 _num_iterated += 1 if _iterations != 0: # print(u\"Iteration", "each iteration (default: 0) [IN] -k --keep Do not delete", "time_taken = _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat", "namespace.template else '') statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output else", "stat += (u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat += (u\"\\nTotal Messages per", "if namespace.occurrences else 1 # interval between each iteration arg_interval", "host localhost port 6683 (default HTTP south plugin port), uri", "parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'], help='Type of payload ' 'and", "FogLAMP host (default: localhost) -I --iterations The number of iterations", "if namespace.keep in ['y', 'yes'] else False # iterations and", "version of fogbench is meant to test the CoAP and", ": \"TI sensorTag/humidity\", \"sensor_values\" : { \"humidity\" : 71.2, \"temperature\"", "str_res) return False return True async def send_to_http(payload): \"\"\" POST", "the json file name specified with -t * Save those", "\"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI sensorTag/temperature\", \"sensor_values\" : { \"object\" :", "one or more FogLAMP instances. This version of fogbench is", "elif send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time", "sensor-reading \"\"\" headers = {'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port)", "\"y\" : 46.2, \"z\" : -12.6 } } { \"timestamp\"", "} { \"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI sensorTag/temperature\", \"sensor_values\"", "[] _tot_msgs_transferred = [] _tot_byte_transferred = [] _num_iterated = 0", "print(u\"Iteration {} completed, waiting for {} seconds\".format(_iterations, _interval)) time.sleep(_interval) if", "'http' else 5683 arg_port = int(namespace.port) if namespace.port else default_port", "the statistics output file') parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'], help='Type", "format, \" u\"Can not parse type {}\".format(fmt[\"type\"])) if fmt[\"type\"] ==", "objects from given template, as per the json file name", "5683 (official IANA assigned CoAP port), URI \"/other/sensor-values\". \"\"\" from", "-o --output Set the output file for statistics [IN] -p", "type of statistics to collect Example: $ cd $FOGLAMP_ROOT/bin $", "and protocol [IN] -S --statistic The type of statistics to", "0 # Bytes transferred in every iteration for r in", "\"number\": # check float precision if any precision = fmt.get(\"precision\",", "statistics to collect ' '(default: total)') namespace = parser.parse_args(sys.argv[1:]) infile", "if _iterations != 0: # print(u\"Iteration {} completed, waiting for", "\"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def", "and size msg_transferred_itr = 0 # Messages transferred in every", "Read those objects * Send those to CoAP or HTTP", "_interval=0, send_to='coap'): global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred", ": \"TI sensorTag/luxometer\", \"sensor_values\" : { \"lux\" : 49 }", ": { \"humidity\" : 71.2, \"temperature\" : 18.6 } }", "\"2017-08-04T07:00:02.863Z\", \"asset\" : \"TI sensorTag/magnetometer\", \"sensor_values\" : { \"x\" :", "(\"other\", \"sensor-values\") response = await context.request(request).response str_res = str(response.code) status_code", "= '{0}'.format(namespace.host) if namespace.host else 'localhost' default_port = 6683 if", "= 0 # Messages transferred in every iteration byte_transferred_itr =", "\" u\"Can not parse type {}\".format(fmt[\"type\"])) if fmt[\"type\"] == \"number\":", "else '') statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output else None", "= '' global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred", "{0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes', 'n', 'no'], help='Do not", "str - current time stamp with microseconds and machine timezone", "$ ./fogbench -h * Create reading objects from given template,", "type {}\".format(fmt[\"type\"])) if fmt[\"type\"] == \"number\": # check float precision", "and exit [IN] -H --host The FogLAMP host (default: localhost)", "= [] for itr in range(_num_iterated): time_taken = _end_time[itr] -", ": 18.6 } } { \"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\" :", "readings_ = _prepare_sensor_reading(data, supported_format_types) for r in readings_: _write_readings_to_file(_write_to_file, r)", "host and port \\n\" if payload_type == 'coap': print(template_str.format(\"CoAP\")) elif", "with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(payload), headers=headers) as", "statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output else None keep_the_file =", "\"\"\" POST request to: host localhost port 6683 (default HTTP", "if min_val is None or max_val is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid", "arg_port) async with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(payload),", "# Pre-calculate the messages and size msg_transferred_itr = 0 #", "arg_payload_protocol == 'http' else 5683 arg_port = int(namespace.port) if namespace.port", "d in data: x_sensor_values = dict() _sensor_value_object_formats = d[\"sensor_values\"] for", "'--payload', default='coap', choices=['coap', 'http'], help='Type of payload ' 'and protocol", "of occurrences of the template (default: 1) [IN] -P --port", "waiting for {} seconds\".format(_iterations, _interval)) time.sleep(_interval) if not _keep: os.remove(_file)", "dict() _sensor_value_object_formats = d[\"sensor_values\"] for fmt in _sensor_value_object_formats: if fmt[\"type\"]", ": \"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall clock\", \"sensor_values\" : { \"tick\"", "total time diff? end_time - start_time def check_server(payload_type='coap'): template_str =", "raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Can not parse type {}\".format(fmt[\"type\"])) if", "sensor_value_object[\"asset\"] = d['name'] sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) #", "= int(namespace.interval) if namespace.interval else 0 arg_stats_type = '{0}'.format(namespace.statistics) if", "plugin server, on specific host and port .. todo:: *", "71.2, \"temperature\" : 18.6 } } { \"timestamp\" : \"2017-08-04T06:59:59.863Z\",", "f] loop = asyncio.get_event_loop() while _iterations > 0: # Pre-calculate", "Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred)))", "test (default: 1)') parser.add_argument('-O', '--occurrences', help='The number of occurrences of", "== 'coap': _start_time.append(datetime.now()) for r in readings_list: is_sent = loop.run_until_complete(send_to_coap(r))", "int(namespace.occurrences) if namespace.occurrences else 1 # interval between each iteration", "import collections import asyncio import aiohttp from .exceptions import *", "parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file)", "--port The FogLAMP port. Default depends on payload and protocol", "global _num_iterated # from pprint import pprint import time #", "max_val = fmt.get(\"max\", None) if min_val is None or max_val", "namespace.payload: arg_payload_protocol = namespace.payload arg_host = '{0}'.format(namespace.host) if namespace.host else", "host address (default: localhost)') parser.add_argument('-P', '--port', help='The FogLAMP port. (default:", "of iterations of the test (default: 1)') parser.add_argument('-O', '--occurrences', help='The", "/ (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat += (u\"\\nMax", "with open(_template_file) as data_file: data = json.load(data_file) supported_format_types = [\"number\",", "CoAP or HTTP south plugin server, on specific host and", "readings = [] for d in data: x_sensor_values = dict()", "is to simulate payloads for input, REST and other requests", "(u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat +=", "to be collected\"\"\" # _logger = logger.setup(__name__) def local_timestamp(): \"\"\"", "help='Server host address (default: localhost)') parser.add_argument('-P', '--port', help='The FogLAMP port.", "byte_transferred_itr += sys.getsizeof(r) if send_to == 'coap': _start_time.append(datetime.now()) for r", "(default: no) [IN] -o --output Set the output file for", "{ \"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI sensorTag/luxometer\", \"sensor_values\" :", "machine timezone info :example '2018-05-08 14:06:40.517313+05:30' \"\"\" return str(datetime.now(timezone.utc).astimezone()) def", "\"x\" : 1.2, \"y\" : 0.0, \"z\" : -0.6 }", "check_server(payload_type='coap'): template_str = \">>> Make sure south {} plugin service", "= os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file) as f: readings_list = [json.loads(line)", "\"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall clock\", \"sensor_values\" : {", "= '{0}'.format(namespace.template if namespace.template else '') statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output))", "'--template', required=True, help='Set the template file, json extension') parser.add_argument('-o', '--output',", ": { \"x\" : 1.2, \"y\" : 0.0, \"z\" :", ": { \"button\" : \"down\" } } { \"timestamp\" :", "to test FogLAMP. The objective is to simulate payloads for", "= [\"number\", \"enum\"] for _ in range(_occurrences): readings_ = _prepare_sensor_reading(data,", ": 21.6 } } { \"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\" :", "-= 1 _num_iterated += 1 if _iterations != 0: #", "os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file) with open(_template_file) as data_file: data =", "6683 (default HTTP south plugin port), uri sensor-reading \"\"\" headers", "return False if status_code in range(500, 600): print(\"Server error |", "= '%(prog)s -- a Python script used to test FogLAMP", "\"TI sensorTag/magnetometer\", \"sensor_values\" : { \"x\" : 101.2, \"y\" :", "{ \"x\" : 101.2, \"y\" : 46.2, \"z\" : -12.6", "statistics [IN] -p --payload Type of payload and protocol (default:", "template_file = os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file) with open(_template_file) as data_file:", "arg_port = int(namespace.port) if namespace.port else default_port check_server(arg_payload_protocol) sample_file =", "'--output', default=None, help='Set the statistics output file') parser.add_argument('-p', '--payload', default='coap',", "* Save those objects to the file, as per the", "+= (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nTotal Messages", "test the south plugin interface of ' \\ 'FogLAMP using", "error | code:{}, reason: {}\".format(status_code, resp.reason)) return False return True", "data: x_sensor_values = dict() _sensor_value_object_formats = d[\"sensor_values\"] for fmt in", "[] _tot_byte_transferred = [] _num_iterated = 0 \"\"\"Statistics to be", "services. fogbench [IN] -h --help Print this help -i --interval", "* __author__ = \"<NAME>\" __copyright__ = \"Copyright (c) 2017 OSIsoft,", "messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat += (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat += (u\"\\nMax", "sensorTag/temperature\", \"sensor_values\" : { \"object\" : 18.2, \"ambient\" : 21.6", "should we also show total time diff? end_time - start_time", "def _prepare_sensor_reading(data, supported_format_types): readings = [] for d in data:", "test FogLAMP. The objective is to simulate payloads for input,", "dumps context = await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host", "} { \"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\", \"sensor_values\" :", "(default: localhost) -I --iterations The number of iterations of the", "(default: 1) [IN] -O --occurrences The number of occurrences of", "with open(_out_file, 'w') as f: f.write(stat) else: print(stat) # should", "= str_res[:4] # or str_res.split()[0] if status_code == \"4.00\" or", "import aiohttp from .exceptions import * __author__ = \"<NAME>\" __copyright__", "# should we also show total time diff? end_time -", "_tot_byte_transferred = [] _num_iterated = 0 \"\"\"Statistics to be collected\"\"\"", "+= (u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat += (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat", "The FogLAMP host (default: localhost) -I --iterations The number of", "21.6 } } { \"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI", "size msg_transferred_itr = 0 # Messages transferred in every iteration", "http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\" fogbench -- a Python script used", "the template file, json extension') parser.add_argument('-o', '--output', default=None, help='Set the", "= {'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession()", "other requests against one or more FogLAMP instances. This version", "= str(response.code) status_code = str_res[:4] # or str_res.split()[0] if status_code", "the_file: json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings = []", "occurrences of the template (default: 1) [IN] -P --port The", "FogLAMP port. Default depends on payload and protocol [IN] -S", "{}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat += (u\"\\nTotal Messages", "sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return", "\"Apache 2.0\" __version__ = \"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\" _start_time =", "from cbor2 import dumps context = await Context.create_client_context() request =", "from pprint import pprint import time # _file = os.path.join(os.path.dirname(__file__),", "get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change below per local_timestamp() values \"\"\"", "49 } } { \"timestamp\" : \"2017-08-04T06:59:57.863Z\", \"asset\" : \"TI", "1)') parser.add_argument('-O', '--occurrences', help='The number of occurrences of the template", "arg_payload_protocol = namespace.payload arg_host = '{0}'.format(namespace.host) if namespace.host else 'localhost'", "\"z\" : -12.6 } } { \"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\"", "extension') parser.add_argument('-o', '--output', default=None, help='Set the statistics output file') parser.add_argument('-p',", "\"TI sensorTag/accelerometer\", \"sensor_values\" : { \"x\" : 1.2, \"y\" :", "read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'): global _start_time global _end_time global", "\"TI sensorTag/gyroscope\", \"sensor_values\" : { \"x\" : 101.2, \"y\" :", "\"4.00\" or status_code == \"5.00\": print(\"Error: \", str_res) return False", "= logger.setup(__name__) def local_timestamp(): \"\"\" :return: str - current time", "help='Type of payload ' 'and protocol (default: coap)') parser.add_argument('-I', '--iterations',", "-t * Save those objects to the file, as per", "(u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file, 'w') as f:", "raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min and Max values must be", "logger.setup(__name__) def local_timestamp(): \"\"\" :return: str - current time stamp", "\"sensor_values\" : { \"button\" : \"down\" } } { \"timestamp\"", "'total' if namespace.payload: arg_payload_protocol = namespace.payload arg_host = '{0}'.format(namespace.host) if", "data_file: data = json.load(data_file) supported_format_types = [\"number\", \"enum\"] for _", "send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change below per local_timestamp() values", "0 arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics else 'total' if namespace.payload:", "= await context.request(request).response str_res = str(response.code) status_code = str_res[:4] #", "-p --payload Type of payload and protocol (default: coap) [IN]", "r in readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if not is_sent: break", "arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics else 'total' if namespace.payload: arg_payload_protocol", "(u\"\\nMin Bytes/second: {}\".format(min(_byte_rate))) stat += (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat +=", "simulate payloads for input, REST and other requests against one", "on specified host and port \\n\" if payload_type == 'coap':", "== \"enum\": reading = random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] =", "loop = asyncio.get_event_loop() while _iterations > 0: # Pre-calculate the", "of the template (default: 1)') parser.add_argument('-H', '--host', help='Server host address", "and occurrences arg_iterations = int(namespace.iterations) if namespace.iterations else 1 arg_occurrences", "\"asset\" : \"wall clock\", \"sensor_values\" : { \"tick\" : \"tock\"", "'a') as the_file: json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings", "__version__ = \"${VERSION}\" _FOGBENCH_VERSION = u\"0.1.1\" _start_time = [] _end_time", "to test the CoAP and HTTP plugins interface of FogLAMP", "any precision = fmt.get(\"precision\", None) min_val = fmt.get(\"min\", None) max_val", "if namespace.iterations else 1 arg_occurrences = int(namespace.occurrences) if namespace.occurrences else", "todo:: * Try generators \"\"\" import sys import os import", "as the_file: json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings =", ": -0.6 } } { \"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\" :", "default='coap', choices=['coap', 'http'], help='Type of payload ' 'and protocol (default:", "be collected\"\"\" # _logger = logger.setup(__name__) def local_timestamp(): \"\"\" :return:", "status_code = resp.status if status_code in range(400, 500): print(\"Bad request", "plugin service is running \\n & listening on specified host", "\"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI sensorTag/accelerometer\", \"sensor_values\" : { \"x\" :", "time # _file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file) as f:", "= _prepare_sensor_reading(data, supported_format_types) for r in readings_: _write_readings_to_file(_write_to_file, r) def", "file, json extension') parser.add_argument('-o', '--output', default=None, help='Set the statistics output", "!= 0: # print(u\"Iteration {} completed, waiting for {} seconds\".format(_iterations,", "send_to_coap(payload): \"\"\" POST request to: localhost port 5683 (official IANA", "} } { \"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\", \"sensor_values\"", "\"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nEnd Time: {}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat", "'--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes', 'n',", "statistics to collect Example: $ cd $FOGLAMP_ROOT/bin $ ./fogbench Help:", "18.2, \"ambient\" : 21.6 } } { \"timestamp\" : \"2017-08-04T07:00:00.863Z\",", "more FogLAMP instances. This version of fogbench is meant to", "use [IN] -v --version Display the version and exit [IN]", "or HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False,", "= [] _tot_msgs_transferred = [] _tot_byte_transferred = [] _num_iterated =", "against one or more FogLAMP instances. This version of fogbench", "'--keep', default=False, choices=['y', 'yes', 'n', 'no'], help='Do not delete the", "| code:{}, reason: {}\".format(status_code, resp.reason)) return False return True def", "\"\"\" return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates = [] return templates", "print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def read_out_file(_file=None, _keep=False,", "'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time of every iteration", "in range(400, 500): print(\"Bad request error | code:{}, reason: {}\".format(status_code,", "+= (u\"\\nTotal Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate", "'total': stat += u\"Total Statistics:\\n\" stat += (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0],", "parser.add_argument('-H', '--host', help='Server host address (default: localhost)') parser.add_argument('-P', '--port', help='The", "time.sleep(_interval) if not _keep: os.remove(_file) async def send_to_coap(payload): \"\"\" POST", "# FOGLAMP_END \"\"\" fogbench -- a Python script used to", "southbound services. fogbench [IN] -h --help Print this help -i", "is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min and Max values", "json from datetime import datetime, timezone import argparse import collections", "print(fmt[\"name\"], reading) x_sensor_values[fmt[\"name\"]] = reading # print(d[\"name\"]) sensor_value_object = dict()", "} } { \"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI sensorTag/humidity\",", "# TODO: Change below per local_timestamp() values \"\"\" Expected output", "= d['name'] sensor_value_object[\"readings\"] = x_sensor_values sensor_value_object[\"timestamp\"] = \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object))", "_out_file=None): stat = '' global _start_time global _end_time global _tot_msgs_transferred", "iterations and occurrences arg_iterations = int(namespace.iterations) if namespace.iterations else 1", "{}\".format(_num_iterated)) stat += (u\"\\nTotal Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat +=", "[\"number\", \"enum\"] for _ in range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types)", "# Bytes transferred in every iteration for r in readings_list:", "port), URI \"/other/sensor-values\". \"\"\" from aiocoap import Context, Message from", "\"wall clock\", \"sensor_values\" : { \"tick\" : \"tock\" } }", "or str_res.split()[0] if status_code == \"4.00\" or status_code == \"5.00\":", "{}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate = [] for itr in", "(u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat += (u\"\\nAvg messages/second: {}\\n\".format(sum(_msg_rate)/_num_iterated)) stat +=", "every iteration for r in readings_list: msg_transferred_itr += 1 byte_transferred_itr", "_keep=False, _iterations=1, _interval=0, send_to='coap'): global _start_time global _end_time global _tot_msgs_transferred", "parse type {}\".format(fmt[\"type\"])) if fmt[\"type\"] == \"number\": # check float", "transferred in every iteration for r in readings_list: msg_transferred_itr +=", "as session: async with session.post(url, data=json.dumps(payload), headers=headers) as resp: await", "def check_server(payload_type='coap'): template_str = \">>> Make sure south {} plugin", ": 71.2, \"temperature\" : 18.6 } } { \"timestamp\" :", "return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file = os.path.join(os.path.dirname(__file__),", "\"object\" : 18.2, \"ambient\" : 21.6 } } { \"timestamp\"", "interval between each iteration arg_interval = int(namespace.interval) if namespace.interval else", "used to test FogLAMP (simulate payloads)' parser.epilog = 'The initial", "to CoAP or HTTP south plugin server, on specific host", "{ \"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall clock\", \"sensor_values\" :", "+= (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat += (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if", "we also show total time diff? end_time - start_time def", "[IN] -t --template Set the template to use [IN] -v", "Display the version and exit [IN] -H --host The FogLAMP", "./fogbench Help: $ ./fogbench -h * Create reading objects from", "range(400, 500): print(\"Bad request error | code:{}, reason: {}\".format(status_code, resp.reason))", "keep_the_file = True if namespace.keep in ['y', 'yes'] else False", "async def send_to_http(payload): \"\"\" POST request to: host localhost port", "meant to test the south plugin interface of ' \\", "test FogLAMP (simulate payloads)' parser.epilog = 'The initial version of", "code:{}, reason: {}\".format(status_code, resp.reason)) return False return True def get_statistics(_stats_type=None,", "uri sensor-reading \"\"\" headers = {'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host,", "{ \"object\" : 18.2, \"ambient\" : 21.6 } } {", "(default: coap) [IN] -t --template Set the template to use", "_tot_msgs_transferred = [] _tot_byte_transferred = [] _num_iterated = 0 \"\"\"Statistics", "readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if not is_sent: break elif send_to", ": \"wall clock\", \"sensor_values\" : { \"tick\" : \"tock\" }", "for r in readings_list: msg_transferred_itr += 1 byte_transferred_itr += sys.getsizeof(r)", "[] return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file =", "in readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r): with open(to_file, 'a')", "== 'http': print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s --", "\"ambient\" : 21.6 } } { \"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\"", "\"sensor_values\" : { \"x\" : 101.2, \"y\" : 46.2, \"z\"", "name specified with -t * Save those objects to the", "to: localhost port 5683 (official IANA assigned CoAP port), URI", "(default: 0) [IN] -k --keep Do not delete (keep) the", "{ \"x\" : 1.2, \"y\" : 0.0, \"z\" : -0.6", "the south plugin interface of ' \\ 'FogLAMP using CoAP", "The FogLAMP port. Default depends on payload and protocol [IN]", "(u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat", "{}\".format(max(_byte_rate))) stat += (u\"\\nAvg Bytes/second: {}\".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file,", "46.2, \"z\" : -12.6 } } { \"timestamp\" : \"2017-08-04T07:00:02.863Z\",", "per the json file name specified with -t * Save", "\"TI sensorTag/temperature\", \"sensor_values\" : { \"object\" : 18.2, \"ambient\" :", "= round(random.uniform(min_val, max_val), precision) elif fmt[\"type\"] == \"enum\": reading =", "or more FogLAMP instances. This version of fogbench is meant", "while _iterations > 0: # Pre-calculate the messages and size", "aiocoap import Context, Message from aiocoap.numbers.codes import Code from cbor2", "get_statistics(_stats_type=None, _out_file=None): stat = '' global _start_time global _end_time global", "= [] _byte_rate = [] for itr in range(_num_iterated): time_taken", "choices=['coap', 'http'], help='Type of payload ' 'and protocol (default: coap)')", "of statistics to collect Example: $ cd $FOGLAMP_ROOT/bin $ ./fogbench", "parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file = os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file)", "Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat += (u\"\\nTotal", "\"enum\"] for _ in range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types) for", "(default: 1) [IN] -P --port The FogLAMP port. Default depends", "elif fmt[\"type\"] == \"enum\": reading = random.choice(fmt[\"list\"]) # print(fmt[\"name\"], reading)", "\"sensor_values\" : { \"pressure\" : 1021.2 } } { \"timestamp\"", "namespace.host else 'localhost' default_port = 6683 if arg_payload_protocol == 'http'", "False if status_code in range(500, 600): print(\"Server error | code:{},", ": 1.2, \"y\" : 0.0, \"z\" : -0.6 } }", "generators \"\"\" import sys import os import random import json", "interface of ' \\ 'FogLAMP using CoAP or HTTP' parser.add_argument('-v',", "Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate = [] for itr", "Default depends on payload and protocol [IN] -S --statistic The", "ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def read_out_file(_file=None, _keep=False, _iterations=1,", "byte_transferred_itr = 0 # Bytes transferred in every iteration for", ": \"TI sensorTag/temperature\", \"sensor_values\" : { \"object\" : 18.2, \"ambient\"", "\"TI sensorTag/luxometer\", \"sensor_values\" : { \"lux\" : 49 } }", "to: host localhost port 6683 (default HTTP south plugin port),", "stat = '' global _start_time global _end_time global _tot_msgs_transferred global", ".exceptions import * __author__ = \"<NAME>\" __copyright__ = \"Copyright (c)", "Try generators \"\"\" import sys import os import random import", ": 1021.2 } } { \"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\" :", "Print this help -i --interval The interval in seconds between", "request.opt.uri_host = arg_host request.opt.uri_port = arg_port request.opt.uri_path = (\"other\", \"sensor-values\")", "current time stamp with microseconds and machine timezone info :example", "else: print(stat) # should we also show total time diff?", "stat += u\"Total Statistics:\\n\" stat += (u\"\\nStart Time: {}\".format(datetime.strftime(_start_time[0], \"%Y-%m-%d", "read_templates(): templates = [] return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1):", "fmt.get(\"max\", None) if min_val is None or max_val is None:", "if _out_file: with open(_out_file, 'w') as f: f.write(stat) else: print(stat)", "not is_sent: break elif send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now())", "CoAP port), URI \"/other/sensor-values\". \"\"\" from aiocoap import Context, Message", "os import random import json from datetime import datetime, timezone", "running sample (default: no)') parser.add_argument('-t', '--template', required=True, help='Set the template", "_iterations=1, _interval=0, send_to='coap'): global _start_time global _end_time global _tot_msgs_transferred global", "and protocol (default: coap) [IN] -t --template Set the template", "version and exit [IN] -H --host The FogLAMP host (default:", "'{0}'.format(namespace.template if namespace.template else '') statistics_file = os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if", "local_timestamp() values \"\"\" Expected output from given template { \"timestamp\"", "south plugin interface of ' \\ 'FogLAMP using CoAP or", "\"\"\"Statistics to be collected\"\"\" # _logger = logger.setup(__name__) def local_timestamp():", "not _keep: os.remove(_file) async def send_to_coap(payload): \"\"\" POST request to:", "(c) 2017 OSIsoft, LLC\" __license__ = \"Apache 2.0\" __version__ =", "each iteration arg_interval = int(namespace.interval) if namespace.interval else 0 arg_stats_type", "_iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change below per", "def read_templates(): templates = [] return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None,", "for fmt in _sensor_value_object_formats: if fmt[\"type\"] not in supported_format_types: raise", "{}\\n\".format(datetime.strftime(_end_time[-1], \"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat", "(u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat += (u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat +=", "str_res.split()[0] if status_code == \"4.00\" or status_code == \"5.00\": print(\"Error:", "min_val is None or max_val is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format,", "and Max values must be defined for type number.\") #", "address (default: localhost)') parser.add_argument('-P', '--port', help='The FogLAMP port. (default: 5683)')", "coap) [IN] -t --template Set the template to use [IN]", "HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y',", "the CoAP and HTTP plugins interface of FogLAMP southbound services.", "also show total time diff? end_time - start_time def check_server(payload_type='coap'):", "[] _num_iterated = 0 \"\"\"Statistics to be collected\"\"\" # _logger", "Context, Message from aiocoap.numbers.codes import Code from cbor2 import dumps", "Max values must be defined for type number.\") # print(precision)", "to collect Example: $ cd $FOGLAMP_ROOT/bin $ ./fogbench Help: $", "on payload and protocol [IN] -S --statistic The type of", "send_to == 'coap': _start_time.append(datetime.now()) for r in readings_list: is_sent =", "_byte_rate = [] for itr in range(_num_iterated): time_taken = _end_time[itr]", "0 \"\"\"Statistics to be collected\"\"\" # _logger = logger.setup(__name__) def", "} { \"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\" : \"wall clock\", \"sensor_values\"", "int(namespace.port) if namespace.port else default_port check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid()))", "global _tot_byte_transferred global _num_iterated if _stats_type == 'total': stat +=", "headers = {'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with", "meant to test the CoAP and HTTP plugins interface of", "namespace.interval else 0 arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics else 'total'", "coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END", "output from given template { \"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\" :", "Bytes transferred in every iteration for r in readings_list: msg_transferred_itr", "from aiocoap import Context, Message from aiocoap.numbers.codes import Code from", "600): print(\"Server error | code:{}, reason: {}\".format(status_code, resp.reason)) return False", "{} completed, waiting for {} seconds\".format(_iterations, _interval)) time.sleep(_interval) if not", "{}\".format(min(_byte_rate))) stat += (u\"\\nMax Bytes/second: {}\".format(max(_byte_rate))) stat += (u\"\\nAvg Bytes/second:", "from given template, as per the json file name specified", "{ \"timestamp\" : \"2017-08-04T07:00:00.863Z\", \"asset\" : \"TI sensorTag/accelerometer\", \"sensor_values\" :", "\"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\", \"sensor_values\" : { \"button\"", "Example: $ cd $FOGLAMP_ROOT/bin $ ./fogbench Help: $ ./fogbench -h", "supported_format_types) for r in readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r):", "This version of fogbench is meant to test the CoAP", "+= (u\"\\nTotal Iterations: {}\".format(_num_iterated)) stat += (u\"\\nTotal Messages per Iteration:", "+= (u\"\\nMin messages/second: {}\".format(min(_msg_rate))) stat += (u\"\\nMax messages/second: {}\".format(max(_msg_rate))) stat", "given template, as per the json file name specified with", "None or max_val is None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min", "loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr)", "given template { \"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI sensorTag/luxometer\",", "os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol)", "is running \\n & listening on specified host and port", "= True if namespace.keep in ['y', 'yes'] else False #", "'--port', help='The FogLAMP port. (default: 5683)') parser.add_argument('-i', '--interval', default=0, help='The", "'The initial version of %(prog)s is meant to test the", "_end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated if _stats_type ==", "Create reading objects from given template, as per the json", "{}\".format(sum(_tot_msgs_transferred))) stat += (u\"\\nTotal Bytes Transferred: {}\\n\".format(sum(_tot_byte_transferred))) stat += (u\"\\nTotal", "Help: $ ./fogbench -h * Create reading objects from given", "'yes'] else False # iterations and occurrences arg_iterations = int(namespace.iterations)", "Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate = []", "parser.add_argument('-o', '--output', default=None, help='Set the statistics output file') parser.add_argument('-p', '--payload',", "utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\"", "\"pressure\" : 1021.2 } } { \"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\"", "# Messages transferred in every iteration byte_transferred_itr = 0 #", "URI \"/other/sensor-values\". \"\"\" from aiocoap import Context, Message from aiocoap.numbers.codes", "+= (u\"\\nTotal Messages per Iteration: {}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal Bytes", "in _sensor_value_object_formats: if fmt[\"type\"] not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format,", "test (default: 1) [IN] -O --occurrences The number of occurrences", "sample_file = os.path.join(\"/tmp\", \"foglamp_running_sample.{}\".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations,", "_num_iterated = 0 \"\"\"Statistics to be collected\"\"\" # _logger =", "_iterations > 0: # Pre-calculate the messages and size msg_transferred_itr", "range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types) for r in readings_: _write_readings_to_file(_write_to_file,", "else 1 arg_occurrences = int(namespace.occurrences) if namespace.occurrences else 1 #", ":return: str - current time stamp with microseconds and machine", "[json.loads(line) for line in f] loop = asyncio.get_event_loop() while _iterations", "if any precision = fmt.get(\"precision\", None) min_val = fmt.get(\"min\", None)", ": \"2017-08-04T07:00:03.863Z\", \"asset\" : \"mouse\", \"sensor_values\" : { \"button\" :", "is meant to test the CoAP and HTTP plugins interface", "\"\"\" headers = {'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async", "import json from datetime import datetime, timezone import argparse import", "namespace.occurrences else 1 # interval between each iteration arg_interval =", "{ \"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI sensorTag/gyroscope\", \"sensor_values\" :", "else 1 # interval between each iteration arg_interval = int(namespace.interval)", ": -12.6 } } { \"timestamp\" : \"2017-08-04T07:00:03.863Z\", \"asset\" :", "= argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s -- a Python script used", "{ \"pressure\" : 1021.2 } } { \"timestamp\" : \"2017-08-04T06:59:58.863Z\",", "# from pprint import pprint import time # _file =", "(default: coap)') parser.add_argument('-I', '--iterations', help='The number of iterations of the", "choices=['y', 'yes', 'n', 'no'], help='Do not delete the running sample", "line in f] loop = asyncio.get_event_loop() while _iterations > 0:", "port \\n\" if payload_type == 'coap': print(template_str.format(\"CoAP\")) elif payload_type ==", "\"button\" : \"down\" } } { \"timestamp\" : \"2017-08-04T07:00:04.863Z\", \"asset\"", ": { \"lux\" : 49 } } { \"timestamp\" :", "south plugin port), uri sensor-reading \"\"\" headers = {'content-type': 'application/json'}", "the file, as per the file name specified with -o", "Python script used to test FogLAMP (simulate payloads)' parser.epilog =", "_tot_byte_transferred global _num_iterated # from pprint import pprint import time", "\\n & listening on specified host and port \\n\" if", "template_str = \">>> Make sure south {} plugin service is", "= \"{!s}\".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings", "= [json.loads(line) for line in f] loop = asyncio.get_event_loop() while", "{}\".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u\"\\nTotal Bytes per Iteration: {}\\n\".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate =", "type of statistics to collect ' '(default: total)') namespace =", "{}\".format(status_code, resp.reason)) return False if status_code in range(500, 600): print(\"Server", "below per local_timestamp() values \"\"\" Expected output from given template", "_start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated if", "None: raise InvalidSensorValueObjectTemplateFormat(u\"Invalid format, \" u\"Min and Max values must", ": 18.2, \"ambient\" : 21.6 } } { \"timestamp\" :", "port. (default: 5683)') parser.add_argument('-i', '--interval', default=0, help='The interval in seconds", "-0.6 } } { \"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI", "$ ./fogbench Help: $ ./fogbench -h * Create reading objects", "seconds between each iteration (default: 0) [IN] -k --keep Do", "session.post(url, data=json.dumps(payload), headers=headers) as resp: await resp.text() status_code = resp.status", "str_res = str(response.code) status_code = str_res[:4] # or str_res.split()[0] if", "(default HTTP south plugin port), uri sensor-reading \"\"\" headers =", "asyncio.get_event_loop() while _iterations > 0: # Pre-calculate the messages and", "running sample (default: no) [IN] -o --output Set the output", "interface of FogLAMP southbound services. fogbench [IN] -h --help Print", "| code:{}, reason: {}\".format(status_code, resp.reason)) return False if status_code in", "as resp: await resp.text() status_code = resp.status if status_code in", "input, REST and other requests against one or more FogLAMP", "_write_to_file=None, _occurrences=1): # template_file = os.path.join(os.path.dirname(__file__), \"templates/\" + _template_file) with", "[IN] -p --payload Type of payload and protocol (default: coap)", "default=None, help='Set the statistics output file') parser.add_argument('-p', '--payload', default='coap', choices=['coap',", "== 'http' else 5683 arg_port = int(namespace.port) if namespace.port else", "plugin interface of ' \\ 'FogLAMP using CoAP or HTTP'", "\"timestamp\" : \"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI sensorTag/gyroscope\", \"sensor_values\" : {", "= int(namespace.port) if namespace.port else default_port check_server(arg_payload_protocol) sample_file = os.path.join(\"/tmp\",", "global _tot_byte_transferred global _num_iterated # from pprint import pprint import", "to the file, as per the file name specified with", "if fmt[\"type\"] == \"number\": # check float precision if any", "False return True def get_statistics(_stats_type=None, _out_file=None): stat = '' global", "\"timestamp\" : \"2017-08-04T06:59:59.863Z\", \"asset\" : \"TI sensorTag/temperature\", \"sensor_values\" : {", "'--occurrences', help='The number of occurrences of the template (default: 1)')", "os.path.join(os.path.dirname(__file__), \"out/{}\".format(namespace.output)) if namespace.output else None keep_the_file = True if", "os.path.join(os.path.dirname(__file__), \"out/{}\".format(outfile)) with open(_file) as f: readings_list = [json.loads(line) for", "_num_iterated if _stats_type == 'total': stat += u\"Total Statistics:\\n\" stat", "# See: http://foglamp.readthedocs.io/ # FOGLAMP_END \"\"\" fogbench -- a Python", "* Read those objects * Send those to CoAP or", "in every iteration for r in readings_list: msg_transferred_itr += 1", "specified host and port \\n\" if payload_type == 'coap': print(template_str.format(\"CoAP\"))", "\"sensor_values\" : { \"lux\" : 49 } } { \"timestamp\"", "precision if any precision = fmt.get(\"precision\", None) min_val = fmt.get(\"min\",", "or status_code == \"5.00\": print(\"Error: \", str_res) return False return", "\"%Y-%m-%d %H:%M:%S.%f\"))) stat += (u\"\\nTotal Messages Transferred: {}\".format(sum(_tot_msgs_transferred))) stat +=", "_ in range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types) for r in", "' '(default: total)') namespace = parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if", "--template Set the template to use [IN] -v --version Display", "d[\"sensor_values\"] for fmt in _sensor_value_object_formats: if fmt[\"type\"] not in supported_format_types:", "'--host', help='Server host address (default: localhost)') parser.add_argument('-P', '--port', help='The FogLAMP", "def _write_readings_to_file(to_file, r): with open(to_file, 'a') as the_file: json.dump(r, the_file)", ": \"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI sensorTag/humidity\", \"sensor_values\" : { \"humidity\"", "None) min_val = fmt.get(\"min\", None) max_val = fmt.get(\"max\", None) if", "--host The FogLAMP host (default: localhost) -I --iterations The number", "import sys import os import random import json from datetime", "default=False, choices=['y', 'yes', 'n', 'no'], help='Do not delete the running", "r) def _write_readings_to_file(to_file, r): with open(to_file, 'a') as the_file: json.dump(r,", "namespace.statistics else 'total' if namespace.payload: arg_payload_protocol = namespace.payload arg_host =", "'http': print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s -- a", "start_time def check_server(payload_type='coap'): template_str = \">>> Make sure south {}", "print(template_str.format(\"CoAP\")) elif payload_type == 'http': print(template_str.format(\"HTTP\")) parser = argparse.ArgumentParser(prog='fogbench') parser.description", "if namespace.interval else 0 arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics else", "if not _keep: os.remove(_file) async def send_to_coap(payload): \"\"\" POST request", "_prepare_sensor_reading(data, supported_format_types): readings = [] for d in data: x_sensor_values", "objective is to simulate payloads for input, REST and other", "parser.description = '%(prog)s -- a Python script used to test", "if namespace.statistics else 'total' if namespace.payload: arg_payload_protocol = namespace.payload arg_host", "import dumps context = await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST)", "template { \"timestamp\" : \"2017-08-04T06:59:57.503Z\", \"asset\" : \"TI sensorTag/luxometer\", \"sensor_values\"", "# End time of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -=", "\"timestamp\" : \"2017-08-04T06:59:58.863Z\", \"asset\" : \"TI sensorTag/humidity\", \"sensor_values\" : {", "\"2017-08-04T07:00:01.863Z\", \"asset\" : \"TI sensorTag/gyroscope\", \"sensor_values\" : { \"x\" :" ]
[ "mitigating the count of '0110' in this step, the following", "in the root directory # of this source tree or", "1, 2, ..., n-1]]`, which exactly corresponds to the complete", "Initialize a tensored measurement error mitigation filter using the cal_matrices", "pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\", "# Apply the correction for data_idx, _ in enumerate(raw_data2): if", "self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit", "`raw_data` Raises: QiskitError: if `raw_data` is not an integer multiple", "isinstance(raw_data, dict): # counts dictionary # convert to list raw_data2", "if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def", "list of counts of `length==len(state_labels)` Form 3: a list of", "correction for data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse':", "error mitigation filter using the cal_matrices from a tensored measurement", "cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] -", "directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #", "reverse endian qubits_to_clbits = [-1 for _ in range(max(meas_layout) +", "raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def flip_state(self,", "for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the", "change to: # raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0] return", "+= str(int(state[flip_pos], 2) ^ 1) # flip the state pos", "raise QiskitError(\"Unrecognized method.\") if data_format == 2: # flatten back", "'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method == 'least_squares':", "size of largest set of mit_pattern. If the `mit_pattern` is", "be `O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained to have physical", "Apache License, Version 2.0. You may # obtain a copy", "_, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the indices", "of largest set of mit_pattern. If the `mit_pattern` is shaped", "in range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state,", "List, Union from copy import deepcopy from scipy.optimize import minimize", "the input quantum state\"\"\" sub_state = \"\" for pos in", "= deepcopy(x) for cal_mat, pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list):", "measurement error mitigation filter using the cal_matrix from a measurement", "QiskitError(\"Unrecognized type for raw_data.\") if method == 'pseudo_inverse': pinv_cal_mat =", "of calibrated states\") elif isinstance(raw_data, qiskit.result.result.Result): # extract out all", "nqubits(self): \"\"\"Return the number of qubits. See also MeasurementFilter.apply() \"\"\"", "may # obtain a copy of this license in the", "return self._cal_matrix @property def state_labels(self): \"\"\"return the state label ordering", "* A counts dictionary from results.get_counts * A Qiskit Result", "to find the closest probability vector to the result from", "cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): \"\"\"Set", "of state_labels for easier # processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)])", "The following methods are supported: * 'pseudo_inverse': direct inversion of", "== 2: # flatten back out the list raw_data2 =", "number of sets in `mit_pattern`, and `t` is the size", "pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction filters. \"\"\" from typing import", "= sum(raw_data2[data_idx]) cons = ({'type': 'eq', 'fun': lambda x: nshots", "# obtain a copy of this license in the LICENSE.txt", "- np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels)) x0 = x0 /", "method=method) return resultidx, new_counts class TensoredFilter(): \"\"\" Tensored measurement error", "cal_matrix self._state_labels = state_labels @property def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return", "def flip_state(self, state: str, mat_index: int, flip_poses: List[int]) -> str:", "== 'least_squares': def fun(x): mat_dot_x = deepcopy(x) for cal_mat, pos_qubits,", "to results. Args: raw_data (dict or list): The data to", "`mit_pattern`, and `t` is the size of largest set of", "if isinstance(raw_data, dict): # counts dictionary # convert to list", "2' calibration matrix `A_3`. When mitigating the count of '0110'", "0 # convert to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for", "def _apply_correction(self, resultidx, raw_data, method): \"\"\"Wrapper to call apply with", "* 'pseudo_inverse': direct inversion of the cal matrices. Mitigated counts", "`None`, then least_squares is used. ``pseudo_inverse``: direct inversion of the", "[] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern", "new_counts = self.apply( raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class TensoredFilter():", "push back into the new result new_result = deepcopy(raw_data) new_counts_list", "Mitigation is conducted qubit wise: For each qubit, mitigate the", "calibration matrices to results. Args: raw_data (dict or Result): The", "number of calibrated states. \"\"\" # check forms of raw_data", "list becomes `[2, 0, 1]` * If `None`, flatten(mit_pattern) is", "i # Apply the correction for data_idx, _ in enumerate(raw_data2):", "method.\") # convert back into a counts dictionary new_count_dict =", "x0 / sum(x0) cons = ({'type': 'eq', 'fun': lambda x:", "tensored measurement error mitigation filter using the cal_matrices from a", "`t` is the size of largest set of mit_pattern. If", "indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits", "[n-1]]`, which corresponds to the tensor product noise model without", "def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list):", "square quadratic programming (SLSQP) is used in the internal process.", "explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices for applying", "..., [n-1]]`, which corresponds to the tensor product noise model", "# # (C) Copyright IBM 2019. # # This code", "indices: dict) -> int: \"\"\"Return the index of (pseudo inverse)", "= new_count_dict else: # TODO: should probably change to: #", "[n-1]]` would take 10 seconds or more. * If `None`,", "= [raw_data] elif int(size_ratio) == size_ratio: data_format = 2 size_ratio", "endian qubits_to_clbits = [-1 for _ in range(max(meas_layout) + 1)]", "type for raw_data.\") if method == 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix)", "= \"\" pos = 0 for flip_pos in flip_poses: new_state", "be `O(n2^n)`. If the `mit_pattern` is shaped like `[[0, 1,", "methods are supported: * 'pseudo_inverse': direct inversion of the cal", "import minimize import scipy.linalg as la import numpy as np", "disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction filters. \"\"\" from typing import List,", "self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(pinv_cal_mat)): # i is", "a notice indicating # that they have been altered from", "dictionary # convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for", "self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit", "meas_layout = meas_layout[::-1] # reverse endian qubits_to_clbits = [-1 for", "copyright notice, and modified files need to carry a notice", "raw_data Raises: QiskitError: if raw_data is not in a one", "tomography data) Form 4: a qiskit Result method (str): fitting", "the same form as raw_data Raises: QiskitError: if raw_data is", "bit of the 4-bit counts using '2\\times 2' calibration matrix", "`1` to `2`, the list becomes `[2, 0, 1]` *", "or derivative works of this code must retain this #", "in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the indices in the", "'fun': lambda x: nshots - sum(x)}) bnds = tuple((0, nshots)", "mat_dot_x = deepcopy(x) for cal_mat, pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern,", "inverse) calibration matrix for the input quantum state\"\"\" sub_state =", "typing import List, Union from copy import deepcopy from scipy.optimize", "in the subspace) \"\"\" self._cal_matrices = cal_matrices self._qubit_list_sizes = []", "resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else:", "a one of the defined forms. \"\"\" all_states = count_keys(self.nqubits)", "qiskit from qiskit import QiskitError from qiskit.tools import parallel_map from", "\"\"\" Tensored measurement error mitigation filter. Produced from a tensored", "this method solve a constrained optimization problem to find the", "[] for qubits in self._mit_pattern: meas_layout += qubits # check", "applying inverse calibration matrices, this method solve a constrained optimization", "for state_idx, state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices)", "new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx,", "that they have been altered from the originals. # pylint:", "to the result from 'pseudo_inverse' method. Sequential least square quadratic", "clbit `0`, `0` to `1`, and `1` to `2`, the", "modifications or derivative works of this code must retain this", "of '0110' in this step, the following formula is applied:", "-> int: \"\"\"Return the index of (pseudo inverse) calibration matrix", "0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total time complexity of this", "matrix to results. Args: raw_data (dict or list): The data", "for pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x =", "correction. substate_labels_list: for each calibration matrix a list of the", "List[int] = None): \"\"\" Apply the calibration matrices to results.", "TensoredFilter(): \"\"\" Tensored measurement error mitigation filter. Produced from a", "count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count", "self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list))))", "SLSQP takes `O(m2^{n+t})` time. Since this method is using the", "deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in", "complexity would be `O(n2^n)`. If the `mit_pattern` is shaped like", "= sorted(flip_poses) new_state = \"\" pos = 0 for flip_pos", "QiskitError(\"Data list is not an integer multiple \" \"of the", "= res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 =", "all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout is None:", "cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix def apply(self, raw_data,", "forms of raw_data if isinstance(raw_data, dict): # counts dictionary #", "the cal_matrices from a tensored measurement calibration fitter. A simple", "the ordering of the cal matrix \"\"\" self._cal_matrix = cal_matrix", "of the logical qubit indices (as int, states in the", "[2], ..., [n-1]]` would take 10 seconds or more. *", "as la import numpy as np import qiskit from qiskit", "counts can contain negative values and the sum of counts", "qubit positions\"\"\" flip_poses = [pos for i, pos in enumerate(flip_poses)", "pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state", "(C) Copyright IBM 2019. # # This code is licensed", "You may # obtain a copy of this license in", "step in SLSQP takes `O(m2^{n+t})` time. Since this method is", "first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(pinv_cal_mat)): #", "in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError(\"Unrecognized", "new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): \"\"\"Return", "`mit_pattern` is shaped like `[[0, 1, 2, ..., n-1]]`, which", "carry a notice indicating # that they have been altered", "into a counts dictionary new_count_dict = {} for stateidx, state", "cal matrix \"\"\" self._cal_matrix = cal_matrix self._state_labels = state_labels @property", "list into chunks the size of state_labels for easier #", "raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\") # convert back", "state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i", "second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(cal_mat)): target_state", "the Apache License, Version 2.0. You may # obtain a", "flip_poses = [pos for i, pos in enumerate(flip_poses) if (mat_index", "qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply the correction", "Result method (str): fitting method. The following methods are supported:", "and `1` to `2`, the list becomes `[2, 0, 1]`", "qubits in self._mit_pattern: meas_layout += qubits # check forms of", "= {} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] !=", "res.x else: raise QiskitError(\"Unrecognized method.\") # convert back into a", "2: # flatten back out the list raw_data2 = raw_data2.flatten()", "method='least_squares'): \"\"\"Apply the calibration matrix to results. Args: raw_data (dict", "a tensored measurement calibration fitter. A simple usage this class", "A simple usage this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args:", "retain this # copyright notice, and modified files need to", "state_labels for easier # processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for", "self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab:", "matrices for applying the correction. substate_labels_list: for each calibration matrix", "make the list into chunks the size of state_labels for", "flip_poses = sorted(flip_poses) new_state = \"\" pos = 0 for", "is used. Returns: dict or Result: The corrected data in", "x0) res = minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx]", "mat_index: int, flip_poses: List[int]) -> str: \"\"\"Flip the state according", "counts with the `mit_pattern = [[0], [1], [2], ..., [n-1]]`", "and can be applied to data. \"\"\" def __init__(self, cal_matrix:", "i, pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\ +=", "tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\") if data_format", "of Qiskit. # # (C) Copyright IBM 2019. # #", "states. \"\"\" # check forms of raw_data if isinstance(raw_data, dict):", "elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call", "if method == 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the", "2)]\\ += cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return", "_qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property def nqubits(self): \"\"\"Return the number of", "used. meas_layout (list of int): the mapping from classical registers", "raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx]", "= meas_layout[::-1] # reverse endian qubits_to_clbits = [-1 for _", "`None`, flatten(mit_pattern) is used. Returns: dict or Result: The corrected", "np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons", "int: \"\"\"Return the index of (pseudo inverse) calibration matrix for", "the correction state_labels: the states for the ordering of the", "lenght `2^n`, the mitigation for 8 bit counts with the", "def apply(self, raw_data: Union[qiskit.result.result.Result, dict], method: str = 'least_squares', meas_layout:", "=\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index, second_index] *", "complexity of this method is `O(m2^{n + t})`, where `n`", "need to carry a notice indicating # that they have", "method. If `None`, then least_squares is used. ``pseudo_inverse``: direct inversion", "the number of sets in `mit_pattern`, and `t` is the", "same form as `raw_data` Raises: QiskitError: if `raw_data` is not", "* 'least_squares': constrained to have physical probabilities. Instead of directly", "def apply(self, raw_data, method='least_squares'): \"\"\"Apply the calibration matrix to results.", "pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits,", "for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif", "i) & 1] flip_poses = sorted(flip_poses) new_state = \"\" pos", "takes `O(m2^{n+t})` time. Since this method is using the SLSQP", "= [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1]", "corrected. Can be in a number of forms: Form 1:", "label ordering of the cal matrix\"\"\" return self._state_labels @state_labels.setter def", "A matrix ``least_squares``: constrained to have physical probabilities Returns: dict", "utf-8 -*- # This code is part of Qiskit. #", "resultidx, raw_data, method): \"\"\"Wrapper to call apply with a counts", "import List, Union from copy import deepcopy from scipy.optimize import", "state_idx, state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for", "x))**2) x0 = np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0) cons", "counts dictionary new_count_dict = {} for stateidx, state in enumerate(self._state_labels):", "the time complexity would be `O(2^(n+n)) = O(4^n)`. * 'least_squares':", "internal process. Every updating step in SLSQP takes `O(m2^{n+t})` time.", "of counts would not equal to the shots. Mitigation is", "or list): The data to be corrected. Can be in", "you measure qubit `2` to clbit `0`, `0` to `1`,", "for state, count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx]", "def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices):", "for flip_pos in flip_poses: new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos],", "def cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix def apply(self,", "of int): the mapping from classical registers to qubits *", "= [[0], [1], [2], ..., [n-1]]` would take 10 seconds", "is using the SLSQP optimization over the vector with lenght", "of directly applying inverse calibration matrices, this method solve a", "'least_squares': constrained to have physical probabilities. Instead of directly applying", "a list of the logical qubit indices (as int, states", "= [] self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern @property def", "form as raw_data Raises: QiskitError: if raw_data is not in", "method == 'least_squares': nshots = sum(raw_data2[data_idx]) def fun(x): return sum(", "\"\"\"Return the index of (pseudo inverse) calibration matrix for the", "from results.get_counts Form 2: a list of counts of `length==len(state_labels)`", "the number of qubits in each subspace self._qubit_list_sizes = []", "complexity would be `O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained to", "`A_3`. When mitigating the count of '0110' in this step,", "state: str, pos_qubits: List[int], indices: dict) -> int: \"\"\"Return the", "state_labels: list): \"\"\" Initialize a measurement error mitigation filter using", "is not an integer multiple of the number of calibrated", "state label ordering of the cal matrix\"\"\" return self._state_labels @state_labels.setter", "raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels)", "from a measurement calibration fitter. Args: cal_matrix: the calibration matrix", "the states for the ordering of the cal matrix \"\"\"", "for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for resultidx,", "range(size_ratio): raw_data2[i][:] = raw_data[ i * len(self._state_labels):(i + 1)*len( self._state_labels)]", "optimization problem to find the closest probability vector to the", "sets in `mit_pattern`, and `t` is the size of largest", "\"\"\" self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list = []", "the cal matrices. Mitigated counts can contain negative values and", "mit_pattern: list): \"\"\" Initialize a tensored measurement error mitigation filter", "(https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices for applying the correction.", "the LICENSE.txt file in the root directory # of this", "x in x0) res = minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds,", "state label ordering of the cal matrix\"\"\" self._state_labels = new_state_labels", "not in a one of the defined forms. \"\"\" all_states", "2) x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots", "pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x", "i in range(len(pinv_cal_mat)): # i is index of pinv_cal_mat source_state", "def cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices) @property def", "else: raise QiskitError(\"Unrecognized method.\") # convert back into a counts", "= [pos for i, pos in enumerate(flip_poses) if (mat_index >>", "minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else:", "_ in range(max(meas_layout) + 1)] for i, qubit in enumerate(meas_layout):", "nshots - sum(x)}) bnds = tuple((0, nshots) for x in", "`O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained to have physical probabilities.", "chosen qubit positions\"\"\" flip_poses = [pos for i, pos in", "size_ratio: data_format = 2 size_ratio = int(size_ratio) # make the", "the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction,", "return new_state def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict)", "compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict) -> int: \"\"\"Return", "= new_cal_matrix def apply(self, raw_data, method='least_squares'): \"\"\"Apply the calibration matrix", "if method == 'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx]) elif", "new_state += state[pos:] return new_state def compute_index_of_cal_mat(self, state: str, pos_qubits:", "or more. * If `None`, 'least_squares' is used. meas_layout (list", "2)] raw_data2[data_idx] = inv_mat_dot_x elif method == 'least_squares': def fun(x):", "self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern @property def cal_matrices(self): \"\"\"Return", "of this code must retain this # copyright notice, and", "is the number of sets in `mit_pattern`, and `t` is", "pos in enumerate(flip_poses) if (mat_index >> i) & 1] flip_poses", "[resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for", "new_count_dict else: # TODO: should probably change to: # raw_data2", "applying the correction. substate_labels_list: for each calibration matrix a list", "the state according to the chosen qubit positions\"\"\" flip_poses =", "Form 4: a qiskit Result method (str): fitting method. If", "new_count_dict def flip_state(self, state: str, mat_index: int, flip_poses: List[int]) ->", "indices) res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x =", "res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x", "applied to data. \"\"\" def __init__(self, cal_matrices: np.matrix, substate_labels_list: list,", "QiskitError: if raw_data is not in a one of the", "qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.ignis.verification.tomography import", "enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts =", "class MeasurementFilter(): \"\"\" Measurement error mitigation filter. Produced from a", "2.0. You may # obtain a copy of this license", "as np import qiskit from qiskit import QiskitError from qiskit.tools", "-> str: \"\"\"Flip the state according to the chosen qubit", "# reverse endian qubits_to_clbits = [-1 for _ in range(max(meas_layout)", "of mit_pattern. If the `mit_pattern` is shaped like `[[0], [1],", "``pseudo_inverse``: direct inversion of the A matrix ``least_squares``: constrained to", "the shots. Mitigation is conducted qubit wise: For each qubit,", "({'type': 'eq', 'fun': lambda x: nshots - sum(x)}) bnds =", "for the ordering of the cal matrix \"\"\" self._cal_matrix =", "(list of int): the mapping from classical registers to qubits", "ordering of the cal matrix \"\"\" self._cal_matrix = cal_matrix self._state_labels", "1)*len( self._state_labels)] else: raise QiskitError(\"Data list is not an integer", "new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def flip_state(self, state: str, mat_index:", "task_args=(raw_data, method, meas_layout)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts =", "correction filters. \"\"\" from typing import List, Union from copy", "This code is licensed under the Apache License, Version 2.0.", "calibration matrix a list of the states (as strings, states", "filter using the cal_matrix from a measurement calibration fitter. Args:", "in SLSQP takes `O(m2^{n+t})` time. Since this method is using", "`[2, 0, 1]` * If `None`, flatten(mit_pattern) is used. Returns:", "= la.pinv(self._cal_matrix) # Apply the correction for data_idx, _ in", "subspace self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append(", "the same form as `raw_data` Raises: QiskitError: if `raw_data` is", "cross-talk, then the time complexity would be `O(n2^n)`. If the", "new_cal_matrix def apply(self, raw_data, method='least_squares'): \"\"\"Apply the calibration matrix to", "# TODO: should probably change to: # raw_data2 = raw_data2[0].tolist()", "corrected. Can be in one of two forms: * A", "self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state, 2)]", "matrix a list of the states (as strings, states in", "direct inversion of the cal matrices. Mitigated counts can contain", "qubit, mitigate the whole counts using the calibration matrices which", "raw_data, method='least_squares'): \"\"\"Apply the calibration matrix to results. Args: raw_data", "meas_layout += qubits # check forms of raw_data if isinstance(raw_data,", "indices[sub_state] def _apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result, method: str, meas_layout:", "back out the list raw_data2 = raw_data2.flatten() elif data_format ==", "\"\"\"Set cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\"", "more. * If `None`, 'least_squares' is used. meas_layout (list of", "counts dictionary for data_label in raw_data.keys(): if data_label not in", "_apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result, method: str, meas_layout: List[int]): \"\"\"Wrapper", "[here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices for applying the", "x0 = x0 / sum(x0) cons = ({'type': 'eq', 'fun':", "raw_data2 = raw_data2.flatten() elif data_format == 0: # convert back", "qiskit Result method (str): fitting method. If `None`, then least_squares", "sum(x)}) bnds = tuple((0, nshots) for x in x0) res", "in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for resultidx, new_counts in new_counts_list:", "formula is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`.", "results. Args: raw_data (dict or Result): The data to be", "np.matrix, substate_labels_list: list, mit_pattern: list): \"\"\" Initialize a tensored measurement", "raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all", "2 size_ratio = int(size_ratio) # make the list into chunks", "physical probabilities. Instead of directly applying inverse calibration matrices, this", "to data. \"\"\" def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern:", "2019. # # This code is licensed under the Apache", "direct inversion of the A matrix ``least_squares``: constrained to have", "measurement calibration fitter. Args: cal_matrix: the calibration matrix for applying", "supported: * 'pseudo_inverse': direct inversion of the cal matrices. Mitigated", "qiskit.ignis.verification.tomography import count_keys class MeasurementFilter(): \"\"\" Measurement error mitigation filter.", "source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or", "closest probability vector to the result from 'pseudo_inverse' method. Sequential", "over the vector with lenght `2^n`, the mitigation for 8", "+ 1)] for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i", "each calibration matrix a list of the logical qubit indices", "code must retain this # copyright notice, and modified files", "the correction for data_idx, _ in enumerate(raw_data2): if method ==", "flip_state(self, state: str, mat_index: int, flip_poses: List[int]) -> str: \"\"\"Flip", "raw_data2.flatten() elif data_format == 0: # convert back into a", "# extract out all the counts, re-call the function with", "if `raw_data` is not an integer multiple of the number", "la.pinv(self._cal_matrix) # Apply the correction for data_idx, _ in enumerate(raw_data2):", "# -*- coding: utf-8 -*- # This code is part", "self.apply( raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class TensoredFilter(): \"\"\" Tensored", "subspace) mit_pattern: for each calibration matrix a list of the", "= cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list =", "input data\") data_format = 0 # convert to form2 raw_data2", "counts dictionary new_count_dict = {} for state_idx, state in enumerate(all_states):", "cal matrix\"\"\" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): \"\"\"set the", "integer multiple \" \"of the number of calibrated states\") elif", "lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes", "substate_labels_list: list, mit_pattern: list): \"\"\" Initialize a tensored measurement error", "isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the", "the number of calibrated states\") elif isinstance(raw_data, qiskit.result.result.Result): # extract", "state: str, mat_index: int, flip_poses: List[int]) -> str: \"\"\"Flip the", "the defined forms. \"\"\" all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits", "dict) -> int: \"\"\"Return the index of (pseudo inverse) calibration", "is used. meas_layout (list of int): the mapping from classical", "of forms: Form 1: a counts dictionary from results.get_counts Form", "dict): # counts dictionary for data_label in raw_data.keys(): if data_label", "list of the logical qubit indices (as int, states in", "nshots = sum(raw_data2[data_idx]) cons = ({'type': 'eq', 'fun': lambda x:", "a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout) return", "of counts of `length==M*len(state_labels)` where M is an integer (e.g.", "raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x elif method == 'least_squares': def", "code is part of Qiskit. # # (C) Copyright IBM", "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any", "a measurement calibration fitter. Args: cal_matrix: the calibration matrix for", "state according to the chosen qubit positions\"\"\" flip_poses = [pos", "the state pos = flip_pos + 1 new_state += state[pos:]", "raw_data (dict or list): The data to be corrected. Can", "\"\"\" Measurement correction filters. \"\"\" from typing import List, Union", "deepcopy(new_cal_matrices) @property def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter def", "counts and push back into the new result new_result =", "= 1 raw_data2 = [raw_data] elif int(size_ratio) == size_ratio: data_format", "parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method,", "= 0 # convert to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)]", "len(self._state_labels):(i + 1)*len( self._state_labels)] else: raise QiskitError(\"Data list is not", "qubits. See also MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes) def apply(self, raw_data:", "# get the number of qubits in each subspace self._qubit_list_sizes", "The corrected data in the same form as `raw_data` Raises:", "cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self):", "qubits, `m` is the number of sets in `mit_pattern`, and", "self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(cal_mat)): target_state = self.flip_state(state,", "int, raw_data: qiskit.result.result.Result, method: str, meas_layout: List[int]): \"\"\"Wrapper to call", "a tensored measurement error mitigation filter using the cal_matrices from", "method: str = 'least_squares', meas_layout: List[int] = None): \"\"\" Apply", "# Any modifications or derivative works of this code must", "qubits * If you measure qubit `2` to clbit `0`,", "in the calibration matrix self._indices_list = [] for _, sub_labels", "to `2`, the list becomes `[2, 0, 1]` * If", "counts of `length==M*len(state_labels)` where M is an integer (e.g. for", "== size_ratio: data_format = 2 size_ratio = int(size_ratio) # make", "stateidx = int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result):", "size_ratio = int(size_ratio) # make the list into chunks the", "# counts dictionary for data_label in raw_data.keys(): if data_label not", "raw_data is not in a one of the defined forms.", "state\"\"\" sub_state = \"\" for pos in pos_qubits: sub_state +=", "constrained to have physical probabilities Returns: dict or list: The", "the internal process. Every updating step in SLSQP takes `O(m2^{n+t})`", "`O(n2^n)`. If the `mit_pattern` is shaped like `[[0, 1, 2,", "raise QiskitError(\"Unrecognized method.\") # convert back into a counts dictionary", "dictionary for data_label in raw_data.keys(): if data_label not in self._state_labels:", "method.\") if data_format == 2: # flatten back out the", "fitter's state labels \" \"correspond to the input data\") data_format", "2) ^ 1) # flip the state pos = flip_pos", "self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix", "with the tomography data) Form 4: a qiskit Result method", "int, states in the subspace) \"\"\" self._cal_matrices = cal_matrices self._qubit_list_sizes", "of (pseudo inverse) calibration matrix for the input quantum state\"\"\"", "'pseudo_inverse': pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout", "the A matrix ``least_squares``: constrained to have physical probabilities Returns:", "which corresponds to the tensor product noise model without cross-talk,", "in enumerate(sub_labels)}) @property def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property", "would be `O(n2^n)`. If the `mit_pattern` is shaped like `[[0,", "of two forms: * A counts dictionary from results.get_counts *", "= len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format = 1 raw_data2", "be applied to data. \"\"\" def __init__(self, cal_matrix: np.matrix, state_labels:", "meas_layout[::-1] # reverse endian qubits_to_clbits = [-1 for _ in", "/ sum(x0) cons = ({'type': 'eq', 'fun': lambda x: nshots", "fun(x): return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels))", "cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices", "list): \"\"\" Initialize a tensored measurement error mitigation filter using", "def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict) -> int:", "-*- # This code is part of Qiskit. # #", "elif method == 'least_squares': nshots = sum(raw_data2[data_idx]) def fun(x): return", "== 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the correction for", "subspace) \"\"\" self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list =", "without cross-talk, then the time complexity would be `O(n2^n)`. If", "self._mit_pattern = mit_pattern @property def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return self._cal_matrices", "pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx]", "qubits_to_clbits = [-1 for _ in range(max(meas_layout) + 1)] for", "= new_counts return new_result else: raise QiskitError(\"Unrecognized type for raw_data.\")", "with lenght `2^n`, the mitigation for 8 bit counts with", "data_format = 2 size_ratio = int(size_ratio) # make the list", "the SLSQP optimization over the vector with lenght `2^n`, the", "correction state_labels: the states for the ordering of the cal", "1 new_state += state[pos:] return new_state def compute_index_of_cal_mat(self, state: str,", "is used. ``pseudo_inverse``: direct inversion of the A matrix ``least_squares``:", "optimization over the vector with lenght `2^n`, the mitigation for", "indices) for i in range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits)", "+ 1 new_state += state[pos:] return new_state def compute_index_of_cal_mat(self, state:", "classical registers to qubits * If you measure qubit `2`", "is an integer (e.g. for use with the tomography data)", "= 'least_squares', meas_layout: List[int] = None): \"\"\" Apply the calibration", "resultidx, new_counts class TensoredFilter(): \"\"\" Tensored measurement error mitigation filter.", "derivative works of this code must retain this # copyright", "in enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply the correction for", "cal_matrix.\"\"\" return self._cal_matrix @property def state_labels(self): \"\"\"return the state label", "from scipy.optimize import minimize import scipy.linalg as la import numpy", "where `n` is the size of calibrated qubits, `m` is", "using the cal_matrices from a tensored measurement calibration fitter. A", "raise QiskitError(\"Unrecognized type for raw_data.\") if method == 'pseudo_inverse': pinv_cal_matrices", "= np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method == 'least_squares': nshots =", "following formula is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1,", "+ data_label + \"', verify the fitter's state labels \"", "..., [n-1]]` would take 10 seconds or more. * If", "is not in a one of the defined forms. \"\"\"", "in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in", "= raw_data2.flatten() elif data_format == 0: # convert back into", "import QiskitError from qiskit.tools import parallel_map from qiskit.ignis.verification.tomography import count_keys", "sum(x0) cons = ({'type': 'eq', 'fun': lambda x: nshots -", "the result from 'pseudo_inverse' method. Sequential least square quadratic programming", "``least_squares``: constrained to have physical probabilities Returns: dict or list:", "`O(m2^{n+t})` time. Since this method is using the SLSQP optimization", "in enumerate(raw_data2): if method == 'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat,", "data_label in raw_data.keys(): if data_label not in self._state_labels: raise QiskitError(\"Unexpected", "state_labels @property def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return self._cal_matrix @property def", "the cal matrix\"\"\" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix):", "file in the root directory # of this source tree", "meas_layout is None: meas_layout = [] for qubits in self._mit_pattern:", "+= qubits # check forms of raw_data if isinstance(raw_data, dict):", "1 raw_data2 = [raw_data] elif int(size_ratio) == size_ratio: data_format =", "= [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state in", "count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts,", "raw_data2 = new_count_dict else: # TODO: should probably change to:", "ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return", "raw_data2[0] return raw_data2 def _apply_correction(self, resultidx, raw_data, method): \"\"\"Wrapper to", "for use with the tomography data) Form 4: a qiskit", "with a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method) return", "new_state_labels): \"\"\"set the state label ordering of the cal matrix\"\"\"", "back into the new result new_result = deepcopy(raw_data) new_counts_list =", "in `mit_pattern`, and `t` is the size of largest set", "model without cross-talk, then the time complexity would be `O(n2^n)`.", "the vector with lenght `2^n`, the mitigation for 8 bit", "counts dictionary from results.get_counts Form 2: a list of counts", "the complete error mitigation, then the time complexity would be", "new_counts class TensoredFilter(): \"\"\" Tensored measurement error mitigation filter. Produced", "(mat_index >> i) & 1] flip_poses = sorted(flip_poses) new_state =", "zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit]", "[-1 for _ in range(max(meas_layout) + 1)] for i, qubit", "list, mit_pattern: list): \"\"\" Initialize a tensored measurement error mitigation", "corrected data in the same form as raw_data Raises: QiskitError:", "a list of counts of `length==M*len(state_labels)` where M is an", "the indices in the calibration matrix self._indices_list = [] for", "cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): \"\"\" Initialize a tensored", "tuple((0, nshots) for x in x0) res = minimize(fun, x0,", "forms: Form 1: a counts dictionary from results.get_counts Form 2:", "import scipy.linalg as la import numpy as np import qiskit", "int, flip_poses: List[int]) -> str: \"\"\"Flip the state according to", "mit_pattern. If the `mit_pattern` is shaped like `[[0], [1], [2],", "mitigation for 8 bit counts with the `mit_pattern = [[0],", "+ t})`, where `n` is the size of calibrated qubits,", "filter using the cal_matrices from a tensored measurement calibration fitter.", "Any modifications or derivative works of this code must retain", "quantum state\"\"\" sub_state = \"\" for pos in pos_qubits: sub_state", "\"\"\" def __init__(self, cal_matrix: np.matrix, state_labels: list): \"\"\" Initialize a", "sorted(flip_poses) new_state = \"\" pos = 0 for flip_pos in", "and modified files need to carry a notice indicating #", "Returns: dict or Result: The corrected data in the same", "in the same form as raw_data Raises: QiskitError: if raw_data", "bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\") if", "new_result else: raise QiskitError(\"Unrecognized type for raw_data.\") if method ==", "list is not an integer multiple \" \"of the number", "of the cal matrix\"\"\" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels):", "be corrected. Can be in one of two forms: *", "'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the correction for data_idx,", "Args: cal_matrix: the calibration matrix for applying the correction state_labels:", "pos_qubits] for state_idx, state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits,", "data in the same form as raw_data Raises: QiskitError: if", "in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return", "apply(self, raw_data: Union[qiskit.result.result.Result, dict], method: str = 'least_squares', meas_layout: List[int]", "'2\\times 2' calibration matrix `A_3`. When mitigating the count of", "deepcopy from scipy.optimize import minimize import scipy.linalg as la import", "import numpy as np import qiskit from qiskit import QiskitError", "to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in", "x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots =", "qiskit.tools import parallel_map from qiskit.ignis.verification.tomography import count_keys class MeasurementFilter(): \"\"\"", "raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2 def _apply_correction(self,", "for i in range(len(pinv_cal_mat)): # i is index of pinv_cal_mat", "method is using the SLSQP optimization over the vector with", "convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count", "total time complexity of this method is `O(m2^{n + t})`,", "enumerate(raw_data2): if method == 'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices in", "state[pos] return indices[sub_state] def _apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result, method:", "A counts dictionary from results.get_counts * A Qiskit Result method", "int): the mapping from classical registers to qubits * If", "for qubits in self._mit_pattern: meas_layout += qubits # check forms", "from 'pseudo_inverse' method. Sequential least square quadratic programming (SLSQP) is", "label '\" + data_label + \"', verify the fitter's state", "str, pos_qubits: List[int], indices: dict) -> int: \"\"\"Return the index", "results. Args: raw_data (dict or list): The data to be", "pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x elif method", "* mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) **", "a counts dictionary from results.get_counts Form 2: a list of", "O(4^n)`. * 'least_squares': constrained to have physical probabilities. Instead of", "error mitigation filter using the cal_matrix from a measurement calibration", "probability vector to the result from 'pseudo_inverse' method. Sequential least", "`n` is the size of calibrated qubits, `m` is the", "this license in the LICENSE.txt file in the root directory", "the function with the # counts and push back into", "i, pos in enumerate(flip_poses) if (mat_index >> i) & 1]", "+ A_3^{-1}[1, 1]*count['0110']`. The total time complexity of this method", "state, count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] =", "return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels)) x0", "Args: raw_data (dict or Result): The data to be corrected.", "strings, states in the subspace) mit_pattern: for each calibration matrix", "str = 'least_squares', meas_layout: List[int] = None): \"\"\" Apply the", "the cal matrix \"\"\" self._cal_matrix = cal_matrix self._state_labels = state_labels", "bnds = tuple((0, nshots) for x in x0) res =", "for applying the correction. substate_labels_list: for each calibration matrix a", "list): \"\"\" Initialize a measurement error mitigation filter using the", "def state_labels(self): \"\"\"return the state label ordering of the cal", "the counts, re-call the function with the # counts and", "`0`, `0` to `1`, and `1` to `2`, the list", "enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(pinv_cal_mat)):", "\"\"\"Return cal_matrix.\"\"\" return self._cal_matrix @property def state_labels(self): \"\"\"return the state", "== len(self._state_labels): data_format = 1 raw_data2 = [raw_data] elif int(size_ratio)", "= self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx]", "probably change to: # raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0]", "a measurement calibration fitter and can be applied to data.", "for data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse': for", "the originals. # pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction filters. \"\"\"", "`mit_pattern` is shaped like `[[0], [1], [2], ..., [n-1]]`, which", "calibrated qubits, `m` is the number of sets in `mit_pattern`,", "shaped like `[[0, 1, 2, ..., n-1]]`, which exactly corresponds", "(raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels)) x0 = x0", "calibration matrix for applying the correction state_labels: the states for", "Raises: QiskitError: if raw_data is not in a one of", "list raw_data2 = raw_data2.flatten() elif data_format == 0: # convert", "qiskit.result.result.Result, method: str, meas_layout: List[int]): \"\"\"Wrapper to call apply with", "data_label + \"', verify the fitter's state labels \" \"correspond", "`[[0], [1], [2], ..., [n-1]]`, which corresponds to the tensor", "a list of the states (as strings, states in the", "contain negative values and the sum of counts would not", "pos = flip_pos + 1 new_state += state[pos:] return new_state", "license in the LICENSE.txt file in the root directory #", "return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): \"\"\"set the state label", "= self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(pinv_cal_mat)): # i", "of the 4-bit counts using '2\\times 2' calibration matrix `A_3`.", "isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format", "dict], method: str = 'least_squares', meas_layout: List[int] = None): \"\"\"", "def substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list # get", "= new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix =", "would be `O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained to have", "* If `None`, 'least_squares' is used. meas_layout (list of int):", "# processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio):", "for raw_data.\") if method == 'pseudo_inverse': pinv_cal_matrices = [] for", "problem to find the closest probability vector to the result", "modified files need to carry a notice indicating # that", "second_index]\\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x elif method ==", "state pos = flip_pos + 1 new_state += state[pos:] return", "@state_labels.setter def state_labels(self, new_state_labels): \"\"\"set the state label ordering of", "np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for", "\"', verify the fitter's state labels \" \"correspond to the", "pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float)", "If `None`, flatten(mit_pattern) is used. Returns: dict or Result: The", "altered from the originals. # pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction", "ordering of the cal matrix\"\"\" self._state_labels = new_state_labels @cal_matrix.setter def", "`2`, the list becomes `[2, 0, 1]` * If `None`,", "List[int], indices: dict) -> int: \"\"\"Return the index of (pseudo", "we are mitigating the 3rd bit of the 4-bit counts", "raw_data2[data_idx] = inv_mat_dot_x elif method == 'least_squares': def fun(x): mat_dot_x", "the tomography data) Form 4: a qiskit Result method (str):", "n-1]]`, which exactly corresponds to the complete error mitigation, then", "dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx,", "raw_data if isinstance(raw_data, dict): # counts dictionary # convert to", "return new_result else: raise QiskitError(\"Unrecognized type for raw_data.\") if method", "raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2 def _apply_correction(self, resultidx, raw_data,", "would take 10 seconds or more. * If `None`, 'least_squares'", "res.x else: raise QiskitError(\"Unrecognized method.\") if data_format == 2: #", "ordering of the cal matrix\"\"\" return self._state_labels @state_labels.setter def state_labels(self,", "i is index of pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits)", "QiskitError: if `raw_data` is not an integer multiple of the", "x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons = ({'type': 'eq',", "QiskitError(\"Unrecognized method.\") # convert back into a counts dictionary new_count_dict", "enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts", "return new_count_dict def flip_state(self, state: str, mat_index: int, flip_poses: List[int])", "'least_squares': nshots = sum(raw_data2[data_idx]) def fun(x): return sum( (raw_data2[data_idx] -", "the states (as strings, states in the subspace) mit_pattern: for", "in the internal process. Every updating step in SLSQP takes", "Form 3: a list of counts of `length==M*len(state_labels)` where M", "elif data_format == 0: # convert back into a counts", "Result method (str): fitting method. If `None`, then least_squares is", "to the input data\") data_format = 0 # convert to", "= [] for qubits in self._mit_pattern: meas_layout += qubits #", "x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise", "the time complexity would be `O(n2^n)`. If the `mit_pattern` is", "counts using '2\\times 2' calibration matrix `A_3`. When mitigating the", "flatten back out the list raw_data2 = raw_data2.flatten() elif data_format", "to data. \"\"\" def __init__(self, cal_matrix: np.matrix, state_labels: list): \"\"\"", "from typing import List, Union from copy import deepcopy from", "Returns: dict or list: The corrected data in the same", "programming (SLSQP) is used in the internal process. Every updating", "raw_data, method): \"\"\"Wrapper to call apply with a counts dictionary.\"\"\"", "sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for ind, lab in", "the chosen qubit positions\"\"\" flip_poses = [pos for i, pos", "= self.apply( raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class TensoredFilter(): \"\"\"", "scipy.optimize import minimize import scipy.linalg as la import numpy as", "import count_keys class MeasurementFilter(): \"\"\" Measurement error mitigation filter. Produced", "a qiskit Result method (str): fitting method. If `None`, then", "two forms: * A counts dictionary from results.get_counts * A", "LICENSE.txt file in the root directory # of this source", "else: raise QiskitError(\"Unrecognized type for raw_data.\") if method == 'pseudo_inverse':", "self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list", "new_substate_labels_list # get the number of qubits in each subspace", "inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in", "result from 'pseudo_inverse' method. Sequential least square quadratic programming (SLSQP)", "the number of calibrated states. \"\"\" # check forms of", "Initialize a measurement error mitigation filter using the cal_matrix from", "# i is index of pinv_cal_mat source_state = self.flip_state(state, i,", "from a measurement calibration fitter and can be applied to", "indices (as int, states in the subspace) \"\"\" self._cal_matrices =", "= np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits]", "cal_matrix: np.matrix, state_labels: list): \"\"\" Initialize a measurement error mitigation", "in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count elif", "QiskitError from qiskit.tools import parallel_map from qiskit.ignis.verification.tomography import count_keys class", "data_format = 1 raw_data2 = [raw_data] elif int(size_ratio) == size_ratio:", "re-call the function with the # counts and push back", "def state_labels(self, new_state_labels): \"\"\"set the state label ordering of the", "mit_pattern @property def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter def", "calibrated states. \"\"\" # check forms of raw_data if isinstance(raw_data,", "`None`, 'least_squares' is used. meas_layout (list of int): the mapping", "the calibration matrices to results. Args: raw_data (dict or Result):", "self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices)", "updating step in SLSQP takes `O(m2^{n+t})` time. Since this method", "Version 2.0. You may # obtain a copy of this", "data. \"\"\" def __init__(self, cal_matrix: np.matrix, state_labels: list): \"\"\" Initialize", "would not equal to the shots. Mitigation is conducted qubit", "calibration matrix a list of the logical qubit indices (as", "i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index,", "else: raise QiskitError(\"Data list is not an integer multiple \"", "= int(size_ratio) # make the list into chunks the size", "using the SLSQP optimization over the vector with lenght `2^n`,", "of the cal matrices. Mitigated counts can contain negative values", "first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index, second_index]", "self._state_labels)] else: raise QiskitError(\"Data list is not an integer multiple", "in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2", "tensored measurement calibration fitter. A simple usage this class is", "substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list # get the", "meas_layout: List[int] = None): \"\"\" Apply the calibration matrices to", "matrices, this method solve a constrained optimization problem to find", "self._cal_matrix @property def state_labels(self): \"\"\"return the state label ordering of", "`length==M*len(state_labels)` where M is an integer (e.g. for use with", "tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative", "the list into chunks the size of state_labels for easier", "in enumerate(raw_data2): if method == 'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices", "cal_matrix from a measurement calibration fitter. Args: cal_matrix: the calibration", "sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 =", "filter. Produced from a tensored measurement calibration fitter and can", "and can be applied to data. \"\"\" def __init__(self, cal_matrices:", "the calibration matrices which affect the corresponding qubit. For example,", "method. Sequential least square quadratic programming (SLSQP) is used in", "A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total time complexity of", "state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx]", "License, Version 2.0. You may # obtain a copy of", "the `mit_pattern` is shaped like `[[0], [1], [2], ..., [n-1]]`,", "If `None`, then least_squares is used. ``pseudo_inverse``: direct inversion of", "self._cal_matrix = new_cal_matrix def apply(self, raw_data, method='least_squares'): \"\"\"Apply the calibration", "raw_data2[i][:] = raw_data[ i * len(self._state_labels):(i + 1)*len( self._state_labels)] else:", "from qiskit.tools import parallel_map from qiskit.ignis.verification.tomography import count_keys class MeasurementFilter():", "counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout) return resultidx,", "cal matrices. Mitigated counts can contain negative values and the", "* raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x elif method == 'least_squares':", "of raw_data if isinstance(raw_data, dict): # counts dictionary for data_label", "def _apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result, method: str, meas_layout: List[int]):", "QiskitError(\"Unrecognized method.\") if data_format == 2: # flatten back out", "for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx, new_counts", "least square quadratic programming (SLSQP) is used in the internal", "list: The corrected data in the same form as `raw_data`", "np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method == 'least_squares': nshots = sum(raw_data2[data_idx])", "`1`, and `1` to `2`, the list becomes `[2, 0,", "method == 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the correction", "For each qubit, mitigate the whole counts using the calibration", "numpy as np import qiskit from qiskit import QiskitError from", "the # counts and push back into the new result", "IBM 2019. # # This code is licensed under the", "Apply the correction for data_idx, _ in enumerate(raw_data2): if method", "str, meas_layout: List[int]): \"\"\"Wrapper to call apply with a counts", "is None: meas_layout = [] for qubits in self._mit_pattern: meas_layout", "np import qiskit from qiskit import QiskitError from qiskit.tools import", "fun(x): mat_dot_x = deepcopy(x) for cal_mat, pos_qubits, indices in zip(self._cal_matrices,", "1)] for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i #", "= mit_pattern @property def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter", "\"correspond to the input data\") data_format = 0 # convert", "the 3rd bit of the 4-bit counts using '2\\times 2'", "data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse': for pinv_cal_mat,", "to qubits * If you measure qubit `2` to clbit", "pos_qubits: sub_state += state[pos] return indices[sub_state] def _apply_correction(self, resultidx: int,", "[np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state,", "1]` * If `None`, flatten(mit_pattern) is used. Returns: dict or", "number of qubits in each subspace self._qubit_list_sizes = [] for", "Copyright IBM 2019. # # This code is licensed under", "out the list raw_data2 = raw_data2.flatten() elif data_format == 0:", "becomes `[2, 0, 1]` * If `None`, flatten(mit_pattern) is used.", "{} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0:", "resultidx: int, raw_data: qiskit.result.result.Result, method: str, meas_layout: List[int]): \"\"\"Wrapper to", "[raw_data] elif int(size_ratio) == size_ratio: data_format = 2 size_ratio =", "\"\"\" from typing import List, Union from copy import deepcopy", "self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse endian qubits_to_clbits =", "is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The", "for _ in range(max(meas_layout) + 1)] for i, qubit in", "in enumerate(flip_poses) if (mat_index >> i) & 1] flip_poses =", "from the originals. # pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction filters.", "<reponame>paulineollitrault/qiskit-ignis<gh_stars>100-1000 # -*- coding: utf-8 -*- # This code is", "is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices for", "calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list):", "coding: utf-8 -*- # This code is part of Qiskit.", "is conducted qubit wise: For each qubit, mitigate the whole", "dictionary new_count_dict = {} for state_idx, state in enumerate(all_states): if", "is shaped like `[[0], [1], [2], ..., [n-1]]`, which corresponds", "dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout) return resultidx, new_counts", "pos in pos_qubits: sub_state += state[pos] return indices[sub_state] def _apply_correction(self,", "= np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:] = raw_data[", "SLSQP optimization over the vector with lenght `2^n`, the mitigation", "seconds or more. * If `None`, 'least_squares' is used. meas_layout", "fitting method. If `None`, then least_squares is used. ``pseudo_inverse``: direct", "The corrected data in the same form as raw_data Raises:", "the list becomes `[2, 0, 1]` * If `None`, flatten(mit_pattern)", "method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized", "_apply_correction(self, resultidx, raw_data, method): \"\"\"Wrapper to call apply with a", "to the chosen qubit positions\"\"\" flip_poses = [pos for i,", "elif method == 'least_squares': def fun(x): mat_dot_x = deepcopy(x) for", "matrix `A_3`. When mitigating the count of '0110' in this", "one of the defined forms. \"\"\" all_states = count_keys(self.nqubits) num_of_states", "0) elif isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data) ==", "= int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): #", "dict or list: The corrected data in the same form", "have physical probabilities Returns: dict or list: The corrected data", "data to be corrected. Can be in a number of", "calibration matrix for the input quantum state\"\"\" sub_state = \"\"", "under the Apache License, Version 2.0. You may # obtain", "* len(self._state_labels):(i + 1)*len( self._state_labels)] else: raise QiskitError(\"Data list is", "None): \"\"\" Apply the calibration matrices to results. Args: raw_data", "dict or Result: The corrected data in the same form", "See also MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result,", "raw_data2 def _apply_correction(self, resultidx, raw_data, method): \"\"\"Wrapper to call apply", "apply(self, raw_data, method='least_squares'): \"\"\"Apply the calibration matrix to results. Args:", "stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state] =", "[1], [2], ..., [n-1]]`, which corresponds to the tensor product", "for i in range(size_ratio): raw_data2[i][:] = raw_data[ i * len(self._state_labels):(i", "'\" + data_label + \"', verify the fitter's state labels", "product noise model without cross-talk, then the time complexity would", "assume we are mitigating the 3rd bit of the 4-bit", "second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\ *", "x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons =", "measurement error mitigation filter. Produced from a tensored measurement calibration", "[[0], [1], [2], ..., [n-1]]` would take 10 seconds or", "to carry a notice indicating # that they have been", "matrices. Mitigated counts can contain negative values and the sum", "least_squares is used. ``pseudo_inverse``: direct inversion of the A matrix", "constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\")", "be applied to data. \"\"\" def __init__(self, cal_matrices: np.matrix, substate_labels_list:", "method == 'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern,", "pos_clbits, indices) for i in range(len(cal_mat)): target_state = self.flip_state(state, i,", "dict): # counts dictionary # convert to list raw_data2 =", "verify the fitter's state labels \" \"correspond to the input", "of the states (as strings, states in the subspace) mit_pattern:", "state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data, list):", "the `mit_pattern` is shaped like `[[0, 1, 2, ..., n-1]]`,", "= 2**self.nqubits if meas_layout is None: meas_layout = [] for", "i in range(size_ratio): raw_data2[i][:] = raw_data[ i * len(self._state_labels):(i +", "of `length==len(state_labels)` Form 3: a list of counts of `length==M*len(state_labels)`", "multiple of the number of calibrated states. \"\"\" # check", "of calibrated qubits, `m` is the number of sets in", "(str): fitting method. The following methods are supported: * 'pseudo_inverse':", "calibrated states\") elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the", "\"\"\"Return cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\"", "def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property def nqubits(self): \"\"\"Return", "copy of this license in the LICENSE.txt file in the", "new_state += str(int(state[flip_pos], 2) ^ 1) # flip the state", "import deepcopy from scipy.optimize import minimize import scipy.linalg as la", "for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse", "in each subspace self._qubit_list_sizes = [] for _, substate_label_list in", "should probably change to: # raw_data2 = raw_data2[0].tolist() raw_data2 =", "flip_pos in flip_poses: new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos], 2)", "raise QiskitError(\"Unrecognized type for raw_data.\") if method == 'pseudo_inverse': pinv_cal_mat", "Instead of directly applying inverse calibration matrices, this method solve", "mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 = x0 /", "get the indices in the calibration matrix self._indices_list = []", "the calibration matrix for applying the correction state_labels: the states", "method)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return", "= x0 / sum(x0) cons = ({'type': 'eq', 'fun': lambda", "in the LICENSE.txt file in the root directory # of", "raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:] =", "the 4-bit counts using '2\\times 2' calibration matrix `A_3`. When", "= [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) #", "# (C) Copyright IBM 2019. # # This code is", "where M is an integer (e.g. for use with the", "the count of '0110' in this step, the following formula", "lambda x: nshots - sum(x)}) bnds = tuple((0, nshots) for", "enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 =", "= self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state,", "len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:] = raw_data[ i *", "matrix ``least_squares``: constrained to have physical probabilities Returns: dict or", "of the defined forms. \"\"\" all_states = count_keys(self.nqubits) num_of_states =", "self.flip_state(state, i, pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\", "error mitigation filter. Produced from a tensored measurement calibration fitter", "mitigation filter. Produced from a tensored measurement calibration fitter and", "in raw_data.keys(): if data_label not in self._state_labels: raise QiskitError(\"Unexpected state", "works of this code must retain this # copyright notice,", "0, 1]` * If `None`, flatten(mit_pattern) is used. Returns: dict", "@property def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property def nqubits(self):", "at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of", "must retain this # copyright notice, and modified files need", "states for the ordering of the cal matrix \"\"\" self._cal_matrix", "size of state_labels for easier # processing raw_data2 = np.zeros([size_ratio,", "convert back into a counts dictionary new_count_dict = {} for", "they have been altered from the originals. # pylint: disable=cell-var-from-loop,invalid-name", "results.get_counts Form 2: a list of counts of `length==len(state_labels)` Form", "into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map(", "\"\" pos = 0 for flip_pos in flip_poses: new_state +=", "of raw_data if isinstance(raw_data, dict): # counts dictionary # convert", "If `None`, 'least_squares' is used. meas_layout (list of int): the", "= raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels) if", "for easier # processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i", "this method is using the SLSQP optimization over the vector", "new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict else: # TODO: should", "states (as strings, states in the subspace) mit_pattern: for each", "= self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(cal_mat)): target_state =", "have been altered from the originals. # pylint: disable=cell-var-from-loop,invalid-name \"\"\"", "qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property def nqubits(self): \"\"\"Return the", "`O(m2^{n + t})`, where `n` is the size of calibrated", "raise QiskitError(\"Unexpected state label '\" + data_label + \"', verify", "& 1] flip_poses = sorted(flip_poses) new_state = \"\" pos =", "return raw_data2 def _apply_correction(self, resultidx, raw_data, method): \"\"\"Wrapper to call", "raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data)", "and push back into the new result new_result = deepcopy(raw_data)", "in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits =", "M is an integer (e.g. for use with the tomography", "(dict or Result): The data to be corrected. Can be", "equal to the shots. Mitigation is conducted qubit wise: For", "from a tensored measurement calibration fitter and can be applied", "same form as raw_data Raises: QiskitError: if raw_data is not", "if isinstance(raw_data, dict): # counts dictionary for data_label in raw_data.keys():", "measurement calibration fitter and can be applied to data. \"\"\"", "for data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse': raw_data2[data_idx]", "If the `mit_pattern` is shaped like `[[0], [1], [2], ...,", "the subspace) mit_pattern: for each calibration matrix a list of", "+ \"', verify the fitter's state labels \" \"correspond to", "raw_data: Union[qiskit.result.result.Result, dict], method: str = 'least_squares', meas_layout: List[int] =", "or Result: The corrected data in the same form as", "indices) for i in range(len(pinv_cal_mat)): # i is index of", "the index of (pseudo inverse) calibration matrix for the input", "counts using the calibration matrices which affect the corresponding qubit.", "Measurement correction filters. \"\"\" from typing import List, Union from", "\"\"\" def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): \"\"\"", "Result: The corrected data in the same form as raw_data", "for pos in pos_qubits: sub_state += state[pos] return indices[sub_state] def", "new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix", "each qubit, mitigate the whole counts using the calibration matrices", "substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the indices in", "= np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0) cons = ({'type':", "'0110' in this step, the following formula is applied: `count['0110']", "[] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] #", "2: a list of counts of `length==len(state_labels)` Form 3: a", "the subspace) \"\"\" self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list", "use with the tomography data) Form 4: a qiskit Result", "using '2\\times 2' calibration matrix `A_3`. When mitigating the count", "vector with lenght `2^n`, the mitigation for 8 bit counts", "affect the corresponding qubit. For example, assume we are mitigating", "inversion of the A matrix ``least_squares``: constrained to have physical", "for stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state]", "x0 = np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0) cons =", "to: # raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2", "fitter. A simple usage this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html).", "enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict", "copy import deepcopy from scipy.optimize import minimize import scipy.linalg as", "enumerate(raw_data2): if method == 'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx])", "_, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for ind, lab", "out all the counts, re-call the function with the #", "'eq', 'fun': lambda x: nshots - sum(x)}) bnds = tuple((0,", "return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list =", "quadratic programming (SLSQP) is used in the internal process. Every", "meas_layout (list of int): the mapping from classical registers to", "corresponds to the complete error mitigation, then the time complexity", "with a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout)", "an integer multiple of the number of calibrated states. \"\"\"", "count of '0110' in this step, the following formula is", "negative values and the sum of counts would not equal", "(as strings, states in the subspace) mit_pattern: for each calibration", "inverse calibration matrices, this method solve a constrained optimization problem", "state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^ 1) # flip the", "+= cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx]", "in range(size_ratio): raw_data2[i][:] = raw_data[ i * len(self._state_labels):(i + 1)*len(", "resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx, new_counts in", "_substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list", "the size of largest set of mit_pattern. If the `mit_pattern`", "raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx", "for qubit in pos_qubits] for state_idx, state in enumerate(all_states): first_index", "can be applied to data. \"\"\" def __init__(self, cal_matrix: np.matrix,", "back into a counts dictionary new_count_dict = {} for state_idx,", "is the size of calibrated qubits, `m` is the number", "files need to carry a notice indicating # that they", "= [-1 for _ in range(max(meas_layout) + 1)] for i,", "= deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _", "forms of raw_data if isinstance(raw_data, dict): # counts dictionary for", "fitting method. The following methods are supported: * 'pseudo_inverse': direct", "matrices which affect the corresponding qubit. For example, assume we", "apply with a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method,", "in pos_qubits: sub_state += state[pos] return indices[sub_state] def _apply_correction(self, resultidx:", "[] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for", "= [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx =", "matrix\"\"\" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\"", "'least_squares', meas_layout: List[int] = None): \"\"\" Apply the calibration matrices", "List[int]): \"\"\"Wrapper to call apply with a counts dictionary.\"\"\" new_counts", "# convert to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx,", "i * len(self._state_labels):(i + 1)*len( self._state_labels)] else: raise QiskitError(\"Data list", "res = minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] =", "a measurement error mitigation filter using the cal_matrix from a", "@property def nqubits(self): \"\"\"Return the number of qubits. See also", "= raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2 def _apply_correction(self, resultidx,", "states in the subspace) mit_pattern: for each calibration matrix a", "a copy of this license in the LICENSE.txt file in", "# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # #", "for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result", "the fitter's state labels \" \"correspond to the input data\")", "\"of the number of calibrated states\") elif isinstance(raw_data, qiskit.result.result.Result): #", "exactly corresponds to the complete error mitigation, then the time", "cal_matrices: the calibration matrices for applying the correction. substate_labels_list: for", "list of counts of `length==M*len(state_labels)` where M is an integer", "or Result): The data to be corrected. Can be in", "inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x", "to have physical probabilities. Instead of directly applying inverse calibration", "a tensored measurement calibration fitter and can be applied to", "raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class TensoredFilter(): \"\"\" Tensored measurement", "raw_data if isinstance(raw_data, dict): # counts dictionary for data_label in", "method is `O(m2^{n + t})`, where `n` is the size", "to be corrected. Can be in a number of forms:", "number of forms: Form 1: a counts dictionary from results.get_counts", "using the calibration matrices which affect the corresponding qubit. For", "# # Any modifications or derivative works of this code", "self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list", "^ 1) # flip the state pos = flip_pos +", "`mit_pattern = [[0], [1], [2], ..., [n-1]]` would take 10", "self._state_labels = state_labels @property def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return self._cal_matrix", "cal_matrices from a tensored measurement calibration fitter. A simple usage", "notice indicating # that they have been altered from the", "of sets in `mit_pattern`, and `t` is the size of", "step, the following formula is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100']", "then the time complexity would be `O(2^(n+n)) = O(4^n)`. *", "i in range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits) first_index =\\", "data_label not in self._state_labels: raise QiskitError(\"Unexpected state label '\" +", "= raw_data2[0][state_idx] return new_count_dict def flip_state(self, state: str, mat_index: int,", "from qiskit.ignis.verification.tomography import count_keys class MeasurementFilter(): \"\"\" Measurement error mitigation", "la import numpy as np import qiskit from qiskit import", "number of calibrated states\") elif isinstance(raw_data, qiskit.result.result.Result): # extract out", "new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^ 1) #", "if (mat_index >> i) & 1] flip_poses = sorted(flip_poses) new_state", "Can be in one of two forms: * A counts", "matrix for applying the correction state_labels: the states for the", "\" \"correspond to the input data\") data_format = 0 #", "substate_labels_list self._mit_pattern = mit_pattern @property def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return", "source_state = self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices)", "physical probabilities Returns: dict or list: The corrected data in", "`count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total time", "mapping from classical registers to qubits * If you measure", "(SLSQP) is used in the internal process. Every updating step", "= np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx])", "self._substate_labels_list = [] self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern @property", "\"\"\" Initialize a measurement error mitigation filter using the cal_matrix", "forms. \"\"\" all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout", "in flip_poses: new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^", "`raw_data` is not an integer multiple of the number of", "in a number of forms: Form 1: a counts dictionary", "mitigation filter using the cal_matrix from a measurement calibration fitter.", "been altered from the originals. # pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement", "# get the indices in the calibration matrix self._indices_list =", "matrices to results. Args: raw_data (dict or Result): The data", "each subspace self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list):", "self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout))", "* If `None`, flatten(mit_pattern) is used. Returns: dict or Result:", "list): The data to be corrected. Can be in a", "mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0", "enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for ind, lab in enumerate(sub_labels)}) @property", "which exactly corresponds to the complete error mitigation, then the", "- sum(x)}) bnds = tuple((0, nshots) for x in x0)", "a list of counts of `length==len(state_labels)` Form 3: a list", "defined forms. \"\"\" all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits if", "-*- coding: utf-8 -*- # This code is part of", "in one of two forms: * A counts dictionary from", "list): size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format =", "state_idx, state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for", "= flip_pos + 1 new_state += state[pos:] return new_state def", "an integer (e.g. for use with the tomography data) Form", "list of the states (as strings, states in the subspace)", "[resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx,", "task_args=(raw_data, method)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts", "raw_data2[0][state_idx] return new_count_dict def flip_state(self, state: str, mat_index: int, flip_poses:", "substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): \"\"\"Return", "in x0) res = minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6)", "in pos_qubits] for state_idx, state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state,", "shots. Mitigation is conducted qubit wise: For each qubit, mitigate", "len(self._state_labels): data_format = 1 raw_data2 = [raw_data] elif int(size_ratio) ==", "new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError(\"Unrecognized type", "\"\"\"Apply the calibration matrix to results. Args: raw_data (dict or", "# convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state,", "* If you measure qubit `2` to clbit `0`, `0`", "part of Qiskit. # # (C) Copyright IBM 2019. #", "MeasurementFilter(): \"\"\" Measurement error mitigation filter. Produced from a measurement", "not equal to the shots. Mitigation is conducted qubit wise:", "Produced from a tensored measurement calibration fitter and can be", "tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\") # convert", "flip the state pos = flip_pos + 1 new_state +=", "this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration", "@property def state_labels(self): \"\"\"return the state label ordering of the", "cal matrix\"\"\" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): \"\"\"Set", "root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.", "processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:]", "time. Since this method is using the SLSQP optimization over", "not an integer multiple of the number of calibrated states.", "qubit. For example, assume we are mitigating the 3rd bit", "data_format = 0 # convert to form2 raw_data2 = [np.zeros(len(self._state_labels),", "flip_pos + 1 new_state += state[pos:] return new_state def compute_index_of_cal_mat(self,", "counts dictionary # convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)]", "constrained optimization problem to find the closest probability vector to", "like `[[0], [1], [2], ..., [n-1]]`, which corresponds to the", "method: str, meas_layout: List[int]): \"\"\"Wrapper to call apply with a", "integer multiple of the number of calibrated states. \"\"\" #", "0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def flip_state(self, state: str,", "meas_layout: List[int]): \"\"\"Wrapper to call apply with a counts dictionary.\"\"\"", "Since this method is using the SLSQP optimization over the", "Args: cal_matrices: the calibration matrices for applying the correction. substate_labels_list:", "of `length==M*len(state_labels)` where M is an integer (e.g. for use", "QiskitError(\"Unexpected state label '\" + data_label + \"', verify the", "2**self.nqubits if meas_layout is None: meas_layout = [] for qubits", "for data_label in raw_data.keys(): if data_label not in self._state_labels: raise", "states in the subspace) \"\"\" self._cal_matrices = cal_matrices self._qubit_list_sizes =", "+= state[pos:] return new_state def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int],", "self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for", "pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float)", "used in the internal process. Every updating step in SLSQP", "calibration fitter. A simple usage this class is explained [here]", "into chunks the size of state_labels for easier # processing", "raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict else:", "check forms of raw_data if isinstance(raw_data, dict): # counts dictionary", "the state label ordering of the cal matrix\"\"\" return self._state_labels", "one of two forms: * A counts dictionary from results.get_counts", "This code is part of Qiskit. # # (C) Copyright", "licensed under the Apache License, Version 2.0. You may #", "in enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts", "raw_data2 = [raw_data] elif int(size_ratio) == size_ratio: data_format = 2", "pos_qubits] for state_idx, state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits,", "len(raw_data) == len(self._state_labels): data_format = 1 raw_data2 = [raw_data] elif", "all the counts, re-call the function with the # counts", "enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(cal_mat)):", "of calibrated states. \"\"\" # check forms of raw_data if", "qubits in each subspace self._qubit_list_sizes = [] for _, substate_label_list", "which affect the corresponding qubit. For example, assume we are", "then least_squares is used. ``pseudo_inverse``: direct inversion of the A", "state_labels: the states for the ordering of the cal matrix", "of the number of calibrated states. \"\"\" # check forms", "2, ..., n-1]]`, which exactly corresponds to the complete error", "is part of Qiskit. # # (C) Copyright IBM 2019.", "for x in x0) res = minimize(fun, x0, method='SLSQP', constraints=cons,", "the mapping from classical registers to qubits * If you", "\"\" for pos in pos_qubits: sub_state += state[pos] return indices[sub_state]", "cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return self._cal_matrix @property def state_labels(self): \"\"\"return the", "self._state_labels: raise QiskitError(\"Unexpected state label '\" + data_label + \"',", "** 2) x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0)", "res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in", "= [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] =", "mitigation filter. Produced from a measurement calibration fitter and can", "of this license in the LICENSE.txt file in the root", "or list: The corrected data in the same form as", "Union[qiskit.result.result.Result, dict], method: str = 'least_squares', meas_layout: List[int] = None):", "have physical probabilities. Instead of directly applying inverse calibration matrices,", "# check forms of raw_data if isinstance(raw_data, dict): # counts", "a constrained optimization problem to find the closest probability vector", "np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:] = raw_data[ i", "states\") elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts,", "If the `mit_pattern` is shaped like `[[0, 1, 2, ...,", "to the complete error mitigation, then the time complexity would", "pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the correction for data_idx, _", "pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse endian qubits_to_clbits = [-1", "'pseudo_inverse': direct inversion of the cal matrices. Mitigated counts can", "for the input quantum state\"\"\" sub_state = \"\" for pos", "\"\"\" # check forms of raw_data if isinstance(raw_data, dict): #", "the size of state_labels for easier # processing raw_data2 =", "_ in enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx, new_counts in new_counts_list:", "new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list # get the number", "counts would not equal to the shots. Mitigation is conducted", "in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits =", "method (str): fitting method. If `None`, then least_squares is used.", "scipy.linalg as la import numpy as np import qiskit from", "http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this", "the whole counts using the calibration matrices which affect the", "and `t` is the size of largest set of mit_pattern.", "of the cal matrix \"\"\" self._cal_matrix = cal_matrix self._state_labels =", "count_keys class MeasurementFilter(): \"\"\" Measurement error mitigation filter. Produced from", "in the subspace) mit_pattern: for each calibration matrix a list", "1: a counts dictionary from results.get_counts Form 2: a list", "in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for ind, lab in enumerate(sub_labels)})", "[np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx = int(state,", "minimize import scipy.linalg as la import numpy as np import", "in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio", "also MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result, dict],", "the number of qubits. See also MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes)", "= self.flip_state(state, i, pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state,", "cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)})", "calibration matrices for applying the correction. substate_labels_list: for each calibration", "this code must retain this # copyright notice, and modified", "raw_data (dict or Result): The data to be corrected. Can", "largest set of mit_pattern. If the `mit_pattern` is shaped like", "then the time complexity would be `O(n2^n)`. If the `mit_pattern`", "def nqubits(self): \"\"\"Return the number of qubits. See also MeasurementFilter.apply()", "a number of forms: Form 1: a counts dictionary from", "@property def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\" return self._cal_matrices @cal_matrices.setter def cal_matrices(self,", "to be corrected. Can be in one of two forms:", "# copyright notice, and modified files need to carry a", "state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i", "of the cal matrix\"\"\" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self,", "np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0) cons = ({'type': 'eq',", "back into a counts dictionary new_count_dict = {} for stateidx,", "[] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get", "`2` to clbit `0`, `0` to `1`, and `1` to", "example, assume we are mitigating the 3rd bit of the", "apply with a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method)", "chunks the size of state_labels for easier # processing raw_data2", "index of pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits) second_index =", "zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit]", "str, mat_index: int, flip_poses: List[int]) -> str: \"\"\"Flip the state", "sub_state += state[pos] return indices[sub_state] def _apply_correction(self, resultidx: int, raw_data:", "the size of calibrated qubits, `m` is the number of", "matrix\"\"\" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): \"\"\"set the state", "= O(4^n)`. * 'least_squares': constrained to have physical probabilities. Instead", "= None): \"\"\" Apply the calibration matrices to results. Args:", "elif isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels):", "When mitigating the count of '0110' in this step, the", "\"\"\" all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout is", "corresponds to the tensor product noise model without cross-talk, then", "Args: raw_data (dict or list): The data to be corrected.", "def fun(x): mat_dot_x = deepcopy(x) for cal_mat, pos_qubits, indices in", "For example, assume we are mitigating the 3rd bit of", "bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\") #", "can be applied to data. \"\"\" def __init__(self, cal_matrices: np.matrix,", "- mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 = x0", "2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract out", "# This code is part of Qiskit. # # (C)", "\"\"\" Apply the calibration matrices to results. Args: raw_data (dict", "..., n-1]]`, which exactly corresponds to the complete error mitigation,", "in pos_qubits] for state_idx, state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state,", "The data to be corrected. Can be in one of", "method == 'pseudo_inverse': pinv_cal_matrices = [] for cal_mat in self._cal_matrices:", "to have physical probabilities Returns: dict or list: The corrected", "registers to qubits * If you measure qubit `2` to", "as `raw_data` Raises: QiskitError: if `raw_data` is not an integer", "the calibration matrix to results. Args: raw_data (dict or list):", "corrected data in the same form as `raw_data` Raises: QiskitError:", "\"\"\" Initialize a tensored measurement error mitigation filter using the", "error mitigation, then the time complexity would be `O(2^(n+n)) =", "\"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property def nqubits(self): \"\"\"Return the number", "list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items():", "\"\"\" self._cal_matrix = cal_matrix self._state_labels = state_labels @property def cal_matrix(self):", "from classical registers to qubits * If you measure qubit", "sub_state = \"\" for pos in pos_qubits: sub_state += state[pos]", "Can be in a number of forms: Form 1: a", "nshots = sum(raw_data2[data_idx]) def fun(x): return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix,", "\"\"\"return the state label ordering of the cal matrix\"\"\" return", "method == 'least_squares': def fun(x): mat_dot_x = deepcopy(x) for cal_mat,", "Tensored measurement error mitigation filter. Produced from a tensored measurement", "error mitigation filter. Produced from a measurement calibration fitter and", "x: nshots - sum(x)}) bnds = tuple((0, nshots) for x", "inv_mat_dot_x elif method == 'least_squares': def fun(x): mat_dot_x = deepcopy(x)", "!= 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict else: #", "for state_idx, state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices)", "the list raw_data2 = raw_data2.flatten() elif data_format == 0: #", "{} for stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0:", "be in one of two forms: * A counts dictionary", "'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x", "or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works", "raw_data2 = raw_data2[0] return raw_data2 def _apply_correction(self, resultidx, raw_data, method):", "can contain negative values and the sum of counts would", "= ({'type': 'eq', 'fun': lambda x: nshots - sum(x)}) bnds", "this step, the following formula is applied: `count['0110'] = A_3^{-1}[1,", "qubits # check forms of raw_data if isinstance(raw_data, dict): #", "with the # counts and push back into the new", "return indices[sub_state] def _apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result, method: str,", "= sum(raw_data2[data_idx]) def fun(x): return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2)", "cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list = []", "0: # convert back into a counts dictionary new_count_dict =", "of this method is `O(m2^{n + t})`, where `n` is", "used. ``pseudo_inverse``: direct inversion of the A matrix ``least_squares``: constrained", "None: meas_layout = [] for qubits in self._mit_pattern: meas_layout +=", "cal_matrix: the calibration matrix for applying the correction state_labels: the", "raw_data2[0][stateidx] raw_data2 = new_count_dict else: # TODO: should probably change", "= 2 size_ratio = int(size_ratio) # make the list into", "flip_poses: new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^ 1)", "@property def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return self._cal_matrix @property def state_labels(self):", "raw_data[ i * len(self._state_labels):(i + 1)*len( self._state_labels)] else: raise QiskitError(\"Data", "def fun(x): return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0 =", "the correction. substate_labels_list: for each calibration matrix a list of", "isinstance(raw_data, dict): # counts dictionary for data_label in raw_data.keys(): if", "data to be corrected. Can be in one of two", "complete error mitigation, then the time complexity would be `O(2^(n+n))", "== 0: # convert back into a counts dictionary new_count_dict", "# convert back into a counts dictionary new_count_dict = {}", "0 for flip_pos in flip_poses: new_state += state[pos:flip_pos] new_state +=", "set of mit_pattern. If the `mit_pattern` is shaped like `[[0],", "List[int]) -> str: \"\"\"Flip the state according to the chosen", "pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout =", "convert to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state", "nshots) for x in x0) res = minimize(fun, x0, method='SLSQP',", "indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] =", "labels \" \"correspond to the input data\") data_format = 0", "are supported: * 'pseudo_inverse': direct inversion of the cal matrices.", "Produced from a measurement calibration fitter and can be applied", "= new_substate_labels_list # get the number of qubits in each", "number of qubits. See also MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes) def", "self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index, second_index] * mat_dot_x[state_idx]", "= count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout is None: meas_layout", "the `mit_pattern = [[0], [1], [2], ..., [n-1]]` would take", "substate_labels_list: for each calibration matrix a list of the states", "constrained to have physical probabilities. Instead of directly applying inverse", "the following formula is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] +", "pos_clbits, indices) for i in range(len(pinv_cal_mat)): # i is index", "this method is `O(m2^{n + t})`, where `n` is the", "flip_poses: List[int]) -> str: \"\"\"Flip the state according to the", "input quantum state\"\"\" sub_state = \"\" for pos in pos_qubits:", "of the A matrix ``least_squares``: constrained to have physical probabilities", "resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for resultidx, new_counts", "values and the sum of counts would not equal to", "[1], [2], ..., [n-1]]` would take 10 seconds or more.", "self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method)) for", "if method == 'pseudo_inverse': pinv_cal_matrices = [] for cal_mat in", "_ in enumerate(raw_data2): if method == 'pseudo_inverse': for pinv_cal_mat, pos_qubits,", "matrix a list of the logical qubit indices (as int,", "@cal_matrix.setter def cal_matrix(self, new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix def", "the logical qubit indices (as int, states in the subspace)", "# flatten back out the list raw_data2 = raw_data2.flatten() elif", "= substate_labels_list self._mit_pattern = mit_pattern @property def cal_matrices(self): \"\"\"Return cal_matrices.\"\"\"", "pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\\ += cal_mat[first_index,", "parallel_map from qiskit.ignis.verification.tomography import count_keys class MeasurementFilter(): \"\"\" Measurement error", "label ordering of the cal matrix\"\"\" self._state_labels = new_state_labels @cal_matrix.setter", "qiskit.result.result.Result): # extract out all the counts, re-call the function", "self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list", "bit counts with the `mit_pattern = [[0], [1], [2], ...,", "wise: For each qubit, mitigate the whole counts using the", "return self._qubit_list_sizes @property def nqubits(self): \"\"\"Return the number of qubits.", "pos = 0 for flip_pos in flip_poses: new_state += state[pos:flip_pos]", "the cal_matrix from a measurement calibration fitter. Args: cal_matrix: the", "def __init__(self, cal_matrix: np.matrix, state_labels: list): \"\"\" Initialize a measurement", "\"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list # get the number of", "new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise", "cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method='least_squares'): \"\"\"Apply the", "state label '\" + data_label + \"', verify the fitter's", "calibration matrices, this method solve a constrained optimization problem to", "according to the chosen qubit positions\"\"\" flip_poses = [pos for", "whole counts using the calibration matrices which affect the corresponding", "If you measure qubit `2` to clbit `0`, `0` to", "(str): fitting method. If `None`, then least_squares is used. ``pseudo_inverse``:", "* A Qiskit Result method (str): fitting method. The following", "the sum of counts would not equal to the shots.", "second_index] * mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x)", "simple usage this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices:", "`0` to `1`, and `1` to `2`, the list becomes", "Qiskit. # # (C) Copyright IBM 2019. # # This", "parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method))", "= state_labels @property def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return self._cal_matrix @property", "'least_squares': def fun(x): mat_dot_x = deepcopy(x) for cal_mat, pos_qubits, indices", "a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method) return resultidx,", "measure qubit `2` to clbit `0`, `0` to `1`, and", "self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list", "return resultidx, new_counts class TensoredFilter(): \"\"\" Tensored measurement error mitigation", "class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices", "len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format = 1 raw_data2 =", "data in the same form as `raw_data` Raises: QiskitError: if", "counts of `length==len(state_labels)` Form 3: a list of counts of", "method == 'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method", "enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio =", "cal_mat, pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states],", "= x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons = ({'type':", "= 0 for flip_pos in flip_poses: new_state += state[pos:flip_pos] new_state", "shaped like `[[0], [1], [2], ..., [n-1]]`, which corresponds to", "1) # flip the state pos = flip_pos + 1", "MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result, dict], method:", "Form 2: a list of counts of `length==len(state_labels)` Form 3:", "size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format = 1", "if data_format == 2: # flatten back out the list", "/ sum(x0) nshots = sum(raw_data2[data_idx]) cons = ({'type': 'eq', 'fun':", "== 'least_squares': nshots = sum(raw_data2[data_idx]) def fun(x): return sum( (raw_data2[data_idx]", "like `[[0, 1, 2, ..., n-1]]`, which exactly corresponds to", "fitter and can be applied to data. \"\"\" def __init__(self,", "__init__(self, cal_matrix: np.matrix, state_labels: list): \"\"\" Initialize a measurement error", "TODO: should probably change to: # raw_data2 = raw_data2[0].tolist() raw_data2", "for 8 bit counts with the `mit_pattern = [[0], [1],", "'pseudo_inverse' method. Sequential least square quadratic programming (SLSQP) is used", "int(np.log2(len(substate_label_list)))) # get the indices in the calibration matrix self._indices_list", "time complexity of this method is `O(m2^{n + t})`, where", "for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for ind,", "for each calibration matrix a list of the states (as", "else: raise QiskitError(\"Unrecognized method.\") if data_format == 2: # flatten", "+= pinv_cal_mat[first_index, second_index]\\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x elif", "sum(raw_data2[data_idx]) cons = ({'type': 'eq', 'fun': lambda x: nshots -", "if data_label not in self._state_labels: raise QiskitError(\"Unexpected state label '\"", "# flip the state pos = flip_pos + 1 new_state", "_ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for resultidx, new_counts in", "== 'pseudo_inverse': pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat))", "originals. # pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction filters. \"\"\" from", "Raises: QiskitError: if `raw_data` is not an integer multiple of", "for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\"", "data) Form 4: a qiskit Result method (str): fitting method.", "process. Every updating step in SLSQP takes `O(m2^{n+t})` time. Since", "the calibration matrices for applying the correction. substate_labels_list: for each", "The data to be corrected. Can be in a number", "as raw_data Raises: QiskitError: if raw_data is not in a", "_ in enumerate(raw_data2): if method == 'pseudo_inverse': raw_data2[data_idx] = np.dot(", "state_labels(self, new_state_labels): \"\"\"set the state label ordering of the cal", "forms: * A counts dictionary from results.get_counts * A Qiskit", "meas_layout)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return", "for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply", "range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits,", "with the `mit_pattern = [[0], [1], [2], ..., [n-1]]` would", "Mitigated counts can contain negative values and the sum of", "mitigation, then the time complexity would be `O(2^(n+n)) = O(4^n)`.", "enumerate(sub_labels)}) @property def qubit_list_sizes(self): \"\"\"Return _qubit_list_sizes.\"\"\" return self._qubit_list_sizes @property def", "of counts of `length==len(state_labels)` Form 3: a list of counts", "self._substate_labels_list = new_substate_labels_list # get the number of qubits in", "from results.get_counts * A Qiskit Result method (str): fitting method.", "target_state = self.flip_state(state, i, pos_clbits) first_index =\\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices)", "using the cal_matrix from a measurement calibration fitter. Args: cal_matrix:", "call apply with a counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx),", "(e.g. for use with the tomography data) Form 4: a", "= cal_matrix self._state_labels = state_labels @property def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\"", "# # This code is licensed under the Apache License,", "(dict or list): The data to be corrected. Can be", "\"\"\" return sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result, dict], method: str", "into a counts dictionary new_count_dict = {} for state_idx, state", "+ 1)*len( self._state_labels)] else: raise QiskitError(\"Data list is not an", "(pseudo inverse) calibration matrix for the input quantum state\"\"\" sub_state", "raw_data: qiskit.result.result.Result, method: str, meas_layout: List[int]): \"\"\"Wrapper to call apply", "the corresponding qubit. For example, assume we are mitigating the", "`length==len(state_labels)` Form 3: a list of counts of `length==M*len(state_labels)` where", "new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError(\"Unrecognized type for", "4: a qiskit Result method (str): fitting method. If `None`,", "= parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data,", "self._state_labels @state_labels.setter def state_labels(self, new_state_labels): \"\"\"set the state label ordering", "in range(max(meas_layout) + 1)] for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit]", "Union from copy import deepcopy from scipy.optimize import minimize import", "new_state = \"\" pos = 0 for flip_pos in flip_poses:", "the state label ordering of the cal matrix\"\"\" self._state_labels =", "usage this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the", "to results. Args: raw_data (dict or Result): The data to", "Qiskit Result method (str): fitting method. The following methods are", "the root directory # of this source tree or at", "is the size of largest set of mit_pattern. If the", "method, meas_layout)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts", "solve a constrained optimization problem to find the closest probability", "self._indices_list.append( {lab: ind for ind, lab in enumerate(sub_labels)}) @property def", "positions\"\"\" flip_poses = [pos for i, pos in enumerate(flip_poses) if", "_substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list # get the number of qubits", "self._mit_pattern: meas_layout += qubits # check forms of raw_data if", "calibration matrices which affect the corresponding qubit. For example, assume", "`2^n`, the mitigation for 8 bit counts with the `mit_pattern", "+= state[pos] return indices[sub_state] def _apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result,", "multiple \" \"of the number of calibrated states\") elif isinstance(raw_data,", "to the tensor product noise model without cross-talk, then the", "counts dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method) return resultidx, new_counts", "probabilities. Instead of directly applying inverse calibration matrices, this method", "flatten(mit_pattern) is used. Returns: dict or Result: The corrected data", "+= state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^ 1) # flip", "and the sum of counts would not equal to the", "state_labels(self): \"\"\"return the state label ordering of the cal matrix\"\"\"", "if len(raw_data) == len(self._state_labels): data_format = 1 raw_data2 = [raw_data]", "Form 1: a counts dictionary from results.get_counts Form 2: a", "indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits", "size of calibrated qubits, `m` is the number of sets", "= res.x else: raise QiskitError(\"Unrecognized method.\") # convert back into", "noise model without cross-talk, then the time complexity would be", "data_format == 2: # flatten back out the list raw_data2", "= inv_mat_dot_x elif method == 'least_squares': def fun(x): mat_dot_x =", "each calibration matrix a list of the states (as strings,", "mitigate the whole counts using the calibration matrices which affect", "is not an integer multiple \" \"of the number of", "Apply the calibration matrices to results. Args: raw_data (dict or", "[] self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern @property def cal_matrices(self):", "A_3^{-1}[1, 1]*count['0110']`. The total time complexity of this method is", "for i in range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits) first_index", "from a tensored measurement calibration fitter. A simple usage this", "def cal_matrix(self): \"\"\"Return cal_matrix.\"\"\" return self._cal_matrix @property def state_labels(self): \"\"\"return", "{lab: ind for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self):", "__init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): \"\"\" Initialize a", "int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract", "not an integer multiple \" \"of the number of calibrated", "# pylint: disable=cell-var-from-loop,invalid-name \"\"\" Measurement correction filters. \"\"\" from typing", "calibration matrix to results. Args: raw_data (dict or list): The", "= [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind", "`[[0, 1, 2, ..., n-1]]`, which exactly corresponds to the", "raw_data.\") if method == 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) # Apply", "new_count_dict = {} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx]", "in this step, the following formula is applied: `count['0110'] =", "is licensed under the Apache License, Version 2.0. You may", "is index of pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits) second_index", "def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): \"\"\" Initialize", "new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx", "an integer multiple \" \"of the number of calibrated states\")", "for each calibration matrix a list of the logical qubit", "data\") data_format = 0 # convert to form2 raw_data2 =", "elif int(size_ratio) == size_ratio: data_format = 2 size_ratio = int(size_ratio)", "to `1`, and `1` to `2`, the list becomes `[2,", "The total time complexity of this method is `O(m2^{n +", "mitigating the 3rd bit of the 4-bit counts using '2\\times", "dictionary.\"\"\" new_counts = self.apply( raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class", "matrix \"\"\" self._cal_matrix = cal_matrix self._state_labels = state_labels @property def", "state labels \" \"correspond to the input data\") data_format =", "[] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list", "if raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict", "counts dictionary from results.get_counts * A Qiskit Result method (str):", "raw_data.\") if method == 'pseudo_inverse': pinv_cal_matrices = [] for cal_mat", "class TensoredFilter(): \"\"\" Tensored measurement error mitigation filter. Produced from", "== 'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list):", "data_format == 0: # convert back into a counts dictionary", "= \"\" for pos in pos_qubits: sub_state += state[pos] return", "sum(x0) nshots = sum(raw_data2[data_idx]) cons = ({'type': 'eq', 'fun': lambda", "new_count_dict = {} for stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx]", "for raw_data.\") if method == 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) #", "Sequential least square quadratic programming (SLSQP) is used in the", "sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels)) x0 =", "else: # TODO: should probably change to: # raw_data2 =", "qubit `2` to clbit `0`, `0` to `1`, and `1`", "# that they have been altered from the originals. #", "the cal matrix\"\"\" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): \"\"\"set", "if method == 'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices,", "= A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total time complexity", "function with the # counts and push back into the", "qubit in pos_qubits] for state_idx, state in enumerate(all_states): second_index =", "sum(raw_data2[data_idx]) def fun(x): return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0", "dictionary from results.get_counts Form 2: a list of counts of", "raw_data2[data_idx] = res.x else: raise QiskitError(\"Unrecognized method.\") if data_format ==", "qubits_to_clbits[qubit] = i # Apply the correction for data_idx, _", "result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for", "data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse': raw_data2[data_idx] =", "cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse endian", "is shaped like `[[0, 1, 2, ..., n-1]]`, which exactly", "# make the list into chunks the size of state_labels", "= [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list self._mit_pattern =", "\" \"of the number of calibrated states\") elif isinstance(raw_data, qiskit.result.result.Result):", "to the shots. Mitigation is conducted qubit wise: For each", "in a one of the defined forms. \"\"\" all_states =", "return sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result, dict], method: str =", "indicating # that they have been altered from the originals.", "new_cal_matrix): \"\"\"Set cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method='least_squares'):", "filters. \"\"\" from typing import List, Union from copy import", "3: a list of counts of `length==M*len(state_labels)` where M is", "filter. Produced from a measurement calibration fitter and can be", "str: \"\"\"Flip the state according to the chosen qubit positions\"\"\"", "probabilities Returns: dict or list: The corrected data in the", "in self._state_labels: raise QiskitError(\"Unexpected state label '\" + data_label +", "import qiskit from qiskit import QiskitError from qiskit.tools import parallel_map", "mit_pattern: for each calibration matrix a list of the logical", "# counts dictionary # convert to list raw_data2 = [np.zeros(num_of_states,", "== 'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method ==", "\"\"\"Set cal_matrix.\"\"\" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method='least_squares'): \"\"\"Apply", "indices in the calibration matrix self._indices_list = [] for _,", "dictionary new_count_dict = {} for stateidx, state in enumerate(self._state_labels): if", "data. \"\"\" def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list):", "the tensor product noise model without cross-talk, then the time", "mitigation filter using the cal_matrices from a tensored measurement calibration", "dtype=float)] for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0)", "used. Returns: dict or Result: The corrected data in the", "# counts and push back into the new result new_result", "@substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\" self._substate_labels_list = new_substate_labels_list #", "\"\"\" Measurement error mitigation filter. Produced from a measurement calibration", "self._qubit_list_sizes @property def nqubits(self): \"\"\"Return the number of qubits. See", "time complexity would be `O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained", "counts, re-call the function with the # counts and push", "is used in the internal process. Every updating step in", "measurement calibration fitter. A simple usage this class is explained", "new_counts return new_result else: raise QiskitError(\"Unrecognized type for raw_data.\") if", "3rd bit of the 4-bit counts using '2\\times 2' calibration", "to clbit `0`, `0` to `1`, and `1` to `2`,", "= [] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list =", "calibration fitter and can be applied to data. \"\"\" def", "are mitigating the 3rd bit of the 4-bit counts using", "4-bit counts using '2\\times 2' calibration matrix `A_3`. When mitigating", "for applying the correction state_labels: the states for the ordering", "inversion of the cal matrices. Mitigated counts can contain negative", "corresponding qubit. For example, assume we are mitigating the 3rd", "= tuple((0, nshots) for x in x0) res = minimize(fun,", "pos_qubits: List[int], indices: dict) -> int: \"\"\"Return the index of", "@property def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self,", "tensored measurement calibration fitter and can be applied to data.", "following methods are supported: * 'pseudo_inverse': direct inversion of the", "dictionary from results.get_counts * A Qiskit Result method (str): fitting", "notice, and modified files need to carry a notice indicating", "range(len(pinv_cal_mat)): # i is index of pinv_cal_mat source_state = self.flip_state(state,", "is `O(m2^{n + t})`, where `n` is the size of", "`m` is the number of sets in `mit_pattern`, and `t`", "obtain a copy of this license in the LICENSE.txt file", "import parallel_map from qiskit.ignis.verification.tomography import count_keys class MeasurementFilter(): \"\"\" Measurement", "Every updating step in SLSQP takes `O(m2^{n+t})` time. Since this", "in the same form as `raw_data` Raises: QiskitError: if `raw_data`", "= deepcopy(new_cal_matrices) @property def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter", "= raw_data2[0][stateidx] raw_data2 = new_count_dict else: # TODO: should probably", "self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] +=", "applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total", "not in self._state_labels: raise QiskitError(\"Unexpected state label '\" + data_label", "if raw_data is not in a one of the defined", "be corrected. Can be in a number of forms: Form", "np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0)", "ind for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): \"\"\"Return", "meas_layout = [] for qubits in self._mit_pattern: meas_layout += qubits", "A Qiskit Result method (str): fitting method. The following methods", "return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices =", "new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)],", "fitter. Args: cal_matrix: the calibration matrix for applying the correction", "[pos for i, pos in enumerate(flip_poses) if (mat_index >> i)", "return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0", "easier # processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i in", "get the number of qubits in each subspace self._qubit_list_sizes =", "count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout is None: meas_layout =", "int(size_ratio) == size_ratio: data_format = 2 size_ratio = int(size_ratio) #", "deepcopy(x) for cal_mat, pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x", "enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply the correction for data_idx,", "cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): \"\"\"Return _substate_labels_list\"\"\" return", "from copy import deepcopy from scipy.optimize import minimize import scipy.linalg", "sum of counts would not equal to the shots. Mitigation", "be in a number of forms: Form 1: a counts", "a counts dictionary new_count_dict = {} for state_idx, state in", "res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states)", "results.get_counts * A Qiskit Result method (str): fitting method. The", "measurement error mitigation filter using the cal_matrices from a tensored", "of qubits. See also MeasurementFilter.apply() \"\"\" return sum(self._qubit_list_sizes) def apply(self,", "applying the correction state_labels: the states for the ordering of", "time complexity would be `O(n2^n)`. If the `mit_pattern` is shaped", "in self._mit_pattern: meas_layout += qubits # check forms of raw_data", "tensor product noise model without cross-talk, then the time complexity", "= count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the", "the closest probability vector to the result from 'pseudo_inverse' method.", "self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for", "integer (e.g. for use with the tomography data) Form 4:", "mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) ** 2)", "num_of_states = 2**self.nqubits if meas_layout is None: meas_layout = []", "= {} for stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx] !=", "# raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2 def", "t})`, where `n` is the size of calibrated qubits, `m`", "new_state def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict) ->", "dtype=float)] for state, count in raw_data.items(): stateidx = int(state, 2)", "sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result, dict], method: str = 'least_squares',", "method): \"\"\"Wrapper to call apply with a counts dictionary.\"\"\" new_counts", "'least_squares' is used. meas_layout (list of int): the mapping from", "(as int, states in the subspace) \"\"\" self._cal_matrices = cal_matrices", "@cal_matrices.setter def cal_matrices(self, new_cal_matrices): \"\"\"Set cal_matrices.\"\"\" self._cal_matrices = deepcopy(new_cal_matrices) @property", "in range(len(pinv_cal_mat)): # i is index of pinv_cal_mat source_state =", "QiskitError(\"Unrecognized type for raw_data.\") if method == 'pseudo_inverse': pinv_cal_matrices =", "qubit indices (as int, states in the subspace) \"\"\" self._cal_matrices", "str(int(state[flip_pos], 2) ^ 1) # flip the state pos =", "enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the indices in the calibration", "method. The following methods are supported: * 'pseudo_inverse': direct inversion", "\"\"\"set the state label ordering of the cal matrix\"\"\" self._state_labels", "take 10 seconds or more. * If `None`, 'least_squares' is", "conducted qubit wise: For each qubit, mitigate the whole counts", "1] flip_poses = sorted(flip_poses) new_state = \"\" pos = 0", ">> i) & 1] flip_poses = sorted(flip_poses) new_state = \"\"", "1]*count['0110']`. The total time complexity of this method is `O(m2^{n", "method solve a constrained optimization problem to find the closest", "the input data\") data_format = 0 # convert to form2", "in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse endian qubits_to_clbits", "i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply the", "np.matrix, state_labels: list): \"\"\" Initialize a measurement error mitigation filter", "if meas_layout is None: meas_layout = [] for qubits in", "0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict else: # TODO:", "for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state]", "raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method == 'least_squares': nshots", "for qubit in pos_qubits] for state_idx, state in enumerate(all_states): second_index", "calibration matrix `A_3`. When mitigating the count of '0110' in", "Measurement error mitigation filter. Produced from a measurement calibration fitter", "pinv_cal_mat, raw_data2[data_idx]) elif method == 'least_squares': nshots = sum(raw_data2[data_idx]) def", "find the closest probability vector to the result from 'pseudo_inverse'", "!= 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def flip_state(self, state:", "= raw_data2[0] return raw_data2 def _apply_correction(self, resultidx, raw_data, method): \"\"\"Wrapper", "stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data,", "of pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state,", "= i # Apply the correction for data_idx, _ in", "directly applying inverse calibration matrices, this method solve a constrained", "calibration fitter. Args: cal_matrix: the calibration matrix for applying the", "[qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state in enumerate(all_states):", "raise QiskitError(\"Data list is not an integer multiple \" \"of", "range(max(meas_layout) + 1)] for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] =", "# This code is licensed under the Apache License, Version", "qubit wise: For each qubit, mitigate the whole counts using", "in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in", "\"\"\"Flip the state according to the chosen qubit positions\"\"\" flip_poses", "self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list self._mit_pattern", "this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications", "logical qubit indices (as int, states in the subspace) \"\"\"", "\"\"\"Wrapper to call apply with a counts dictionary.\"\"\" new_counts =", "method (str): fitting method. The following methods are supported: *", "int(size_ratio) # make the list into chunks the size of", "enumerate(flip_poses) if (mat_index >> i) & 1] flip_poses = sorted(flip_poses)", "raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data,", "of qubits in each subspace self._qubit_list_sizes = [] for _,", "applied to data. \"\"\" def __init__(self, cal_matrix: np.matrix, state_labels: list):", "self._cal_matrix = cal_matrix self._state_labels = state_labels @property def cal_matrix(self): \"\"\"Return", "= raw_data[ i * len(self._state_labels):(i + 1)*len( self._state_labels)] else: raise", "\"\"\"Return _substate_labels_list\"\"\" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): \"\"\"Return _substate_labels_list\"\"\"", "vector to the result from 'pseudo_inverse' method. Sequential least square", "extract out all the counts, re-call the function with the", "state in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx]", "from qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.ignis.verification.tomography", "the calibration matrix self._indices_list = [] for _, sub_labels in", "type for raw_data.\") if method == 'pseudo_inverse': pinv_cal_matrices = []", "form as `raw_data` Raises: QiskitError: if `raw_data` is not an", "pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states],", "to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in", "a counts dictionary new_count_dict = {} for stateidx, state in", "= res.x else: raise QiskitError(\"Unrecognized method.\") if data_format == 2:", "8 bit counts with the `mit_pattern = [[0], [1], [2],", "for i, pos in enumerate(flip_poses) if (mat_index >> i) &", "code is licensed under the Apache License, Version 2.0. You", "to call apply with a counts dictionary.\"\"\" new_counts = self.apply(", "= minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x", "state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] =", "index of (pseudo inverse) calibration matrix for the input quantum", "form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in enumerate(self._state_labels):", "state[pos:] return new_state def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices:", "\"\"\"Return the number of qubits. See also MeasurementFilter.apply() \"\"\" return", "Result): The data to be corrected. Can be in one", "raw_data2[data_idx]) elif method == 'least_squares': nshots = sum(raw_data2[data_idx]) def fun(x):", "[2], ..., [n-1]]`, which corresponds to the tensor product noise", "this # copyright notice, and modified files need to carry", "for cal_mat, pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x =", "raw_data.keys(): if data_label not in self._state_labels: raise QiskitError(\"Unexpected state label", "qubit in pos_qubits] for state_idx, state in enumerate(all_states): first_index =", "matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append(", "self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the indices in the calibration matrix", "10 seconds or more. * If `None`, 'least_squares' is used.", "matrix for the input quantum state\"\"\" sub_state = \"\" for", "the mitigation for 8 bit counts with the `mit_pattern =" ]
[ "e.g. enantiomers as being duplicates. :return: list of unique Molecules", "together edges that lie on periodic boundaries. In principle, any", "in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped, \"specie\")", "pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments for strategy. If", "Edge weights can be different and StructureGraphs can still be", "def types_of_coordination_environments(self, anonymous=False): \"\"\" Extract information on the different co-ordination", "import MSONable from monty.os.path import which from networkx.drawing.nx_agraph import write_dot", "False, will compare bonds from different Molecules, with node indices", "False. :param validate_proximity: For Molecule.insert(); if True (default False), distance", "d[\"to_jimage\"] # set edge style d[\"style\"] = \"solid\" if to_image", "{tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda", "edges_other) and (self.molecule == other_sorted.molecule) def isomorphic_to(self, other): \"\"\" Checks", "has many benefits, but made it more difficult to #", "None. If any edge properties are to be changed, it", "i + offset return grp_map if isinstance(func_grp, Molecule): func_grp =", "other): \"\"\" Two MoleculeGraphs are equal if they have equal", "PeriodicSite, Structure from pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell", "other connection between sites) doesn't have a direction, from_index, from_jimage", "bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Structure.substitute to", "self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of edges", "The Jaccard distance is a simple measure of the dissimilarity", "return False f2_edges = frag2.edges() if len(f2_edges) != len(f2_edges): return", "of edges edges_to_remove = [] edges_to_add = [] for u,", "edges_other = { (u, v, d.get(\"to_jimage\", (0, 0, 0))) for", "retrieve from/to images, set as origin if not defined if", "for StructureGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param structure:", "del edge_props[\"weight\"] if 0 not in list(graph.graph.nodes()): # If graph", ":param edges: dict representing the bonds of the functional group", "incorporates the new site into the MoleculeGraph. :param i: Index", "g = g.subgraph([n for n in g.degree() if g.degree()[n] !=", "in both. The Jaccard distance is a simple measure of", "edge weight units e.g. \"Å\" or \"eV\" :return (MoleculeGraph): \"\"\"", "format (not intended to be constructed manually, see as_dict method", "this means molecules will need to have the same bond", "to_directed() will mean that each cycle always appears twice #", "filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False,", "must be remapped, incrementing from 0 mapping = {} for", "connected_site_images.add((v, to_jimage)) # return list sorted by closest sites first", "\"tuples\") if props is not None: if \"weight\" in props.keys():", "k in green_edges: g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"}) for u, v,", "None) if (v, to_jimage) not in connected_site_images: connected_site = ConnectedSite(site=site,", "return False f1_comp_dict = {} f2_comp_dict = {} for node", "between Sites. Edge weights can be different and MoleculeGraphs can", "new_v, new_u, new_d = u, v, d.copy() new_d[\"to_jimage\"] = (0,", "props[\"weight\"] del props[\"weight\"] else: weight = None if len(props.items()) ==", ":Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph \"\"\" if not", "k)) for u, v, k in green_edges: g.edges[u, v, k].update({\"color_uv\":", "molecules! \" \"Please choose another strategy.\" ) extend_structure = strategy.extend_structure_molecules", "other: MoleculeGraph :param strict: if False, will compare bonds from", "to_index, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge to graph.", "is not None, then find_rings will only return those rings", "cycles_edges def get_connected_sites(self, n): \"\"\" Returns a named tuple of", ") frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\" + str(len(unique_mol_graph_list[0].graph.edges()))", "key 'dist'. Important note: all node indices are in terms", "edge properties to be changed following the split. :param allow_reverse:", "* 0.299 + c[1] * 0.587 + c[2] * 0.114)", "site indices. If including is not None, then find_rings will", "\"\"\" Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`.", "in properties.items(): if len(v) != len(species): del properties[k] new_mol =", "they have equal Structures, and have the same edges between", "f2_nodes = frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes): return False f2_edges", "to molecule graphs unique_mol_graph_dict = {} for key in unique_frag_dict:", "in nx.connected_components(supercell_sg.graph)] # discount subgraphs that lie across *supercell* boundaries", "self.structure.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy atom", "weight = d.get(\"weight\", None) if v == n: site =", "= \"<EMAIL>\" __status__ = \"Production\" __date__ = \"August 2017\" ConnectedSite", "to all unique fragments using graph isomorphism unique_frag_dict = {}", "edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props)", "0))) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other =", "used for debugging, edges to periodic images always appear as", "issues with finite precision leading to incorrect image v_expec_image =", "ii in range(1, len(self.molecule)): for combination in combinations(graph.nodes, ii): mycomp", "site_properties: Site properties for Molecule :param edges: List of dicts", "create disjoint graphs (two or more separate molecules). This function", "have to be a chemical bond, but can store any", "then the algorithm will attempt to automatically determine bonds using", "graph. :return: A dictionary with keys specifying the species involved", "to prevent problems with misdirected edges, both graphs are converted", "new functional group. TODO: Figure out how to replace into", ":param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified bond", "only nodes defined that correspond to Sites in Structure). :param", "key=None, reverse=False): \"\"\" Same as Molecule.sort(), also remaps nodes in", "If True, only treat subgraphs as isomorphic if edges have", "coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j", "> neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"] to_index = n else: from_index", "is None: strategy_params = {} strat = strategy(**strategy_params) for site", "use_weights=False): \"\"\" Retrieve subgraphs as molecules, useful for extracting molecules", "MoleculeGraph. These edges must include the index of the new", "True, do not draw edges that go through periodic boundaries", "self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise ValueError( \"Edge", "np.add(site_d[\"abc\"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d) # from_site if jimage arg", "in a connection in alphabetical order (e.g. string 'Fe-O') and", "d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\" # optionally", "Molecule object :param edges: dict representing the bonds of the", "def draw_graph_to_file( self, filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False,", "name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod", "connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return list sorted by closest sites", "add weights to graph if weight_labels: units = g.graph.get(\"edge_weight_units\", \"\")", "nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): \"\"\" This is a class", "= json_graph.adjacency_data(new_graph) # create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols", "`pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to store graph", "= self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties,", "exists before attempting to change it if not existing_edges: raise", "if node_labels else \"\" # use standard color scheme for", "Providing an actual molecule as the input. The first atom", "!= len(other.molecule): return False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False", "to remove the index site, and connect the nearest neighbor", "label in labels: sp = label[1] if sp not in", "weight_labels: units = g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"): d[\"label\"] = \"{:.2f}", "optional edge parameters. :param molecule: Molecule object :param edges: dict", "convenient key try: mapping = {tuple(site.coords): self.molecule.index(site) for site in", "one node per site # graph attributes don't change behavior", "sort edges for consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for", "set() out_edges = [(u, v, d, \"out\") for u, v,", "validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j in range(len(self.molecule)", "tuples, sorted by closest first \"\"\" connected_sites = set() out_edges", "the new site :param coords: 3x1 array representing coordinates of", "edges = {} for from_index, to_index, key in remapped.edges: edge_props", "StructureGraphs are equal if they have equal Structures, and have", "EL_COLORS try: import igraph IGRAPH_AVAILABLE = True except ImportError: IGRAPH_AVAILABLE", "the new site i, and all indices used for these", "the graphs of two MoleculeGraphs are isomorphic to one another.", "a direction, from_index, from_jimage can be swapped with to_index, to_jimage.", "e.g. (1, 0, 0) for periodic image in +x direction", "validate_proximity: For Molecule.insert(); if True (default False), distance will be", "{} edges, adding {} new edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked", "v) in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight = None", "self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge", "units = g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"): d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"],", "\" indices.\" ) mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return mg", "TODO: actually figure out how to distribute charge if 0", "distance is a simple measure of the dissimilarity between two", "for bond in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise", "= self.graph.get_edge_data(to_index, from_index) if existing_reverse: for i, properties in existing_reverse.items():", "dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return list sorted by closest", "ring\" \"structure.\" ) to_remove = set() sizes = dict() disconnected", "for n in subgraph.nodes()] molecule = Molecule(species, coords) # shift", "s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def", "weight units e.g. \"Å\" or \"eV\" :return (MoleculeGraph): \"\"\" if", "nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self): \"\"\" Determine if the", "MoleculeGraphs by breaking a set of bonds. This function uses", "= edge[1] from_image = edge[2] to_image = edge[3] except TypeError:", "= set() connected_site_images = set() out_edges = [(u, v, d,", "jimage))) site_d = self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist() site =", "in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes, # these", "indices): \"\"\" A wrapper for Molecule.remove_sites(). :param indices: list of", "self.structure[n_u].frac_coords # using the position of node u as a", "= [] for subgraph in all_subgraphs: intersects_boundary = any(d[\"to_jimage\"] !=", "using its frac_coords as a convenient key try: mapping =", "{} to site {}.\".format(from_index, to_index) ) return # generic container", "\"\"\" existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists", "np.subtract(v_image_cart, u_cart) # now retrieve position of node v in", "subgraph.nodes()] molecule = Molecule(species, coords) # shift so origin is", "it if not existing_edge: raise ValueError( \"Edge between {} and", "direction if new_v < new_u: new_u, new_v = new_v, new_u", "from_index = from_index, to_index # sanitize types from_index, to_index =", "v)]: weight = alterations[(u, v)][\"weight\"] del alterations[(u, v)][\"weight\"] edge_properties =", "to 1. :param graph_dict: Dictionary representing the bonds of the", "appearance and also correctly displays # mutli-graphs (matplotlib can superimpose", "\"Please choose another strategy.\" ) sg = StructureGraph.with_empty_graph(structure, name=\"bonds\") for", "remove two edges for everyone one we add if {new_u,", "must be present for all atoms in the molecule #", "properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]] # Site properties must be", "to graph. Since physically a 'bond' (or other connection between", "ValueError( \"Chosen strategy is not designed for use with structures!", "is the second site. What the code will do is", "= self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords,", "is not None: for (u, v) in alterations.keys(): if \"weight\"", "the specified sites. By default, this parameter is None, and", "self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor", "= [\"weight\"] edge_label = g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"] if edge_weight_units:", "Cartesian co-ordinates of where # atoms defined by edge are", "if sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is", "{new_u, new_v} not in edges_inside_supercell: # normalize direction if new_v", "reverse=reverse) # apply Structure ordering to graph mapping = {idx:", "edge_match=edge_match) for g in unique_subgraphs ] if not any(already_present): unique_subgraphs.append(subgraph)", "If allow_reverse is True, then break_edge will attempt to break", "------------\" edge_weight_name = g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights = [\"weight\"] edge_label", "\"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None):", "{} for from_index, to_index, key in remapped.edges: edge_props = fragment.get_edge_data(from_index,", "this include storing bonding information, NMR J-couplings, Heisenberg exchange parameters,", "species name label = \"{}({})\".format(str(self.molecule[n].specie), n) if node_labels else \"\"", "using `from_dict_of_dicts` from NetworkX to restore graph information. \"\"\" s", "1 - (size of the intersection / size of the", ":return: length of Molecule / number of nodes in graph", "to_index: index of site connecting to :param from_jimage (tuple of", ":return: \"\"\" old_structure = self.structure.copy() # sort Structure self.structure._sites =", ":param bond_order: A specified bond order to calculate the bond", "image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist = min(dists)", "properties for Molecule :param edges: List of dicts representing edges", "green_edges = [] red_edges = [] for u, v, k,", "so node indices # must be remapped, incrementing from 0", "index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return list sorted", "+= \" {}\".format(edge_label) header_line += \" {}\".format(\"-\" * max([18, len(edge_label)]))", "if weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties)", "coordinate instead\") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove", "(u, v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"to_jimage\"", "of dicts representing edges to be added to the MoleculeGraph.", "Split MoleculeGraph into two or more MoleculeGraphs by breaking a", "2] # Using to_directed() will mean that each cycle always", "with weights :param image_labels (bool): if True, label edges with", "consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for u, v, data", "class for annotating a Structure with bond information, stored in", "\"with your edge weights. Can be \" \"empty string if", "i: mapping[j] = j else: mapping[j] = j + 1", "get label by species name label = \"{}({})\".format(str(self.structure[n].specie), n) if", "new_v = new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d)) else:", "useful for extracting molecules from periodic crystals. Will only return", "to be compared. :return: bool \"\"\" if len(self.molecule) != len(other.molecule):", "invalid.\") def set_node_attributes(self): \"\"\" Replicates molecule site properties (specie, coords,", "edges with weights :param image_labels (bool): if True, label edges", "(MoleculeGraph): \"\"\" if edge_weight_name and (edge_weight_units is None): raise ValueError(", "not np.array_equal(from_jimage, (0, 0, 0)): shift = from_jimage from_jimage =", "\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return", "@classmethod def from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Structure` except", "edge are expected to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart =", "or violate the dimensions of the Lattice. :param index: Index", "your\" \" indices.\" ) sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight,", "in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"],", "for n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors: #", "0 # TODO: actually figure out how to distribute charge", "mapping) species = nx.get_node_attributes(remapped, \"specie\") coords = nx.get_node_attributes(remapped, \"coords\") edges", "data=True) } edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v,", "edges_to_add.append((new_u, new_v, new_d)) else: # want to find new_v such", "v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v) for", "return molecules class MolGraphSplitError(Exception): \"\"\" Raised when a molecule graph", "correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def substitute_group( self, index, func_grp,", "bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot split", "correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False)", "connect the atoms. 2. A string name. The molecule will", "= orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart) #", "that we have # full periodic boundary conditions # so", "g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label += \" ({})\".format(edge_weight_units) header += \"", "i, species, coords, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper", "not in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow", "+ 100 b = max(coords[:, 1]) - min(coords[:, 1]) +", "function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs (two or", "= 1 else: f2_comp_dict[node[1][\"specie\"]] += 1 if f1_comp_dict != f2_comp_dict:", "graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"to_jimage\" in edge_props.keys(): to_jimage", "images will always always be shifted so that from_index <", "properties, including weight. Props should be None if no additional", "'other'), and edges that are present in both. The Jaccard", "weight and/or edge properties to be changed following the split.", "adapted from Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16) if scale_matrix.shape !=", "= j else: mapping[j] = j + 1 nx.relabel_nodes(self.graph, mapping,", "to_index, to_jimage. However, images will always always be shifted so", "(for more crowded graphs) usually give good outputs :return: \"\"\"", "u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v,", "is None: self._supercell_sg = supercell_sg = self * (3, 3,", "# using its frac_coords as a convenient key try: mapping", "to match given position to an # existing Site in", "existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if existing_edge: self.graph.remove_edge(from_index,", "more separate molecules). This function does not only alter the", "for u, v, d in other_sorted.graph.edges(keys=False, data=True) } else: edges", "for n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define how", "s def __len__(self): \"\"\" :return: length of Structure / number", "those sites.\".format( from_index, to_index ) ) def remove_nodes(self, indices): \"\"\"", "is not necessary for the class to work, but #", ":param weights: if True, use weights from local_env class (consult", "this function will fail. Currently, this function naively assigns the", "Here, the # number of nodes != number of sites", "original graph to its image mapping = {n: n +", "strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified bond order", "specifying the species involved in a connection in alphabetical order", "site v # and another form site v to site", "if arbitrary or \" \"dimensionless.\" ) # construct graph with", "= 0 # relabel nodes in graph to match mapping", "if len(f2_edges) != len(f2_edges): return False f1_comp_dict = {} f2_comp_dict", "MoleculeGraph this method is called from, not the 'other' MoleculeGraph:", "would be easier to multiply the Structure # *before* generating", "return sg @property def name(self): \"\"\" :return: Name of graph", "this is None. If weight is to be changed, it", "def _igraph_from_nxgraph(graph): \"\"\" Helper function that converts a networkx graph", "available_letters.pop(0) centre_sp = \"A\" labels = [(label[0], mapping[label[1]]) for label", "file for later visualization :param algo: any graphviz algo, \"neato\"", "standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0,", "n in enumerate(nodes): mapping[n] = i # just give charge", "the insertion, NOT before. Each dict should at least have", "= 0 # by definition else: jaccard_dist = 1 -", "site. Defaults to 1. :param graph_dict: Dictionary representing the bonds", "For periodic graphs, class stores information on the graph edges", "graph object itself can also be drawn with networkx's in-built", "expected position # of an image node, and seeing if", "3x3 scaling matrices raise NotImplementedError(\"Not tested with 3x3 scaling matrices", "nodes and to_index in nodes): raise ValueError( \"Edges cannot be", "in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions", "if existing_edge_data and warn_duplicates: warnings.warn( \"Trying to add an edge", "edge properties, # similar to site properties edge_properties = edge_properties", "node v # reduce unnecessary checking if to_jimage != (0,", "in existing_edge_data.items(): if d[\"to_jimage\"] == to_jimage: if warn_duplicates: warnings.warn( \"Trying", "self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites = []", "if node[1][\"specie\"] not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1 else: f1_comp_dict[node[1][\"specie\"]]", "= {tuple(site.frac_coords): self.structure.index(site) for site in other.structure} other_sorted = other.__copy__()", "exists before attempting to change it if not existing_edge: raise", "0, 0), but making this # assumption simplifies logic later", "simple measure of the dissimilarity between two StructureGraphs (ignoring edge", "= Molecule(species, coords, charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) # create", "nodes: charge = self.molecule.charge else: charge = 0 # relabel", "is terminal if len(neighbors) == 1: self.substitute_group( index, func_grp, strategy,", "terminal if len(neighbors) == 1: self.substitute_group( index, func_grp, strategy, bond_order=bond_order,", "E\" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def", "group (format: {(u, v): props}, where props is a dictionary", "remove periodic image edges, # these can be confusing due", "if to_jimage != (0, 0, 0): # get index in", "the dummy atom X should not count atoms = len(grp)", "node indices will be the same if the underlying Structures", "not in mapping: mapping[sp] = available_letters.pop(0) centre_sp = \"A\" labels", "self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\")", "def insert_node( self, i, species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None,", "nearest neighbor. The second atom must be the next nearest", "0 else None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v,", "= list(g.edges(data=True)) # sort edges for consistent ordering edges.sort(key=itemgetter(0, 1))", "graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Molecule.substitute and MoleculeGraph.substitute_group", "\"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge( self, from_index, to_index, to_jimage=None,", "as O'Keeffe). This class that contains connection information: relationships between", "\"#ffffff\" # convert color to hex string color = \"#{:02x}{:02x}{:02x}\".format(c[0],", "Sites in Molecule). :param molecule (Molecule): :param name (str): name", "(instead of MultiDiGraph), with node indices # representing both site", "boundaries. In principle, any operations on the expanded graph could", "edges that are present in only one MoleculeGraph ('self' and", "to_index) if existing_edge_data: for key, d in existing_edge_data.items(): if d[\"to_jimage\"]", "for nnsite in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage =", "molecule graphs unique_mol_graph_dict = {} for key in unique_frag_dict: unique_mol_graph_list", "remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)] = edge_props", "lengths can differ. This is a fairly robust approach, but", "nx.union(new_g, new_graph) edges_to_remove = [] # tuple of (u, v,", "name of edge weights, e.g. \"bond_length\" or \"exchange_constant\" :param edge_weight_units", "if not keep_dot: os.remove(basename + \".dot\") @property def types_and_weights_of_connections(self): \"\"\"", "atom within a ring\" \"structure.\" ) to_remove = set() sizes", "a dict {(from_index, to_index): alt}, where alt is a dictionary", "ensure that edge exists before attempting to change it if", "n + len(new_sites) for n in range(len(self.structure))} for idx, site", "if existing_reverse: for i, properties in existing_reverse.items(): if properties[\"to_jimage\"] ==", "image_labels: d[\"headlabel\"] = \"\" if to_image == (0, 0, 0)", "(e.g. bond lengths). \"\"\" def get_label(u, v): u_label = self.structure[u].species_string", "\"weight\" in alterations[(u, v)]: weight = alterations[(u, v)][\"weight\"] del alterations[(u,", "the MoleculeGraph. :return: \"\"\" species = {} coords = {}", "they have equal Molecules, and have the same edges between", "\" \"Please choose another strategy.\" ) sg = StructureGraph.with_empty_graph(structure, name=\"bonds\")", "if len(f1_nodes) != len(f2_nodes): return False f2_edges = frag2.edges() if", "the edge weight property of graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def", "if appropriate if to_jimage is None: # assume we want", "+ \"\\n\" edges = list(g.edges(data=True)) # sort edges for consistent", "def weight_statistics(self): \"\"\" Extract a statistical summary of edge weights", "However, images will always always be shifted so that from_index", "'median', 'mean', 'std_dev' \"\"\" all_weights = [d.get(\"weight\", None) for u,", "of the dissimilarity between two MoleculeGraphs (ignoring edge weights), and", "to break (to_index, from_index). :return: list of MoleculeGraphs \"\"\" self.set_node_attributes()", "input graph_data = molecule.as_dict()[\"graphs\"] self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data)", "label in labels] motif = \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return sorted(list(motifs))", "and 'other'), and edges that are present in both. The", "to_image = (0, 0, 0) # set edge style d[\"style\"]", "changes the underlying Molecules. If the bonds parameter does not", "have # full periodic boundary conditions # so that nodes", "self.structure.copy() # sort Structure self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse) #", "image. Here, the # number of nodes != number of", "annotating a Molecule with bond information, stored in the form", "u as a reference, # get relative Cartesian co-ordinates of", "found = False for f in unique_frags: if _isomorphic(frag, f):", "back to molecule graphs unique_mol_graph_dict = {} for key in", "of site connecting to :param weight (float): e.g. bond length", "mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) def replace_group( self, index, func_grp,", "present in supercell # and if so, delete old edge", "to_index) representing bonds to be broken to split the MoleculeGraph.", "self.molecule.index(site) for idx, site in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping,", "not defined to_image = d[\"to_jimage\"] # set edge style d[\"style\"]", "n. :param n: index of site :return (int): \"\"\" number_of_self_loops", "a simple measure of the dissimilarity between two StructureGraphs (ignoring", "if isinstance(molecule, MoleculeGraph): # just make a copy from input", "= {idx: self.structure.index(site) for idx, site in enumerate(old_structure)} self.graph =", "edges: s += \"{:4} {:4} {:12} {:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\",", "approach was also trialed, using # a simple Graph (instead", "subgraph of the original. Currently, this function naively assigns the", "- min(coords[:, 0]) + 100 b = max(coords[:, 1]) -", "to be removed. :return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {}", "\" \"dimensionless.\" ) # construct graph with one node per", "information, NMR J-couplings, Heisenberg exchange parameters, etc. :param molecule: Molecule", "def __eq__(self, other): \"\"\" Two StructureGraphs are equal if they", "each cycle always appears twice # So, we must also", "Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s", "of ConnectedSite tuples, sorted by closest first \"\"\" connected_sites =", "Developer note: a different approach was also trialed, using #", "methods for drawing # graphs using matplotlib, these also work", "new_u: new_u, new_v = new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v,", "not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is None: cycles_nodes", "sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes() return", "IGRAPH_AVAILABLE = False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = \"<NAME>,", "3x1 array representing coordinates of the new site :param validate_proximity:", "\"\"\" return len(self.molecule) def sort(self, key=None, reverse=False): \"\"\" Same as", "\"weight\" and a \"properties\" key. :return: \"\"\" self.structure.insert( i, species,", "for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) # get", "\"coords\") raw_props = nx.get_node_attributes(new_graph, \"properties\") properties = {} for prop_set", "if anonymous: mapping = {centre_sp: \"A\"} available_letters = [chr(66 +", "def edge_match(e1, e2): if use_weights: return e1[\"weight\"] == e2[\"weight\"] return", "if 0 in nodes: charge = self.molecule.charge else: charge =", "to be changed, it should be a dictionary of edge", "edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data)", "from \" \"site {} to site {}.\".format(from_index, to_index) ) return", "not. \"\"\" f1_nodes = frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if len(f1_nodes)", "for u, v, d in self.graph.in_edges(n, data=True)] for u, v,", "= False for f in unique_frags: if _isomorphic(frag, f): found", "also remove duplicates unique_sorted = [] unique_cycles = [] for", "frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes): return False", "precision leading to incorrect image v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image", "nx.get_node_attributes(remapped, \"coords\") edges = {} for from_index, to_index, key in", "def node_match(n1, n2): return n1[\"specie\"] == n2[\"specie\"] def edge_match(e1, e2):", "= self.graph.get_edge_data(from_index, to_index) existing_reverse = None if to_jimage is None:", "are in terms of the MoleculeGraph this method is called", "(Structure): :param name (str): name of graph, e.g. \"bonds\" :param", "and all rings will be returned. :return: dict {index:cycle}. Each", "for label in labels] labels = [\"{}({})\".format(label[1], label[0]) for label", ") else: for u, v, data in edges: s +=", "edges_other - edges, \"both\": edges.intersection(edges_other), \"dist\": jaccard_dist, } def get_subgraphs_as_molecules(self,", "+ str(len(subgraph.edges())) if mykey not in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)]", "node per site # graph attributes don't change behavior of", "change it if not existing_edges: raise ValueError( \"Edge between {}", "boundary conditions # so that nodes on one side of", "len(species): del properties[k] new_mol = Molecule(species, coords, charge=charge, site_properties=properties) graph_data", "{} for j in range(len(self.molecule) - 1): if j <", "f2_nodes: if node[1][\"specie\"] not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1 else:", "edge_props[\"to_jimage\"] else: # By default, assume that all edges should", "\"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return", "d in self.graph.out_edges(n, data=True)] in_edges = [(u, v, d, \"in\")", "from scipy.spatial import KDTree from scipy.stats import describe from pymatgen.core", "if image_labels: d[\"headlabel\"] = \"\" if to_image == (0, 0,", "count = connected_species.count(sp) labels.append((count, sp)) labels = sorted(labels, reverse=True) if", "index of the corresponding site in the original structure, weight", "in the Molecule. If there is no cycle including an", "extra logic if getattr(self, \"_supercell_sg\", None) is None: self._supercell_sg =", "if to_jimage is None: edge_index = 0 else: for i,", "also remaps nodes in graph. :param key: :param reverse: :return:", ":param weight_labels (bool): if True, label edges with weights :param", "node identities. \"\"\" return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\"", "0]) # get contrasting font color # magic numbers account", "# just make a copy from input graph_data = molecule.as_dict()[\"graphs\"]", "remove duplicates unique_sorted = [] unique_cycles = [] for cycle", "\" \"empty string if arbitrary or \" \"dimensionless.\" ) #", "molecule # in order to be used for Molecule instantiation", "of image :param weight (float): e.g. bond length :param warn_duplicates", "molecule, graph_data=None): \"\"\" If constructing this class manually, use the", "edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for StructureGraph, returns a StructureGraph object", "connected.\" ) # alter any bonds before partition, to avoid", "# atoms defined by edge are expected to be v_image_cart", "group in list. \" \"Provide explicit coordinate instead\") self.structure.substitute(index, func_grp,", "self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for connected_site in connected_sites] labels =", "[] # Remove all two-edge cycles all_cycles = [c for", "strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Structure.substitute", "filename: filename to output, will detect filetype from extension (any", "import defaultdict, namedtuple from itertools import combinations from operator import", "def with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for MoleculeGraph,", "to compare MoleculeGraphs if \" \"corresponding Molecules are different.\") if", "None, warn_duplicates=False, ) return sg @property def name(self): \"\"\" :return:", "False other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges = {(u,", "(str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) }", "existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(from_index, to_index,", "count atoms = len(grp) - 1 offset = len(self.structure) -", "with one node per site # graph attributes don't change", "MoleculeGraphs, where each resulting MoleculeGraph is a disconnected subgraph of", "edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for MoleculeGraph, returns a MoleculeGraph object", "nodes on opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find new", "bonds: list of tuples (from_index, to_index) representing bonds to be", "nodes from original graph to its image mapping = {n:", "If the bonds parameter does not include sufficient bonds to", "without adding extra logic if getattr(self, \"_supercell_sg\", None) is None:", "func_grp.remove_species(\"X\") if graph_dict is not None: for (u, v) in", "# get Molecule objects for each subgraph molecules = []", "import describe from pymatgen.core import Lattice, Molecule, PeriodicSite, Structure from", "if graph_dict is not None: for (u, v) in graph_dict.keys():", "new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage))", "props.keys(): weight = props[\"weight\"] del props[\"weight\"] else: weight = None", "AFTER the insertion, NOT before. Each dict should at least", "from_image, to_image): props}, where props is a dictionary of properties,", "[copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols = list() # Had to", "replace_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\"", "edge_weight_units = g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label += \" ({})\".format(edge_weight_units) header", "Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self.molecule", "for node in f2_nodes: if node[1][\"specie\"] not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]]", "= molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr", "automatic detection of to_jimage if user doesn't specify # will", "to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, )", "edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) else: if strategy_params", "index of site :return (int): \"\"\" number_of_self_loops = sum([1 for", "= {} for from_index, to_index, key in remapped.edges: edge_props =", "J-couplings, Heisenberg exchange parameters, etc. For periodic graphs, class stores", "all rings will be returned. :return: dict {index:cycle}. Each entry", "to_index, from_image, to_image): props}, where props is a dictionary of", "to add an edge that already exists from \" \"site", "bond_order=bond_order) mapping = map_indices(func_grp.molecule) for (u, v) in list(func_grp.graph.edges()): edge_props", "sites.\".format( from_index, to_index ) ) # Third index should always", "= map_indices(func_grp.molecule) for (u, v) in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u,", "keep the graph in sync with its corresponding Structure. #", "new_v = v_present new_d = d.copy() # node now inside", "= g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"): d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"], units)", "= nx.get_node_attributes(new_graph, \"specie\") coords = nx.get_node_attributes(new_graph, \"coords\") raw_props = nx.get_node_attributes(new_graph,", "edge has been deleted red_edges.append((u, v, k)) elif (u, v,", "changed, it should be a dictionary of edge properties to", "allow_reverse=False, alterations=None): \"\"\" Split MoleculeGraph into two or more MoleculeGraphs", "weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage,", "two MoleculeGraphs. Returns dict with keys 'self', 'other', 'both' with", "(consult relevant class for their meaning) :return: \"\"\" if not", "asgolute Cartesian # co-ordinates of where atoms defined by edge", "graph_data=None): \"\"\" If constructing this class manually, use the `with_empty_graph`", "for u, v, d in new_g.edges(data=True) if d[\"to_jimage\"] == (0,", "in other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges =", "[] red_edges = [] for u, v, k, d in", "and add multiple # edges if appropriate if to_jimage is", "True, use node colors to color edges :param node_labels (bool):", ":param coords: 3x1 array representing coordinates of the new site", "supercell # and if so, delete old edge that went", "the split. :param allow_reverse: If allow_reverse is True, then break_edge", "structures! \" \"Please choose another strategy.\" ) sg = StructureGraph.with_empty_graph(structure,", "of occurrences of bonds :return: \"\"\" if self.structure != other.structure", "validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j in range(len(self.structure)", "weight can be None if not defined. :param n: index", "is still connected.\" ) # alter any bonds before partition,", "given position to an # existing Site in Structure kd_tree", "`pymatgen.analysis.local_env.NearNeighbors` object :param weights: if True, use weights from local_env", "when from_index == to_index, # typically in primitive single-atom lattices", "weight or the edge_properties of an edge in the StructureGraph.", "molecules, useful for extracting molecules from periodic crystals. Will only", "which new lattice images present, but should hopefully be #", "big graph new_g = nx.MultiDiGraph() for new_graph in new_graphs: new_g", "import subprocess import warnings from collections import defaultdict, namedtuple from", "from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except", "dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev'", "= new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d)) else: #", "charge = self.molecule.charge else: charge = 0 # relabel nodes", "= molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False) else: structure = None", "set as origin if not defined if \"to_image\" in d:", "structure, graph_data=None): \"\"\" If constructing this class manually, use the", "0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return list sorted", "one edge # between two sites existing_edge_data = self.graph.get_edge_data(from_index, to_index)", "split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): \"\"\" Split MoleculeGraph into two or", "np.int16) else: # TODO: test __mul__ with full 3x3 scaling", "to compare StructureGraphs if \" \"corresponding Structures are different.\") if", "species[node] = self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph,", "v_present new_d = d.copy() new_to_jimage = tuple(map(int, v_expec_image)) # normalize", "not using graph_dict). :param index: Index of atom to substitute.", "in the graph. :return: A dict with an 'all_weights' list,", "that node exists in the # supercell. If it does,", "existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise ValueError( \"Edge cannot be broken", "will treat e.g. enantiomers as being duplicates. :return: list of", "f1_comp_dict != f2_comp_dict: return False if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1)", "_igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\",", "rs.communicate() if rs.returncode != 0: raise RuntimeError(\"{} exited with return", "\"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def with_empty_graph(cls,", "0, 0]): continue if n > neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"]", "group. This method also amends self.graph to incorporate the new", "to_index) and, failing that, will attempt to break (to_index, from_index).", "or more separate molecules). This function does not only alter", "ring structure. :param index: Index of atom to substitute. :param", "{:12} {:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\", (0, 0, 0))), data.get(\"weight\", 0)", "# typically in primitive single-atom lattices images = [1, 0,", "{} properties = {} for node in self.graph.nodes(): species[node] =", "Structure from pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell from", "edge # are expected to be v_expec = new_structure[u].coords +", "== to_index, # typically in primitive single-atom lattices images =", "drawing methods, but note that this might give misleading results", "- number_of_self_loops def draw_graph_to_file( self, filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False,", "# periodic boundary if v_present is not None: new_u =", "to actually accurately assign charge. NOTE: This function does not", "out how to replace into a ring structure. :param index:", "for idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp)) subgraph =", "from_jimage != (0, 0, 0), but making this # assumption", "bonds :return: \"\"\" if self.molecule != other.molecule and strict: return", "= [c for c in nx.simple_cycles(directed) if len(c) > 2]", "edges: s += \"{:4} {:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0,", "This method also amends self.graph to incorporate the new functional", "mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination) if nx.is_connected(subgraph):", "object :param weights: if True, use weights from local_env class", "**d) # return new instance of StructureGraph with supercell d", "if v_present[0] <= tol else None if v_present is not", "= max(sizes, key=lambda x: sizes[x]) for i in sizes.keys(): if", "return cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule, edges): \"\"\" Constructor for", "used for these edges should reflect the MoleculeGraph AFTER the", "Internal function to check if two graph objects are isomorphic,", "\"\"\" Extract a dictionary summarizing the types and weights of", "bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy atom \"X\" func_grp.remove_species(\"X\")", "import copy import logging import os.path import subprocess import warnings", "= {} for prop_set in raw_props.values(): for prop in prop_set.keys():", "data=True): to_jimage = d[\"to_jimage\"] # for node v # reduce", "(generally) work with structures # molecules have to be boxed", "{} for node in self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node] =", "if strategy_params is None: strategy_params = {} strat = strategy(**strategy_params)", "mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor classes only", "from_index: int :param to_index: int :param new_weight: alter_edge does not", "for those connections (e.g. bond lengths). \"\"\" def get_label(u, v):", "if existing_edges: for i, properties in existing_edges.items(): if properties[\"to_jimage\"] ==", "to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights else None, warn_duplicates=False, ) return", "warn_duplicates (bool): if True, will warn if trying to add", "undirected = self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes = [] cycles_edges", "sites now present in supercell # and if so, delete", "(u, v) in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight =", "# Remove all two-edge cycles all_cycles = [c for c", "or \"exchange_constant\" :param edge_weight_units (str): name of edge weight units", "under the terms of the MIT License. \"\"\" Module for", "edges.items(): try: from_index = edge[0] to_index = edge[1] from_image =", "smaller tol = 0.05 for u, v, k, d in", "kd_tree = KDTree(new_structure.cart_coords) # tolerance in Å for sites to", "== 1: self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, )", "attempt to automatically determine bonds using one of a list", "if existing_edge_data: for key, d in existing_edge_data.items(): if d[\"to_jimage\"] ==", "prop in prop_set.keys(): if prop in properties: properties[prop].append(prop_set[prop]) else: properties[prop]", "in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes, key=lambda", "raise ValueError(\"Edges must be given as (from_index, to_index)\" \"tuples\") if", "adding {} new edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked edges for", "a 'bond' (or other connection between sites) doesn't have a", "that, will attempt to break (to_index, from_index). :return: \"\"\" #", "nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def substitute_group( self, index, func_grp, strategy,", "then break_edge will attempt to break both (from_index, to_index) and,", "returns a StructureGraph object with an empty graph (no edges,", "given molecule easier. Use cases for this include storing bonding", "if not np.array_equal(from_jimage, (0, 0, 0)): shift = from_jimage from_jimage", "other.molecule and strict: return ValueError(\"Meaningless to compare MoleculeGraphs if \"", "= self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0,", "if the underlying Molecules are ordered differently. :param other: MoleculeGraph", "else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: for", "\"out\") for u, v, d in self.graph.out_edges(n, data=True)] in_edges =", "charge. NOTE: This function does not modify the original MoleculeGraph.", "if not which(algo): raise RuntimeError(\"StructureGraph graph drawing requires \" \"GraphViz", "self.graph.edges(keys=False, data=True)} edges_other = {(u, v) for u, v, d", "= neighbor[\"site_index\"] to_index = n else: from_index = n to_index", ":return: \"\"\" # this is not necessary for the class", "u, v, k, d in new_g.edges(keys=True, data=True): to_jimage = d[\"to_jimage\"]", "to_index = edge[1] from_image = edge[2] to_image = edge[3] except", "filetype supported, such as pdf or png) :param diff (StructureGraph):", "now define how we test for isomorphism def node_match(n1, n2):", ":param species: Species for the new site :param coords: 3x1", "= g.subgraph([n for n in g.degree() if g.degree()[n] != 0])", "group that is substituted will not place atoms to close", "strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings = self.find_rings(including=[index]) if", "A, B, C, etc. :return: a list of co-ordination environments,", "[] # add display options for edges for u, v,", "\"\"\" Compares two StructureGraphs. Returns dict with keys 'self', 'other',", "not the 'other' StructureGraph: there is no guarantee the node", "*supercell* boundaries # these will subgraphs representing crystals molecule_subgraphs =", "str (when not using graph_dict). :param index: Index of atom", "f1_comp_dict[node[1][\"specie\"]] = 1 else: f1_comp_dict[node[1][\"specie\"]] += 1 for node in", "import json_graph from scipy.spatial import KDTree from scipy.stats import describe", ") else: rings = self.find_rings(including=[index]) if len(rings) != 0: raise", "Molecule(species, coords, charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) # create new", "of edge weight units e.g. \"Å\" or \"eV\" :return (MoleculeGraph):", "If including is not None, then find_rings will only return", "the index site, and connect the nearest neighbor to the", "neighbors = strategy.get_nn_info(structure, n) for neighbor in neighbors: # all", "sub_mols = list() # Had to use nx.weakly_connected_components because of", "from NetworkX to restore graph information. \"\"\" m = Molecule.from_dict(d[\"molecule\"])", "self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds", "graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Structure.substitute to replace", "from site u to site v # and another form", "constructed manually, see as_dict method for format) \"\"\" if isinstance(molecule,", "monty.os.path import which from networkx.drawing.nx_agraph import write_dot from networkx.readwrite import", "if new_weight is not None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if new_edge_properties", "can help, especially in larger graphs. :param filename: filename to", "`pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore", "in neighbors: # local_env will always try to add two", "connected to nodes on opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) #", "Molecule (and graph) to be removed. :return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices)", "MoleculeGraph will generally produce a different graph compared with using", "defined if \"to_image\" in d: to_image = d[\"to_jimage\"] else: to_image", "in labels] motif = \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return sorted(list(motifs)) def", "in graph \"\"\" return len(self.molecule) def sort(self, key=None, reverse=False): \"\"\"", "and (self.structure == other_sorted.structure) def diff(self, other, strict=True): \"\"\" Compares", "# Had to use nx.weakly_connected_components because of deprecation # of", "= v_present new_d = d.copy() # node now inside supercell", "to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError: raise RuntimeError(\"Some", "old_molecule = self.molecule.copy() # sort Molecule self.molecule._sites = sorted(self.molecule._sites, key=key,", "before attempting to change it if not existing_edges: raise ValueError(", "= extension[1:] write_dot(g, basename + \".dot\") with open(filename, \"w\") as", "new_edge_properties=None): \"\"\" Alters either the weight or the edge_properties of", "as being duplicates. :return: list of unique Molecules in Structure", "nx.simple_cycles(directed) if len(c) > 2] # Using to_directed() will mean", "u, v, data in edges: s += \"{:4} {:4} {:12}\\n\".format(u,", "= edge_props[\"weight\"] del edge_props[\"weight\"] if 0 not in list(graph.graph.nodes()): #", "not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names to graph to", "100 c = max(coords[:, 2]) - min(coords[:, 2]) + 100", "del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) else: if", "coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in graph.edges()]) return new_igraph def", "\"\"\" # ensure that edge exists before attempting to remove", "are essentially list-based, so node indices # must be remapped,", "= list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n, data=True)) for u, v,", "new_graph) edges_to_remove = [] # tuple of (u, v, k)", "now retrieve position of node v in # new supercell,", "atoms in the molecule # in order to be used", "alterations: a dict {(from_index, to_index): alt}, where alt is a", "else: self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node( self, i, species, coords,", ":return: list of ConnectedSite tuples, sorted by closest first \"\"\"", "[c for c in nx.simple_cycles(directed) if len(c) > 2] #", "as isomorphic if edges have the same weights. Typically, this", "= \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s += \"\\nGraph:", "object. \"\"\" nodes = graph.nodes(data=True) new_igraph = igraph.Graph() for node", "at most one edge # between a given (site, jimage)", "= strategy(**strategy_params) for site in mapping.values(): neighbors = strat.get_nn_info(self.structure, site)", "True except ImportError: IGRAPH_AVAILABLE = False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO)", "using graph_dict). :param index: Index of atom to substitute. :param", "d.get(\"to_jimage\", (0, 0, 0))) for u, v, d in self.graph.edges(keys=False,", "to site u: this is # harmless, so warn_duplicates=False sg.add_edge(", "to_jimage: if warn_duplicates: warnings.warn( \"Trying to add an edge that", "sg @property def name(self): \"\"\" :return: Name of graph \"\"\"", "labels for images that are not the origin if image_labels:", "if d[\"to_jimage\"] == (0, 0, 0)] new_periodic_images = [] orig_lattice", "strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self, including=None): \"\"\" Find", "defaultdict, namedtuple from itertools import combinations from operator import itemgetter", "of Structure.substitute to replace an atom in self.structure with a", "- (c[0] * 0.299 + c[1] * 0.587 + c[2]", "subgraphs as isomorphic if edges have the same weights. Typically,", "d in subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie", "add an edge that already exists from \" \"site {}", "periodic crystals. Will only return unique molecules, not any duplicates", "v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True))", "fragments, then this function will fail. Currently, this function naively", "should be None if no additional properties are to be", "sites to be considered equal # this could probably be", "if hide_image_edges: edges_to_delete.append((u, v, k)) # don't show edge directions", "self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\")", "The second atom must be the next nearest atom. For", "generic container for additional edge properties, # similar to site", "superimpose multiple edges). g = self.graph.copy() g.graph = {\"nodesep\": 10.0,", "= self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords,", "to_index) existing_reverse = None if to_jimage is None: raise ValueError(\"Image", "StructureGraph :param strict: if False, will compare bonds from different", "\"\"\" Add edge to graph. Since physically a 'bond' (or", "lattice image the edge belongs to. :param structure: a Structure", "in terms of the StructureGraph this method is called from,", "- min(coords[:, 2]) + 100 structure = molecule.get_boxed_structure(a, b, c,", "from pymatgen.analysis.local_env. :param bond_order: A specified bond order to calculate", "normalize directions of edges edges_to_remove = [] edges_to_add = []", "to_index) existing_reverse = None if existing_edge: self.graph.remove_edge(from_index, to_index) else: if", "# supercell. If it does, the edge is updated. This", "[0, 1, 0], [0, 0, 1] dists = [] for", "of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph \"\"\"", "incorporate the new functional group. NOTE: using a MoleculeGraph will", "= ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight, dist=dist) else: site", "edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing {} edges, adding", ") graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod def", "if weights else None, warn_duplicates=False, ) return sg @property def", "d in self.graph.in_edges(n, data=True)] for u, v, d, dir in", "in func_groups.json. 3. A MoleculeGraph object. :param strategy: Class from", "weight. Props should be None if no additional properties are", "map of nodes from original graph to its image mapping", "is given, this method will fail. :param from_index: int :param", "information, stored in the form of a graph. A \"bond\"", "it does, the edge is updated. This is more #", "in sync with its corresponding Structure. # Broadly, it would", "ever be at most one edge # between a given", "\"\\nStructure: \\n{}\".format(self.structure.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return", "edges for u, v, k, d in g.edges(keys=True, data=True): #", "basename + \".dot\"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate()", "graph can be easier to visualize and reason about. :param", "list of MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original =", "and returns two or more new MoleculeGraph objects. :param bonds:", "connecting from :param to_index: index of site connecting to :param", "will fail. Currently, this function naively assigns the charge of", "return self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self): \"\"\" :return: Units of the", "cycles_nodes: cycles_nodes.append(cycle) for cycle in cycles_nodes: edges = [] for", "from pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk", "nx.weakly_connected_components because of deprecation # of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c)", "of the union) of the sets of edges. This is", "alterations is not None: for (u, v) in alterations.keys(): if", "else: raise ValueError( \"Edge cannot be broken between {} and", "orig_lattice = self.structure.lattice # use k-d tree to match given", "if \"id\" in d: del d[\"id\"] if \"key\" in d:", "in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, allow_reverse=False):", "such, by default, this is None. If weight is to", "sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): \"\"\" Split MoleculeGraph into", "easier to multiply the Structure # *before* generating the StructureGraph,", "Helper function that converts a networkx graph object into an", "to False. :param validate_proximity: For Molecule.insert(); if True (default False),", "d in self.graph.edges(data=True): label = get_label(u, v) types[label].append(d[\"weight\"]) return dict(types)", "j in range(len(self.molecule) - 1): if j < i: mapping[j]", "if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u],", "edges that go through periodic boundaries :param edge_colors (bool): if", "also amends self.graph to incorporate the new functional group. TODO:", "+ offset return grp_map if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp)", "a copy from input graph_data = structure.as_dict()[\"graphs\"] self.structure = structure", "+ str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group(", "= self.graph.get_edge_data(from_index, to_index) if existing_edge_data and warn_duplicates: warnings.warn( \"Trying to", "change it if not existing_edge: raise ValueError( \"Edge between {}", "\"\"\" Returns a named tuple of neighbors of site n:", "leading to incorrect image v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image =", "func_grp should be X-CH3, where X is the first site", "= u new_v = v_present new_d = d.copy() # node", "v, d in self.graph.edges(keys=False, data=True) } edges_other = { (str(other.structure[u].specie),", "get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve subgraphs as molecules, useful for extracting", "mass molecule = molecule.get_centered_molecule() molecules.append(molecule) return molecules class MolGraphSplitError(Exception): \"\"\"", "Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph.", "try to add two edges # for any one bond,", "mapping = {} for i, n in enumerate(nodes): mapping[n] =", ":param node_labels (bool): if True, label nodes with species and", "from/to images, set as origin if not defined if \"to_image\"", "\"{}({})\".format(str(self.structure[n].specie), n) if node_labels else \"\" # use standard color", "v = (u - 1), (v - 1) self.add_edge( mapping[u],", "to_index: int :param allow_reverse: If allow_reverse is True, then break_edge", "try: mapping = {tuple(site.coords): self.molecule.index(site) for site in other.molecule} except", "of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in", "for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) # get", "easier # control over graph appearance and also correctly displays", "module, such as O'Keeffe). This class that contains connection information:", "in nx.simple_cycles(directed) if len(c) > 2] # Using to_directed() will", "site in other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges", "ValueError( \"Chosen strategy is not designed for use with molecules!", "= (0, 0, 0) # set edge style d[\"style\"] =", "present in both. The Jaccard distance is a simple measure", "return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, from_jimage=(0, 0, 0),", "self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d", "example, for a methyl group substitution, func_grp should be X-CH3,", "os.remove(basename + \".dot\") @property def types_and_weights_of_connections(self): \"\"\" Extract a dictionary", "Two StructureGraphs are equal if they have equal Structures, and", "== 0: # this will happen when from_index == to_index,", "# lattice (keeping original lattice has # significant benefits) v_image_frac", "0, 0), to_jimage=to_jimage, to_index=nnsite.index, ) return # sanitize types from_jimage,", "to change it if not existing_edges: raise ValueError( \"Edge between", "v, k, d in g.edges(keys=True, data=True): # retrieve from/to images,", "index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off", "if True, will warn if trying to add duplicate edges", "layers of a 2D crystal) # without adding extra logic", "already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g in", ") sg = StructureGraph.with_empty_graph(structure, name=\"bonds\") for n, neighbors in enumerate(strategy.get_all_nn_info(structure)):", "sort(self, key=None, reverse=False): \"\"\" Same as Molecule.sort(), also remaps nodes", "tidy up edge attr dicts, reading to/from json duplicates #", "over graph appearance and also correctly displays # mutli-graphs (matplotlib", "v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\" Find all", "key: :param reverse: :return: \"\"\" old_structure = self.structure.copy() # sort", "0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError: raise", "self.set_node_attributes() if edges is not None: for edge in edges:", "new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d) return sg def", "will need to have the same bond lengths to be", "an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' \"\"\" all_weights", "try and detect all equivalent images and add multiple #", "in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight = None if", "u, v, d in other_sorted.graph.edges(keys=False, data=True) } else: edges =", "if to_image != (0, 0, 0): d[\"style\"] = \"dashed\" if", "to graph if weight_labels: units = g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"):", "= EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) # get contrasting font color", "tuples\") if props is not None: if \"weight\" in props.keys():", "v, d) in edges_to_add: new_g.add_edge(u, v, **d) # return new", "= {} for node in f1_nodes: if node[1][\"specie\"] not in", "edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in edges.items(): try: from_index =", "1 for node in f2_nodes: if node[1][\"specie\"] not in f2_comp_dict:", "n > neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"] to_index = n else:", "neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors: # local_env will", "v_present[0] <= tol else None if v_present is not None:", "import Lattice, Molecule, PeriodicSite, Structure from pymatgen.core.structure import FunctionalGroups from", "if so, delete old edge that went through # periodic", "site properties (specie, coords, etc.) in the MoleculeGraph. :return: \"\"\"", "if len(alterations[(u, v)]) != 0 else None original.alter_edge(u, v, new_weight=weight,", "for edge in mg.graph.edges: if edge[2] != 0: duplicates.append(edge) for", "1. :param graph_dict: Dictionary representing the bonds of the functional", "in out_edges + in_edges: weight = d.get(\"weight\", None) if v", "= frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes): return False f2_edges =", "EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) # get contrasting font color #", "two edges # for any one bond, one from site", "edge properties to be changed. :return: \"\"\" existing_edges = self.graph.get_edge_data(from_index,", "ValueError( \"Please specify units associated \" \"with your edge weights.", "edge exists before attempting to remove it existing_edge = self.graph.get_edge_data(from_index,", "to_index and from_jimage becomes (0, 0, 0). :param from_index: index", "= self.with_local_env_strategy(func_grp, strat) for (u, v) in list(graph.graph.edges()): edge_props =", "def insert_node( self, i, species, coords, validate_proximity=False, site_properties=None, edges=None, ):", "not None: for (u, v) in alterations.keys(): if \"weight\" in", "size of the union) of the sets of edges. This", "This is more # computationally expensive than just keeping track", "also changes the underlying Molecules. If the bonds parameter does", "structure for these atoms # query returns (distance, index) v_present", "self * (3, 3, 3) # make undirected to find", "new_to_jimage)) logger.debug(\"Removing {} edges, adding {} new edges.\".format(len(edges_to_remove), len(edges_to_add))) #", "in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node] =", "lot of helper methods to make associating a graph with", "including weight. Props should be None if no additional properties", "to_jimage=None, new_weight=None, new_edge_properties=None, ): \"\"\" Alters either the weight or", "dict should at least have a \"to_index\" and \"from_index\" key,", "labels.append((count, sp)) labels = sorted(labels, reverse=True) if anonymous: mapping =", "because of deprecation # of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for", "# a simple Graph (instead of MultiDiGraph), with node indices", "k-d tree to match given position to an # existing", "index site, and connect the nearest neighbor to the C", "StructureGraph with supercell d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__,", "new site into the MoleculeGraph. :param i: Index at which", ") edges_to_delete = [] # add display options for edges", "prop_set.keys(): if prop in properties: properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]]", "s += self._edges_to_string(self.graph) return s def __repr__(self): s = \"Structure", "existing Site in Structure kd_tree = KDTree(new_structure.cart_coords) # tolerance in", "if (new_u, new_v, new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u, new_v, new_d))", "d.get(\"weight\"): d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"], units) # update edge with", "book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data", "new functional group. NOTE: using a MoleculeGraph will generally produce", "for (u, v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if", "(u, v, d) in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self):", "graph to be able to test for isomorphism for subgraph", "an empty list. \"\"\" # Copies self.graph such that all", "(0, 0, 0)): shift = from_jimage from_jimage = np.subtract(from_jimage, shift)", "# Distributed under the terms of the MIT License. \"\"\"", "but making this # assumption simplifies logic later if not", "return dict(types) @property def weight_statistics(self): \"\"\" Extract a statistical summary", "\"\"\" Builds off of Structure.substitute to replace an atom in", "\"dist\": jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve subgraphs as", "strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments", "mg.graph.edges: if edge[2] != 0: duplicates.append(edge) for duplicate in duplicates:", "defined to_image = d[\"to_jimage\"] # set edge style d[\"style\"] =", "of graph, # they're just for book-keeping graph = nx.MultiDiGraph(", "rings including the specified sites. By default, this parameter is", "sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes, key=lambda x: sizes[x])", "!= number of sites in the Structure. This # approach", "= {tuple(site.coords): self.molecule.index(site) for site in other.molecule} except ValueError: return", "Structures, and have the same edges between Sites. Edge weights", "new_d)) else: # want to find new_v such that we", "+ c[1] * 0.587 + c[2] * 0.114) / 255", ":Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance", "if trying to add duplicate edges (duplicate edges will not", "+x direction :param to_jimage (tuple of ints): lattice vector of", "molecule_subgraphs: for n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define", "if new_edge_properties is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop]", "func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off of", "incorporate the new functional group. NOTE: Care must be taken", "len(edges_to_add))) # add/delete marked edges for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove)", "Builds off of Structure.substitute to replace an atom in self.structure", "of two MoleculeGraphs are isomorphic to one another. In order", "import KDTree from scipy.stats import describe from pymatgen.core import Lattice,", "method (using an algorithm provided by the `local_env` module, such", "subgraph). :param use_weights (bool): If True, only treat subgraphs as", "additional graph to compare with, will color edges red that", "tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod def", "Substituent molecule. There are two options: 1. Providing an actual", "terms) including the index found in the Molecule. If there", "in {}.\".format(from_index, to_index, to_jimage) ) return # generic container for", "int(from_index), int(to_index) # check we're not trying to add a", "fail. :param from_index: int :param to_index: int :param to_jimage: tuple", "to match mapping new_graph = nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph,", "Molecule with bond information, stored in the form of a", "on periodic boundaries. In principle, any operations on the expanded", "to :param weight (float): e.g. bond length :param warn_duplicates (bool):", "B, C, etc. :return: a list of co-ordination environments, e.g.", "unique_frag_dict = {} for key in frag_dict: unique_frags = []", "by closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist)", "site u to site v # and another form site", "environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs = set() for idx,", "scale_matrix.shape != (3, 3): scale_matrix = np.array(scale_matrix * np.eye(3), np.int16)", "to be specified. :return: mg, a MoleculeGraph \"\"\" mg =", "\"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name)", "MultiDiGraph), with node indices # representing both site index and", "original site n_u = u % len(self.structure) n_v = v", "== g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\" Helper function that converts a", "to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure = Structure.from_sites(new_sites) #", "edges (duplicate edges will not be added in either case)", "0) if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"]", ":param hide_image_edges: if True, do not draw edges that go", "the form of a graph. A \"bond\" does not necessarily", "\"to_jimage\" in edge_props.keys(): to_jimage = edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else: #", "C, etc. :return: a list of co-ordination environments, e.g. ['Mo-S(6)',", "getattr(self, \"_supercell_sg\", None) is None: self._supercell_sg = supercell_sg = self", "for n in range(len(molecule)): if structure is None: neighbors =", "in self.graph.edges(keys=True, data=True): if \"id\" in d: del d[\"id\"] if", "allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index) else:", "len(v) != len(species): del properties[k] new_mol = Molecule(species, coords, charge=charge,", "be a chemical bond, but can store any kind of", "a \"specie\" and a \"coords\" attribute, updated with the current", "MoleculeGraph object with an empty graph (no edges, only nodes", "for i, properties in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index", "can be confusing due to periodic boundaries if hide_image_edges: for", "# initial version of this class worked even if #", "the new site :param coords_are_cartesian: Whether coordinates are cartesian. Defaults", ":param hide_unconnected_nodes: if True, hide unconnected nodes :param hide_image_edges: if", "\"\"\" return len(self.structure) def sort(self, key=None, reverse=False): \"\"\" Same as", "= {} f2_comp_dict = {} for node in f1_nodes: if", "to visualize and reason about. :param scaling_matrix: same as Structure.__mul__", "by looking for the expected position # of an image", "in d: del d[\"key\"] # ensure images are tuples (conversion", "lattice (keeping original lattice has # significant benefits) v_image_frac =", "correctly displays # mutli-graphs (matplotlib can superimpose multiple edges). g", "EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) # get contrasting font color #", "for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule:", "of weights for those connections (e.g. bond lengths). \"\"\" def", "duplicate edge # there should only ever be at most", "return False return _isomorphic(self.graph, other.graph) def diff(self, other, strict=True): \"\"\"", "hashable/immutable if \"to_jimage\" in d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if \"from_jimage\"", "closest first \"\"\" connected_sites = set() out_edges = list(self.graph.out_edges(n, data=True))", "FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS try:", "to_index, from_index = from_index, to_index to_jimage, from_jimage = from_jimage, to_jimage", "charge if 0 in nodes: charge = self.molecule.charge else: charge", "at least have a \"to_index\" and \"from_index\" key, and can", "sg = StructureGraph.from_dict(d) return sg def __rmul__(self, other): return self.__mul__(other)", "label by species name label = \"{}({})\".format(str(self.structure[n].specie), n) if node_labels", "to graph mapping = {idx: self.molecule.index(site) for idx, site in", "check your\" \" indices.\" ) sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image,", "the underlying Structures are ordered differently. :param other: StructureGraph :param", "hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ):", "edge_properties = edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, weight=weight,", "in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination)", "else: for i in including: for cycle in unique_cycles: if", "image to_jimage = (0, 0, 0) if \"weight\" in edge_props.keys():", "strategy. If None, default parameters will be used. :return: \"\"\"", "new_igraph = igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"])", "+ \"\\n\" + header_line + \"\\n\" edges = list(g.edges(data=True)) #", "d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v, d[\"to_jimage\"]) for", "site connecting to :param from_jimage (tuple of ints): lattice vector", "from :Class: `pymatgen.analysis.local_env`. :param structure: Structure object :param strategy: an", "connected_sites.add(connected_site) # return list sorted by closest sites first connected_sites", "v, d in self.graph.out_edges(n, data=True)] in_edges = [(u, v, d,", "= [] cycles_edges = [] # Remove all two-edge cycles", "its image mapping = {n: n + len(new_sites) for n", "[] for image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist", "so, delete old edge that went through # periodic boundary", "properties, \"properties\") def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): \"\"\" Alters", "replace an atom in self.molecule with a functional group. This", "are hashable/immutable if \"to_jimage\" in d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if", "= edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight,", "could probably be a lot smaller tol = 0.05 for", "frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes): return False f2_edges = frag2.edges()", "# when serializing back from json), it's important images #", "of the new site :param coords_are_cartesian: Whether coordinates are cartesian.", "{} cannot be altered;\\ no edge exists between those sites.\".format(", "# just make a copy from input graph_data = structure.as_dict()[\"graphs\"]", "\"Edge cannot be broken between {} and {};\\ no edge", "of where atoms defined by edge # are expected to", "raise ValueError( \"Edges cannot be added if nodes are not\"", "os.path.splitext(filename) extension = extension[1:] write_dot(g, basename + \".dot\") with open(filename,", "those sites.\".format( from_index, to_index ) ) # Third index should", "weight = edge_props[\"weight\"] del edge_props[\"weight\"] if 0 not in list(graph.graph.nodes()):", "`pymatgen.analysis.local_env`. :param structure: Structure object :param strategy: an instance of", "strategy_params = {} strat = strategy(**strategy_params) for site in mapping.values():", "s = header + \"\\n\" + header_line + \"\\n\" edges", "{} in {}.\".format(from_index, to_index, to_jimage) ) return # generic container", "to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates = [] for edge in", "not count atoms = len(grp) - 1 offset = len(self.molecule)", "perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\" if 1 -", "c_lat: # create a map of nodes from original graph", "def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): \"\"\" Alters either the", "self.graph.edges(keys=False, data=True)} edges_other = { (u, v, d.get(\"to_jimage\", (0, 0,", "__repr__(self): s = \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s", "same edges between Sites. Edge weights can be different and", "new_periodic_images = [] orig_lattice = self.structure.lattice # use k-d tree", "nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for c in", "from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an", "properties = {} for node in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol", "present for all atoms in the molecule # in order", "frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all unique fragments using graph isomorphism", "\"\"\" def get_label(u, v): u_label = self.structure[u].species_string v_label = self.structure[v].species_string", "import which from networkx.drawing.nx_agraph import write_dot from networkx.readwrite import json_graph", "The first atom must be a DummySpecies X, indicating the", ":param n: index of site :return (int): \"\"\" number_of_self_loops =", ") def find_rings(self, including=None): \"\"\" Find ring structures in the", "be a DummySpecies X, indicating the position of nearest neighbor.", "coords) # shift so origin is at center of mass", "extend_structure = strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") #", "ValueError(\"Image must be supplied, to avoid ambiguity.\") if existing_edges: for", "i self.graph.remove_edge(from_index, to_index, edge_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index,", "list sorted by closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda", "k, d in new_g.edges(keys=True, data=True): to_jimage = d[\"to_jimage\"] # for", "outputs :return: \"\"\" if not which(algo): raise RuntimeError(\"StructureGraph graph drawing", "edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: new_g.add_edge(u, v,", "mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self): \"\"\"", ") to_remove = set() sizes = dict() disconnected = self.graph.to_undirected()", "duplicates, otherwise bond lengths can differ. This is a fairly", "must be given as (from_index, to_index)\" \"tuples\") if props is", "func_groups.json. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified", "new_weight if new_edge_properties is not None: for prop in list(new_edge_properties.keys()):", "fragments using graph isomorphism unique_frag_dict = {} for key in", "to extract # molecules (and not, e.g., layers of a", "# in order to be used for Molecule instantiation for", "edges: List of dicts representing edges to be added to", "annotating a Structure with bond information, stored in the form", "describe(all_weights, nan_policy=\"omit\") return { \"all_weights\": all_weights, \"min\": stats.minmax[0], \"max\": stats.minmax[1],", "has been deleted red_edges.append((u, v, k)) elif (u, v, d[\"to_jimage\"])", "_compare(g1, g2, i1, i2): \"\"\" Helper function called by isomorphic", "in self.graph.edges(keys=False, data=True) } edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for", "will compare bonds from different Structures, with node indices replaced", "color # magic numbers account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color", "if (u, v, d[\"to_jimage\"]) in diff[\"self\"]: # edge has been", "# optionally color edges using node colors color_u = g.nodes[u][\"fillcolor\"]", "# narrow to all unique fragments using graph isomorphism unique_frag_dict", "v): props}, where props is a dictionary of properties, including", "= { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g),", "(site, jimage) pair existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for", "if new_v < new_u: new_u, new_v = new_v, new_u edges_inside_supercell.append({new_u,", "d in g.edges(keys=True, data=True): if (u, v, d[\"to_jimage\"]) in diff[\"self\"]:", "sizes = dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index) for neighbor in", "to restore graph information. \"\"\" m = Molecule.from_dict(d[\"molecule\"]) return cls(m,", "bonds before partition, to avoid remapping if alterations is not", ":param new_edge_properties: alter_edge does not require that edge_properties be altered.", "edges are invalid.\") def set_node_attributes(self): \"\"\" Gives each node a", "i # just give charge to whatever subgraph has node", "edge_weight_units: edge_label += \" ({})\".format(edge_weight_units) header += \" {}\".format(edge_label) header_line", "neighbor in neighbors: self.add_edge( from_index=site, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"],", "fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", ) edges_to_delete = [] # add display", "now inside supercell new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v,", "\"---- ---- ------------\" edge_weight_name = g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights =", "frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\" + str(len(unique_mol_graph_list[0].graph.edges())) )", "can be easier to visualize and reason about. :param scaling_matrix:", "d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked", "in self.graph.edges(keys=False, data=True)} edges_other = {(u, v, d[\"to_jimage\"]) for u,", "default parameters will be used. :return: \"\"\" def map_indices(grp): grp_map", "copy from input graph_data = molecule.as_dict()[\"graphs\"] self.molecule = molecule self.graph", "coords, charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) # create new MoleculeGraph", "nx.MultiDiGraph() for new_graph in new_graphs: new_g = nx.union(new_g, new_graph) edges_to_remove", "v, k, d in g.edges(keys=True, data=True): if (u, v, d[\"to_jimage\"])", "# add display options for nodes for n in g.nodes():", "as origin if not defined if \"to_image\" in d: to_image", "present in the graph. :return: A dict with an 'all_weights'", "object :param edges: dict representing the bonds of the functional", "shift = from_jimage from_jimage = np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage,", "not in list(graph.graph.nodes()): # If graph indices have different indexing", "i, properties in existing_reverse.items(): if properties[\"to_jimage\"] == to_jimage: edge_index =", "new_u, new_v = new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d))", "this isn't # possible when generating the graph using critic2", "obtained from the relevant template in func_groups.json. :param strategy: Class", "that from_index < to_index and from_jimage becomes (0, 0, 0).", "not designed for use with molecules! \" \"Please choose another", "edge weights, e.g. \"bond_length\" or \"exchange_constant\" :param edge_weight_units (str): name", "intersects_boundary = any(d[\"to_jimage\"] != (0, 0, 0) for u, v,", "\"\"\" mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props", "to_jimage = np.multiply(-1, to_jimage) to_jimage = tuple(map(int, np.add(to_jimage, jimage))) site_d", "bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self, including=None): \"\"\" Find ring", "subgraphs = [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for subg in", "\"\"\" pass class MoleculeGraph(MSONable): \"\"\" This is a class for", "corresponding Structure. # Broadly, it would be easier to multiply", "delete old edge that went through # periodic boundary if", "in molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for", "its frac_coords as a convenient key try: mapping = {tuple(site.coords):", "g, node_match=node_match, edge_match=edge_match) for g in unique_subgraphs ] if not", "\"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\" # optionally add weights", "new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u, v, k)) if (new_u, new_v, new_to_jimage)", "was also trialed, using # a simple Graph (instead of", "min(coords[:, 1]) + 100 c = max(coords[:, 2]) - min(coords[:,", "neighbors = self.get_connected_sites(index) # If the atom at index is", "but note that this might give misleading results for multigraphs", "be used for Molecule instantiation for k, v in properties.items():", "labels = [(label[0], mapping[label[1]]) for label in labels] labels =", "\"\"\" if self.structure != other.structure and strict: return ValueError(\"Meaningless to", "g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes, # these can appear", "in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is None: cycles_nodes =", "{(u, v): props}, where props is a dictionary of properties,", "Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"]) @classmethod def _edges_to_string(cls, g): header =", "= d[\"to_jimage\"] # set edge style d[\"style\"] = \"solid\" if", ":param to_index: index of site connecting to :param from_jimage (tuple", "directions d[\"arrowhead\"] = \"none\" # only add labels for images", "* 0.114) / 255 < 0.5 else \"#ffffff\" # convert", "and C is the second site. What the code will", "only one MoleculeGraph ('self' and 'other'), and edges that are", "doesn't have a direction, from_index, from_jimage can be swapped with", ":param from_jimage (tuple of ints): lattice vector of periodic image,", "any(d[\"to_jimage\"] != (0, 0, 0) for u, v, d in", "specie names to graph to be able to test for", "\"Cannot split molecule; \\ MoleculeGraph is still connected.\" ) #", "to split the MoleculeGraph. :param alterations: a dict {(from_index, to_index):", "graph but not in the reference graph :param hide_unconnected_nodes: if", "is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop]", "at an atom within a ring\" \"structure.\" ) to_remove =", "\" present in the graph. Please check your\" \" indices.\"", "from json), it's important images # are hashable/immutable if \"to_jimage\"", "strategy is not designed for use with structures! \" \"Please", "nm = iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable):", "for consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for u, v,", "enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def substitute_group(", ":param other: StructureGraph :return (bool): \"\"\" # sort for consistent", "be different and StructureGraphs can still be considered equal. :param", "new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def", "nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts, reading to/from json", ":param strict: if False, will compare bonds from different Structures,", "'dist'. Important note: all node indices are in terms of", "list-based, so node indices # must be remapped, incrementing from", "undirected.to_directed() cycles_nodes = [] cycles_edges = [] # Remove all", "also incorporates the new site into the MoleculeGraph. :param i:", "that all edges (u, v) matched by edges (v, u)", "the crystal (a duplicate defined as an isomorphic subgraph). :param", "else: weight = None nodes = sg.graph.nodes if not (from_index", "0)): shift = from_jimage from_jimage = np.subtract(from_jimage, shift) to_jimage =", "are expected to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac)", "cycles_edges.append(edges) return cycles_edges def get_connected_sites(self, n): \"\"\" Returns a named", "0) for periodic image in +x direction :param to_jimage (tuple", "arbitrary or \" \"dimensionless.\" ) # construct graph with one", "d in new_g.edges(data=True) if d[\"to_jimage\"] == (0, 0, 0)] new_periodic_images", "e2): if use_weights: return e1[\"weight\"] == e2[\"weight\"] return True #", "the StructureGraph this method is called from, not the 'other'", "edge exists between those sites.\".format( from_index, to_index ) ) if", "\"\"\" Constructor for StructureGraph, using a strategy from :Class: `pymatgen.analysis.local_env`.", "not necessarily have to be a chemical bond, but can", "not strategy.molecules_allowed: raise ValueError( \"Chosen strategy is not designed for", "a connection in alphabetical order (e.g. string 'Fe-O') and values", "nx.Graph objects. :param other: MoleculeGraph object to be compared. :return:", "+ \".dot\") with open(filename, \"w\") as f: args = [algo,", "unique_mol_graph_dict def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None,", "None if existing_edge: self.graph.remove_edge(from_index, to_index) else: if allow_reverse: existing_reverse =", "weight = d.get(\"weight\", None) if (v, to_jimage) not in connected_site_images:", "i, properties in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index =", "hide_unconnected_nodes: g = g.subgraph([n for n in g.degree() if g.degree()[n]", "in green_edges: g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"}) for u, v, k", "# *before* generating the StructureGraph, but this isn't # possible", "using graph isomorphism unique_frag_dict = {} for key in frag_dict:", "sync with its corresponding Structure. # Broadly, it would be", "graph_data = structure.as_dict()[\"graphs\"] self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) #", "(0, 0, 0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) #", "same if the underlying Molecules are ordered differently. :param other:", "except with using `to_dict_of_dicts` from NetworkX to store graph information.", "= describe(all_weights, nan_policy=\"omit\") return { \"all_weights\": all_weights, \"min\": stats.minmax[0], \"max\":", "# merge all graphs into one big graph new_g =", "present in only one MoleculeGraph ('self' and 'other'), and edges", "to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def", ":param keep_dot (bool): keep GraphViz .dot file for later visualization", "= np.subtract(v_image_cart, u_cart) # now retrieve position of node v", "new_v, new_d)) # add/delete marked edges for edges_to_remove in edges_to_remove:", "in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to", "from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add", "green that are in diff graph but not in the", "{(u, v) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other", "(tuple of ints): lattice vector of periodic image, e.g. (1,", "to_jimage is None: edge_index = 0 else: for i, properties", "+= self._edges_to_string(self.graph) return s def __repr__(self): s = \"Structure Graph\"", "edges should reflect the MoleculeGraph AFTER the insertion, NOT before.", "edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else:", "the directionality to connect the atoms. 2. A string name.", "edges, # these can be confusing due to periodic boundaries", "u new_v = v_present new_d = d.copy() new_to_jimage = tuple(map(int,", "we must also remove duplicates unique_sorted = [] unique_cycles =", "existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if to_jimage is", "the input. The first atom must be a DummySpecies X,", "to_index, # typically in primitive single-atom lattices images = [1,", "= json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure, edges): \"\"\"", "= { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph),", "new edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked edges for edges_to_remove in", "d[\"style\"] = \"dashed\" if hide_image_edges: edges_to_delete.append((u, v, k)) # don't", "if if is available and networkx if it is not.", "v, **d) def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\"", "k, d in self.graph.edges(keys=True, data=True): if v < u: new_v,", "'minimum', 'maximum', 'median', 'mean', 'std_dev' \"\"\" all_weights = [d.get(\"weight\", None)", "site in enumerate(self.structure): centre_sp = site.species_string connected_sites = self.get_connected_sites(idx) connected_species", "atoms defined # by edge are expected to be, relative", "lattice vector of periodic image, e.g. (1, 0, 0) for", "n, v in self.graph.edges(n) if n == v]) return self.graph.degree(n)", "\"mean\": stats.mean, \"variance\": stats.variance, } def types_of_coordination_environments(self, anonymous=False): \"\"\" Extract", "f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1 else: f1_comp_dict[node[1][\"specie\"]] += 1 for node", "!= other.structure and strict: return ValueError(\"Meaningless to compare StructureGraphs if", "in g.edges(keys=True, data=True): # retrieve from/to images, set as origin", "lie across *supercell* boundaries # these will subgraphs representing crystals", "except ImportError: IGRAPH_AVAILABLE = False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__", "d[\"to_jimage\"]) in diff[\"self\"]: # edge has been deleted red_edges.append((u, v,", "v) in alterations.keys(): if \"weight\" in alterations[(u, v)]: weight =", "def __rmul__(self, other): return self.__mul__(other) @classmethod def _edges_to_string(cls, g): header", "to_index < from_index: to_index, from_index = from_index, to_index # sanitize", "to be (0, 0, 0), # initial version of this", "in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def", "substitute. :param func_grp: Substituent molecule. There are three options: 1.", "np.around to fix issues with finite precision leading to incorrect", "\"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return", "to_index) if existing_edge_data and warn_duplicates: warnings.warn( \"Trying to add an", "then this function will fail. Currently, this function naively assigns", "try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except", "subgraph.nodes()] species = [supercell_sg.structure[n].specie for n in subgraph.nodes()] molecule =", "molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for MoleculeGraph, returns a", "with bond information, stored in the form of a graph.", "} if len(edges) == 0 and len(edges_other) == 0: jaccard_dist", "to be, relative to original # lattice (keeping original lattice", "supercell_sg.graph = nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for", "one another. In order to prevent problems with misdirected edges,", "replace a functional group in self.molecule with a functional group.", "degree of node corresponding to site n. :param n: index", "all graphs into one big graph new_g = nx.MultiDiGraph() for", "mapping[v], weight=weight, edge_properties=edge_props) else: if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp)", "in original site n_u = u % len(self.structure) n_v =", "\".dot\"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode", "combination) if nx.is_connected(subgraph): mykey = mycomp + str(len(subgraph.edges())) if mykey", "jimage, index, weight, dist\") def _compare(g1, g2, i1, i2): \"\"\"", "jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { \"self\":", "del props[\"weight\"] else: weight = None if len(props.items()) == 0:", "\"\"\" connected_sites = set() connected_site_images = set() out_edges = [(u,", "different and StructureGraphs can still be considered equal. :param other:", "atom to substitute. :param func_grp: Substituent molecule. There are two", "edges.items(): try: from_index = edge[0] to_index = edge[1] except TypeError:", ":param from_index: int :param to_index: int :param allow_reverse: If allow_reverse", "amends self.graph to incorporate the new functional group. TODO: Figure", "reverse: :return: \"\"\" old_molecule = self.molecule.copy() # sort Molecule self.molecule._sites", "its corresponding Structure. # Broadly, it would be easier to", "k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked edges for edges_to_remove", "pymatgen.analysis.local_env. :param bond_order: A specified bond order to calculate the", "hide_unconnected_nodes: if True, hide unconnected nodes :param hide_image_edges: if True,", "0: props = None else: weight = None nodes =", ") def remove_nodes(self, indices): \"\"\" A wrapper for Molecule.remove_sites(). :param", "if edge_weight_name: print_weights = [\"weight\"] edge_label = g.graph[\"edge_weight_name\"] edge_weight_units =", "edge_properties=edge.get(\"properties\", None), ) except KeyError: raise RuntimeError(\"Some edges are invalid.\")", "subgraph in molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match)", ":Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights: if True, use weights from", "is failed to split into two disconnected subgraphs \"\"\" pass", "for n in range(len(self.structure))} for idx, site in enumerate(self.structure): s", "exist in diff and edges green that are in diff", "crystallographic structure easier. Use cases for this include storing bonding", "bond indicates the directionality to connect the atoms. 2. A", "Care must be taken to ensure that the functional group", "to_jimage = tuple(map(int, np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict() site_d[\"abc\"] =", "graphs into one big graph new_g = nx.MultiDiGraph() for new_graph", ") ) # Third index should always be 0 because", "rs.returncode)) if not keep_dot: os.remove(basename + \".dot\") def as_dict(self): \"\"\"", "= self.structure[n_u].frac_coords # using the position of node u as", "graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self, including=None): \"\"\" Find ring structures", "for idx, site in enumerate(self.structure): s = PeriodicSite( site.species, site.coords", "cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure, edges): \"\"\" Constructor for MoleculeGraph,", "\"#000000\" if 1 - (c[0] * 0.299 + c[1] *", "are a list of weights for those connections (e.g. bond", "for c in nx.weakly_connected_components(original.graph)] for subg in subgraphs: nodes =", "elif (u, v, d[\"to_jimage\"]) in diff[\"other\"]: # edge has been", "other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d[\"to_jimage\"]) for", "\"trying to automatically detect.\") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist", "index of site connecting to :param from_jimage (tuple of ints):", "nx.get_node_attributes(new_graph, \"coords\") raw_props = nx.get_node_attributes(new_graph, \"properties\") properties = {} for", ":return: mg, a MoleculeGraph \"\"\" mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\",", "= set() out_edges = list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n, data=True))", "@classmethod def _edges_to_string(cls, g): header = \"from to to_image \"", "\" \"Provide explicit coordinate instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping =", "all possible fragments, aka connected induced subgraphs frag_dict = {}", "this parameter is None, and all rings will be returned.", "should stay remain # inside the initial image to_jimage =", "to_jimage) to_jimage = tuple(map(int, np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict() site_d[\"abc\"]", "edges between Sites. Edge weights can be different and StructureGraphs", "name. The molecule will be obtained from the relevant template", "as_dict method for format) \"\"\" if isinstance(structure, StructureGraph): # just", "be v_expec = new_structure[u].coords + v_rel # now search in", "local_env class (consult relevant class for their meaning) :return: \"\"\"", "create a map of nodes from original graph to its", "Will only return unique molecules, not any duplicates present in", "data=True)} return (edges == edges_other) and (self.molecule == other_sorted.molecule) def", "new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing {} edges, adding {} new edges.\".format(len(edges_to_remove),", "edges_to_add: new_g.add_edge(u, v, **d) # return new instance of StructureGraph", "self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node( self, i, species, coords, validate_proximity=False,", "# find new to_jimage # use np.around to fix issues", "insert_node( self, i, species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ):", "v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec)", "properties = {} for prop_set in raw_props.values(): for prop in", "green_edges.append((u, v, k)) for u, v, k in green_edges: g.edges[u,", "is no guarantee the node indices will be the same", "data=True)] in_edges = [(u, v, d, \"in\") for u, v,", "narrow to all unique fragments using graph isomorphism unique_frag_dict =", "# for any one bond, one from site u to", "props = None else: weight = None nodes = sg.graph.nodes", "a dictionary of properties, including weight. Props should be None", "Heisenberg exchange parameters, etc. For periodic graphs, class stores information", "is None): raise ValueError( \"Please specify units associated \" \"with", "- v_expec_image % 1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec =", "mapping[label[1]]) for label in labels] labels = [\"{}({})\".format(label[1], label[0]) for", "+ 100 structure = molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False) else:", "Site in Structure kd_tree = KDTree(new_structure.cart_coords) # tolerance in Å", "0: jaccard_dist = 0 # by definition else: jaccard_dist =", "( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), ) from_index, to_index = int(from_index),", "self, i, species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ): \"\"\"", "Sites. \"\"\" def __init__(self, molecule, graph_data=None): \"\"\" If constructing this", "nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return", "changed, it should be a float. :param new_edge_properties: alter_edge does", "A dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean',", "Gives each node a \"specie\" and a \"coords\" attribute, updated", "0))), data.get(\"weight\", 0) ) else: for u, v, data in", "isn't # possible when generating the graph using critic2 from", "% len(self.structure) # get fractional co-ordinates of where atoms defined", "a larger graph can be easier to visualize and reason", "__status__ = \"Production\" __date__ = \"August 2017\" ConnectedSite = namedtuple(\"ConnectedSite\",", "subprocess import warnings from collections import defaultdict, namedtuple from itertools", "graph_dict: Dictionary representing the bonds of the functional group (format:", "one edge between any two nodes if new_weight is not", "about. :param scaling_matrix: same as Structure.__mul__ :return: \"\"\" # Developer", "\"\"\" As in :Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts`", "any kind of information that connects two Sites. \"\"\" def", "if 0 not in list(graph.graph.nodes()): # If graph indices have", "is defined by 1 - (size of the intersection /", "compare with, will color edges red that do not exist", "0, 0)))) return s def __str__(self): s = \"Molecule Graph\"", "\"\"\" :return: Name of graph \"\"\" return self.graph.graph[\"name\"] @property def", "and a \"properties\" key. :return: \"\"\" self.structure.insert( i, species, coords,", ") except KeyError: raise RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self):", "(bool): if True, label edges with their periodic images (usually", "duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg @property", "== e2[\"weight\"] return True # prune duplicate subgraphs unique_subgraphs =", "\"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__str__()) s += \"\\nGraph: {}\\n\".format(self.name)", "def __init__(self, molecule, graph_data=None): \"\"\" If constructing this class manually,", "\"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" __date__ = \"August", "copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError(\"Can't", "original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\" Find all possible fragment combinations of", "= None else: weight = None nodes = sg.graph.nodes if", "MoleculeGraph. :param from_index: int :param to_index: int :param new_weight: alter_edge", "\"\"\" if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols =", "= edge[1] except TypeError: raise ValueError(\"Edges must be given as", "enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors: # local_env will always try", "cannot be altered;\\ no edge exists between those sites.\".format( from_index,", "actually figure out how to distribute charge if 0 in", "= nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of edges edges_to_remove", "def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): \"\"\" Remove an edge", "to test for isomorphism for subgraph in molecule_subgraphs: for n", "len(neighbors) == 1: self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params,", "relative_jimage = np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight =", "g.edges(keys=True, data=True): # retrieve from/to images, set as origin if", "u, v, k, d in self.graph.edges(keys=True, data=True): if v <", "= [] unique_cycles = [] for cycle in all_cycles: if", "s def __str__(self): s = \"Molecule Graph\" s += \"\\nMolecule:", "centre_sp = \"A\" labels = [(label[0], mapping[label[1]]) for label in", ":param new_weight: alter_edge does not require that weight be altered.", "i, n in enumerate(nodes): mapping[n] = i # just give", "definition else: jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return", "dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index) for neighbor in neighbors: sizes[neighbor[2]]", "nodes = mg.graph.nodes if not (from_index in nodes and to_index", "if \"weight\" in props.keys(): weight = props[\"weight\"] del props[\"weight\"] else:", "of ints): lattice vector of image :param weight (float): e.g.", "bonds of the functional group (format: {(from_index, to_index, from_image, to_image):", "# these will subgraphs representing crystals molecule_subgraphs = [] for", "isomorphism def node_match(n1, n2): return n1[\"specie\"] == n2[\"specie\"] def edge_match(e1,", "graph to match mapping new_graph = nx.relabel_nodes(subg, mapping) species =", "= max(coords[:, 0]) - min(coords[:, 0]) + 100 b =", "\" \"Please choose another strategy.\" ) extend_structure = strategy.extend_structure_molecules mg", "assigns the charge of the total molecule to a single", "if i in cycle and cycle not in cycles_nodes: cycles_nodes.append(cycle)", "\"\"\" all_weights = [d.get(\"weight\", None) for u, v, d in", "data=True)) in_edges = list(self.graph.in_edges(n, data=True)) for u, v, d in", "be \" \"empty string if arbitrary or \" \"dimensionless.\" )", "boundaries if hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally", "header_line += \" {}\".format(\"-\" * max([18, len(edge_label)])) else: print_weights =", "means molecules will need to have the same bond lengths", "e2[\"weight\"] return True # prune duplicate subgraphs unique_subgraphs = []", "updated. This is more # computationally expensive than just keeping", "strategy from :Class: `pymatgen.analysis.local_env`. :param structure: Structure object :param strategy:", "find new to_jimage # use np.around to fix issues with", "= connected_species.count(sp) labels.append((count, sp)) labels = sorted(labels, reverse=True) if anonymous:", "0.114) / 255 < 0.5 else \"#ffffff\" # convert color", "in combinations(graph.nodes, ii): mycomp = [] for idx in combination:", "If None, default parameters will be used. :return: \"\"\" self.set_node_attributes()", "graph terms, simply returns degree of node corresponding to site", "new_g.edges(data=True) if d[\"to_jimage\"] == (0, 0, 0)] new_periodic_images = []", "= defaultdict(list) for u, v, d in self.graph.edges(data=True): label =", "# Developer note: NetworkX also has methods for drawing #", "warn_duplicates=False, ) def get_connected_sites(self, n, jimage=(0, 0, 0)): \"\"\" Returns", "new lattice images present, but should hopefully be # easier", "hex string color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color,", "other.graph) def diff(self, other, strict=True): \"\"\" Compares two MoleculeGraphs. Returns", "# between a given (site, jimage) pair and another #", "sites. By default, this parameter is None, and all rings", "f2_comp_dict[node[1][\"specie\"]] = 1 else: f2_comp_dict[node[1][\"specie\"]] += 1 if f1_comp_dict !=", "information that connects two Sites. \"\"\" def __init__(self, molecule, graph_data=None):", "except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph", "use nx.weakly_connected_components because of deprecation # of nx.weakly_connected_component_subgraphs subgraphs =", "for these atoms # query returns (distance, index) v_present =", "edge_label = g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label +=", "indices are essentially list-based, so node indices # must be", "to be unambiguous, \" \"trying to automatically detect.\") dist, to_jimage", "by the `local_env` module, such as O'Keeffe). This class that", "index of the new site i, and all indices used", "parameters will be used. :return: \"\"\" self.set_node_attributes() neighbors = self.get_connected_sites(index)", "properties edge_properties = edge_properties or {} if weight: self.graph.add_edge(from_index, to_index,", "_isomorphic(frag1, frag2): \"\"\" Internal function to check if two graph", "empty graph (no edges, only nodes defined that correspond to", "our new style attributes g.edges[u, v, k].update(d) # optionally remove", "sg, a StructureGraph \"\"\" sg = StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\")", "stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode != 0: raise RuntimeError(\"{} exited", "[chr(66 + i) for i in range(25)] for label in", "v, d in other.graph.edges(keys=False, data=True) } if len(edges) == 0", "props in edges.items(): try: from_index = edge[0] to_index = edge[1]", "it if not existing_edges: raise ValueError( \"Edge between {} and", "if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot split molecule; \\ MoleculeGraph is", "at which to insert the new site :param species: Species", "edges, ) ) frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\"", "= self.structure.lattice # use k-d tree to match given position", "convert back to molecule graphs unique_mol_graph_dict = {} for key", "and cycle not in cycles_nodes: cycles_nodes.append(cycle) for cycle in cycles_nodes:", "name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for MoleculeGraph, returns a MoleculeGraph", "graph edges of what lattice image the edge belongs to.", "\"other\": edges_other - edges, \"both\": edges.intersection(edges_other), \"dist\": jaccard_dist, } def", "not count number of occurrences of bonds :return: \"\"\" if", "strategy(**strategy_params) for site in mapping.values(): neighbors = strat.get_nn_info(self.structure, site) for", "range(atoms): grp_map[i] = i + offset return grp_map if isinstance(func_grp,", "strategy_params is None: strategy_params = {} strat = strategy(**strategy_params) for", "edge in graph.edges()]) return new_igraph def _isomorphic(frag1, frag2): \"\"\" Internal", "if True, use weights from local_env class (consult relevant class", "edge_weight_name: print_weights = [\"weight\"] edge_label = g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"]", "diff and edges green that are in diff graph but", "\"\"\" Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a", "\"fdp\" (for more crowded graphs) usually give good outputs :return:", "MSONable from monty.os.path import which from networkx.drawing.nx_agraph import write_dot from", "neighbors = strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure, n) for", "v_present = v_present[1] if v_present[0] <= tol else None if", "by edge # are expected to be v_expec = new_structure[u].coords", "coordinates of the new site :param coords_are_cartesian: Whether coordinates are", "should not cross # (artificial) periodic boundaries if not np.array_equal(neighbor[\"image\"],", "= self.structure.copy() # sort Structure self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse)", "edge_properties = alterations[(u, v)] if len(alterations[(u, v)]) != 0 else", "nodes defined that correspond to Sites in Structure). :param structure", "be boxed first coords = molecule.cart_coords if extend_structure: a =", "all edges (u, v) matched by edges (v, u) undirected", "\"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name)", "# are hashable/immutable if \"to_jimage\" in d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"])", "converted into undirected nx.Graph objects. :param other: MoleculeGraph object to", "length of Structure / number of nodes in graph \"\"\"", "then find_rings will only return those rings including the specified", "node indices # must be remapped, incrementing from 0 mapping", "= len(grp) - 1 offset = len(self.molecule) - atoms for", ":return: \"\"\" if self.structure != other.structure and strict: return ValueError(\"Meaningless", "\"\"\" old_structure = self.structure.copy() # sort Structure self.structure._sites = sorted(self.structure._sites,", "v, d[\"to_jimage\"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return", "Molecule.substitute to replace an atom in self.molecule with a functional", "list of indices in the current Molecule (and graph) to", "raise RuntimeError(\"Can't find functional group in list. \" \"Provide explicit", "for u, v, d in self.graph.edges(data=True): label = get_label(u, v)", "matplotlib, these also work here. However, # a dedicated tool", "= self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties,", "key=duplicate[2]) mg.set_node_attributes() return mg @property def name(self): \"\"\" :return: Name", "existing_reverse = None if to_jimage is None: raise ValueError(\"Image must", "Constructor for StructureGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param", "image, e.g. (1, 0, 0) for periodic image in +x", "of where atoms defined # by edge are expected to", "the edge_properties of an edge in the StructureGraph. :param from_index:", "for edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None),", "\"\"\" if self.molecule != other.molecule and strict: return ValueError(\"Meaningless to", "\"<NAME>, <NAME>, <NAME>\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__", "edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ): \"\"\" Draws", "algorithm will attempt to automatically determine bonds using one of", "side of supercell # are connected to nodes on opposite", "current Molecule (and graph) to be removed. :return: \"\"\" self.structure.remove_sites(indices)", "in new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing {}", "len(other.graph.edges()): return False return _isomorphic(self.graph, other.graph) def diff(self, other, strict=True):", "mapping.values(): neighbors = strat.get_nn_info(self.structure, site) for neighbor in neighbors: self.add_edge(", "attribute, updated with the current species and coordinates. :return: \"\"\"", "changed. :return: \"\"\" existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure that", "if not defined. :param n: index of Site in Structure", "if len(v) != len(species): del properties[k] new_mol = Molecule(species, coords,", "of the new site :param validate_proximity: For Molecule.insert(); if True", "that, will attempt to break (to_index, from_index). :return: list of", "other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u,", "'bond' (or other connection between sites) doesn't have a direction,", "= copy.deepcopy(unique_frags) # convert back to molecule graphs unique_mol_graph_dict =", "properties to be changed. :return: \"\"\" existing_edges = self.graph.get_edge_data(from_index, to_index)", "= available_letters.pop(0) centre_sp = \"A\" labels = [(label[0], mapping[label[1]]) for", "isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp])", "networkx.readwrite import json_graph from scipy.spatial import KDTree from scipy.stats import", "n) else: neighbors = strategy.get_nn_info(structure, n) for neighbor in neighbors:", "A later effort will be to actually accurately assign charge.", "be considered equal. :param other: StructureGraph :return (bool): \"\"\" #", "multiple # edges if appropriate if to_jimage is None: #", "0 in nodes: charge = self.molecule.charge else: charge = 0", "Extract information on the different co-ordination environments present in the", "= MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor classes only (generally)", "c = max(coords[:, 2]) - min(coords[:, 2]) + 100 structure", "only nodes defined that correspond to Sites in Molecule). :param", "unique_cycles: if i in cycle and cycle not in cycles_nodes:", "= new_weight if new_edge_properties is not None: for prop in", "None if len(props.items()) == 0: props = None else: weight", "of nearest neighbor. The second atom must be the next", "mapping = {centre_sp: \"A\"} available_letters = [chr(66 + i) for", "also amends self.graph to incorporate the new functional group. NOTE:", "nearest neighbor to the C atom in CH3. The X-C", "subgraph in all_subgraphs: intersects_boundary = any(d[\"to_jimage\"] != (0, 0, 0)", "= \"{}({})\".format(str(self.molecule[n].specie), n) if node_labels else \"\" # use standard", "g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors", "reverse: :return: \"\"\" old_structure = self.structure.copy() # sort Structure self.structure._sites", "\"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current in", "graph attributes don't change behavior of graph, # they're just", "images that are not the origin if image_labels: d[\"headlabel\"] =", "= [] for image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] )", "ValueError( \"Edges cannot be added if nodes are not\" \"", "{idx: self.molecule.index(site) for idx, site in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph,", "If weight is to be changed, it should be a", "index) v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <=", "there should only ever be at most one edge #", "[] for subgraph in unique_subgraphs: coords = [supercell_sg.structure[n].coords for n", "graph_dict is not None: for (u, v) in graph_dict.keys(): edge_props", "{} and {};\\ no edge exists between those sites.\".format( from_index,", "object into an igraph graph object. \"\"\" nodes = graph.nodes(data=True)", "Developer note: NetworkX also has methods for drawing # graphs", "possible when generating the graph using critic2 from # charge", "if new_edge_properties is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop]", "- edges, \"both\": edges.intersection(edges_other), \"dist\": jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False):", "in the graph. Please check your\" \" indices.\" ) sg.add_edge(", "detect.\") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0: #", "of atom to substitute. :param func_grp: Substituent molecule. There are", "keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params,", "{(from_index, to_index): alt}, where alt is a dictionary including weight", "anonymous: if anonymous, will replace specie names with A, B,", "1], e)) cycles_edges.append(edges) return cycles_edges def get_connected_sites(self, n): \"\"\" Returns", "exchange parameters, etc. For periodic graphs, class stores information on", ") return sg @property def name(self): \"\"\" :return: Name of", "will be used. :return: \"\"\" def map_indices(grp): grp_map = {}", ":param molecule: Molecule object :param edges: dict representing the bonds", "# Third index should always be 0 because there should", "happens # when serializing back from json), it's important images", "with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for StructureGraph, returns", "to_jimage is None: raise ValueError(\"Image must be supplied, to avoid", "original structure, weight can be None if not defined. :param", "import networkx.algorithms.isomorphism as iso import numpy as np from monty.json", "networkx if it is not. \"\"\" f1_nodes = frag1.nodes(data=True) f2_nodes", "an edge from the MoleculeGraph :param from_index: int :param to_index:", "the functional group (format: {(u, v): props}, where props is", "def get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve subgraphs as molecules, useful for", "not the origin if image_labels: d[\"headlabel\"] = \"\" if to_image", "if structure is None: neighbors = strategy.get_nn_info(molecule, n) else: neighbors", "graph to its image mapping = {n: n + len(new_sites)", "v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present = v_present[1] if", "in edges.items(): try: from_index = edge[0] to_index = edge[1] from_image", "% 1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present", "to one another. In order to prevent problems with misdirected", "Third index should always be 0 because there should only", "isomorphic if edges have the same weights. Typically, this means", "edges, adding {} new edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked edges", "find_rings(self, including=None): \"\"\" Find ring structures in the MoleculeGraph. :param", "a 2D crystal) # without adding extra logic if getattr(self,", "MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters.", "get_connected_sites(self, n): \"\"\" Returns a named tuple of neighbors of", "== v]) return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self, filename=\"graph\",", "d @classmethod def from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Structure`", "close_fds=True) rs.communicate() if rs.returncode != 0: raise RuntimeError(\"{} exited with", "structure is None: neighbors = strategy.get_nn_info(molecule, n) else: neighbors =", "v, k)) # don't show edge directions d[\"arrowhead\"] = \"none\"", "int :param new_weight: alter_edge does not require that weight be", "= nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped, \"specie\") coords = nx.get_node_attributes(remapped,", "= g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights = [\"weight\"] edge_label = g.graph[\"edge_weight_name\"]", "be in the path.\") # Developer note: NetworkX also has", "(and graph) to be removed. :return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping", "is True, then break_edge will attempt to break both (from_index,", "v, k)) if (new_u, new_v, new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u,", "edge_properties be altered. As such, by default, this is None.", "weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties) def", "def find_rings(self, including=None): \"\"\" Find ring structures in the MoleculeGraph.", "v, d, dir in out_edges + in_edges: to_jimage = d[\"to_jimage\"]", "duplicate edges # will remove two edges for everyone one", "strat.get_nn_info(self.structure, site) for neighbor in neighbors: self.add_edge( from_index=site, from_jimage=(0, 0,", "attempting to change it if not existing_edges: raise ValueError( \"Edge", "inside supercell # for duplicate checking edges_inside_supercell = [{u, v}", "to work, but # just makes it neater if to_index", "new_d)) # add/delete marked edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove)", "v, k, d in self.graph.edges(keys=True, data=True): if \"id\" in d:", "unique Molecules in Structure \"\"\" # creating a supercell is", "{};\\ no edge exists between those sites.\".format( from_index, to_index )", "need to have the same bond lengths to be defined", "usually give good outputs :return: \"\"\" if not which(algo): raise", "with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for MoleculeGraph, returns", "= {} for key in unique_frag_dict: unique_mol_graph_list = [] for", "be constructed manually, see as_dict method for format) \"\"\" if", "d[\"to_jimage\"] # for node v # reduce unnecessary checking if", "+ \".dot\") def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Molecule` except", "that connects two Sites. \"\"\" def __init__(self, molecule, graph_data=None): \"\"\"", "copy=True) # normalize directions of edges edges_to_remove = [] edges_to_add", "mapping, copy=True)) new_structure = Structure.from_sites(new_sites) # merge all graphs into", "\"<EMAIL>\" __status__ = \"Production\" __date__ = \"August 2017\" ConnectedSite =", "d[\"to_jimage\"] else: to_image = (0, 0, 0) # set edge", "edges that are present in both. The Jaccard distance is", "v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present = v_present[1]", "style attributes g.edges[u, v, k].update(d) # optionally remove periodic image", "Broadly, it would be easier to multiply the Structure #", "return s def __str__(self): s = \"Molecule Graph\" s +=", "= d[\"to_jimage\"] else: to_image = (0, 0, 0) # set", "v, k].update({\"color_uv\": \"#ff0000\"}) basename, extension = os.path.splitext(filename) extension = extension[1:]", "for subgraph in all_subgraphs: intersects_boundary = any(d[\"to_jimage\"] != (0, 0,", "or {} if weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index,", "self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes = [] cycles_edges = []", "and also correctly displays # mutli-graphs (matplotlib can superimpose multiple", "for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges ==", "= neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates =", "separate two molecule fragments, then this function will fail. Currently,", "arguments for strategy. If None, default parameters will be used.", "index, weight. Index is the index of the corresponding site", "the MoleculeGraph is connected. If it is not, separate the", "= u % len(self.structure) n_v = v % len(self.structure) #", "logic if getattr(self, \"_supercell_sg\", None) is None: self._supercell_sg = supercell_sg", "information, but also changes the underlying Molecules. If the bonds", "self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts, reading", "\"\"\" Returns the number of neighbors of site n. In", "if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names to graph", "{} f2_comp_dict = {} for node in f1_nodes: if node[1][\"specie\"]", "# list of new edges inside supercell # for duplicate", "0 and len(edges_other) == 0: jaccard_dist = 0 # by", "(from_index, to_index) representing bonds to be broken to split the", "Please check your\" \" indices.\" ) sg.add_edge( from_index, to_index, from_jimage=from_image,", "0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights else None, warn_duplicates=False, )", "in the molecule # in order to be used for", "the `local_env` module, such as O'Keeffe). This class that contains", "new_v, new_u new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u,", "if no additional properties are to be specified. :return: mg,", "mapping[tuple(site.frac_coords)]) edges = {(u, v, d[\"to_jimage\"]) for u, v, d", "J-couplings, Heisenberg exchange parameters, etc. :param molecule: Molecule object :param", "new_d = u, v, d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u,", "charge density. # Multiplication works by looking for the expected", "self.graph.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: self.graph.add_edge(u, v, **d)", "incorrect image v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image -", "insert the new site :param species: Species for the new", "a \"weight\" and a \"properties\" key. :return: \"\"\" self.structure.insert( i,", "isinstance(molecule, MoleculeGraph): # just make a copy from input graph_data", "def add_edge( self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None,", "else: neighbors = strategy.get_nn_info(structure, n) for neighbor in neighbors: #", "connected_sites] labels = [] for sp in set(connected_species): count =", "StructureGraph.with_empty_graph(structure, name=\"bonds\") for n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor in", "v, k) edges_to_add = [] # tuple of (u, v,", "are to be specified. :return: sg, a StructureGraph \"\"\" sg", "sorted by closest first \"\"\" connected_sites = set() connected_site_images =", "site index and periodic image. Here, the # number of", "np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index, ) return", "= logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = \"<NAME>, <NAME>, <NAME>\" __version__ =", "in range(len(self.molecule) - 1): if j < i: mapping[j] =", "in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i if", "a single submolecule. A later effort will be to actually", "in range(len(molecule)): if structure is None: neighbors = strategy.get_nn_info(molecule, n)", "if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges()) != len(other.graph.edges()):", "new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v, k)) # make", "* (3, 3, 3) # make undirected to find connected", "sure we don't try to add duplicate edges # will", "self.graph.edges(data=True)] stats = describe(all_weights, nan_policy=\"omit\") return { \"all_weights\": all_weights, \"min\":", "manually, see as_dict method for format) \"\"\" if isinstance(molecule, MoleculeGraph):", "raise ValueError(\"Edges must be given as (from_index, to_index,\" \" from_image,", "compared with using a Molecule or str (when not using", "json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls, d): \"\"\" As", "indices will be the same if the underlying Molecules are", "0) else \"to {}\".format((to_image)) d[\"arrowhead\"] = \"normal\" if d[\"headlabel\"] else", "__author__ = \"<NAME>, <NAME>, <NAME>\" __version__ = \"0.1\" __maintainer__ =", "v_present is not None: new_u = u new_v = v_present", "with 3x3 scaling matrices yet.\") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat", "inside the initial image to_jimage = (0, 0, 0) if", "easier to extend to a general 3x3 scaling matrix. #", "attributes don't change behavior of graph, # they're just for", "highlight differences with another graph if diff: diff = self.diff(diff,", "graph, e.g. \"bonds\" :param edge_weight_name (str): name of edge weights,", "data=True): if (u, v, d[\"to_jimage\"]) in diff[\"self\"]: # edge has", "extension, basename + \".dot\"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True)", "grp_map[i] = i + offset return grp_map if isinstance(func_grp, Molecule):", "for debugging, edges to periodic images always appear as dashed", "MoleculeGraphs are equal if they have equal Molecules, and have", "from different Structures, with node indices replaced by Species strings,", "- atoms for i in range(atoms): grp_map[i] = i +", "self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist * 0.01, include_index=True ) for nnsite", "g.degree() if g.degree()[n] != 0]) # optionally highlight differences with", "including=None): \"\"\" Find ring structures in the MoleculeGraph. :param including:", "can be different and MoleculeGraphs can still be considered equal.", "for consistent node indices # PeriodicSite should have a proper", "the underlying Molecules. If the bonds parameter does not include", "= u, v, d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v,", "`pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph \"\"\" if not strategy.molecules_allowed:", "new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False,", "edge_properties (dict): any other information to store on graph edges,", "data=True): if v < u: new_v, new_u, new_d = u,", "= list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites def get_coordination_of_site(self, n):", "in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1 else: f1_comp_dict[node[1][\"specie\"]] += 1 for", "frac_coords as a convenient key try: mapping = {tuple(site.coords): self.molecule.index(site)", "existing_edge_data: for key, d in existing_edge_data.items(): if d[\"to_jimage\"] == to_jimage:", "an isomorphic subgraph). :param use_weights (bool): If True, only treat", "are present in only one StructureGraph ('self' and 'other'), and", "= [supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)] # discount subgraphs that", "on the graph itself, but contains a lot of helper", "sites.\".format( from_index, to_index ) ) def remove_nodes(self, indices): \"\"\" A", "or \"JMOL\" :param keep_dot (bool): keep GraphViz .dot file for", "the union) of the sets of edges. This is returned", "= len(self.molecule) - atoms for i in range(atoms): grp_map[i] =", "= self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes = [] cycles_edges =", "to compare with, will color edges red that do not", ":return: \"\"\" if self.molecule != other.molecule and strict: return ValueError(\"Meaningless", "new site i, and all indices used for these edges", "should be a float. :param new_edge_properties: alter_edge does not require", "\"\"\" sg = StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props", "altered. As such, by default, this is None. If weight", "intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names to graph to be", "sorted by closest first \"\"\" connected_sites = set() out_edges =", "not draw edges that go through periodic boundaries :param edge_colors", "fix issues with finite precision leading to incorrect image v_expec_image", "new_edge_properties[prop] def break_edge(self, from_index, to_index, allow_reverse=False): \"\"\" Remove an edge", "with a given crystallographic structure easier. Use cases for this", "= Molecule(species, coords) # shift so origin is at center", "graph \"\"\" return self.graph.graph[\"name\"] @property def edge_weight_name(self): \"\"\" :return: Name", "vector of periodic image, e.g. (1, 0, 0) for periodic", "to_image == (0, 0, 0) else \"to {}\".format((to_image)) d[\"arrowhead\"] =", "coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge( self, from_index, to_index,", "new_weight=None, new_edge_properties=None): \"\"\" Alters either the weight or the edge_properties", "label edges with weights :param image_labels (bool): if True, label", "to check if two graph objects are isomorphic, using igraph", "other: StructureGraph :return (bool): \"\"\" # sort for consistent node", "header_line + \"\\n\" edges = list(g.edges(data=True)) # sort edges for", "None if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"]", "has methods for drawing # graphs using matplotlib, these also", "is a fairly robust approach, but will treat e.g. enantiomers", "associated structure object. This class uses the NetworkX package to", "__init__(self, molecule, graph_data=None): \"\"\" If constructing this class manually, use", "to_image = edge[3] except TypeError: raise ValueError(\"Edges must be given", "in graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"weight\" in edge_props.keys():", "return s def __len__(self): \"\"\" :return: length of Molecule /", "require that weight be altered. As such, by default, this", "for nodes for n in g.nodes(): # get label by", "\"properties\" key. :return: \"\"\" self.molecule.insert( i, species, coords, validate_proximity=validate_proximity, properties=site_properties,", "be confusing due to periodic boundaries if hide_image_edges: for edge_to_delete", "node with index 0 # TODO: actually figure out how", ") # alter any bonds before partition, to avoid remapping", "that each cycle always appears twice # So, we must", "\"weight\" and a \"properties\" key. :return: \"\"\" self.molecule.insert( i, species,", "\"\"\" Checks if the graphs of two MoleculeGraphs are isomorphic", "atoms # query returns (distance, index) v_present = kd_tree.query(v_expec) v_present", "False f2_edges = frag2.edges() if len(f2_edges) != len(f2_edges): return False", "def get_coordination_of_site(self, n): \"\"\" Returns the number of neighbors of", "if mykey not in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph))", "if n > neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"] to_index = n", "{e: i for i, e in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment,", "extension (any graphviz filetype supported, such as pdf or png)", "sites in the Structure. This # approach has many benefits,", "\"JMOL\" :param keep_dot (bool): keep GraphViz .dot file for later", "of bonds. This function uses MoleculeGraph.break_edge repeatedly to create disjoint", "another # (site, jimage) pair existing_edge_data = self.graph.get_edge_data(from_index, to_index) if", "= new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage # use np.around to", "= structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr", "except Exception: raise RuntimeError(\"Can't find functional group in list. \"", "for k, v in properties.items(): if len(v) != len(species): del", "not defined. :param n: index of Site in Molecule :param", "is not None: self.graph[from_index][to_index][0][\"weight\"] = new_weight if new_edge_properties is not", "return len(self.molecule) def sort(self, key=None, reverse=False): \"\"\" Same as Molecule.sort(),", "anonymous, will replace specie names with A, B, C, etc.", "an edge from the StructureGraph. If no image is given,", "\"structure.\" ) to_remove = set() sizes = dict() disconnected =", "Molecule (and graph) to be removed. :return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices)", "correspond to Sites in Structure). :param structure (Structure): :param name", "(edges are super-imposed on each other). If visualization is difficult", "if False, will compare bonds from different Molecules, with node", "unique molecules, not any duplicates present in the crystal (a", "stats.minmax[1], \"mean\": stats.mean, \"variance\": stats.variance, } def types_of_coordination_environments(self, anonymous=False): \"\"\"", "connected_sites = self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for connected_site in connected_sites]", "of (u, v, k) edges_to_add = [] # tuple of", "edge that already exists from \" \"site {} to site", "the MoleculeGraphs (in other words, all connected induced subgraphs) :return:", "using `to_dict_of_dicts` from NetworkX to store graph information. \"\"\" d", "tree to match given position to an # existing Site", "if edge_colors else \"#000000\" # optionally add weights to graph", "Site in Molecule :param jimage: lattice vector of site :return:", "dict(types) @property def weight_statistics(self): \"\"\" Extract a statistical summary of", "\"eV\" :return (StructureGraph): \"\"\" if edge_weight_name and (edge_weight_units is None):", "general 3x3 scaling matrix. # code adapted from Structure.__mul__ scale_matrix", "remaps nodes in graph. :param key: :param reverse: :return: \"\"\"", ":param use_weights (bool): If True, only treat subgraphs as isomorphic", "molecule: Molecule object :param strategy: an instance of a :Class:", "self.graph.get_edge_data(from_index, to_index) existing_reverse = None if existing_edge: self.graph.remove_edge(from_index, to_index) else:", "user doesn't specify # will try and detect all equivalent", "where props is a dictionary of properties, including weight. If", "are isomorphic, using igraph if if is available and networkx", "unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group( self, index, func_grp,", "MIT License. \"\"\" Module for graph representations of crystals. \"\"\"", "significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords #", "optionally hide unconnected nodes, # these can appear when removing", "and networkx if it is not. \"\"\" f1_nodes = frag1.nodes(data=True)", "# add specie names to graph to be able to", "version of this class worked even if # from_jimage !=", "to_index = n else: from_index = n to_index = neighbor[\"site_index\"]", "keep_dot (bool): keep GraphViz .dot file for later visualization :param", "labels = sorted(labels, reverse=True) if anonymous: mapping = {centre_sp: \"A\"}", "# just makes it neater if to_index < from_index: to_index,", "species[node] = self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph,", "{tuple(site.frac_coords): self.structure.index(site) for site in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda", "self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties)", "to_image): props}, where props is a dictionary of properties, including", "If visualization is difficult to interpret, `hide_image_edges` can help, especially", "get_connected_sites(self, n, jimage=(0, 0, 0)): \"\"\" Returns a named tuple", "hopefully be # easier to extend to a general 3x3", "to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, ) def get_connected_sites(self, n, jimage=(0, 0, 0)):", "{idx: self.structure.index(site) for idx, site in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph,", "strategy_params=None, ): \"\"\" Builds off of Molecule.substitute to replace an", "= d.get(\"weight\", None) if v == n: site = self.molecule[u]", "to add two edges # for any one bond, one", "def alter_edge( self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ): \"\"\"", "set(connected_species): count = connected_species.count(sp) labels.append((count, sp)) labels = sorted(labels, reverse=True)", "self.graph to incorporate the new functional group. TODO: Figure out", ":return: a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\"", "if prop in properties: properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]] #", "header = \"from to to_image \" header_line = \"---- ----", "min(coords[:, 2]) + 100 structure = molecule.get_boxed_structure(a, b, c, no_cross=True,", "to change it if not existing_edge: raise ValueError( \"Edge between", "Substituent molecule. There are three options: 1. Providing an actual", "edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes, #", "the bonds parameter does not include sufficient bonds to separate", "local_env will always try to add two edges # for", "the graph itself, but contains a lot of helper methods", "of site connecting from :param to_index: index of site connecting", "NetworkX package to store and operate on the graph itself,", "if a graph is already in place if isinstance(func_grp, MoleculeGraph):", "still be considered equal. :param other: MoleculeGraph :return (bool): \"\"\"", "self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) for (u, v) in", "an edge in the MoleculeGraph. :param from_index: int :param to_index:", "bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings = self.find_rings(including=[index]) if len(rings)", "# Copies self.graph such that all edges (u, v) matched", "ints): lattice vector of periodic image, e.g. (1, 0, 0)", "\"\"\" :return: Name of the edge weight property of graph", "{centre_sp: \"A\"} available_letters = [chr(66 + i) for i in", "the position of nearest neighbor. The second atom must be", "data=True) } if len(edges) == 0 and len(edges_other) == 0:", "Lattice. :param index: Index of atom to substitute. :param func_grp:", "mapping = {e: i for i, e in enumerate(sorted(fragment.nodes))} remapped", "the edge weight property of graph \"\"\" return self.graph.graph[\"edge_weight_name\"] @property", "defaultdict(list) for u, v, d in self.graph.edges(data=True): label = get_label(u,", "given crystallographic structure easier. Use cases for this include storing", "new_u, new_d = u, v, d.copy() new_d[\"to_jimage\"] = (0, 0,", "# find all possible fragments, aka connected induced subgraphs frag_dict", "of the MIT License. \"\"\" Module for graph representations of", "the charge of the total molecule to a single submolecule.", "enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self):", "expected to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel", "\"none\" # only add labels for images that are not", "weights. Typically, this means molecules will need to have the", "making this # assumption simplifies logic later if not np.array_equal(from_jimage,", "all_subgraphs = [supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)] # discount subgraphs", "note: NetworkX also has methods for drawing # graphs using", "else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index,", "decimals=3) v_expec_image = v_expec_image - v_expec_image % 1 v_expec_frac =", "\"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def __len__(self): \"\"\"", "return sorted(list(motifs)) def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Structure` except", "if to_index < from_index: to_index, from_index = from_index, to_index #", "first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites def", "the next nearest atom. For example, for a methyl group", "True, label edges with their periodic images (usually only used", "edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError: raise RuntimeError(\"Some", "nodes): raise ValueError( \"Edges cannot be added if nodes are", "with, will color edges red that do not exist in", "color edges :param node_labels (bool): if True, label nodes with", "= correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def substitute_group( self, index,", "# make sure we don't try to add duplicate edges", "index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return list sorted by closest", "to be changed. :return: \"\"\" existing_edge = self.graph.get_edge_data(from_index, to_index) #", "unique_subgraphs = [] for subgraph in molecule_subgraphs: already_present = [", "if the MoleculeGraph is connected. If it is not, separate", "= i self.graph.remove_edge(from_index, to_index, edge_index) else: if allow_reverse: existing_reverse =", "dict containing graph information in dict format (not intended to", "np.eye(3), np.int16) else: # TODO: test __mul__ with full 3x3", "+= \"\\nStructure: \\n{}\".format(self.structure.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph)", "'S-Mo(3)'] \"\"\" motifs = set() for idx, site in enumerate(self.structure):", "Structures are ordered differently. :param other: StructureGraph :param strict: if", "edge to graph. Since physically a 'bond' (or other connection", "def name(self): \"\"\" :return: Name of graph \"\"\" return self.graph.graph[\"name\"]", "directions of edges edges_to_remove = [] edges_to_add = [] for", "site can be safely added. :param site_properties: Site properties for", "for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v, d) in", "For example, for a methyl group substitution, func_grp should be", "to incorporate the new functional group. NOTE: using a MoleculeGraph", "grp_map if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp", "containing graph information in dict format (not intended to be", "# ensure that edge exists before attempting to remove it", "they're just for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name,", "/ len(edges.union(edges_other)) return { \"self\": edges - edges_other, \"other\": edges_other", "jimage=(0, 0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return list", "but not in the reference graph :param hide_unconnected_nodes: if True,", "self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None, ):", "merge all graphs into one big graph new_g = nx.MultiDiGraph()", "are to be specified. :return: mg, a MoleculeGraph \"\"\" mg", "class worked even if # from_jimage != (0, 0, 0),", "n2): return n1[\"specie\"] == n2[\"specie\"] def edge_match(e1, e2): if use_weights:", "i if new_weight is not None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if", "a list of strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary", "later effort will be to actually accurately assign charge. NOTE:", "False for f in unique_frags: if _isomorphic(frag, f): found =", "\"corresponding Structures are different.\") if strict: # sort for consistent", "[0, 0, 0]): continue if n > neighbor[\"site_index\"]: from_index =", "connected_sites = set() connected_site_images = set() out_edges = [(u, v,", "[copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all unique fragments using", "properties=site_properties, ) mapping = {} for j in range(len(self.structure) -", "graph. :return: A dict with an 'all_weights' list, 'minimum', 'maximum',", "isomorphic to ensure comparison of node identities. \"\"\" return g1.vs[i1][\"species\"]", "test for isomorphism def node_match(n1, n2): return n1[\"specie\"] == n2[\"specie\"]", "in edges.items(): try: from_index = edge[0] to_index = edge[1] except", "\"none\" # optionally color edges using node colors color_u =", "count number of occurrences of bonds :return: \"\"\" if self.structure", "a simple Graph (instead of MultiDiGraph), with node indices #", "a ring (cycle, in graph theory terms) including the index", "Since physically a 'bond' (or other connection between sites) doesn't", "three options: 1. Providing an actual molecule as the input.", "default, this is None. If any edge properties are to", "!= 0: raise RuntimeError( \"Currently functional group replacement\" \"cannot occur", "for (u, v) in alterations.keys(): if \"weight\" in alterations[(u, v)]:", "# NearNeighbor classes only (generally) work with structures # molecules", "0]) - min(coords[:, 0]) + 100 b = max(coords[:, 1])", "isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) for (u,", "= [(label[0], mapping[label[1]]) for label in labels] labels = [\"{}({})\".format(label[1],", "the MoleculeGraph. :param i: Index at which to insert the", "0) edges_to_remove.append((u, v, k)) # make sure we don't try", "0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, ) def get_connected_sites(self, n, jimage=(0,", "PeriodicSite.from_dict(site_d) # from_site if jimage arg != (0, 0, 0)", "np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0, 0),", "weight units e.g. \"Å\" or \"eV\" :return (StructureGraph): \"\"\" if", "in other.graph.edges(keys=False, data=True) } if len(edges) == 0 and len(edges_other)", "= { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d in self.graph.edges(keys=False,", "If no image is given, this method will fail. :param", "np from monty.json import MSONable from monty.os.path import which from", "if the underlying Structures are ordered differently. :param other: StructureGraph", "are converted into undirected nx.Graph objects. :param other: MoleculeGraph object", "unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, ) ) frag_key =", "by definition else: jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other))", "graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): \"\"\" Split", "if not defined if \"to_image\" in d: to_image = d[\"to_jimage\"]", "atom in self.structure with a functional group. This method also", "v, k].update(d) # optionally remove periodic image edges, # these", "new site :param validate_proximity: For Molecule.insert(); if True (default False),", "For Molecule.insert(); if True (default False), distance will be checked", "= [] for sp in set(connected_species): count = connected_species.count(sp) labels.append((count,", "edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] if 0 not in", "and all indices used for these edges should reflect the", "else \"none\" # optionally color edges using node colors color_u", "Molecules, and have the same edges between Sites. Edge weights", "of periodic image, e.g. (1, 0, 0) for periodic image", "especially in larger graphs. :param filename: filename to output, will", "in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions", "if edge_weight_units: edge_label += \" ({})\".format(edge_weight_units) header += \" {}\".format(edge_label)", "edge_index = i if new_weight is not None: self.graph[from_index][to_index][edge_index][\"weight\"] =", "n) for neighbor in neighbors: # all bonds in molecules", "self.structure != other.structure and strict: return ValueError(\"Meaningless to compare StructureGraphs", ":param n: index of Site in Structure :param jimage: lattice", "StructureGraph. If no image is given, this method will fail.", "False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = \"<NAME>, <NAME>, <NAME>\"", "return those rings including the specified sites. By default, this", "site.species, site.coords + v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s)", "\" header_line = \"---- ---- ------------\" edge_weight_name = g.graph[\"edge_weight_name\"] if", "else: structure = None for n in range(len(molecule)): if structure", "of edge weight units e.g. \"Å\" or \"eV\" :return (StructureGraph):", "v, **d) # return new instance of StructureGraph with supercell", "A dictionary with keys specifying the species involved in a", "get index in original site n_u = u % len(self.structure)", "from_jimage can be swapped with to_index, to_jimage. However, images will", "mapping[v], weight=weight, edge_properties=edge_props, ) def replace_group( self, index, func_grp, strategy,", "will always always be shifted so that from_index < to_index", "insert_node( self, i, species, coords, validate_proximity=False, site_properties=None, edges=None, ): \"\"\"", "if alterations is not None: for (u, v) in alterations.keys():", "# reduce unnecessary checking if to_jimage != (0, 0, 0):", "{}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + \".dot\") def as_dict(self):", "(0, 0, 0) # set edge style d[\"style\"] = \"solid\"", "primitive single-atom lattices images = [1, 0, 0], [0, 1,", "in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.structure ==", "+ v_rel # now search in new structure for these", "Structure. # Broadly, it would be easier to multiply the", "+ 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is", "# new supercell, and get asgolute Cartesian # co-ordinates of", "raise RuntimeError(\"StructureGraph graph drawing requires \" \"GraphViz binaries to be", "of properties, including weight. Props should be None if no", "substitution, func_grp should be X-CH3, where X is the first", "self.graph.remove_edge(to_index, from_index, edge_index) else: raise ValueError( \"Edge cannot be broken", "of edge weights, e.g. \"bond_length\" or \"exchange_constant\" :param edge_weight_units (str):", "nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return", "!= len(f2_nodes): return False f2_edges = frag2.edges() if len(f2_edges) !=", "(u, v) matched by edges (v, u) undirected = self.graph.to_undirected()", "\" \"with your edge weights. Can be \" \"empty string", "benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords # using", "edge[0] to_index = edge[1] except TypeError: raise ValueError(\"Edges must be", "dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get(\"weight\", None) if (v,", "0, 0): # get index in original site n_u =", "graph appearance and also correctly displays # mutli-graphs (matplotlib can", "molecule (Molecule): :param name (str): name of graph, e.g. \"bonds\"", "is an easy way to extract # molecules (and not,", "len(self.structure) # get fractional co-ordinates of where atoms defined #", "v_rel # now search in new structure for these atoms", "graph. Please check your\" \" indices.\" ) sg.add_edge( from_index, to_index,", "only return unique molecules, not any duplicates present in the", "= self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get(\"weight\", None) if (v, to_jimage)", "d): \"\"\" As in :Class: `pymatgen.core.Structure` except restoring graphs using", "split the MoleculeGraph. :param alterations: a dict {(from_index, to_index): alt},", "self.graph.edges(keys=True, data=True): if v < u: new_v, new_u, new_d =", "\"Please choose another strategy.\" ) extend_structure = strategy.extend_structure_molecules mg =", ":param site_properties: Site properties for Molecule :param edges: List of", "weights: if True, use weights from local_env class (consult relevant", "molecule = Molecule(species, coords) # shift so origin is at", "= [] for frag in frag_dict[key]: found = False for", "find connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs", "\"\\n\" + header_line + \"\\n\" edges = list(g.edges(data=True)) # sort", "the relevant template in func_groups.json. 3. A MoleculeGraph object. :param", "edge[2] != 0: duplicates.append(edge) for duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1],", "= tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\"", "later if not np.array_equal(from_jimage, (0, 0, 0)): shift = from_jimage", "only be one edge between any two nodes if new_weight", "have a \"to_index\" and \"from_index\" key, and can also have", "will happen when from_index == to_index, # typically in primitive", "# will remove two edges for everyone one we add", "False s = header + \"\\n\" + header_line + \"\\n\"", "v, k].update({\"color_uv\": \"#00ff00\"}) for u, v, k in red_edges: g.edges[u,", "a supercell is an easy way to extract # molecules", "keeping track of the # which new lattice images present,", "induced subgraphs frag_dict = {} for ii in range(1, len(self.molecule)):", "from_index = edge[0] to_index = edge[1] from_image = edge[2] to_image", "new MoleculeGraph objects. :param bonds: list of tuples (from_index, to_index)", "just make a copy from input graph_data = structure.as_dict()[\"graphs\"] self.structure", "alter_edge does not require that edge_properties be altered. As such,", "# sort edges for consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights:", ":param other: MoleculeGraph object to be compared. :return: bool \"\"\"", "self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, allow_reverse=False): \"\"\" Remove", "= nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph)", "with species and site index :param weight_labels (bool): if True,", "Find all possible fragment combinations of the MoleculeGraphs (in other", "in enumerate(nodes): mapping[n] = i # just give charge to", "data=True) } else: edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u,", "all_cycles = [c for c in nx.simple_cycles(directed) if len(c) >", "to site properties edge_properties = edge_properties or {} if weight:", "isomorphic to one another. In order to prevent problems with", "no edge exists between those sites.\".format( from_index, to_index ) )", "{(u, v, d[\"to_jimage\"]) for u, v, d in self.graph.edges(keys=False, data=True)}", "A specified bond order to calculate the bond length between", "within a ring\" \"structure.\" ) to_remove = set() sizes =", "nodes for n in g.nodes(): # get label by species", "= d.copy() # node now inside supercell new_d[\"to_jimage\"] = (0,", ":param molecule (Molecule): :param name (str): name of graph, e.g.", "RuntimeError(\"Can't find functional group in list. \" \"Provide explicit coordinate", "= edge[2] to_image = edge[3] except TypeError: raise ValueError(\"Edges must", "else: weight = None if len(props.items()) == 0: props =", "anonymous=False): \"\"\" Extract information on the different co-ordination environments present", "edges that are present in only one StructureGraph ('self' and", "j in range(len(self.structure) - 1): if j < i: mapping[j]", "This # approach has many benefits, but made it more", "!= other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges()) != len(other.graph.edges()): return False", "ordered differently. :param other: MoleculeGraph :param strict: if False, will", "in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define how we test", "existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise", "two or more MoleculeGraphs by breaking a set of bonds.", "the attached functional group and the nearest neighbor site. Defaults", "\"eV\" :return (MoleculeGraph): \"\"\" if edge_weight_name and (edge_weight_units is None):", "Remove an edge from the MoleculeGraph :param from_index: int :param", "# edge has been deleted red_edges.append((u, v, k)) elif (u,", "site in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize", ") ) frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\" +", "d in other.graph.edges(keys=False, data=True) } if len(edges) == 0 and", "for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes,", "mg, a MoleculeGraph \"\"\" if not strategy.molecules_allowed: raise ValueError( \"Chosen", "NOTE: This function does not modify the original MoleculeGraph. It", "\"empty string if arbitrary or \" \"dimensionless.\" ) # construct", "= from_jimage, to_jimage # constrain all from_jimages to be (0,", "from NetworkX to store graph information. \"\"\" d = {", "# tolerance in Å for sites to be considered equal", "both site index and periodic image. Here, the # number", "mean that each cycle always appears twice # So, we", "node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class", "self, i, species, coords, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A", "\"\"\" Remove an edge from the StructureGraph. If no image", "occurrences of bonds :return: \"\"\" if self.structure != other.structure and", "functional group. TODO: Figure out how to replace into a", "strict=True) green_edges = [] red_edges = [] for u, v,", "i in range(25)] for label in labels: sp = label[1]", "i) for i in range(25)] for label in labels: sp", "if edge_weight_name and (edge_weight_units is None): raise ValueError( \"Please specify", "the graph, creating a supercell, intelligently joining together edges that", "of the sets of edges. This is returned with key", "form of a graph. A \"bond\" does not necessarily have", "that weight be altered. As such, by default, this is", "require that edge_properties be altered. As such, by default, this", "a MoleculeGraph object with an empty graph (no edges, only", "available_letters = [chr(66 + i) for i in range(25)] for", "species, coords, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper around", "= from_jimage from_jimage = np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage, shift)", ":param graph_dict: Dictionary representing the bonds of the functional group", "nodes in graph \"\"\" return len(self.structure) def sort(self, key=None, reverse=False):", "coords = {} properties = {} for node in self.graph.nodes():", "functional group (format: {(u, v): props}, where props is a", "v, k, d in self.graph.edges(keys=True, data=True): if v < u:", "information. \"\"\" m = Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"]) @classmethod def", "must be a DummySpecies X, indicating the position of nearest", "[supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)] # discount subgraphs that lie", "species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(self,", "to_image = d[\"to_jimage\"] # set edge style d[\"style\"] = \"solid\"", "nodes = sorted(list(subg.nodes)) # Molecule indices are essentially list-based, so", "_edges_to_string(cls, g): header = \"from to to_image \" header_line =", "indices will be the same if the underlying Structures are", "**edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node( self, i, species,", "graph compared with using a Molecule or str (when not", "= n to_index = neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False,", "first \"\"\" connected_sites = set() out_edges = list(self.graph.out_edges(n, data=True)) in_edges", "periodic boundaries :param edge_colors (bool): if True, use node colors", "and returns two or more new MoleculeGraph objects. :return: list", "weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates = [] for edge in mg.graph.edges:", "0, 0))), data.get(\"weight\", 0) ) else: for u, v, data", "in_edges: to_jimage = d[\"to_jimage\"] if dir == \"in\": u, v", "to to_image \" header_line = \"---- ---- ------------\" edge_weight_name =", "Index of atom to substitute. :param func_grp: Substituent molecule. There", "self.__mul__(other) @classmethod def _edges_to_string(cls, g): header = \"from to to_image", "container for additional edge properties, # similar to site properties", "images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist = min(dists) equiv_sites =", "self.graph.edges(keys=True, data=True): if \"id\" in d: del d[\"id\"] if \"key\"", "made it more difficult to # keep the graph in", "v): u_label = self.structure[u].species_string v_label = self.structure[v].species_string return \"-\".join(sorted((u_label, v_label)))", "= edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props,", "the molecule # in order to be used for Molecule", "all two-edge cycles all_cycles = [c for c in nx.simple_cycles(directed)", "nearest atom. For example, for a methyl group substitution, func_grp", "0.05 for u, v, k, d in new_g.edges(keys=True, data=True): to_jimage", "= False s = header + \"\\n\" + header_line +", "labels = [] for sp in set(connected_species): count = connected_species.count(sp)", "ordering to graph mapping = {idx: self.molecule.index(site) for idx, site", "= other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges = {(u, v) for", "store on graph edges, similar to Structure's site_properties :return: \"\"\"", "altered. As such, by default, this is None. If any", "): \"\"\" Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace", "to_jimage)) # return list sorted by closest sites first connected_sites", "self.structure.index(site) for site in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site:", "\"\"\" def map_indices(grp): grp_map = {} # Get indices now", "list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False):", "information on the graph edges of what lattice image the", "= {(u, v, d[\"to_jimage\"]) for u, v, d in self.graph.edges(keys=False,", "is not designed for use with structures! \" \"Please choose", "\"dpi\": 300, \"overlap\": \"false\"} # add display options for nodes", "bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Molecule.substitute to", "+ in_edges: weight = d.get(\"weight\", None) if v == n:", "frag_dict = {} for ii in range(1, len(self.molecule)): for combination", "dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=v,", "graph with one node per site # graph attributes don't", "no guarantee the node indices will be the same if", "to_jimage) ) return # generic container for additional edge properties,", "coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure = Structure.from_sites(new_sites)", "self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get(\"weight\", None) if (v, to_jimage) not", "aka connected induced subgraphs frag_dict = {} for ii in", "= graph.nodes(data=True) new_igraph = igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]),", "are invalid.\") def set_node_attributes(self): \"\"\" Replicates molecule site properties (specie,", "in supercell # and if so, delete old edge that", "in frag_dict[key]: found = False for f in unique_frags: if", "d in new_g.edges(keys=True, data=True): to_jimage = d[\"to_jimage\"] # for node", "contrasting font color # magic numbers account for perceived luminescence", "key mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure} other_sorted", "the 'other' StructureGraph: there is no guarantee the node indices", "unique_cycles else: for i in including: for cycle in unique_cycles:", "None: neighbors = strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure, n)", "if props is not None: if \"weight\" in props.keys(): weight", "self.with_local_env_strategy(func_grp, strat) for (u, v) in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u,", "to_remove = set() sizes = dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index)", "i for i, e in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping)", "diff[\"other\"]: # edge has been added green_edges.append((u, v, k)) for", "of site n: periodic_site, jimage, index, weight. Index is the", "of a list of strategies defined in pymatgen.analysis.local_env. :param strategy_params:", "atoms defined by edge are expected to be v_image_cart =", "RuntimeError(\"{} exited with return code {}.\".format(algo, rs.returncode)) if not keep_dot:", "d[\"to_jimage\"] == to_jimage: if warn_duplicates: warnings.warn( \"Trying to add an", "from periodic crystals. Will only return unique molecules, not any", "if n == v]) return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file(", "in graph. :param key: :param reverse: :return: \"\"\" old_molecule =", "original graph, but a larger graph can be easier to", ":param anonymous: if anonymous, will replace specie names with A,", "bond lengths to be defined as duplicates, otherwise bond lengths", "d in existing_edge_data.items(): if d[\"to_jimage\"] == to_jimage: if warn_duplicates: warnings.warn(", "self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse) # apply Structure ordering to", "min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist * 0.01, include_index=True", "is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop]", "for image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist =", "frag2.edges() if len(f2_edges) != len(f2_edges): return False f1_comp_dict = {}", "using pre-existing or pre-defined edges with optional edge parameters. :param", "find new_v such that we have # full periodic boundary", "undirected to find connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) # find", "c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) # get contrasting font", "graph object. \"\"\" nodes = graph.nodes(data=True) new_igraph = igraph.Graph() for", "!= 0]) # optionally highlight differences with another graph if", "raise ValueError( \"Edge cannot be broken between {} and {};\\", "be specified. :return: sg, a StructureGraph \"\"\" sg = StructureGraph.with_empty_graph(structure,", "site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d[\"to_jimage\"]) for u, v,", "defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments for", "edges of what lattice image the edge belongs to. :param", "not cross # (artificial) periodic boundaries if not np.array_equal(neighbor[\"image\"], [0,", "edge weights), and is defined by 1 - (size of", "to. :param structure: a Structure object :param graph_data: dict containing", "weight or the edge_properties of an edge in the MoleculeGraph.", "index, the value will be an empty list. \"\"\" #", "u, v, d in self.graph.edges(data=True): label = get_label(u, v) types[label].append(d[\"weight\"])", "g.nodes(): # get label by species name label = \"{}({})\".format(str(self.structure[n].specie),", "to create disjoint graphs (two or more separate molecules). This", "\"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d)", "# and if so, delete old edge that went through", "functional group # Subtracting 1 because the dummy atom X", "(bool): if True, label edges with weights :param image_labels (bool):", "closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return", "if True, label edges with their periodic images (usually only", "# constrain all from_jimages to be (0, 0, 0), #", "are in terms of the StructureGraph this method is called", "# get contrasting font color # magic numbers account for", "subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)] # discount", "bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot split molecule; \\", "if hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide", "used. :return: \"\"\" def map_indices(grp): grp_map = {} # Get", "are connected to nodes on opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec)", "MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) for (u, v)", "list. \"\"\" # Copies self.graph such that all edges (u,", "associating a graph with a given molecule easier. Use cases", "warn_duplicates=False, ) duplicates = [] for edge in mg.graph.edges: if", "do is to remove the index site, and connect the", "max(coords[:, 1]) - min(coords[:, 1]) + 100 c = max(coords[:,", "class MolGraphSplitError(Exception): \"\"\" Raised when a molecule graph is failed", "for site in mapping.values(): neighbors = strat.get_nn_info(self.structure, site) for neighbor", "coordinates are cartesian. Defaults to False. :param validate_proximity: For Molecule.insert();", "def types_and_weights_of_connections(self): \"\"\" Extract a dictionary summarizing the types and", "mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) else: if strategy_params is None:", "this function naively assigns the charge of the total molecule", "else: from_index = n to_index = neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index,", "terms of the MIT License. \"\"\" Module for graph representations", "from pymatgen.vis.structure_vtk import EL_COLORS try: import igraph IGRAPH_AVAILABLE = True", "(u, v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"weight\"", "should only ever be at most one edge # between", "similar to Structure's site_properties :return: \"\"\" # this is not", "{} for node in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node] =", "weight (float): e.g. bond length :param warn_duplicates (bool): if True,", "v, data in edges: s += \"{:4} {:4} {:12}\\n\".format(u, v,", "< new_u: new_u, new_v = new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u,", "image sites now present in supercell # and if so,", "in props.keys(): weight = props[\"weight\"] del props[\"weight\"] else: weight =", "def add_edge( self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\"", "self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current in enumerate(sorted(self.graph.nodes)):", "misleading results for multigraphs (edges are super-imposed on each other).", "array representing coordinates of the new site :param validate_proximity: For", "trialed, using # a simple Graph (instead of MultiDiGraph), with", "else: f2_comp_dict[node[1][\"specie\"]] += 1 if f1_comp_dict != f2_comp_dict: return False", "i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {}", "coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j in", ":return: \"\"\" existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure that edge", "an additional graph to compare with, will color edges red", "but will treat e.g. enantiomers as being duplicates. :return: list", "MoleculeGraph :param strict: if False, will compare bonds from different", "e.g. \"Å\" or \"eV\" :return (MoleculeGraph): \"\"\" if edge_weight_name and", "[connected_site.site.species_string for connected_site in connected_sites] labels = [] for sp", "diff = self.diff(diff, strict=True) green_edges = [] red_edges = []", "original lattice has # significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage)", "cycles_nodes.append(cycle) for cycle in cycles_nodes: edges = [] for i,", "!= 0: duplicates.append(edge) for duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2])", "in self.graph.in_edges(n, data=True)] for u, v, d, dir in out_edges", "v, d[\"to_jimage\"]) in diff[\"self\"]: # edge has been deleted red_edges.append((u,", "for their meaning) :return: \"\"\" if not strategy.structures_allowed: raise ValueError(", "happen when from_index == to_index, # typically in primitive single-atom", "= self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d) #", "\"in\") for u, v, d in self.graph.in_edges(n, data=True)] for u,", "v_rel = np.subtract(v_image_cart, u_cart) # now retrieve position of node", "= None if to_jimage is None: raise ValueError(\"Image must be", "print_weights = [\"weight\"] edge_label = g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"] if", "appear as dashed lines) :param color_scheme (str): \"VESTA\" or \"JMOL\"", "\"\"\" self.set_node_attributes() graph = self.graph.to_undirected() # find all possible fragments,", "MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two MoleculeGraphs are equal if", "possible fragments, aka connected induced subgraphs frag_dict = {} for", "to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0: # this will", "the second site. What the code will do is to", "use the `with_empty_graph` method or `with_local_env_strategy` method (using an algorithm", "self.structure.index(site) for idx, site in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping,", "in the graph. Please check your\" \" indices.\" ) mg.add_edge(from_index,", "def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two StructureGraphs", "return original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\" Find all possible fragment combinations", "length between the attached functional group and the nearest neighbor", "self.graph.in_edges(n, data=True)] for u, v, d, dir in out_edges +", "frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all unique", "None, default parameters will be used. :return: \"\"\" def map_indices(grp):", "new_graph = nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph, \"specie\") coords =", "0, 0), index=u, weight=weight, dist=dist) else: site = self.molecule[v] dist", "for extracting molecules from periodic crystals. Will only return unique", "self.molecule.index(site) for site in other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda site:", "will be a ring (cycle, in graph theory terms) including", "display options for nodes for n in g.nodes(): # get", "additional properties are to be specified. :return: mg, a MoleculeGraph", "the same edges between Sites. Edge weights can be different", "u_frac = self.structure[n_u].frac_coords # using the position of node u", "\"\"\" As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from", "node a \"specie\" and a \"coords\" attribute, updated with the", "\",\".join(labels)) motifs.add(motif) return sorted(list(motifs)) def as_dict(self): \"\"\" As in :Class:", "return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two StructureGraphs are equal", "but made it more difficult to # keep the graph", "be obtained from the relevant template in func_groups.json. 3. A", "v_present[1] if v_present[0] <= tol else None # check if", "duplicates = [] for edge in mg.graph.edges: if edge[2] !=", ") mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return mg @staticmethod def", "return d @classmethod def from_dict(cls, d): \"\"\" As in :Class:", "self.add_edge( from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index, ) return #", "node[1][\"specie\"] not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1 else: f2_comp_dict[node[1][\"specie\"]] +=", "(and not, e.g., layers of a 2D crystal) # without", "/ 255 < 0.5 else \"#ffffff\" # convert color to", "to color edges :param node_labels (bool): if True, label nodes", "attr_dict) # list of new edges inside supercell # for", "weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError: raise RuntimeError(\"Some edges", "does not require that edge_properties be altered. As such, by", "i in including: for cycle in unique_cycles: if i in", "= [] for cycle in all_cycles: if sorted(cycle) not in", "tuples, sorted by closest first \"\"\" connected_sites = set() connected_site_images", "# coding: utf-8 # Copyright (c) Pymatgen Development Team. #", "False f1_comp_dict = {} f2_comp_dict = {} for node in", "methyl group substitution, func_grp should be X-CH3, where X is", ":param jimage: lattice vector of site :return: list of ConnectedSite", "# molecules have to be boxed first coords = molecule.cart_coords", "key: :param reverse: :return: \"\"\" old_molecule = self.molecule.copy() # sort", "This function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs (two", "\\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s", ") return # generic container for additional edge properties, #", "see as_dict method for format) \"\"\" if isinstance(molecule, MoleculeGraph): #", ":Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to store", "of information that connects two Sites. \"\"\" def __init__(self, structure,", "information, NMR J-couplings, Heisenberg exchange parameters, etc. For periodic graphs,", "still connected.\" ) # alter any bonds before partition, to", "graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure,", "NetworkX also has methods for drawing # graphs using matplotlib,", "# sort for consistent node indices # PeriodicSite should have", "in the Structure. This # approach has many benefits, but", "bool \"\"\" if len(self.molecule) != len(other.molecule): return False if self.molecule.composition.alphabetical_formula", "in connected_sites] labels = [] for sp in set(connected_species): count", "subgraphs) :return: \"\"\" self.set_node_attributes() graph = self.graph.to_undirected() # find all", "to_index # sanitize types from_index, to_index = int(from_index), int(to_index) #", "def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): \"\"\" Split MoleculeGraph into two", "n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define how we", "which(algo): raise RuntimeError(\"StructureGraph graph drawing requires \" \"GraphViz binaries to", "\"-\".join(sorted((u_label, v_label))) types = defaultdict(list) for u, v, d in", "# for node v # reduce unnecessary checking if to_jimage", "X, indicating the position of nearest neighbor. The second atom", "of the corresponding site in the original structure, weight can", "index of Site in Molecule :param jimage: lattice vector of", "keep_dot=False, algo=\"fdp\", ): \"\"\" Draws graph using GraphViz. The networkx", "existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before", "= mg.graph.nodes if not (from_index in nodes and to_index in", "jimage=(0, 0, 0)): \"\"\" Returns a named tuple of neighbors", "off of Molecule.substitute to replace an atom in self.molecule with", "for n in g.degree() if g.degree()[n] != 0]) # optionally", "with its corresponding Structure. # Broadly, it would be easier", "= [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for subg in subgraphs:", "jimage) pair and another # (site, jimage) pair existing_edge_data =", "else \"#ffffff\" # convert color to hex string color =", "these atoms # query returns (distance, index) v_present = kd_tree.query(v_expec)", "monty.json import MSONable from monty.os.path import which from networkx.drawing.nx_agraph import", "dict representing the bonds of the functional group (format: {(u,", "v, str(data.get(\"to_jimage\", (0, 0, 0)))) return s def __str__(self): s", "edges have the same weights. Typically, this means molecules will", "for from_index, to_index, key in remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index,", ":return: mg, a MoleculeGraph \"\"\" if not strategy.molecules_allowed: raise ValueError(", "strategy, weights=False): \"\"\" Constructor for StructureGraph, using a strategy from", "props}, where props is a dictionary of properties, including weight.", "default, this parameter is None, and all rings will be", "return cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure, edges): \"\"\" Constructor for", "the reference graph :param hide_unconnected_nodes: if True, hide unconnected nodes", "edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage,", "= [] for subgraph in unique_subgraphs: coords = [supercell_sg.structure[n].coords for", "to remove it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse = None", "to an # existing Site in Structure kd_tree = KDTree(new_structure.cart_coords)", "same if the underlying Structures are ordered differently. :param other:", "ordered differently. :param other: StructureGraph :param strict: if False, will", "= {(u, v) for u, v, d in other_sorted.graph.edges(keys=False, data=True)}", "Defaults to False. :param validate_proximity: For Molecule.insert(); if True (default", "periodic boundary conditions # so that nodes on one side", "{} for node in f1_nodes: if node[1][\"specie\"] not in f1_comp_dict:", "+ in_edges: to_jimage = d[\"to_jimage\"] if dir == \"in\": u,", "Development Team. # Distributed under the terms of the MIT", ":param func_grp: Substituent molecule. There are three options: 1. Providing", "it neater if to_index < from_index: to_index, from_index = from_index,", "edges = [] for i, e in enumerate(cycle): edges.append((cycle[i -", "d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v,", "i, species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A", "two edges for everyone one we add if {new_u, new_v}", "site in other.molecule} except ValueError: return False other_sorted = other.__copy__()", "return sg def __rmul__(self, other): return self.__mul__(other) @classmethod def _edges_to_string(cls,", "{}\".format(edge_label) header_line += \" {}\".format(\"-\" * max([18, len(edge_label)])) else: print_weights", "if to_index < from_index: to_index, from_index = from_index, to_index to_jimage,", "igraph IGRAPH_AVAILABLE = True except ImportError: IGRAPH_AVAILABLE = False logger", "crystals. \"\"\" import copy import logging import os.path import subprocess", "stored in the form of a graph. A \"bond\" does", "Site properties must be present for all atoms in the", "self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge", "cycle not in cycles_nodes: cycles_nodes.append(cycle) for cycle in cycles_nodes: edges", "= self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species,", "can be swapped with to_index, to_jimage. However, images will always", "in mapping.values(): neighbors = strat.get_nn_info(self.structure, site) for neighbor in neighbors:", "sorted(list(motifs)) def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Structure` except with", "is not None: new_u = u new_v = v_present new_d", "edge from the StructureGraph. If no image is given, this", "nodes defined that correspond to Sites in Molecule). :param molecule", "in g.degree() if g.degree()[n] != 0]) # optionally highlight differences", "around Molecule.insert(), which also incorporates the new site into the", "Molecule :param jimage: lattice vector of site :return: list of", "parameter does not include sufficient bonds to separate two molecule", "consistent node indices # PeriodicSite should have a proper __hash__()", "dimensions of the Lattice. :param index: Index of atom to", "lattice vector of image :param weight (float): e.g. bond length", "object to be compared. :return: bool \"\"\" if len(self.molecule) !=", "TypeError: raise ValueError(\"Edges must be given as (from_index, to_index)\" \"tuples\")", "frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.structure.index(site) for", "to_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse:", "logger.setLevel(logging.INFO) __author__ = \"<NAME>, <NAME>, <NAME>\" __version__ = \"0.1\" __maintainer__", "for cycle in cycles_nodes: edges = [] for i, e", "try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None),", "Structure's site_properties :return: \"\"\" # this is not necessary for", "= True except ImportError: IGRAPH_AVAILABLE = False logger = logging.getLogger(__name__)", "graph objects are isomorphic, using igraph if if is available", "\" indices.\" ) sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props,", "v) types[label].append(d[\"weight\"]) return dict(types) @property def weight_statistics(self): \"\"\" Extract a", "from_index). :return: \"\"\" # ensure that edge exists before attempting", "amends self.graph to incorporate the new functional group. NOTE: Care", "neighbors: # all bonds in molecules should not cross #", "= self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight,", "import EL_COLORS try: import igraph IGRAPH_AVAILABLE = True except ImportError:", "coordinate instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove", "cross # (artificial) periodic boundaries if not np.array_equal(neighbor[\"image\"], [0, 0,", "v, k)) # make sure we don't try to add", "allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot split molecule; \\ MoleculeGraph", "as Molecule.sort(), also remaps nodes in graph. :param key: :param", "be added in either case) :param edge_properties (dict): any other", "closest first \"\"\" connected_sites = set() connected_site_images = set() out_edges", "**edge_properties) def insert_node( self, i, species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None,", "\"properties\") def alter_edge( self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ):", "will attempt to break both (from_index, to_index) and, failing that,", "def _isomorphic(frag1, frag2): \"\"\" Internal function to check if two", "existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before", ":param to_jimage: tuple :param allow_reverse: If allow_reverse is True, then", "mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return mg @staticmethod def with_local_env_strategy(molecule,", "A wrapper around Molecule.insert(), which also incorporates the new site", "'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' \"\"\" all_weights =", "subgraph molecules = [] for subgraph in unique_subgraphs: coords =", "supplied, to avoid ambiguity.\") if existing_edges: for i, properties in", "this is # harmless, so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0,", "for graph representations of crystals. \"\"\" import copy import logging", "are not the origin if image_labels: d[\"headlabel\"] = \"\" if", "given (site, jimage) pair and another # (site, jimage) pair", "equal # this could probably be a lot smaller tol", ":param i: Index at which to insert the new site", "to fix issues with finite precision leading to incorrect image", "index=u, weight=weight, dist=dist) else: site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v])", "one MoleculeGraph ('self' and 'other'), and edges that are present", "for j in range(len(self.molecule) - 1): if j < i:", "that are present in only one StructureGraph ('self' and 'other'),", "back from json), it's important images # are hashable/immutable if", "to_jimage) u_frac = self.structure[n_u].frac_coords # using the position of node", "out_edges + in_edges: to_jimage = d[\"to_jimage\"] if dir == \"in\":", "current Molecule (and graph) to be removed. :return: \"\"\" self.molecule.remove_sites(indices)", "\"Please specify units associated \" \"with your edge weights. Can", "must include the index of the new site i, and", "keys specifying the species involved in a connection in alphabetical", "with finite precision leading to incorrect image v_expec_image = np.around(v_expec_frac,", "1 if f1_comp_dict != f2_comp_dict: return False if IGRAPH_AVAILABLE: ifrag1", "0): # get index in original site n_u = u", "mg @property def name(self): \"\"\" :return: Name of graph \"\"\"", "to :param from_jimage (tuple of ints): lattice vector of periodic", "If graph indices have different indexing u, v = (u", "periodic graphs, class stores information on the graph edges of", "Distributed under the terms of the MIT License. \"\"\" Module", "in diff[\"self\"]: # edge has been deleted red_edges.append((u, v, k))", "__version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__", "objects are isomorphic, using igraph if if is available and", "1] dists = [] for image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index],", "for sp in set(connected_species): count = connected_species.count(sp) labels.append((count, sp)) labels", "cycle always appears twice # So, we must also remove", "from_index, to_index # sanitize types from_index, to_index = int(from_index), int(to_index)", "edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add:", "not the 'other' MoleculeGraph: there is no guarantee the node", "ring (cycle, in graph theory terms) including the index found", "neighbors: self.add_edge( from_index=site, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False,", "ImportError: IGRAPH_AVAILABLE = False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ =", "Builds off of Molecule.substitute to replace an atom in self.molecule", "in primitive single-atom lattices images = [1, 0, 0], [0,", "= strategy.get_nn_info(structure, n) for neighbor in neighbors: # all bonds", "key in unique_frag_dict: unique_mol_graph_list = [] for fragment in unique_frag_dict[key]:", "representing the bonds of the functional group (format: {(from_index, to_index,", "from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse:", "kind of information that connects two Sites. \"\"\" def __init__(self,", "(0, 0, 0): # get index in original site n_u", "new_edge_properties: alter_edge does not require that edge_properties be altered. As", "k, v in properties.items(): if len(v) != len(species): del properties[k]", "is difficult to interpret, `hide_image_edges` can help, especially in larger", "molecule.cart_coords if extend_structure: a = max(coords[:, 0]) - min(coords[:, 0])", "StructureGraphs can still be considered equal. :param other: StructureGraph :return", "only add labels for images that are not the origin", "MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in edges.items(): try:", "instead\") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy", "algo: any graphviz algo, \"neato\" (for simple graphs) or \"fdp\"", "of node corresponding to site n. :param n: index of", "group. NOTE: Care must be taken to ensure that the", "\"\"\" self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping", "be at most one edge # between two sites existing_edge_data", "find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)] #", "StructureGraph.from_dict(d) return sg def __rmul__(self, other): return self.__mul__(other) @classmethod def", "but should hopefully be # easier to extend to a", "always be shifted so that from_index < to_index and from_jimage", "MoleculeGraph): # just make a copy from input graph_data =", "scipy.stats import describe from pymatgen.core import Lattice, Molecule, PeriodicSite, Structure", "d in self.graph.edges(keys=True, data=True): if v < u: new_v, new_u,", "up edge attr dicts, reading to/from json duplicates # information", "indices now occupied by functional group # Subtracting 1 because", "graph drawing methods, but note that this might give misleading", "tuples (conversion to lists happens # when serializing back from", "\"\"\" Replicates molecule site properties (specie, coords, etc.) in the", "to_index, key=key) edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords,", "unique_frags = [] for frag in frag_dict[key]: found = False", "itself, but contains a lot of helper methods to make", "find functional group in list. \" \"Provide explicit coordinate instead\")", "supercell, intelligently joining together edges that lie on periodic boundaries.", "in diff and edges green that are in diff graph", "connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight, dist=dist) else:", "remapping if alterations is not None: for (u, v) in", "edge exists before attempting to remove it existing_edges = self.graph.get_edge_data(from_index,", "stats = describe(all_weights, nan_policy=\"omit\") return { \"all_weights\": all_weights, \"min\": stats.minmax[0],", "v % len(self.structure) # get fractional co-ordinates of where atoms", "molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names to graph to be able", "and have the same edges between Sites. Edge weights can", "str(self.molecule[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) } edges_other", "0, 0). :param from_index: index of site connecting from :param", "e in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped,", "index of Site in Structure :param jimage: lattice vector of", "the index of the new site i, and all indices", "self.graph.add_edge(u, v, **d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other):", "= \"normal\" if d[\"headlabel\"] else \"none\" # optionally color edges", "new_sites = [] new_graphs = [] for v in c_lat:", "new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d)) else: # want", "else: edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d", "in dict format (not intended to be constructed manually, see", "# PeriodicSite should have a proper __hash__() value, # using", "(u, v, d) in edges_to_add: new_g.add_edge(u, v, **d) # return", "np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present =", "graphs, class stores information on the graph edges of what", "1 offset = len(self.structure) - atoms for i in range(atoms):", "self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else: if isinstance(func_grp, Molecule): func_grp =", "weights for those connections (e.g. bond lengths). \"\"\" def get_label(u,", "['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs = set() for idx, site in", "\"\"\" d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(),", "isomorphic subgraph). :param use_weights (bool): If True, only treat subgraphs", "coords = [supercell_sg.structure[n].coords for n in subgraph.nodes()] species = [supercell_sg.structure[n].specie", "joining together edges that lie on periodic boundaries. In principle,", "\"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d) return sg", "mapping = {tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule} other_sorted =", "name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for StructureGraph, returns a StructureGraph", "to_jimage = np.subtract(to_jimage, shift) # automatic detection of to_jimage if", "objects. :param bonds: list of tuples (from_index, to_index) representing bonds", "optionally color edges using node colors color_u = g.nodes[u][\"fillcolor\"] color_v", "= frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes): return", "rs.returncode)) if not keep_dot: os.remove(basename + \".dot\") @property def types_and_weights_of_connections(self):", "all indices used for these edges should reflect the MoleculeGraph", "graph if diff: diff = self.diff(diff, strict=True) green_edges = []", "= self.find_rings(including=[index]) if len(rings) != 0: raise RuntimeError( \"Currently functional", "species involved in a connection in alphabetical order (e.g. string", "# using its frac_coords as a convenient key mapping =", "in mg.graph.edges: if edge[2] != 0: duplicates.append(edge) for duplicate in", "that, and returns two or more new MoleculeGraph objects. :return:", "set() sizes = dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index) for neighbor", "options for nodes for n in g.nodes(): # get label", "None if to_jimage is None: raise ValueError(\"Image must be supplied,", "@staticmethod def with_edges(molecule, edges): \"\"\" Constructor for MoleculeGraph, using pre-existing", "will be returned. :return: dict {index:cycle}. Each entry will be", "the edge belongs to. :param structure: a Structure object :param", "are equal if they have equal Structures, and have the", "proper __hash__() value, # using its frac_coords as a convenient", "MoleculeGraph(MSONable): \"\"\" This is a class for annotating a Molecule", "co-ordinates of where # atoms defined by edge are expected", "== n: site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site =", "1. Providing an actual molecule as the input. The first", "None: edge_index = 0 else: for i, properties in existing_edges.items():", "use standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0,", "# creating a supercell is an easy way to extract", "indicating the position of nearest neighbor. The second atom must", "ints): lattice vector of image :param weight (float): e.g. bond", "tuple :param new_weight: alter_edge does not require that weight be", "mapping = {tuple(site.coords): self.molecule.index(site) for site in other.molecule} except ValueError:", "range(len(self.structure) - 1): if j < i: mapping[j] = j", "can appear when removing periodic edges if hide_unconnected_nodes: g =", "to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights else None, warn_duplicates=False, ) return sg", "class manually, use the `with_empty_graph` method or `with_local_env_strategy` method (using", "two Sites. \"\"\" def __init__(self, structure, graph_data=None): \"\"\" If constructing", "been added green_edges.append((u, v, k)) for u, v, k in", "the StructureGraph. :param from_index: int :param to_index: int :param to_jimage:", "is not None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if new_edge_properties is not", ":Class: `pymatgen.analysis.local_env`. :param structure: Structure object :param strategy: an instance", "0), # initial version of this class worked even if", "invalid.\") def set_node_attributes(self): \"\"\" Gives each node a \"specie\" and", "edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d in", "other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges = {(u, v)", "# assume we want the closest site warnings.warn(\"Please specify to_jimage", ":return: \"\"\" old_molecule = self.molecule.copy() # sort Molecule self.molecule._sites =", "an edge that already exists from \" \"site {} to", "(str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d in other.graph.edges(keys=False, data=True) }", "a proper __hash__() value, # using its frac_coords as a", "self.get_connected_sites(index) # If the atom at index is terminal if", "n, jimage=(0, 0, 0)): \"\"\" Returns a named tuple of", "if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] if", "\"#00ff00\"}) for u, v, k in red_edges: g.edges[u, v, k].update({\"color_uv\":", "found in the Molecule. If there is no cycle including", "original = copy.deepcopy(self) sub_mols = list() # Had to use", "0))) for u, v, d in other_sorted.graph.edges(keys=False, data=True) } else:", "for duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg", "list of MoleculeGraphs \"\"\" self.set_node_attributes() original = copy.deepcopy(self) for bond", "might give misleading results for multigraphs (edges are super-imposed on", "None: for (u, v) in graph_dict.keys(): edge_props = graph_dict[(u, v)]", "bond lengths). \"\"\" def get_label(u, v): u_label = self.structure[u].species_string v_label", "keep_dot: os.remove(basename + \".dot\") @property def types_and_weights_of_connections(self): \"\"\" Extract a", "{} for key in unique_frag_dict: unique_mol_graph_list = [] for fragment", "as_dict(self): \"\"\" As in :Class: `pymatgen.core.Structure` except with using `to_dict_of_dicts`", "if not strategy.structures_allowed: raise ValueError( \"Chosen strategy is not designed", "manually, see as_dict method for format) \"\"\" if isinstance(structure, StructureGraph):", "from_index, edge_index) else: raise ValueError( \"Edge cannot be broken between", "edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes, # these can", "# mutli-graphs (matplotlib can superimpose multiple edges). g = self.graph.copy()", "given as (from_index, to_index,\" \" from_image, to_image) tuples\") if props", "of the StructureGraph this method is called from, not the", "In order to prevent problems with misdirected edges, both graphs", "f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1 else: f2_comp_dict[node[1][\"specie\"]] += 1 if f1_comp_dict", "edges # for any one bond, one from site u", ":Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX to", "of edge weights present in the graph. :return: A dict", "add a duplicate edge # there should only ever be", "a StructureGraph \"\"\" sg = StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for", "self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def", "enumerate(self.structure): s = PeriodicSite( site.species, site.coords + v, new_lattice, properties=site.properties,", "node indices replaced by Species strings, will not count number", "neighbors of site n. In graph terms, simply returns degree", "\"X\" func_grp.remove_species(\"X\") if graph_dict is not None: for (u, v)", "edges to be added to the MoleculeGraph. These edges must", "possible fragment combinations of the MoleculeGraphs (in other words, all", "nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped, \"specie\") coords = nx.get_node_attributes(remapped, \"coords\")", "order to be used for Molecule instantiation for k, v", "periodic boundaries if hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) #", "indices in the current Molecule (and graph) to be removed.", "(0, 0, 0), but making this # assumption simplifies logic", "and StructureGraphs can still be considered equal. :param other: StructureGraph", "will be obtained from the relevant template in func_groups.json. :param", "list of new edges inside supercell # for duplicate checking", "= unique_cycles else: for i in including: for cycle in", "return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): \"\"\" This is a", "is substituted will not place atoms to close to each", "original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot split molecule;", "will detect filetype from extension (any graphviz filetype supported, such", "not in the reference graph :param hide_unconnected_nodes: if True, hide", "nodes in graph \"\"\" return len(self.molecule) def sort(self, key=None, reverse=False):", "Jaccard distance is a simple measure of the dissimilarity between", "not (from_index in nodes and to_index in nodes): raise ValueError(", "new_weight is not None: self.graph[from_index][to_index][0][\"weight\"] = new_weight if new_edge_properties is", "exists before attempting to remove it existing_edges = self.graph.get_edge_data(from_index, to_index)", "group # Subtracting 1 because the dummy atom X should", "sp = label[1] if sp not in mapping: mapping[sp] =", "edges will not be added in either case) :param edge_properties", "if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index,", "\"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return sorted(list(motifs)) def as_dict(self): \"\"\" As in", "comparison of node identities. \"\"\" return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def", "jimage=relative_jimage) weight = d.get(\"weight\", None) if (v, to_jimage) not in", "group and the nearest neighbor site. Defaults to 1. :param", "make sure we don't try to add duplicate edges #", "group (format: {(from_index, to_index, from_image, to_image): props}, where props is", "due to periodic boundaries if hide_image_edges: for edge_to_delete in edges_to_delete:", "always be 0 because there should only be one edge", "to_index to_jimage, from_jimage = from_jimage, to_jimage # constrain all from_jimages", "as Structure.__mul__ :return: \"\"\" # Developer note: a different approach", "if not defined. :param n: index of Site in Molecule", "< i: mapping[j] = j else: mapping[j] = j +", "a lot smaller tol = 0.05 for u, v, k,", "# tidy up edge attr dicts, reading to/from json duplicates", "existing_reverse.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(to_index, from_index,", "to_jimage # constrain all from_jimages to be (0, 0, 0),", "): \"\"\" Alters either the weight or the edge_properties of", "assume that all edges should stay remain # inside the", "# optionally remove periodic image edges, # these can be", ") for nnsite in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage", "% len(self.structure) n_v = v % len(self.structure) # get fractional", "__str__(self): s = \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__str__()) s", "new_v = new_v, new_u new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] =", "new edges inside supercell # for duplicate checking edges_inside_supercell =", "other: MoleculeGraph object to be compared. :return: bool \"\"\" if", "Name of the edge weight property of graph \"\"\" return", "reduce unnecessary checking if to_jimage != (0, 0, 0): #", "{} new edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked edges for edges_to_remove", "} edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d", "< from_index: to_index, from_index = from_index, to_index to_jimage, from_jimage =", "in existing_reverse.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(to_index,", "in CH3. The X-C bond indicates the directionality to connect", "mg.set_node_attributes() return mg @property def name(self): \"\"\" :return: Name of", "j + 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges", "In graph terms, simply returns degree of node corresponding to", "= ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) #", "be changed, it should be a float. :param new_edge_properties: alter_edge", "StructureGraph, but this isn't # possible when generating the graph", "self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage,", "= PeriodicSite( site.species, site.coords + v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False,", "two-edge cycles all_cycles = [c for c in nx.simple_cycles(directed) if", "\"coords\") edges = {} for from_index, to_index, key in remapped.edges:", "if is available and networkx if it is not. \"\"\"", "= self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0,", "# keep the graph in sync with its corresponding Structure.", "def sort(self, key=None, reverse=False): \"\"\" Same as Molecule.sort(), also remaps", "StructureGraph object with an empty graph (no edges, only nodes", "nodes in graph to match mapping new_graph = nx.relabel_nodes(subg, mapping)", "node colors color_u = g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"] =", "the new site into the MoleculeGraph. :param i: Index at", "the number of neighbors of site n. In graph terms,", "edge_props.keys(): to_jimage = edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else: # By default,", "header + \"\\n\" + header_line + \"\\n\" edges = list(g.edges(data=True))", "to incorporate the new functional group. NOTE: Care must be", "Important note: all node indices are in terms of the", "= np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present", "__eq__(self, other): \"\"\" Two MoleculeGraphs are equal if they have", "graph is already in place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule,", "new_graphs = [] for v in c_lat: # create a", "n: index of Site in Molecule :param jimage: lattice vector", "(0, 0, 0) relative_jimage = np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v],", "\"\"\" # this is not necessary for the class to", "but # just makes it neater if to_index < from_index:", "if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2,", "the original. Currently, this function naively assigns the charge of", "self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for key, d in existing_edge_data.items(): if", "in new structure for these atoms # query returns (distance,", "add_edge( self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add", "is a dictionary of properties, including weight. If None, then", "nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g in unique_subgraphs ] if", "edge_properties=None, ): \"\"\" Add edge to graph. Since physically a", "sort(self, key=None, reverse=False): \"\"\" Same as Structure.sort(), also remaps nodes", "in enumerate(self.structure): centre_sp = site.species_string connected_sites = self.get_connected_sites(idx) connected_species =", "= set() sizes = dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index) for", "that converts a networkx graph object into an igraph graph", "else None, warn_duplicates=False, ) return sg @property def name(self): \"\"\"", "site_d = self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d)", "\"\"\" if edge_weight_name and (edge_weight_units is None): raise ValueError( \"Please", "\"false\"} # add display options for nodes for n in", "== (0, 0, 0)] new_periodic_images = [] orig_lattice = self.structure.lattice", "function to check if two graph objects are isomorphic, using", "assumption simplifies logic later if not np.array_equal(from_jimage, (0, 0, 0)):", "the Molecule. If there is no cycle including an index,", "Returns a named tuple of neighbors of site n: periodic_site,", "molecule to a single submolecule. A later effort will be", "is the index of the corresponding site in the original", "list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' \"\"\" all_weights = [d.get(\"weight\",", "\" \"corresponding Structures are different.\") if strict: # sort for", "cycle in unique_cycles: if i in cycle and cycle not", "tuple(map(int, np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist()", "edges): \"\"\" Constructor for MoleculeGraph, using pre-existing or pre-defined edges", "a given (site, jimage) pair and another # (site, jimage)", "# by definition else: jaccard_dist = 1 - len(edges.intersection(edges_other)) /", "index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self, including=None):", "Subtracting 1 because the dummy atom X should not count", "c, no_cross=True, reorder=False) else: structure = None for n in", "site into the MoleculeGraph. :param i: Index at which to", "3): scale_matrix = np.array(scale_matrix * np.eye(3), np.int16) else: # TODO:", "reorder=False) else: structure = None for n in range(len(molecule)): if", "site connecting from :param to_index: index of site connecting to", "*before* generating the StructureGraph, but this isn't # possible when", "node indices # representing both site index and periodic image.", "v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <= tol", "= list() # Had to use nx.weakly_connected_components because of deprecation", "# So, we must also remove duplicates unique_sorted = []", "properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(from_index, to_index, edge_index) else:", "sp)) labels = sorted(labels, reverse=True) if anonymous: mapping = {centre_sp:", "Had to use nx.weakly_connected_components because of deprecation # of nx.weakly_connected_component_subgraphs", "{} for key in frag_dict: unique_frags = [] for frag", "# control over graph appearance and also correctly displays #", "origin is at center of mass molecule = molecule.get_centered_molecule() molecules.append(molecule)", "None if v_present is not None: new_u = u new_v", "full periodic boundary conditions # so that nodes on one", "sum([1 for n, v in self.graph.edges(n) if n == v])", "= [] for edge in mg.graph.edges: if edge[2] != 0:", "when serializing back from json), it's important images # are", "NetworkX to store graph information. \"\"\" d = { \"@module\":", "if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) for", "tol = 0.05 for u, v, k, d in new_g.edges(keys=True,", "# check if image sites now present in supercell #", "\"\"\" If constructing this class manually, use the `with_empty_graph` method", "in graph. :param key: :param reverse: :return: \"\"\" old_structure =", "class for annotating a Molecule with bond information, stored in", "to lists happens # when serializing back from json), it's", "As in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from", "in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX", "\"\"\" A wrapper around Molecule.insert(), which also incorporates the new", "del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else: if isinstance(func_grp, Molecule):", "where atoms defined # by edge are expected to be,", "at center of mass molecule = molecule.get_centered_molecule() molecules.append(molecule) return molecules", "nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in graph.edges()])", "0: raise RuntimeError(\"{} exited with return code {}.\".format(algo, rs.returncode)) if", "original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return", ":param key: :param reverse: :return: \"\"\" old_structure = self.structure.copy() #", "# query returns (distance, index) v_present = kd_tree.query(v_expec) v_present =", ":param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_reverse", "only (generally) work with structures # molecules have to be", "if True, label edges with weights :param image_labels (bool): if", "both (from_index, to_index) and, failing that, will attempt to break", "default, assume that all edges should stay remain # inside", "(bool): if True, label nodes with species and site index", "for u, v, k, d in self.graph.edges(keys=True, data=True): if v", "(not intended to be constructed manually, see as_dict method for", "edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return cls(structure,", "can also have a \"weight\" and a \"properties\" key. :return:", "changed. :return: \"\"\" existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure that", "in frag_dict: unique_frags = [] for frag in frag_dict[key]: found", "including the specified sites. By default, this parameter is None,", "coords=coords, charge=self.molecule.charge), edges, ) ) frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) +", "out_edges = list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n, data=True)) for u,", "colors color_u = g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u,", "(cycle, in graph theory terms) including the index found in", "graph information in dict format (not intended to be constructed", "\"\"\" return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\" Helper function", "remove_nodes(self, indices): \"\"\" A wrapper for Molecule.remove_sites(). :param indices: list", "new_d = d.copy() # node now inside supercell new_d[\"to_jimage\"] =", "for all atoms in the molecule # in order to", "and to_index in nodes): raise ValueError( \"Edges cannot be added", "only ever be at most one edge # between two", "This is a class for annotating a Molecule with bond", "to_jimage (tuple of ints): lattice vector of image :param weight", "\"VESTA\" or \"JMOL\" :param keep_dot (bool): keep GraphViz .dot file", "set edge style d[\"style\"] = \"solid\" if to_image != (0,", "new_edge_properties is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] =", "number of nodes != number of sites in the Structure.", "with_edges(structure, edges): \"\"\" Constructor for MoleculeGraph, using pre-existing or pre-defined", "atoms defined by edge # are expected to be v_expec", "dummy atom X should not count atoms = len(grp) -", "co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs = set() for", "__copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two StructureGraphs are", "connect the nearest neighbor to the C atom in CH3.", "returns two or more new MoleculeGraph objects. :param bonds: list", "new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs = [] for v in", ":return: Units of the edge weight property of graph \"\"\"", "should at least have a \"to_index\" and \"from_index\" key, and", "# which new lattice images present, but should hopefully be", "= np.add(site_d[\"abc\"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d) # from_site if jimage", "tuple of neighbors of site n: periodic_site, jimage, index, weight.", "Molecule / number of nodes in graph \"\"\" return len(self.molecule)", "a networkx graph object into an igraph graph object. \"\"\"", "to_jimage: edge_index = i if new_weight is not None: self.graph[from_index][to_index][edge_index][\"weight\"]", "other): \"\"\" Checks if the graphs of two MoleculeGraphs are", "from original graph to its image mapping = {n: n", "len(self.molecule)): for combination in combinations(graph.nodes, ii): mycomp = [] for", "in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def", "for a methyl group substitution, func_grp should be X-CH3, where", "[] new_graphs = [] for v in c_lat: # create", "in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight = None if", "most one edge # between two sites existing_edge_data = self.graph.get_edge_data(from_index,", "methods to make associating a graph with a given molecule", "one edge # between a given (site, jimage) pair and", "which from networkx.drawing.nx_agraph import write_dot from networkx.readwrite import json_graph from", "dicts, reading to/from json duplicates # information for u, v,", "{} # Get indices now occupied by functional group #", "to automatically determine bonds using one of a list of", "of edges in the graph. :return: A dictionary with keys", "to remove it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse = None", "u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v)", "in unique_cycles: if i in cycle and cycle not in", "algo=\"fdp\", ): \"\"\" Draws graph using GraphViz. The networkx graph", "# between two sites existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data", "enantiomers as being duplicates. :return: list of unique Molecules in", "which also incorporates the new site into the MoleculeGraph. :param", "# optionally hide unconnected nodes, # these can appear when", "g = self.graph.copy() g.graph = {\"nodesep\": 10.0, \"dpi\": 300, \"overlap\":", "\"\"\" return self.graph.graph[\"name\"] @property def edge_weight_name(self): \"\"\" :return: Name of", "node u as a reference, # get relative Cartesian co-ordinates", "site.species_string connected_sites = self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for connected_site in", "graph_data=graph_data) @staticmethod def with_edges(molecule, edges): \"\"\" Constructor for MoleculeGraph, using", "connected_species = [connected_site.site.species_string for connected_site in connected_sites] labels = []", "= sum([1 for n, v in self.graph.edges(n) if n ==", "for periodic image in +x direction :param to_jimage (tuple of", "n: site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site,", "coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper around", ") def get_connected_sites(self, n, jimage=(0, 0, 0)): \"\"\" Returns a", "g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\" #", "mapping[j] = j else: mapping[j] = j + 1 nx.relabel_nodes(self.graph,", "next nearest atom. For example, for a methyl group substitution,", "data=True)} edges_other = {(u, v, d[\"to_jimage\"]) for u, v, d", "range(25)] for label in labels: sp = label[1] if sp", "v in c_lat: # create a map of nodes from", "2]) - min(coords[:, 2]) + 100 structure = molecule.get_boxed_structure(a, b,", "the NetworkX package to store and operate on the graph", "int :param to_index: int :param to_jimage: tuple :param new_weight: alter_edge", "== to_jimage: edge_index = i if new_weight is not None:", "including the index found in the Molecule. If there is", "!= len(other.graph.edges()): return False return _isomorphic(self.graph, other.graph) def diff(self, other,", "= ( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), ) from_index, to_index =", "to periodic boundaries if hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete)", "two or more new MoleculeGraph objects. :param bonds: list of", ":param other: MoleculeGraph :param strict: if False, will compare bonds", "Lattice, Molecule, PeriodicSite, Structure from pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord", "is a disconnected subgraph of the original. Currently, this function", "MoleculeGraph \"\"\" if not strategy.molecules_allowed: raise ValueError( \"Chosen strategy is", "update edge with our new style attributes g.edges[u, v, k].update(d)", "logger.debug(\"Removing {} edges, adding {} new edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete", "= self.diff(diff, strict=True) green_edges = [] red_edges = [] for", "def _compare(g1, g2, i1, i2): \"\"\" Helper function called by", "strategy_params=strategy_params, ) else: rings = self.find_rings(including=[index]) if len(rings) != 0:", "color_u = g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v)", "(site, jimage) pair and another # (site, jimage) pair existing_edge_data", "new MoleculeGraph objects. :return: list of MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph):", "if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols = list()", "None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)])", "self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\")", "v_expec = new_structure[u].coords + v_rel # now search in new", "Structure kd_tree = KDTree(new_structure.cart_coords) # tolerance in Å for sites", "d.copy() new_to_jimage = tuple(map(int, v_expec_image)) # normalize direction if new_v", "in f1_nodes: if node[1][\"specie\"] not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1", "the MoleculeGraph. These edges must include the index of the", "weight = props[\"weight\"] del props[\"weight\"] else: weight = None if", ") unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group( self, index,", "define how we test for isomorphism def node_match(n1, n2): return", "weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight,", "self.set_node_attributes() graph = self.graph.to_undirected() # find all possible fragments, aka", "between sites) doesn't have a direction, from_index, from_jimage can be", "if j < i: mapping[j] = j else: mapping[j] =", "periodic_site, jimage, index, weight. Index is the index of the", "an image node, and seeing if that node exists in", "to find connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) # find subgraphs", "to_index in nodes): raise ValueError( \"Edges cannot be added if", "edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d)", "graph_data = json_graph.adjacency_data(new_graph) # create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return", "site.coords + v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph,", "the code will do is to remove the index site,", "the original graph, but a larger graph can be easier", "to_index=nnsite.index, ) return # sanitize types from_jimage, to_jimage = (", "shifted so that from_index < to_index and from_jimage becomes (0,", "RuntimeError(\"StructureGraph graph drawing requires \" \"GraphViz binaries to be in", "MoleculeGraphs can still be considered equal. :param other: MoleculeGraph :return", "pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS try: import igraph", "# use k-d tree to match given position to an", "alter_edge does not require that weight be altered. As such,", "is not None: for (u, v) in graph_dict.keys(): edge_props =", "diff graph but not in the reference graph :param hide_unconnected_nodes:", "supercell. If it does, the edge is updated. This is", "return s def __repr__(self): s = \"Molecule Graph\" s +=", "self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d) # from_site", "other information to store on graph edges, similar to Structure's", "\"self\": edges - edges_other, \"other\": edges_other - edges, \"both\": edges.intersection(edges_other),", "indices are in terms of the MoleculeGraph this method is", "specified. :return: mg, a MoleculeGraph \"\"\" mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\",", "or more MoleculeGraphs by breaking a set of bonds. This", "dashed lines) :param color_scheme (str): \"VESTA\" or \"JMOL\" :param keep_dot", "# apply Structure ordering to graph mapping = {idx: self.structure.index(site)", "treat e.g. enantiomers as being duplicates. :return: list of unique", "del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else:", "using a MoleculeGraph will generally produce a different graph compared", "# add display options for edges for u, v, k,", "dicts representing edges to be added to the MoleculeGraph. These", "frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.molecule.index(site) for", "each subgraph molecules = [] for subgraph in unique_subgraphs: coords", "inside supercell new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v, k))", "only alter the graph information, but also changes the underlying", "alterations[(u, v)]: weight = alterations[(u, v)][\"weight\"] del alterations[(u, v)][\"weight\"] edge_properties", "equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index,", "v = v, u to_jimage = np.multiply(-1, to_jimage) to_jimage =", "{ \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), }", "(to_index, from_index). :return: \"\"\" # ensure that edge exists before", "= np.array(scale_matrix * np.eye(3), np.int16) else: # TODO: test __mul__", "to the MoleculeGraph. These edges must include the index of", "appears twice # So, we must also remove duplicates unique_sorted", "Molecule). :param molecule (Molecule): :param name (str): name of graph,", "from, not the 'other' StructureGraph: there is no guarantee the", "will be the same if the underlying Molecules are ordered", "for use with structures! \" \"Please choose another strategy.\" )", "= kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <= tol else", "weight. Index is the index of the corresponding site in", "format) \"\"\" if isinstance(molecule, MoleculeGraph): # just make a copy", "len(edges) == 0 and len(edges_other) == 0: jaccard_dist = 0", "== \"in\": u, v = v, u to_jimage = np.multiply(-1,", "(str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) }", "be specified. :return: mg, a MoleculeGraph \"\"\" mg = MoleculeGraph.with_empty_graph(molecule,", "Molecule, PeriodicSite, Structure from pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord import", "This function does not only alter the graph information, but", "and MoleculeGraph.substitute_group to replace a functional group in self.molecule with", "None) is None: self._supercell_sg = supercell_sg = self * (3,", "group. TODO: Figure out how to replace into a ring", "for idx, site in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True)", "edges if hide_unconnected_nodes: g = g.subgraph([n for n in g.degree()", "[{u, v} for u, v, d in new_g.edges(data=True) if d[\"to_jimage\"]", "include the index of the new site i, and all", "for Molecule :param edges: List of dicts representing edges to", "edges.append((cycle[i - 1], e)) cycles_edges.append(edges) return cycles_edges def get_connected_sites(self, n):", "= subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode != 0:", "None, default parameters will be used. :return: \"\"\" self.set_node_attributes() neighbors", "edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self,", "structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for StructureGraph, returns a", "the `with_empty_graph` method or `with_local_env_strategy` method (using an algorithm provided", ":param structure (Structure): :param name (str): name of graph, e.g.", "edges_other = {(u, v, d[\"to_jimage\"]) for u, v, d in", "\"\"\" Draws graph using GraphViz. The networkx graph object itself", "O'Keeffe). This class that contains connection information: relationships between sites", "bonds parameter does not include sufficient bonds to separate two", "f2_edges = frag2.edges() if len(f2_edges) != len(f2_edges): return False f1_comp_dict", "= d[\"to_jimage\"] if dir == \"in\": u, v = v,", "from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes() return sg", ":return: list of unique Molecules in Structure \"\"\" # creating", "\"corresponding Molecules are different.\") if strict: # sort for consistent", "no additional properties are to be specified. :return: mg, a", "StructureGraph \"\"\" sg = StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge,", "structure: Structure object :param strategy: an instance of a :Class:", "return sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): \"\"\" Split MoleculeGraph", "func_groups.json. 3. A MoleculeGraph object. :param strategy: Class from pymatgen.analysis.local_env.", "graph, creating a supercell, intelligently joining together edges that lie", "logging import os.path import subprocess import warnings from collections import", "of ints): lattice vector of periodic image, e.g. (1, 0,", "site warnings.warn(\"Please specify to_jimage to be unambiguous, \" \"trying to", "Figure out how to replace into a ring structure. :param", "if 1 - (c[0] * 0.299 + c[1] * 0.587", "RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\" Replicates molecule site", "= \"{:.2f} {}\".format(d[\"weight\"], units) # update edge with our new", "periodic image, e.g. (1, 0, 0) for periodic image in", "indices are in terms of the StructureGraph this method is", "= None nodes = sg.graph.nodes if not (from_index in nodes", "graph.nodes(data=True) new_igraph = igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"],", "available and networkx if it is not. \"\"\" f1_nodes =", "node in f1_nodes: if node[1][\"specie\"] not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] =", "into two disconnected subgraphs \"\"\" pass class MoleculeGraph(MSONable): \"\"\" This", "nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for subg", "green_edges: g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"}) for u, v, k in", "= False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = \"<NAME>, <NAME>,", "= u, v, d.copy() new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u,", "critic2 from # charge density. # Multiplication works by looking", "list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, allow_reverse=False): \"\"\"", "False if len(self.graph.edges()) != len(other.graph.edges()): return False return _isomorphic(self.graph, other.graph)", "strategy_params=strategy_params, ) def find_rings(self, including=None): \"\"\" Find ring structures in", "in graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"to_jimage\" in edge_props.keys():", "n in g.degree() if g.degree()[n] != 0]) # optionally highlight", "structure = molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False) else: structure =", "label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", ) edges_to_delete = [] # add", "graph to compare with, will color edges red that do", "(u, v, d[\"to_jimage\"]) in diff[\"self\"]: # edge has been deleted", "yet.\") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat =", "or {} if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else:", "charge of the total molecule to a single submolecule. A", "can superimpose multiple edges). g = self.graph.copy() g.graph = {\"nodesep\":", "len(f2_nodes): return False f2_edges = frag2.edges() if len(f2_edges) != len(f2_edges):", "that already exists from \" \"site {} to site {}.\".format(from_index,", "= [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g in unique_subgraphs", "more # computationally expensive than just keeping track of the", "specify to_jimage to be unambiguous, \" \"trying to automatically detect.\")", "self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse) # apply Molecule ordering to", "[] for frag in frag_dict[key]: found = False for f", "it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if existing_edge:", "structure. :param index: Index of atom to substitute. :param func_grp:", "weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else:", "m = Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"]) @classmethod def _edges_to_string(cls, g):", "s = \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s +=", "max(coords[:, 0]) - min(coords[:, 0]) + 100 b = max(coords[:,", "graph information. \"\"\" d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__,", "connects two Sites. \"\"\" def __init__(self, molecule, graph_data=None): \"\"\" If", "itself can also be drawn with networkx's in-built graph drawing", "list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs =", "other, or violate the dimensions of the Lattice. :param index:", "not None: new_u = u new_v = v_present new_d =", "Whether coordinates are cartesian. Defaults to False. :param validate_proximity: For", "with A, B, C, etc. :return: a list of co-ordination", "looking for the expected position # of an image node,", "# sort Molecule self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse) # apply", "edge that went through # periodic boundary if v_present is", "duplicate defined as an isomorphic subgraph). :param use_weights (bool): If", "into the MoleculeGraph. :param i: Index at which to insert", "{n: n + len(new_sites) for n in range(len(self.structure))} for idx,", "MolGraphSplitError( \"Cannot split molecule; \\ MoleculeGraph is still connected.\" )", "strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) for (u, v) in list(graph.graph.edges()):", "def from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Structure` except restoring", "edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else: if isinstance(func_grp,", "alterations[(u, v)] if len(alterations[(u, v)]) != 0 else None original.alter_edge(u,", "does not only alter the graph information, but also changes", "self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def insert_node( self, i, species, coords,", "to multiply the Structure # *before* generating the StructureGraph, but", "prop_set in raw_props.values(): for prop in prop_set.keys(): if prop in", "before. Each dict should at least have a \"to_index\" and", "} else: edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v,", "* 0.587 + c[2] * 0.114) / 255 < 0.5", "0, 0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete", "objects. :param other: MoleculeGraph object to be compared. :return: bool", "specified. :return: sg, a StructureGraph \"\"\" sg = StructureGraph.with_empty_graph(structure, name=\"bonds\",", "the position of node u as a reference, # get", "pymatgen.vis.structure_vtk import EL_COLORS try: import igraph IGRAPH_AVAILABLE = True except", "worked even if # from_jimage != (0, 0, 0), but", "= KDTree(new_structure.cart_coords) # tolerance in Å for sites to be", "in subgraph.nodes()] molecule = Molecule(species, coords) # shift so origin", "site in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize", "physically a 'bond' (or other connection between sites) doesn't have", "alterations[(u, v)][\"weight\"] del alterations[(u, v)][\"weight\"] edge_properties = alterations[(u, v)] if", "molecule fragments, then this function will fail. Currently, this function", "graph.edges()]) return new_igraph def _isomorphic(frag1, frag2): \"\"\" Internal function to", "another strategy.\" ) sg = StructureGraph.with_empty_graph(structure, name=\"bonds\") for n, neighbors", "1 - (c[0] * 0.299 + c[1] * 0.587 +", "color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0])", "= self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0: # this will happen", "this method will fail. :param from_index: int :param to_index: int", "\"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current in", "with structures # molecules have to be boxed first coords", "site properties edge_properties = edge_properties or {} if weight: self.graph.add_edge(from_index,", "# sanitize types from_index, to_index = int(from_index), int(to_index) # check", "nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of edges edges_to_remove =", "if they have equal Structures, and have the same edges", "in neighbors: # all bonds in molecules should not cross", "add labels for images that are not the origin if", "= _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm =", "Constructor for StructureGraph, returns a StructureGraph object with an empty", "MoleculeGraphs if \" \"corresponding Molecules are different.\") if strict: #", "shift so origin is at center of mass molecule =", "for StructureGraph, returns a StructureGraph object with an empty graph", "detection of to_jimage if user doesn't specify # will try", "= [] for v in c_lat: # create a map", "key in remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)]", "the node indices will be the same if the underlying", "Index is the index of the corresponding site in the", "to_jimage: edge_index = i self.graph.remove_edge(from_index, to_index, edge_index) else: if allow_reverse:", "node_match=nm) class StructureGraph(MSONable): \"\"\" This is a class for annotating", "\"bond_length\" or \"exchange_constant\" :param edge_weight_units (str): name of edge weight", "between any two nodes if new_weight is not None: self.graph[from_index][to_index][0][\"weight\"]", "to interpret, `hide_image_edges` can help, especially in larger graphs. :param", "additional edge properties, # similar to site properties edge_properties =", "subgraphs \"\"\" pass class MoleculeGraph(MSONable): \"\"\" This is a class", "from_jimage becomes (0, 0, 0). :param from_index: index of site", "Each entry will be a ring (cycle, in graph theory", "= g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label += \"", "tuple(map(int, to_jimage)), ) from_index, to_index = int(from_index), int(to_index) # check", "label in labels] labels = [\"{}({})\".format(label[1], label[0]) for label in", "bonds of the functional group (format: {(u, v): props}, where", "naively assigns the charge of the total molecule to a", ":return (StructureGraph): \"\"\" if edge_weight_name and (edge_weight_units is None): raise", "in labels] labels = [\"{}({})\".format(label[1], label[0]) for label in labels]", "# check we're not trying to add a duplicate edge", "copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError(\"Can't find functional group in list.", "self.structure with a functional group. This method also amends self.graph", "number of nodes in graph \"\"\" return len(self.molecule) def sort(self,", "but also changes the underlying Molecules. If the bonds parameter", "to break both (from_index, to_index) and, failing that, will attempt", "func_grp = copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception:", "in range(25)] for label in labels: sp = label[1] if", "NOTE: using a MoleculeGraph will generally produce a different graph", "in self.structure with a functional group. This method also amends", "weights, e.g. \"bond_length\" or \"exchange_constant\" :param edge_weight_units (str): name of", "algo, \"neato\" (for simple graphs) or \"fdp\" (for more crowded", "with index 0 # TODO: actually figure out how to", "site :param coords_are_cartesian: Whether coordinates are cartesian. Defaults to False.", "of helper methods to make associating a graph with a", "Props should be None if no additional properties are to", "don't try to add duplicate edges # will remove two", "# just give charge to whatever subgraph has node with", "other): return self.__mul__(other) @classmethod def _edges_to_string(cls, g): header = \"from", "a \"properties\" key. :return: \"\"\" self.molecule.insert( i, species, coords, validate_proximity=validate_proximity,", "= u new_v = v_present new_d = d.copy() new_to_jimage =", "self.set_node_attributes() original = copy.deepcopy(self) for bond in bonds: original.break_edge(bond[0], bond[1],", "nx.get_node_attributes(new_graph, \"properties\") properties = {} for prop_set in raw_props.values(): for", "be compared. :return: bool \"\"\" if len(self.molecule) != len(other.molecule): return", "typically in primitive single-atom lattices images = [1, 0, 0],", "to incorrect image v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image", "idx, site in enumerate(self.structure): centre_sp = site.species_string connected_sites = self.get_connected_sites(idx)", "\"max\": stats.minmax[1], \"mean\": stats.mean, \"variance\": stats.variance, } def types_of_coordination_environments(self, anonymous=False):", "\"neato\" (for simple graphs) or \"fdp\" (for more crowded graphs)", "figure out how to distribute charge if 0 in nodes:", "build_unique_fragments(self): \"\"\" Find all possible fragment combinations of the MoleculeGraphs", "where atoms defined by edge # are expected to be", "co-ordinates of where atoms defined by edge # are expected", "indices. If including is not None, then find_rings will only", "= iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): \"\"\"", "logic later if not np.array_equal(from_jimage, (0, 0, 0)): shift =", "np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist() site", "structure easier. Use cases for this include storing bonding information,", "0: # this will happen when from_index == to_index, #", "= tuple(map(int, v_expec_image)) # normalize direction if new_v < new_u:", "keys 'self', 'other', 'both' with edges that are present in", "kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <= tol else None", "that already exists from \" \"site {} to site {}", "ensure that the functional group that is substituted will not", "jaccard_dist = 0 # by definition else: jaccard_dist = 1", "= {} for key in frag_dict: unique_frags = [] for", "displays # mutli-graphs (matplotlib can superimpose multiple edges). g =", "g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"}) for u, v, k in red_edges:", "= { (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d in self.graph.edges(keys=False,", "of Molecule.substitute to replace an atom in self.molecule with a", "\"\"\" d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(),", "# from_jimage != (0, 0, 0), but making this #", "first coords = molecule.cart_coords if extend_structure: a = max(coords[:, 0])", "[] for v in c_lat: # create a map of", "= undirected.to_directed() cycles_nodes = [] cycles_edges = [] # Remove", "Compares two MoleculeGraphs. Returns dict with keys 'self', 'other', 'both'", "edges_to_remove = [] edges_to_add = [] for u, v, k,", "have a \"weight\" and a \"properties\" key. :return: \"\"\" self.structure.insert(", "<NAME>\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\"", "strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure, n) for neighbor in", "(default False), distance will be checked to ensure that site", "= graph.graph.get_edge_data(u, v)[0] weight = None if \"weight\" in edge_props.keys():", "i != keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy, bond_order=bond_order,", "the original structure, weight can be None if not defined.", "properties (specie, coords, etc.) in the MoleculeGraph. :return: \"\"\" species", "# use standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol),", "method will fail. :param from_index: int :param to_index: int :param", "new_to_jimage = tuple(map(int, v_expec_image)) # normalize direction if new_v <", "a set of bonds. This function uses MoleculeGraph.break_edge repeatedly to", "\"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\",", "numbers account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\"", "to_jimage=None, allow_reverse=False): \"\"\" Remove an edge from the StructureGraph. If", "# sanitize types from_jimage, to_jimage = ( tuple(map(int, from_jimage)), tuple(map(int,", "if True, do not draw edges that go through periodic", "key, and can also have a \"weight\" and a \"properties\"", "`from_dict_of_dicts` from NetworkX to restore graph information. \"\"\" s =", "NotImplementedError(\"Not tested with 3x3 scaling matrices yet.\") new_lattice = Lattice(np.dot(scale_matrix,", "connected induced subgraphs frag_dict = {} for ii in range(1,", "of edge properties to be changed. :return: \"\"\" existing_edge =", "of bonds :return: \"\"\" if self.molecule != other.molecule and strict:", "e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs = set() for idx, site", "other_sorted.molecule) def isomorphic_to(self, other): \"\"\" Checks if the graphs of", "equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist * 0.01, include_index=True )", "substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\"", "@property def name(self): \"\"\" :return: Name of graph \"\"\" return", "e.g. \"Å\" or \"eV\" :return (StructureGraph): \"\"\" if edge_weight_name and", "0], [0, 0, 1] dists = [] for image in", "edge_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse:", "def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Structure` except with using", "in edges_to_add: new_g.add_edge(u, v, **d) # return new instance of", "more difficult to # keep the graph in sync with", "can still be considered equal. :param other: StructureGraph :return (bool):", "be returned. :return: dict {index:cycle}. Each entry will be a", "# Molecule indices are essentially list-based, so node indices #", "called by isomorphic to ensure comparison of node identities. \"\"\"", "a ring\" \"structure.\" ) to_remove = set() sizes = dict()", "np.array(scaling_matrix, np.int16) if scale_matrix.shape != (3, 3): scale_matrix = np.array(scale_matrix", "functional group in list. \" \"Provide explicit coordinate instead\") self.molecule.substitute(index,", "**d) def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two", "\"to {}\".format((to_image)) d[\"arrowhead\"] = \"normal\" if d[\"headlabel\"] else \"none\" #", "graph itself, but contains a lot of helper methods to", "d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None):", "split. :param allow_reverse: If allow_reverse is True, then break_edge will", "{} and {} cannot be altered;\\ no edge exists between", "of node identities. \"\"\" return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph):", "functional group. This method also amends self.graph to incorporate the", "all possible fragment combinations of the MoleculeGraphs (in other words,", "@classmethod def from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Molecule` except", "computationally expensive than just keeping track of the # which", "graphviz filetype supported, such as pdf or png) :param diff", "of where # atoms defined by edge are expected to", "MoleculeGraph is a disconnected subgraph of the original. Currently, this", "images (usually only used for debugging, edges to periodic images", "v_expec_image % 1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac)", "if not defined to_image = d[\"to_jimage\"] # set edge style", "of edges. This is returned with key 'dist'. Important note:", "lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs = []", "= list(self.graph.in_edges(n, data=True)) for u, v, d in out_edges +", "raw_props = nx.get_node_attributes(new_graph, \"properties\") properties = {} for prop_set in", "= \"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey =", "extend to a general 3x3 scaling matrix. # code adapted", "not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1 else: f1_comp_dict[node[1][\"specie\"]] += 1", "Structure # *before* generating the StructureGraph, but this isn't #", "site n_u = u % len(self.structure) n_v = v %", "the new site :param species: Species for the new site", "for prop in prop_set.keys(): if prop in properties: properties[prop].append(prop_set[prop]) else:", "of Molecule / number of nodes in graph \"\"\" return", "from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index, ) return # sanitize", "a list of weights for those connections (e.g. bond lengths).", "different co-ordination environments present in the graph. :param anonymous: if", "weights from local_env class (consult relevant class for their meaning)", "pair existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for key, d", "Structure ordering to graph mapping = {idx: self.structure.index(site) for idx,", "method or `with_local_env_strategy` method (using an algorithm provided by the", "will fail. :param from_index: int :param to_index: int :param to_jimage:", "# now define how we test for isomorphism def node_match(n1,", "i self.graph.remove_edge(to_index, from_index, edge_index) else: raise ValueError( \"Edge cannot be", "def __eq__(self, other): \"\"\" Two MoleculeGraphs are equal if they", "to_jimage: tuple :param new_weight: alter_edge does not require that weight", "unique_subgraphs: coords = [supercell_sg.structure[n].coords for n in subgraph.nodes()] species =", ":param edges: List of dicts representing edges to be added", "{} strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) for (u,", "if True, use node colors to color edges :param node_labels", "= [(u, v, d, \"out\") for u, v, d in", "u, v, k, d in g.edges(keys=True, data=True): # retrieve from/to", "mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def substitute_group( self,", "has node with index 0 # TODO: actually figure out", "if extend_structure: a = max(coords[:, 0]) - min(coords[:, 0]) +", "the bonds of the functional group (format: {(from_index, to_index, from_image,", "else: to_image = (0, 0, 0) # set edge style", "this method is called from, not the 'other' MoleculeGraph: there", "If None, then the algorithm will attempt to automatically determine", "allow_reverse: If allow_reverse is True, then break_edge will attempt to", "= \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\",", "<= tol else None if v_present is not None: new_u", "shift) to_jimage = np.subtract(to_jimage, shift) # automatic detection of to_jimage", "= v_present new_d = d.copy() new_to_jimage = tuple(map(int, v_expec_image)) #", "= self.structure[v].species_string return \"-\".join(sorted((u_label, v_label))) types = defaultdict(list) for u,", "in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight,", "# generic container for additional edge properties, # similar to", ") duplicates = [] for edge in mg.graph.edges: if edge[2]", "\"id\" in d: del d[\"id\"] if \"key\" in d: del", "strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) for (u, v)", "a graph with a given molecule easier. Use cases for", "of to_jimage if user doesn't specify # will try and", "copy from input graph_data = structure.as_dict()[\"graphs\"] self.structure = structure self.graph", "0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge to", "label edges with their periodic images (usually only used for", "\"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(self, from_index,", "\"Edges cannot be added if nodes are not\" \" present", "@staticmethod def with_local_env_strategy(structure, strategy, weights=False): \"\"\" Constructor for StructureGraph, using", "exists from \" \"site {} to site {}.\".format(from_index, to_index) )", "an atom within a ring\" \"structure.\" ) to_remove = set()", "the # number of nodes != number of sites in", "prop in properties: properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]] # Site", "# (artificial) periodic boundaries if not np.array_equal(neighbor[\"image\"], [0, 0, 0]):", "\"normal\" if d[\"headlabel\"] else \"none\" # optionally color edges using", "format) \"\"\" if isinstance(structure, StructureGraph): # just make a copy", "just for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, )", "unambiguous, \" \"trying to automatically detect.\") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index])", "will be used. :return: \"\"\" self.set_node_attributes() neighbors = self.get_connected_sites(index) #", "color_v) if edge_colors else \"#000000\" # optionally add weights to", "new_weight is not None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if new_edge_properties is", "will not be added in either case) :param edge_properties (dict):", "when generating the graph using critic2 from # charge density.", ":param molecule: Molecule object :param graph_data: dict containing graph information", "first site and C is the second site. What the", "= set() out_edges = [(u, v, d, \"out\") for u,", "image :param weight (float): e.g. bond length :param warn_duplicates (bool):", "nodes on one side of supercell # are connected to", "= new_to_jimage edges_to_remove.append((u, v, k)) if (new_u, new_v, new_to_jimage) not", "NOT before. Each dict should at least have a \"to_index\"", "\"min\": stats.minmax[0], \"max\": stats.minmax[1], \"mean\": stats.mean, \"variance\": stats.variance, } def", "a Graph structure, and an associated structure object. This class", "types from_index, to_index = int(from_index), int(to_index) # check we're not", "allows for much easier # control over graph appearance and", "= d[\"to_jimage\"] # for node v # reduce unnecessary checking", "for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self, from_index,", "0). :param from_index: index of site connecting from :param to_index:", "across *supercell* boundaries # these will subgraphs representing crystals molecule_subgraphs", "with molecules! \" \"Please choose another strategy.\" ) extend_structure =", "nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge( self, from_index,", "motif = \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return sorted(list(motifs)) def as_dict(self): \"\"\"", "g2, i1, i2): \"\"\" Helper function called by isomorphic to", "that are not the origin if image_labels: d[\"headlabel\"] = \"\"", "bonds. This function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs", "information that connects two Sites. \"\"\" def __init__(self, structure, graph_data=None):", "tolerance in Å for sites to be considered equal #", "structure (Structure): :param name (str): name of graph, e.g. \"bonds\"", "g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"}) basename, extension = os.path.splitext(filename) extension =", "= tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) #", "d in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.molecule", "v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v, d[\"to_jimage\"])", "a convenient key mapping = {tuple(site.frac_coords): self.structure.index(site) for site in", "string color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor,", "return unique_mol_graph_dict def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None,", "simplified if a graph is already in place if isinstance(func_grp,", "is updated. This is more # computationally expensive than just", "dictionary of properties, including weight. Props should be None if", "graph. :param anonymous: if anonymous, will replace specie names with", "a statistical summary of edge weights present in the graph.", "graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, from_jimage=(0,", "edge_weight_name(self): \"\"\" :return: Name of the edge weight property of", "Remove all two-edge cycles all_cycles = [c for c in", "subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode != 0: raise", "from_index, to_index = int(from_index), int(to_index) # check we're not trying", "for edges for u, v, k, d in g.edges(keys=True, data=True):", "mapping: mapping[sp] = available_letters.pop(0) centre_sp = \"A\" labels = [(label[0],", "def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two MoleculeGraphs", "equal Structures, and have the same edges between Sites. Edge", "\"specie\") coords = nx.get_node_attributes(new_graph, \"coords\") raw_props = nx.get_node_attributes(new_graph, \"properties\") properties", "e.g., layers of a 2D crystal) # without adding extra", "del d[\"id\"] if \"key\" in d: del d[\"key\"] # ensure", "much easier # control over graph appearance and also correctly", "current species and coordinates. :return: \"\"\" species = {} coords", "value, # using its frac_coords as a convenient key mapping", "different indexing u, v = (u - 1), (v -", "cycle in cycles_nodes: edges = [] for i, e in", "return cycles_edges def get_connected_sites(self, n): \"\"\" Returns a named tuple", "[] unique_cycles = [] for cycle in all_cycles: if sorted(cycle)", "in edges: s += \"{:4} {:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0,", "self, filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\",", "should always be 0 because there should only be one", "in self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node] =", "with misdirected edges, both graphs are converted into undirected nx.Graph", "key try: mapping = {tuple(site.coords): self.molecule.index(site) for site in other.molecule}", "tested with 3x3 scaling matrices yet.\") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix))", "} sg = StructureGraph.from_dict(d) return sg def __rmul__(self, other): return", "its frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.molecule.index(site)", "True, then break_edge will attempt to break both (from_index, to_index)", "(distance, index) v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0]", "= json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule, edges): \"\"\"", "v to site u: this is # harmless, so warn_duplicates=False", "broken to split the MoleculeGraph. :param alterations: a dict {(from_index,", "graph_data=graph_data) @staticmethod def with_edges(structure, edges): \"\"\" Constructor for MoleculeGraph, using", "0, 0)): \"\"\" Returns a named tuple of neighbors of", "with keys 'self', 'other', 'both' with edges that are present", ":return: A dict with an 'all_weights' list, 'minimum', 'maximum', 'median',", "two molecule fragments, then this function will fail. Currently, this", "copy import logging import os.path import subprocess import warnings from", "if self.structure != other.structure and strict: return ValueError(\"Meaningless to compare", "such that all edges (u, v) matched by edges (v,", "raise MolGraphSplitError( \"Cannot split molecule; \\ MoleculeGraph is still connected.\"", "marked edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v,", "for connected_site in connected_sites] labels = [] for sp in", "scheme for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) #", "a molecule graph is failed to split into two disconnected", "if \"to_jimage\" in d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if \"from_jimage\" in", "If the atom at index is terminal if len(neighbors) ==", "\"\"\" This is a class for annotating a Structure with", "# update edge with our new style attributes g.edges[u, v,", "removed. :return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct,", "---- ------------\" edge_weight_name = g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights = [\"weight\"]", "\"\"\" # Developer note: a different approach was also trialed,", "**d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two", "if not existing_edge: raise ValueError( \"Edge between {} and {}", "d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"] =", "using matplotlib, these also work here. However, # a dedicated", "= [] for fragment in unique_frag_dict[key]: mapping = {e: i", "1 offset = len(self.molecule) - atoms for i in range(atoms):", "alt is a dictionary including weight and/or edge properties to", "graph = self.graph.to_undirected() # find all possible fragments, aka connected", "MoleculeGraph :param from_index: int :param to_index: int :param allow_reverse: If", "information for u, v, k, d in self.graph.edges(keys=True, data=True): if", "edges = {(u, v) for u, v, d in self.graph.edges(keys=False,", "if len(rings) != 0: raise RuntimeError( \"Currently functional group replacement\"", "to/from json duplicates # information for u, v, k, d", "= edge[3] except TypeError: raise ValueError(\"Edges must be given as", "with an empty graph (no edges, only nodes defined that", "(v - 1) self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) def", "ensure images are tuples (conversion to lists happens # when", "(any graphviz filetype supported, such as pdf or png) :param", ":return: \"\"\" self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, )", "True (default False), distance will be checked to ensure that", "in d: del d[\"id\"] if \"key\" in d: del d[\"key\"]", "are not\" \" present in the graph. Please check your\"", "query returns (distance, index) v_present = kd_tree.query(v_expec) v_present = v_present[1]", "(bool): if True, will warn if trying to add duplicate", "MoleculeGraphs are isomorphic to one another. In order to prevent", "MoleculeGraph object to be compared. :return: bool \"\"\" if len(self.molecule)", "func_grp: Substituent molecule. There are two options: 1. Providing an", "new_structure = Structure.from_sites(new_sites) # merge all graphs into one big", "edge_weight_units=None): \"\"\" Constructor for StructureGraph, returns a StructureGraph object with", "if properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(to_index, from_index, edge_index)", "as f: args = [algo, \"-T\", extension, basename + \".dot\"]", "be a dictionary of edge properties to be changed. :return:", "can be None if not defined. :param n: index of", "\"both\": edges.intersection(edges_other), \"dist\": jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve", "draw edges that go through periodic boundaries :param edge_colors (bool):", "# retrieve from/to images, set as origin if not defined", "v, data in edges: s += \"{:4} {:4} {:12} {:.3e}\\n\".format(", "0)): \"\"\" Returns a named tuple of neighbors of site", "the class to work, but # just makes it neater", "!= len(species): del properties[k] new_mol = Molecule(species, coords, charge=charge, site_properties=properties)", "and can also have a \"weight\" and a \"properties\" key.", ":param alterations: a dict {(from_index, to_index): alt}, where alt is", "v, d in self.graph.edges(data=True): label = get_label(u, v) types[label].append(d[\"weight\"]) return", "[] edges_to_add = [] for u, v, k, d in", "weight=weight, edge_properties=edge_props) else: if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else:", "new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat)", "to_index < from_index: to_index, from_index = from_index, to_index to_jimage, from_jimage", "= \"#000000\" if 1 - (c[0] * 0.299 + c[1]", "d: to_image = d[\"to_jimage\"] else: to_image = (0, 0, 0)", "other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges()) != len(other.graph.edges()): return False return", "not necessary for the class to work, but # just", "node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge", "default parameters will be used. :return: \"\"\" self.set_node_attributes() neighbors =", "to graph mapping = {idx: self.structure.index(site) for idx, site in", "\".dot\") @property def types_and_weights_of_connections(self): \"\"\" Extract a dictionary summarizing the", "d in self.graph.edges(keys=True, data=True): if \"id\" in d: del d[\"id\"]", "atom. For example, for a methyl group substitution, func_grp should", "an edge in the StructureGraph. :param from_index: int :param to_index:", "False), distance will be checked to ensure that site can", ":return: list of MoleculeGraphs \"\"\" self.set_node_attributes() original = copy.deepcopy(self) for", "label[1] if sp not in mapping: mapping[sp] = available_letters.pop(0) centre_sp", "boxed first coords = molecule.cart_coords if extend_structure: a = max(coords[:,", "alterations.keys(): if \"weight\" in alterations[(u, v)]: weight = alterations[(u, v)][\"weight\"]", "\"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, weight=None, warn_duplicates=True,", "existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for key, d in", "= len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes, key=lambda x: sizes[x]) for", "edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return cls(molecule,", "connected induced subgraphs) :return: \"\"\" self.set_node_attributes() graph = self.graph.to_undirected() #", "to ensure that the functional group that is substituted will", "\"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): \"\"\" This is", "def diff(self, other, strict=True): \"\"\" Compares two StructureGraphs. Returns dict", "\"{}({})\".format(str(self.molecule[n].specie), n) if node_labels else \"\" # use standard color", "new instance of StructureGraph with supercell d = { \"@module\":", "to_index) ) return # generic container for additional edge properties,", "== edges_other) and (self.molecule == other_sorted.molecule) def isomorphic_to(self, other): \"\"\"", "[] for edge in mg.graph.edges: if edge[2] != 0: duplicates.append(edge)", "__len__(self): \"\"\" :return: length of Molecule / number of nodes", "unique_mol_graph_list = [] for fragment in unique_frag_dict[key]: mapping = {e:", "= igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]),", "nx import networkx.algorithms.isomorphism as iso import numpy as np from", "for MoleculeGraph, using pre-existing or pre-defined edges with optional edge", "jimage, index, weight. Index is the index of the corresponding", "of the # which new lattice images present, but should", "new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d))", "1. Providing an actual Molecule as the input. The first", "molecules should not cross # (artificial) periodic boundaries if not", "new structure for these atoms # query returns (distance, index)", "following the split. :param allow_reverse: If allow_reverse is True, then", "\"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls, structure,", "Molecule.insert(); if True (default False), distance will be checked to", "larger graphs. :param filename: filename to output, will detect filetype", "return self.__mul__(other) @classmethod def _edges_to_string(cls, g): header = \"from to", "and seeing if that node exists in the # supercell.", "replaced by Species strings, will not count number of occurrences", "duplicates unique_sorted = [] unique_cycles = [] for cycle in", "if v_present is not None: new_u = u new_v =", "StructureGraph ('self' and 'other'), and edges that are present in", "molecule.as_dict()[\"graphs\"] self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up", "u, v, d, dir in out_edges + in_edges: to_jimage =", "occur at an atom within a ring\" \"structure.\" ) to_remove", "if diff: diff = self.diff(diff, strict=True) green_edges = [] red_edges", "s = Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"]) def __mul__(self, scaling_matrix): \"\"\"", "def set_node_attributes(self): \"\"\" Gives each node a \"specie\" and a", "existing_reverse: for i, properties in existing_reverse.items(): if properties[\"to_jimage\"] == to_jimage:", "will attempt to break (to_index, from_index). :return: \"\"\" # ensure", "for neighbor in neighbors: # local_env will always try to", "information. \"\"\" s = Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"]) def __mul__(self,", "License. \"\"\" Module for graph representations of crystals. \"\"\" import", "# existing Site in Structure kd_tree = KDTree(new_structure.cart_coords) # tolerance", "MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None):", "a different graph compared with using a Molecule or str", "* 0.01, include_index=True ) for nnsite in equiv_sites: to_jimage =", "mykey not in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) #", "Structure.substitute to replace an atom in self.structure with a functional", "use_weights: return e1[\"weight\"] == e2[\"weight\"] return True # prune duplicate", "with node indices replaced by Species strings, will not count", "whatever subgraph has node with index 0 # TODO: actually", "for cycle in unique_cycles: if i in cycle and cycle", "= np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get(\"weight\",", "because there should only be one edge between any two", "color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0])", "and/or edge properties to be changed following the split. :param", "func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy atom \"X\"", "= correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self): \"\"\" Determine", "note: all node indices are in terms of the StructureGraph", "or pre-defined edges with optional edge parameters. :param molecule: Molecule", "boundaries # these will subgraphs representing crystals molecule_subgraphs = []", "u, v, k, d in g.edges(keys=True, data=True): if (u, v,", "between {} and {} cannot be altered;\\ no edge exists", "atoms for i in range(atoms): grp_map[i] = i + offset", "ValueError: return False other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges", "appropriate if to_jimage is None: # assume we want the", "a Structure with bond information, stored in the form of", "if including is None: cycles_nodes = unique_cycles else: for i", "list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n, data=True)) for u, v, d", "\"\"\" This is a class for annotating a Molecule with", "dist = min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist *", "nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot split molecule; \\ MoleculeGraph is still", "self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current in enumerate(sorted(self.graph.nodes)):", "__email__ = \"<EMAIL>\" __status__ = \"Production\" __date__ = \"August 2017\"", "frag_dict[key]: found = False for f in unique_frags: if _isomorphic(frag,", "dict {index:cycle}. Each entry will be a ring (cycle, in", "# TODO: test __mul__ with full 3x3 scaling matrices raise", "raise ValueError( \"Edge between {} and {} cannot be altered;\\", "{tuple(site.coords): self.molecule.index(site) for site in other.molecule} except ValueError: return False", "c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\",", "0.5 else \"#ffffff\" # convert color to hex string color", "edge # between a given (site, jimage) pair and another", "in new_g.edges(data=True) if d[\"to_jimage\"] == (0, 0, 0)] new_periodic_images =", "= orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart) # now retrieve position", "Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s", "< from_index: to_index, from_index = from_index, to_index # sanitize types", "else: site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site,", "# without adding extra logic if getattr(self, \"_supercell_sg\", None) is", "properties.items(): if len(v) != len(species): del properties[k] new_mol = Molecule(species,", "when removing periodic edges if hide_unconnected_nodes: g = g.subgraph([n for", "except KeyError: raise RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\"", "the original MoleculeGraph. It creates a copy, modifies that, and", "these will subgraphs representing crystals molecule_subgraphs = [] for subgraph", ":param indices: list of indices in the current Molecule (and", "new_v < new_u: new_u, new_v = new_v, new_u edges_inside_supercell.append({new_u, new_v})", "edges (v, u) undirected = self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes", "else: # TODO: test __mul__ with full 3x3 scaling matrices", "is called from, not the 'other' MoleculeGraph: there is no", "n, fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", ) edges_to_delete =", "with_local_env_strategy(molecule, strategy): \"\"\" Constructor for MoleculeGraph, using a strategy from", "for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping,", "image in +x direction :param to_jimage (tuple of ints): lattice", "0 # by definition else: jaccard_dist = 1 - len(edges.intersection(edges_other))", "strategy.\" ) extend_structure = strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\",", "be remapped, incrementing from 0 mapping = {} for i,", "properties: properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]] # Site properties must", "edges :param node_labels (bool): if True, label nodes with species", "] if not any(already_present): unique_subgraphs.append(subgraph) # get Molecule objects for", "[] for subgraph in all_subgraphs: intersects_boundary = any(d[\"to_jimage\"] != (0,", ":return: sg, a StructureGraph \"\"\" sg = StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\",", "'std_dev' \"\"\" all_weights = [d.get(\"weight\", None) for u, v, d", "don't show edge directions d[\"arrowhead\"] = \"none\" # only add", "in the reference graph :param hide_unconnected_nodes: if True, hide unconnected", "must also remove duplicates unique_sorted = [] unique_cycles = []", "props is not None: if \"weight\" in props.keys(): weight =", "StructureGraph this method is called from, not the 'other' StructureGraph:", "): \"\"\" Draws graph using GraphViz. The networkx graph object", "\"\"\" A wrapper for Molecule.remove_sites(). :param indices: list of indices", "for annotating a Molecule with bond information, stored in the", "sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): \"\"\"", "for u, v, d in other.graph.edges(keys=False, data=True) } if len(edges)", "warn if trying to add duplicate edges (duplicate edges will", "None: for edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\",", "connected_species.count(sp) labels.append((count, sp)) labels = sorted(labels, reverse=True) if anonymous: mapping", "lines) :param color_scheme (str): \"VESTA\" or \"JMOL\" :param keep_dot (bool):", "only treat subgraphs as isomorphic if edges have the same", "and a \"properties\" key. :return: \"\"\" self.molecule.insert( i, species, coords,", "enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of", "strategy_params = {} strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat)", "ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return", "there should only be one edge between any two nodes", "isomorphism for subgraph in molecule_subgraphs: for n in subgraph: subgraph.add_node(n,", "graph with a given crystallographic structure easier. Use cases for", "list(graph.graph.nodes()): # If graph indices have different indexing u, v", "edge[0] to_index = edge[1] from_image = edge[2] to_image = edge[3]", "= {} # Get indices now occupied by functional group", "= sorted(self.molecule._sites, key=key, reverse=reverse) # apply Molecule ordering to graph", "self.structure[from_index].coords, dist, dist * 0.01, include_index=True ) for nnsite in", "now search in new structure for these atoms # query", "import FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS", "the atoms. 2. A string name. The molecule will be", "v # and another form site v to site u:", "== 0 and len(edges_other) == 0: jaccard_dist = 0 #", "subgraphs that lie across *supercell* boundaries # these will subgraphs", "same weights. Typically, this means molecules will need to have", "new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\" Find all possible", "bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Molecule.substitute and", "to be used for Molecule instantiation for k, v in", "\"\"\" Module for graph representations of crystals. \"\"\" import copy", "molecules have to be boxed first coords = molecule.cart_coords if", "the path.\") # Developer note: NetworkX also has methods for", "\"August 2017\" ConnectedSite = namedtuple(\"ConnectedSite\", \"site, jimage, index, weight, dist\")", "self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else: if strategy_params", "to_image \" header_line = \"---- ---- ------------\" edge_weight_name = g.graph[\"edge_weight_name\"]", "luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\" if 1 - (c[0]", "self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\")", "nodes :param hide_image_edges: if True, do not draw edges that", "in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments for strategy.", "not which(algo): raise RuntimeError(\"StructureGraph graph drawing requires \" \"GraphViz binaries", "with optional edge parameters. :param molecule: Molecule object :param edges:", "= self.molecule.charge else: charge = 0 # relabel nodes in", "and connect the nearest neighbor to the C atom in", "for subg in subgraphs: nodes = sorted(list(subg.nodes)) # Molecule indices", "None if no additional properties are to be specified. :return:", "etc.) in the MoleculeGraph. :return: \"\"\" species = {} coords", ":return: \"\"\" existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure that edge", "new_to_jimage edges_to_remove.append((u, v, k)) if (new_u, new_v, new_to_jimage) not in", "called from, not the 'other' StructureGraph: there is no guarantee", "being duplicates. :return: list of unique Molecules in Structure \"\"\"", "edge_props[\"weight\"] if 0 not in list(graph.graph.nodes()): # If graph indices", "must be supplied, to avoid ambiguity.\") if existing_edges: for i,", "= \"{}({})\".format(str(self.structure[n].specie), n) if node_labels else \"\" # use standard", "is a dictionary of properties, including weight. Props should be", "to_index)] = edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, )", "add_edge( self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True,", "scaling_matrix: same as Structure.__mul__ :return: \"\"\" # Developer note: a", "where each resulting MoleculeGraph is a disconnected subgraph of the", "\"\"\" old_molecule = self.molecule.copy() # sort Molecule self.molecule._sites = sorted(self.molecule._sites,", "StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in edges.items(): try:", "dictionary including weight and/or edge properties to be changed following", "s += self._edges_to_string(self.graph) return s def __repr__(self): s = \"Molecule", "bond, but can store any kind of information that connects", "to its image mapping = {n: n + len(new_sites) for", "unconnected nodes, # these can appear when removing periodic edges", "function will fail. Currently, this function naively assigns the charge", "new_g.edges(keys=True, data=True): to_jimage = d[\"to_jimage\"] # for node v #", "properties=site_properties, ) mapping = {} for j in range(len(self.molecule) -", "d in other_sorted.graph.edges(keys=False, data=True)} else: edges = { (str(self.structure[u].specie), str(self.structure[v].specie))", "\"properties\") def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): \"\"\" Alters either", "new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u, v, k))", "in either case) :param edge_properties (dict): any other information to", "(0, 0, 0), # initial version of this class worked", "checked to ensure that site can be safely added. :param", "v, k)) elif (u, v, d[\"to_jimage\"]) in diff[\"other\"]: # edge", "self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self,", "the MoleculeGraph AFTER the insertion, NOT before. Each dict should", "returns a MoleculeGraph object with an empty graph (no edges,", "in properties: properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]] # Site properties", ":param including: list of site indices. If including is not", "self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def", "for u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u,", "can still be considered equal. :param other: MoleculeGraph :return (bool):", "\"\"\" def __init__(self, structure, graph_data=None): \"\"\" If constructing this class", "new_u: new_u, new_v = new_v, new_u new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int))", "edge_weight_units=\"\") # NearNeighbor classes only (generally) work with structures #", "{ \"self\": edges - edges_other, \"other\": edges_other - edges, \"both\":", "subgraph in molecule_subgraphs: for n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) #", "into undirected nx.Graph objects. :param other: MoleculeGraph object to be", "present in the graph. Please check your\" \" indices.\" )", "structure.as_dict()[\"graphs\"] self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up", "we want the closest site warnings.warn(\"Please specify to_jimage to be", "with the current species and coordinates. :return: \"\"\" species =", "mykey = mycomp + str(len(subgraph.edges())) if mykey not in frag_dict:", "will do is to remove the index site, and connect", "(float): e.g. bond length :param warn_duplicates (bool): if True, will", "# will try and detect all equivalent images and add", "to hex string color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node( n,", "offset return grp_map # Work is simplified if a graph", "\"\"\" Find all possible fragment combinations of the MoleculeGraphs (in", "!= other.molecule and strict: return ValueError(\"Meaningless to compare MoleculeGraphs if", "images, set as origin if not defined if \"to_image\" in", "we add if {new_u, new_v} not in edges_inside_supercell: # normalize", "site_properties=None, edges=None, ): \"\"\" A wrapper around Molecule.insert(), which also", "+ len(new_sites) for n in range(len(self.structure))} for idx, site in", "nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): \"\"\"", "hide_image_edges: edges_to_delete.append((u, v, k)) # don't show edge directions d[\"arrowhead\"]", "None: # assume we want the closest site warnings.warn(\"Please specify", "d[\"to_jimage\"]) in diff[\"other\"]: # edge has been added green_edges.append((u, v,", "supercell is an easy way to extract # molecules (and", "Find ring structures in the MoleculeGraph. :param including: list of", "edge weight property of graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge(", "= lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs =", "defined. :param n: index of Site in Structure :param jimage:", "from monty.os.path import which from networkx.drawing.nx_agraph import write_dot from networkx.readwrite", "than just keeping track of the # which new lattice", "= {} for node in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node]", "else: # By default, assume that all edges should stay", "_isomorphic(frag, f): found = True break if not found: unique_frags.append(frag)", "# assumption simplifies logic later if not np.array_equal(from_jimage, (0, 0,", "\" {}\".format(\"-\" * max([18, len(edge_label)])) else: print_weights = False s", "map_indices(func_grp.molecule) for (u, v) in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0]", "and from_jimage becomes (0, 0, 0). :param from_index: index of", "\"\"\" Extract information on the different co-ordination environments present in", "is not None: if \"weight\" in props.keys(): weight = props[\"weight\"]", "\"\"\" self.set_node_attributes() neighbors = self.get_connected_sites(index) # If the atom at", "# Copyright (c) Pymatgen Development Team. # Distributed under the", "edges = list(g.edges(data=True)) # sort edges for consistent ordering edges.sort(key=itemgetter(0,", "reflect the MoleculeGraph AFTER the insertion, NOT before. Each dict", "TODO: test __mul__ with full 3x3 scaling matrices raise NotImplementedError(\"Not", "utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under", "\\n{}\".format(self.structure.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s", "updated with the current species and coordinates. :return: \"\"\" species", ":param edge_weight_name (str): name of edge weights, e.g. \"bond_length\" or", "get asgolute Cartesian # co-ordinates of where atoms defined by", "two graph objects are isomorphic, using igraph if if is", "0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights else None, warn_duplicates=False,", "be one edge between any two nodes if new_weight is", "json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure, edges): \"\"\" Constructor", "the dimensions of the Lattice. :param index: Index of atom", "differently. :param other: StructureGraph :param strict: if False, will compare", "subgraph has node with index 0 # TODO: actually figure", "method is called from, not the 'other' StructureGraph: there is", "in self.graph.edges(data=True): label = get_label(u, v) types[label].append(d[\"weight\"]) return dict(types) @property", "extracting molecules from periodic crystals. Will only return unique molecules,", "same as Structure.__mul__ :return: \"\"\" # Developer note: a different", "None) if v == n: site = self.molecule[u] dist =", "edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor classes only (generally) work with structures", "unique_frag_dict: unique_mol_graph_list = [] for fragment in unique_frag_dict[key]: mapping =", "len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { \"self\": edges - edges_other, \"other\":", "new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure = Structure.from_sites(new_sites) # merge all", "in Å for sites to be considered equal # this", "for later visualization :param algo: any graphviz algo, \"neato\" (for", "edge in mg.graph.edges: if edge[2] != 0: duplicates.append(edge) for duplicate", "= {} for i, n in enumerate(nodes): mapping[n] = i", "way to extract # molecules (and not, e.g., layers of", "(when not using graph_dict). :param index: Index of atom to", "= PeriodicSite.from_dict(site_d) # from_site if jimage arg != (0, 0,", "igraph graph object. \"\"\" nodes = graph.nodes(data=True) new_igraph = igraph.Graph()", "that connects two Sites. \"\"\" def __init__(self, structure, graph_data=None): \"\"\"", "u, v = v, u to_jimage = np.multiply(-1, to_jimage) to_jimage", "to_index): alt}, where alt is a dictionary including weight and/or", "always always be shifted so that from_index < to_index and", "c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) # get contrasting font", "if not existing_edges: raise ValueError( \"Edge between {} and {}", "functional group. NOTE: using a MoleculeGraph will generally produce a", "`hide_image_edges` can help, especially in larger graphs. :param filename: filename", "a lot of helper methods to make associating a graph", "in terms of the MoleculeGraph this method is called from,", "0, 0) edges_to_remove.append((u, v, k)) # make sure we don't", "in list(graph.graph.nodes()): # If graph indices have different indexing u,", "off of Structure.substitute to replace an atom in self.structure with", "frag2): \"\"\" Internal function to check if two graph objects", "to_jimage)), ) from_index, to_index = int(from_index), int(to_index) # check we're", "on the different co-ordination environments present in the graph. :param", "array representing coordinates of the new site :param coords_are_cartesian: Whether", "in list. \" \"Provide explicit coordinate instead\") self.structure.substitute(index, func_grp, bond_order=bond_order)", "extract # molecules (and not, e.g., layers of a 2D", "motifs.add(motif) return sorted(list(motifs)) def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Structure`", "d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule, name=\"bonds\",", "range(1, len(self.molecule)): for combination in combinations(graph.nodes, ii): mycomp = []", "properties, # similar to site properties edge_properties = edge_properties or", "of properties, including weight. If None, then the algorithm will", "list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites def get_coordination_of_site(self, n): \"\"\"", "= [] # add display options for edges for u,", "exists between those sites.\".format( from_index, to_index ) ) def remove_nodes(self,", "\".dot\") with open(filename, \"w\") as f: args = [algo, \"-T\",", "= {} for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct", "be easier to multiply the Structure # *before* generating the", "- 1 offset = len(self.molecule) - atoms for i in", "str(edge[1])) for edge in graph.edges()]) return new_igraph def _isomorphic(frag1, frag2):", "sort Structure self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse) # apply Structure", "not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def", "\"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod", "duplicate edges (duplicate edges will not be added in either", "def __str__(self): s = \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__())", "simply returns degree of node corresponding to site n. :param", "to ensure comparison of node identities. \"\"\" return g1.vs[i1][\"species\"] ==", "current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes()", "for (u, v, d) in edges_to_add: new_g.add_edge(u, v, **d) #", "remain # inside the initial image to_jimage = (0, 0,", "len(grp) - 1 offset = len(self.structure) - atoms for i", "list of unique Molecules in Structure \"\"\" # creating a", "only ever be at most one edge # between a", "# want to find new_v such that we have #", "u, v, d in other.graph.edges(keys=False, data=True) } if len(edges) ==", "Structures, with node indices replaced by Species strings, will not", "graph = self.with_local_env_strategy(func_grp, strat) for (u, v) in list(graph.graph.edges()): edge_props", "to_index, allow_reverse=False): \"\"\" Remove an edge from the MoleculeGraph :param", "1]) - min(coords[:, 1]) + 100 c = max(coords[:, 2])", "not None: if \"weight\" in props.keys(): weight = props[\"weight\"] del", "motifs = set() for idx, site in enumerate(self.structure): centre_sp =", "[] orig_lattice = self.structure.lattice # use k-d tree to match", "have a proper __hash__() value, # using its frac_coords as", "return _isomorphic(self.graph, other.graph) def diff(self, other, strict=True): \"\"\" Compares two", "self._edges_to_string(self.graph) return s def __repr__(self): s = \"Molecule Graph\" s", "edges in the graph. :return: A dictionary with keys specifying", "{ (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d in other.graph.edges(keys=False, data=True)", "self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\")", "single-atom lattices images = [1, 0, 0], [0, 1, 0],", "return sg @staticmethod def with_local_env_strategy(structure, strategy, weights=False): \"\"\" Constructor for", "edges. This is returned with key 'dist'. Important note: all", "the new functional group. NOTE: Care must be taken to", "union) of the sets of edges. This is returned with", "to be broken to split the MoleculeGraph. :param alterations: a", "behavior of graph, # they're just for book-keeping graph =", "and weights of edges in the graph. :return: A dictionary", "weight = None if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"]", "are two options: 1. Providing an actual Molecule as the", "molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g", "the 'other' MoleculeGraph: there is no guarantee the node indices", "= StructureGraph.with_empty_graph(structure, name=\"bonds\") for n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor", "for cycle in all_cycles: if sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle))", "d @classmethod def from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Molecule`", "to be boxed first coords = molecule.cart_coords if extend_structure: a", "= nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey = mycomp + str(len(subgraph.edges()))", "name(self): \"\"\" :return: Name of graph \"\"\" return self.graph.graph[\"name\"] @property", "dist == 0: # this will happen when from_index ==", "return # sanitize types from_jimage, to_jimage = ( tuple(map(int, from_jimage)),", "restore graph information. \"\"\" m = Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"])", "to_jimage).tolist() site = PeriodicSite.from_dict(site_d) # from_site if jimage arg !=", "= molecule.as_dict()[\"graphs\"] self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy", "of graph \"\"\" return self.graph.graph[\"name\"] @property def edge_weight_name(self): \"\"\" :return:", "frag in frag_dict[key]: found = False for f in unique_frags:", "(u, v, k) edges_to_add = [] # tuple of (u,", "Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional", "tol else None # check if image sites now present", "function called by isomorphic to ensure comparison of node identities.", "Structure object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors`", "self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node] = self.structure[node].properties", "atom X should not count atoms = len(grp) - 1", "strat = strategy(**strategy_params) for site in mapping.values(): neighbors = strat.get_nn_info(self.structure,", "extension[1:] write_dot(g, basename + \".dot\") with open(filename, \"w\") as f:", "be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart,", "edges for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v, d)", "with a given molecule easier. Use cases for this include", "adding extra logic if getattr(self, \"_supercell_sg\", None) is None: self._supercell_sg", "original # lattice (keeping original lattice has # significant benefits)", "coords = nx.get_node_attributes(remapped, \"coords\") edges = {} for from_index, to_index,", ":param to_index: index of site connecting to :param weight (float):", "= np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage, shift) # automatic detection", "= self.graph.to_undirected() # find all possible fragments, aka connected induced", "def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ):", "or the edge_properties of an edge in the StructureGraph. :param", "to extend to a general 3x3 scaling matrix. # code", "1) self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) def replace_group( self,", "to add duplicate edges # will remove two edges for", "to_index ) ) # Third index should always be 0", ":param index: Index of atom to substitute. :param func_grp: Substituent", "edge_weight_units=None): \"\"\" Constructor for MoleculeGraph, returns a MoleculeGraph object with", "sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites", "# and another form site v to site u: this", "in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges =", "in the original structure, weight can be None if not", "molecules). This function does not only alter the graph information,", "the same if the underlying Molecules are ordered differently. :param", "for c in nx.simple_cycles(directed) if len(c) > 2] # Using", "0], [0, 1, 0], [0, 0, 1] dists = []", "graph.graph.get_edge_data(u, v)[0] weight = None if \"weight\" in edge_props.keys(): weight", "NearNeighbor classes only (generally) work with structures # molecules have", "a graph. A \"bond\" does not necessarily have to be", "checking edges_inside_supercell = [{u, v} for u, v, d in", "use np.around to fix issues with finite precision leading to", "u, v, d.copy() new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v,", "Work is simplified if a graph is already in place", "name of edge weight units e.g. \"Å\" or \"eV\" :return", "not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def", "images # are hashable/immutable if \"to_jimage\" in d: d[\"to_jimage\"] =", "in alterations[(u, v)]: weight = alterations[(u, v)][\"weight\"] del alterations[(u, v)][\"weight\"]", "it is not. \"\"\" f1_nodes = frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True)", "e.g. \"bonds\" :param edge_weight_name (str): name of edge weights, e.g.", "s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s +=", "graphs using `from_dict_of_dicts` from NetworkX to restore graph information. \"\"\"", "self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) else: if strategy_params is", "density. # Multiplication works by looking for the expected position", "graph representations of crystals. \"\"\" import copy import logging import", "between Sites. Edge weights can be different and StructureGraphs can", "return list sorted by closest sites first connected_sites = list(connected_sites)", "to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge to graph.", "to_jimage to be unambiguous, \" \"trying to automatically detect.\") dist,", "all edges should stay remain # inside the initial image", "is not. \"\"\" f1_nodes = frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if", "for u, v, k, d in g.edges(keys=True, data=True): # retrieve", "a reference, # get relative Cartesian co-ordinates of where #", "disjoint graphs (two or more separate molecules). This function does", "(u, v) in alterations.keys(): if \"weight\" in alterations[(u, v)]: weight", "code {}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + \".dot\") def", "node indices # PeriodicSite should have a proper __hash__() value,", "= i self.graph.remove_edge(to_index, from_index, edge_index) else: raise ValueError( \"Edge cannot", "co-ordination environments present in the graph. :param anonymous: if anonymous,", "= site.species_string connected_sites = self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for connected_site", "order (e.g. string 'Fe-O') and values which are a list", "dictionary of edge properties to be changed. :return: \"\"\" existing_edge", "# code adapted from Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16) if", "(StructureGraph): \"\"\" if edge_weight_name and (edge_weight_units is None): raise ValueError(", "v in # new supercell, and get asgolute Cartesian #", "replace an atom in self.structure with a functional group. This", "Molecule object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors`", "v in properties.items(): if len(v) != len(species): del properties[k] new_mol", "# for duplicate checking edges_inside_supercell = [{u, v} for u,", "else: f1_comp_dict[node[1][\"specie\"]] += 1 for node in f2_nodes: if node[1][\"specie\"]", "with edges that are present in only one MoleculeGraph ('self'", "\"Chosen strategy is not designed for use with structures! \"", ") extend_structure = strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\")", "if sp not in mapping: mapping[sp] = available_letters.pop(0) centre_sp =", "u % len(self.structure) n_v = v % len(self.structure) # get", ":param to_jimage (tuple of ints): lattice vector of image :param", "from itertools import combinations from operator import itemgetter import networkx", "in place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping =", "on the graph edges of what lattice image the edge", "supercell, and get asgolute Cartesian # co-ordinates of where atoms", "X is the first site and C is the second", "be shifted so that from_index < to_index and from_jimage becomes", "Sites. Edge weights can be different and StructureGraphs can still", "(u, v) in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight =", "are super-imposed on each other). If visualization is difficult to", "node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ): \"\"\" Draws graph", "species = nx.get_node_attributes(remapped, \"specie\") coords = nx.get_node_attributes(remapped, \"coords\") edges =", "(str): name of edge weight units e.g. \"Å\" or \"eV\"", "molecule as the input. The first atom must be a", "As such, by default, this is None. If weight is", "in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] if 0 not", "True, label nodes with species and site index :param weight_labels", "always appear as dashed lines) :param color_scheme (str): \"VESTA\" or", "weights else None, warn_duplicates=False, ) return sg @property def name(self):", "from # charge density. # Multiplication works by looking for", "isomorphic_to(self, other): \"\"\" Checks if the graphs of two MoleculeGraphs", "operations on the expanded graph could also be done on", "s += \"{:4} {:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0, 0))))", "of an edge in the StructureGraph. :param from_index: int :param", "= strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) for (u, v) in", "X should not count atoms = len(grp) - 1 offset", "in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: new_g.add_edge(u,", "c in nx.connected_components(supercell_sg.graph)] # discount subgraphs that lie across *supercell*", "f: args = [algo, \"-T\", extension, basename + \".dot\"] rs", "edge_props = graph.graph.get_edge_data(u, v)[0] weight = None if \"weight\" in", "coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper around Molecule.insert(),", "{}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def __len__(self): \"\"\" :return:", "d) in edges_to_add: new_g.add_edge(u, v, **d) # return new instance", "self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d) return", "# these can be confusing due to periodic boundaries if", "Molecule :param edges: List of dicts representing edges to be", "list of tuples (from_index, to_index) representing bonds to be broken", "\"#000000\" # optionally add weights to graph if weight_labels: units", "subgraph = nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey = mycomp +", "of neighbors of site n: periodic_site, jimage, index, weight. Index", "not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1 else: f2_comp_dict[node[1][\"specie\"]] += 1", ":param reverse: :return: \"\"\" old_molecule = self.molecule.copy() # sort Molecule", "edge belongs to. :param structure: a Structure object :param graph_data:", "new_g.add_edge(u, v, **d) # return new instance of StructureGraph with", "X-CH3, where X is the first site and C is", "edge directions d[\"arrowhead\"] = \"none\" # only add labels for", "otherwise bond lengths can differ. This is a fairly robust", "data in edges: s += \"{:4} {:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\",", "number of occurrences of bonds :return: \"\"\" if self.structure !=", "Å for sites to be considered equal # this could", "try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError(\"Can't find functional", "to store graph information. \"\"\" d = { \"@module\": self.__class__.__module__,", ":param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param", "molecule: Molecule object :param graph_data: dict containing graph information in", "terms, simply returns degree of node corresponding to site n.", "<= tol else None # check if image sites now", "\"Trying to add an edge that already exists from \"", "v, d in self.graph.in_edges(n, data=True)] for u, v, d, dir", "alterations=None): \"\"\" Split MoleculeGraph into two or more MoleculeGraphs by", "= self.structure[u].species_string v_label = self.structure[v].species_string return \"-\".join(sorted((u_label, v_label))) types =", "existing_edge: raise ValueError( \"Edge between {} and {} cannot be", "Sites. \"\"\" def __init__(self, structure, graph_data=None): \"\"\" If constructing this", "strategy_params: dictionary of keyword arguments for strategy. If None, default", "explicit coordinate instead\") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) #", "a different approach was also trialed, using # a simple", "be changed following the split. :param allow_reverse: If allow_reverse is", "etc. :param molecule: Molecule object :param graph_data: dict containing graph", "distance will be checked to ensure that site can be", "__init__(self, structure, graph_data=None): \"\"\" If constructing this class manually, use", "(size of the intersection / size of the union) of", "C atom in CH3. The X-C bond indicates the directionality", "and warn_duplicates: warnings.warn( \"Trying to add an edge that already", "new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure", "how to replace into a ring structure. :param index: Index", "not place atoms to close to each other, or violate", "(from_index in nodes and to_index in nodes): raise ValueError( \"Edges", "attempting to remove it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse =", "new_v = v_present new_d = d.copy() new_to_jimage = tuple(map(int, v_expec_image))", "in the path.\") # Developer note: NetworkX also has methods", "the index found in the Molecule. If there is no", "just make a copy from input graph_data = molecule.as_dict()[\"graphs\"] self.molecule", "found = True break if not found: unique_frags.append(frag) unique_frag_dict[key] =", "properties must be present for all atoms in the molecule", "ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\", \"ERROR\")", "d[\"key\"] # ensure images are tuples (conversion to lists happens", "note that this might give misleading results for multigraphs (edges", "to replace into a ring structure. :param index: Index of", "d, \"out\") for u, v, d in self.graph.out_edges(n, data=True)] in_edges", "False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges()) !=", "ValueError(\"Edges must be given as (from_index, to_index,\" \" from_image, to_image)", "KeyError: raise RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\" Gives", "- edges_other, \"other\": edges_other - edges, \"both\": edges.intersection(edges_other), \"dist\": jaccard_dist,", "their meaning) :return: \"\"\" if not strategy.structures_allowed: raise ValueError( \"Chosen", "red_edges.append((u, v, k)) elif (u, v, d[\"to_jimage\"]) in diff[\"other\"]: #", "a graph is already in place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index,", "v, d, \"out\") for u, v, d in self.graph.out_edges(n, data=True)]", "i1, i2): \"\"\" Helper function called by isomorphic to ensure", "+ \".dot\"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if", "self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\")", "in set(connected_species): count = connected_species.count(sp) labels.append((count, sp)) labels = sorted(labels,", "to be v_expec = new_structure[u].coords + v_rel # now search", "# tuple of (u, v, k) edges_to_add = [] #", "the underlying Molecules are ordered differently. :param other: MoleculeGraph :param", "return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two MoleculeGraphs are equal", "edge weight units e.g. \"Å\" or \"eV\" :return (StructureGraph): \"\"\"", "indices # must be remapped, incrementing from 0 mapping =", "will replace specie names with A, B, C, etc. :return:", "# possible when generating the graph using critic2 from #", "2D crystal) # without adding extra logic if getattr(self, \"_supercell_sg\",", "a \"weight\" and a \"properties\" key. :return: \"\"\" self.molecule.insert( i,", "False return _isomorphic(self.graph, other.graph) def diff(self, other, strict=True): \"\"\" Compares", "alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): \"\"\" Alters either the weight", "(0, 0, 0). :param from_index: index of site connecting from", "edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges,", "with their periodic images (usually only used for debugging, edges", "Molecule.sort(), also remaps nodes in graph. :param key: :param reverse:", "v_present = v_present[1] if v_present[0] <= tol else None #", "d[\"headlabel\"] = \"\" if to_image == (0, 0, 0) else", "= None if len(props.items()) == 0: props = None else:", "as a reference, # get relative Cartesian co-ordinates of where", "= [connected_site.site.species_string for connected_site in connected_sites] labels = [] for", "\"in\": u, v = v, u to_jimage = np.multiply(-1, to_jimage)", "code {}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + \".dot\") @property", "'self', 'other', 'both' with edges that are present in only", "those rings including the specified sites. By default, this parameter", "@staticmethod def with_local_env_strategy(molecule, strategy): \"\"\" Constructor for MoleculeGraph, using a", "Molecules are different.\") if strict: # sort for consistent node", "True, use weights from local_env class (consult relevant class for", "edge_index = i self.graph.remove_edge(to_index, from_index, edge_index) else: raise ValueError( \"Edge", "\"\"\" # sort for consistent node indices # PeriodicSite should", "new_v such that we have # full periodic boundary conditions", "class stores information on the graph edges of what lattice", "c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", )", "Molecule object :param graph_data: dict containing graph information in dict", "from operator import itemgetter import networkx as nx import networkx.algorithms.isomorphism", "approach has many benefits, but made it more difficult to", "self.molecule.insert( i, species, coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {}", "(1, 0, 0) for periodic image in +x direction :param", "representing edges to be added to the MoleculeGraph. These edges", "jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve subgraphs as molecules,", "to find new_v such that we have # full periodic", "but contains a lot of helper methods to make associating", "defined as duplicates, otherwise bond lengths can differ. This is", "boundary if v_present is not None: new_u = u new_v", "= 1 else: f1_comp_dict[node[1][\"specie\"]] += 1 for node in f2_nodes:", "reverse=reverse) # apply Molecule ordering to graph mapping = {idx:", "return cls(s, d[\"graphs\"]) def __mul__(self, scaling_matrix): \"\"\" Replicates the graph,", "# now retrieve position of node v in # new", "\"w\") as f: args = [algo, \"-T\", extension, basename +", "site {} in {}.\".format(from_index, to_index, to_jimage) ) return # generic", "node now inside supercell new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u,", "c[2] * 0.114) / 255 < 0.5 else \"#ffffff\" #", "an atom in self.molecule with a functional group. This method", "d.get(\"weight\", None) if v == n: site = self.molecule[u] dist", "weights of edges in the graph. :return: A dictionary with", "Checks if the graphs of two MoleculeGraphs are isomorphic to", "graphs) or \"fdp\" (for more crowded graphs) usually give good", "optionally highlight differences with another graph if diff: diff =", "not np.array_equal(neighbor[\"image\"], [0, 0, 0]): continue if n > neighbor[\"site_index\"]:", "difficult to interpret, `hide_image_edges` can help, especially in larger graphs.", "to_image) tuples\") if props is not None: if \"weight\" in", "by edge are expected to be, relative to original #", "not any duplicates present in the crystal (a duplicate defined", "[original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for subg in subgraphs: nodes", "mapping = map_indices(func_grp) # Remove dummy atom \"X\" func_grp.remove_species(\"X\") if", "# representing both site index and periodic image. Here, the", "jimage) pair existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for key,", "corresponding site in the original structure, weight can be None", "sorted(self.molecule._sites, key=key, reverse=reverse) # apply Molecule ordering to graph mapping", "will remove two edges for everyone one we add if", "set() for idx, site in enumerate(self.structure): centre_sp = site.species_string connected_sites", "__repr__(self): s = \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s", "v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage # use np.around", "existing_edges: raise ValueError( \"Edge between {} and {} cannot be", "= [] edges_to_add = [] for u, v, k, d", "to replace an atom in self.structure with a functional group.", "to replace an atom in self.molecule with a functional group.", "= n else: from_index = n to_index = neighbor[\"site_index\"] mg.add_edge(", "\"\"\" Same as Molecule.sort(), also remaps nodes in graph. :param", "None nodes = mg.graph.nodes if not (from_index in nodes and", "site n. In graph terms, simply returns degree of node", "set as origin if not defined to_image = d[\"to_jimage\"] #", "u, v, d in self.graph.out_edges(n, data=True)] in_edges = [(u, v,", "for u, v, d in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy=\"omit\")", "indexing u, v = (u - 1), (v - 1)", "d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v) for u,", "for key, d in existing_edge_data.items(): if d[\"to_jimage\"] == to_jimage: if", "in g.edges(keys=True, data=True): if (u, v, d[\"to_jimage\"]) in diff[\"self\"]: #", "d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"], units) # update edge with our", "object. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified", "Structure). :param structure (Structure): :param name (str): name of graph,", "MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor classes only (generally) work", "graph using critic2 from # charge density. # Multiplication works", "for u, v, data in edges: s += \"{:4} {:4}", "self._supercell_sg = supercell_sg = self * (3, 3, 3) #", "isomorphic, using igraph if if is available and networkx if", "a dictionary summarizing the types and weights of edges in", "= from_index, to_index # sanitize types from_index, to_index = int(from_index),", "tol else None if v_present is not None: new_u =", "(u, v, d[\"to_jimage\"]) in diff[\"other\"]: # edge has been added", "add two edges # for any one bond, one from", "defined as an isomorphic subgraph). :param use_weights (bool): If True,", "does not include sufficient bonds to separate two molecule fragments,", "must be taken to ensure that the functional group that", "for duplicate checking edges_inside_supercell = [{u, v} for u, v,", "weights :param image_labels (bool): if True, label edges with their", "= new_edge_properties[prop] def break_edge(self, from_index, to_index, allow_reverse=False): \"\"\" Remove an", "# all bonds in molecules should not cross # (artificial)", "if not found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert back", "the Structure. This # approach has many benefits, but made", "two options: 1. Providing an actual Molecule as the input.", "np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image - v_expec_image % 1 v_expec_frac", "(dict): any other information to store on graph edges, similar", "not be added in either case) :param edge_properties (dict): any", "the graph. Please check your\" \" indices.\" ) sg.add_edge( from_index,", "dictionary summarizing the types and weights of edges in the", "to insert the new site :param species: Species for the", "range(len(self.structure))} for idx, site in enumerate(self.structure): s = PeriodicSite( site.species,", "# sort Structure self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse) # apply", "of keyword arguments for strategy. If None, default parameters will", "(duplicate edges will not be added in either case) :param", "to ensure that site can be safely added. :param site_properties:", "returned with key 'dist'. Important note: all node indices are", "duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg @property def name(self):", "to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\"", "[] for u, v, k, d in g.edges(keys=True, data=True): if", "get relative Cartesian co-ordinates of where # atoms defined by", "Molecule self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse) # apply Molecule ordering", "subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define how we test for isomorphism", "filename to output, will detect filetype from extension (any graphviz", "RuntimeError( \"Currently functional group replacement\" \"cannot occur at an atom", "{} for j in range(len(self.structure) - 1): if j <", "Molecule(species, coords) # shift so origin is at center of", "else: rings = self.find_rings(including=[index]) if len(rings) != 0: raise RuntimeError(", "as a convenient key try: mapping = {tuple(site.coords): self.molecule.index(site) for", "ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return", "words, all connected induced subgraphs) :return: \"\"\" self.set_node_attributes() graph =", "specified sites. By default, this parameter is None, and all", "grp_map = {} # Get indices now occupied by functional", "should only be one edge between any two nodes if", "rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode !=", "MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols", "[(u, v, d, \"out\") for u, v, d in self.graph.out_edges(n,", "None), edge_properties=edge.get(\"properties\", None), ) except KeyError: raise RuntimeError(\"Some edges are", "# get label by species name label = \"{}({})\".format(str(self.molecule[n].specie), n)", "if new_v < new_u: new_u, new_v = new_v, new_u new_to_jimage", "the species involved in a connection in alphabetical order (e.g.", "replace into a ring structure. :param index: Index of atom", "compare MoleculeGraphs if \" \"corresponding Molecules are different.\") if strict:", "group substitution, func_grp should be X-CH3, where X is the", "graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"weight\" in edge_props.keys(): weight", "other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges = {(u, v) for u,", "strategy.molecules_allowed: raise ValueError( \"Chosen strategy is not designed for use", "in alterations.keys(): if \"weight\" in alterations[(u, v)]: weight = alterations[(u,", "import numpy as np from monty.json import MSONable from monty.os.path", "between {} and {};\\ no edge exists between those sites.\".format(", "rs.returncode != 0: raise RuntimeError(\"{} exited with return code {}.\".format(algo,", "`with_local_env_strategy` method (using an algorithm provided by the `local_env` module,", "write_dot(g, basename + \".dot\") with open(filename, \"w\") as f: args", "account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\" if", "edge from the MoleculeGraph :param from_index: int :param to_index: int", "instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy", "return s def __len__(self): \"\"\" :return: length of Structure /", "strict: return ValueError(\"Meaningless to compare StructureGraphs if \" \"corresponding Structures", "in subgraphs: nodes = sorted(list(subg.nodes)) # Molecule indices are essentially", "of the MoleculeGraphs (in other words, all connected induced subgraphs)", "species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for", "= strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure, n) for neighbor", "return mg @property def name(self): \"\"\" :return: Name of graph", "check your\" \" indices.\" ) mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes()", "for i, e in enumerate(cycle): edges.append((cycle[i - 1], e)) cycles_edges.append(edges)", "convenient key mapping = {tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule}", "= {n: n + len(new_sites) for n in range(len(self.structure))} for", "if no additional properties are to be specified. :return: sg,", "x.dist) return connected_sites def get_coordination_of_site(self, n): \"\"\" Returns the number", "not only alter the graph information, but also changes the", "the Structure # *before* generating the StructureGraph, but this isn't", "explicit coordinate instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) #", "be changed. :return: \"\"\" existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure", "how we test for isomorphism def node_match(n1, n2): return n1[\"specie\"]", "side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage # use", "in molecule_subgraphs: for n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now", "set() connected_site_images = set() out_edges = [(u, v, d, \"out\")", "if True, hide unconnected nodes :param hide_image_edges: if True, do", "length of Molecule / number of nodes in graph \"\"\"", "# inside the initial image to_jimage = (0, 0, 0)", "the functional group (format: {(from_index, to_index, from_image, to_image): props}, where", "(0, 0, 0) else \"to {}\".format((to_image)) d[\"arrowhead\"] = \"normal\" if", "be a ring (cycle, in graph theory terms) including the", "site n: periodic_site, jimage, index, weight. Index is the index", "to_image != (0, 0, 0): d[\"style\"] = \"dashed\" if hide_image_edges:", "on the original graph, but a larger graph can be", "want the closest site warnings.warn(\"Please specify to_jimage to be unambiguous,", "for n in subgraph.nodes()] species = [supercell_sg.structure[n].specie for n in", "only return those rings including the specified sites. By default,", "edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else: if isinstance(func_grp, Molecule): func_grp", "these also work here. However, # a dedicated tool like", "if use_weights: return e1[\"weight\"] == e2[\"weight\"] return True # prune", "images, set as origin if not defined to_image = d[\"to_jimage\"]", "name=\"bonds\") for n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors:", "bonds using one of a list of strategies defined in", "of occurrences of bonds :return: \"\"\" if self.molecule != other.molecule", "a dedicated tool like GraphViz allows for much easier #", "sg = StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in", "new_g = nx.union(new_g, new_graph) edges_to_remove = [] # tuple of", "index, weight, dist\") def _compare(g1, g2, i1, i2): \"\"\" Helper", "= Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites", "bond lengths can differ. This is a fairly robust approach,", "environments present in the graph. :param anonymous: if anonymous, will", "else None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u,", "warnings.warn( \"Trying to add an edge that already exists from", "ValueError(\"Meaningless to compare MoleculeGraphs if \" \"corresponding Molecules are different.\")", "(bool): \"\"\" # sort for consistent node indices # PeriodicSite", "be removed. :return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for", "func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) for (u, v) in list(func_grp.graph.edges()):", "unconnected nodes :param hide_image_edges: if True, do not draw edges", "to site n. :param n: index of site :return (int):", "add/delete marked edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u,", "for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule)))", "indices.\" ) sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, )", "edges, similar to Structure's site_properties :return: \"\"\" # this is", "it should be a dictionary of edge properties to be", "= edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, )", "from_index = neighbor[\"site_index\"] to_index = n else: from_index = n", "c[1] * 0.587 + c[2] * 0.114) / 255 <", "avoid remapping if alterations is not None: for (u, v)", "None: for edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0,", "255 < 0.5 else \"#ffffff\" # convert color to hex", ") # construct graph with one node per site #", "indices # PeriodicSite should have a proper __hash__() value, #", "ValueError(\"Meaningless to compare StructureGraphs if \" \"corresponding Structures are different.\")", "str(data.get(\"to_jimage\", (0, 0, 0))), data.get(\"weight\", 0) ) else: for u,", "v, **d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\"", "i in range(atoms): grp_map[i] = i + offset return grp_map", "def _edges_to_string(cls, g): header = \"from to to_image \" header_line", ":param validate_proximity: For Molecule.insert(); if True (default False), distance will", "edges is not None: for edge in edges: try: self.add_edge(", "that edge exists before attempting to remove it existing_edge =", "of a 2D crystal) # without adding extra logic if", "self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, ) ) frag_key = (", "set_node_attributes(self): \"\"\" Gives each node a \"specie\" and a \"coords\"", ") mapping = {} for j in range(len(self.structure) - 1):", "species: Species for the new site :param coords: 3x1 array", "neighbor site. Defaults to 1. :param graph_dict: Dictionary representing the", "max(sizes, key=lambda x: sizes[x]) for i in sizes.keys(): if i", "idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph,", "\"\"\" Compares two MoleculeGraphs. Returns dict with keys 'self', 'other',", "networkx graph object itself can also be drawn with networkx's", "wrapper for Molecule.remove_sites(). :param indices: list of indices in the", "try: from_index = edge[0] to_index = edge[1] except TypeError: raise", "StructureGraphs if \" \"corresponding Structures are different.\") if strict: #", "any two nodes if new_weight is not None: self.graph[from_index][to_index][0][\"weight\"] =", "u, v, d in self.graph.edges(keys=False, data=True)} edges_other = { (u,", "Graph (instead of MultiDiGraph), with node indices # representing both", "Constructor for MoleculeGraph, returns a MoleculeGraph object with an empty", "unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert back to molecule graphs unique_mol_graph_dict", "dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=u,", "offset = len(self.molecule) - atoms for i in range(atoms): grp_map[i]", "to periodic images always appear as dashed lines) :param color_scheme", "image mapping = {n: n + len(new_sites) for n in", "MoleculeGraphs (in other words, all connected induced subgraphs) :return: \"\"\"", "a strategy from :Class: `pymatgen.analysis.local_env`. :param structure: Structure object :param", "has been added green_edges.append((u, v, k)) for u, v, k", "from, not the 'other' MoleculeGraph: there is no guarantee the", "edge_colors (bool): if True, use node colors to color edges", "count atoms = len(grp) - 1 offset = len(self.molecule) -", "input graph_data = structure.as_dict()[\"graphs\"] self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data)", "attempting to remove it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse =", "hide unconnected nodes, # these can appear when removing periodic", "in labels: sp = label[1] if sp not in mapping:", "graphs are converted into undirected nx.Graph objects. :param other: MoleculeGraph", "\"\"\" Remove an edge from the MoleculeGraph :param from_index: int", "props[\"weight\"] else: weight = None if len(props.items()) == 0: props", "function that converts a networkx graph object into an igraph", "< new_u: new_u, new_v = new_v, new_u new_to_jimage = tuple(np.multiply(-1,", "using node colors color_u = g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"]", "new_v < new_u: new_u, new_v = new_v, new_u new_to_jimage =", "all_cycles: if sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including", "not defined if \"to_image\" in d: to_image = d[\"to_jimage\"] else:", "edges are invalid.\") def set_node_attributes(self): \"\"\" Replicates molecule site properties", "is not designed for use with molecules! \" \"Please choose", "to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ): \"\"\" Alters either the weight", "for sites to be considered equal # this could probably", "combinations(graph.nodes, ii): mycomp = [] for idx in combination: mycomp.append(str(self.molecule[idx].specie))", "in Molecule). :param molecule (Molecule): :param name (str): name of", "f in unique_frags: if _isomorphic(frag, f): found = True break", "raise NotImplementedError(\"Not tested with 3x3 scaling matrices yet.\") new_lattice =", "nan_policy=\"omit\") return { \"all_weights\": all_weights, \"min\": stats.minmax[0], \"max\": stats.minmax[1], \"mean\":", "Providing an actual Molecule as the input. The first atom", "Units of the edge weight property of graph \"\"\" return", "structure = None for n in range(len(molecule)): if structure is", "parameters. :param molecule: Molecule object :param edges: dict representing the", "(in other words, all connected induced subgraphs) :return: \"\"\" self.set_node_attributes()", "get_label(u, v): u_label = self.structure[u].species_string v_label = self.structure[v].species_string return \"-\".join(sorted((u_label,", "= copy.deepcopy(self) sub_mols = list() # Had to use nx.weakly_connected_components", "list of weights for those connections (e.g. bond lengths). \"\"\"", "v_present[0] <= tol else None # check if image sites", "a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph \"\"\" if", "b, c, no_cross=True, reorder=False) else: structure = None for n", "site and C is the second site. What the code", "a functional group in self.molecule with a functional group. This", "def get_connected_sites(self, n): \"\"\" Returns a named tuple of neighbors", "\" from_image, to_image) tuples\") if props is not None: if", "by default, this is None. If any edge properties are", "0, 0)): shift = from_jimage from_jimage = np.subtract(from_jimage, shift) to_jimage", "any duplicates present in the crystal (a duplicate defined as", "is None: strategy_params = {} strat = strategy(**strategy_params) graph =", "None else: weight = None nodes = mg.graph.nodes if not", "= [] for i, e in enumerate(cycle): edges.append((cycle[i - 1],", "from_jimage, to_jimage = ( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), ) from_index,", "if len(self.graph.edges()) != len(other.graph.edges()): return False return _isomorphic(self.graph, other.graph) def", ") from_index, to_index = int(from_index), int(to_index) # check we're not", "+= \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def __repr__(self):", "by breaking a set of bonds. This function uses MoleculeGraph.break_edge", "name label = \"{}({})\".format(str(self.molecule[n].specie), n) if node_labels else \"\" #", "0) # set edge style d[\"style\"] = \"solid\" if to_image", "def remove_nodes(self, indices): \"\"\" A wrapper for Molecule.remove_sites(). :param indices:", "bond_order: A specified bond order to calculate the bond length", "induced subgraphs) :return: \"\"\" self.set_node_attributes() graph = self.graph.to_undirected() # find", "0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked", "= \"Production\" __date__ = \"August 2017\" ConnectedSite = namedtuple(\"ConnectedSite\", \"site,", "edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), )", "nx.get_node_attributes(new_graph, \"specie\") coords = nx.get_node_attributes(new_graph, \"coords\") raw_props = nx.get_node_attributes(new_graph, \"properties\")", "# magic numbers account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor", "objects. :return: list of MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)]", "must be given as (from_index, to_index,\" \" from_image, to_image) tuples\")", "return unique molecules, not any duplicates present in the crystal", "options: 1. Providing an actual Molecule as the input. The", "be at most one edge # between a given (site,", "f2_comp_dict[node[1][\"specie\"]] += 1 if f1_comp_dict != f2_comp_dict: return False if", "where alt is a dictionary including weight and/or edge properties", "n: index of site :return (int): \"\"\" number_of_self_loops = sum([1", "d[\"headlabel\"] else \"none\" # optionally color edges using node colors", "ordering to graph mapping = {idx: self.structure.index(site) for idx, site", "0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, ) def get_connected_sites(self, n,", "is not None: for edge in edges: try: self.add_edge( edge[\"from_index\"],", "subgraphs representing crystals molecule_subgraphs = [] for subgraph in all_subgraphs:", "to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0,", "and periodic image. Here, the # number of nodes !=", "red_edges: g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"}) basename, extension = os.path.splitext(filename) extension", "break (to_index, from_index). :return: list of MoleculeGraphs \"\"\" self.set_node_attributes() original", "weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def insert_node( self,", "input. The first atom must be a DummySpecies X, indicating", "edge[\"to_index\"], from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), )", "for neighbor in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep =", "properties are to be specified. :return: sg, a StructureGraph \"\"\"", "the first site and C is the second site. What", "use weights from local_env class (consult relevant class for their", "to_index) # ensure that edge exists before attempting to change", "self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy atom", "@classmethod def with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for", "StructureGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param structure: Structure", "new_u, new_d = u, v, d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int))", "'other' StructureGraph: there is no guarantee the node indices will", "functional group and the nearest neighbor site. Defaults to 1.", "for node v # reduce unnecessary checking if to_jimage !=", "import lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS try: import igraph IGRAPH_AVAILABLE", "`local_env` module, such as O'Keeffe). This class that contains connection", "@staticmethod def with_edges(structure, edges): \"\"\" Constructor for MoleculeGraph, using pre-existing", "warnings.warn(\"Please specify to_jimage to be unambiguous, \" \"trying to automatically", "node in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node]", "k, d in self.graph.edges(keys=True, data=True): if \"id\" in d: del", "add duplicate edges (duplicate edges will not be added in", "original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\" Find", "to_index, from_index = from_index, to_index # sanitize types from_index, to_index", "but can store any kind of information that connects two", "have equal Molecules, and have the same edges between Sites.", "Molecules, with node indices replaced by Species strings, will not", "weight = None if len(props.items()) == 0: props = None", "v < u: new_v, new_u, new_d = u, v, d.copy()", "that edge_properties be altered. As such, by default, this is", "u, v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other)", "__eq__(self, other): \"\"\" Two StructureGraphs are equal if they have", "return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self, filename=\"graph\", diff=None, hide_unconnected_nodes=False,", "u, v, str(data.get(\"to_jimage\", (0, 0, 0))), data.get(\"weight\", 0) ) else:", "with_local_env_strategy(structure, strategy, weights=False): \"\"\" Constructor for StructureGraph, using a strategy", "for fragment in unique_frag_dict[key]: mapping = {e: i for i,", "tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u, v, k)) if (new_u,", "Index at which to insert the new site :param species:", "if # from_jimage != (0, 0, 0), but making this", "- 1): if j < i: mapping[j] = j else:", "PeriodicSite( site.species, site.coords + v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, )", "be, relative to original # lattice (keeping original lattice has", "coordinates of the new site :param validate_proximity: For Molecule.insert(); if", "StructureGraph): # just make a copy from input graph_data =", "d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\":", "in :Class: `pymatgen.core.Structure` except with using `to_dict_of_dicts` from NetworkX to", "Molecule indices are essentially list-based, so node indices # must", "= \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\" # optionally add", "site {}.\".format(from_index, to_index) ) return # generic container for additional", "copy.deepcopy(unique_frags) # convert back to molecule graphs unique_mol_graph_dict = {}", "MoleculeGraph, returns a MoleculeGraph object with an empty graph (no", "node_labels else \"\" # use standard color scheme for nodes", "# Site properties must be present for all atoms in", "always try to add two edges # for any one", "in out_edges + in_edges: to_jimage = d[\"to_jimage\"] if dir ==", "neighbor in neighbors: # local_env will always try to add", "# co-ordinates of where atoms defined by edge # are", "Copies self.graph such that all edges (u, v) matched by", "edge_index = i self.graph.remove_edge(from_index, to_index, edge_index) else: if allow_reverse: existing_reverse", "an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a", "warnings from collections import defaultdict, namedtuple from itertools import combinations", "benefits, but made it more difficult to # keep the", "is None: raise ValueError(\"Image must be supplied, to avoid ambiguity.\")", ":return: dict {index:cycle}. Each entry will be a ring (cycle,", "self.graph.get_edge_data(from_index, to_index) if existing_edge_data and warn_duplicates: warnings.warn( \"Trying to add", "sorted by closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x:", "not require that edge_properties be altered. As such, by default,", "# significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords", "KeyError: raise RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\" Replicates", "number of nodes in graph \"\"\" return len(self.structure) def sort(self,", "self.graph.remove_edge(from_index, to_index, edge_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index)", "k)) # make sure we don't try to add duplicate", "if jimage arg != (0, 0, 0) relative_jimage = np.subtract(to_jimage,", "self._edges_to_string(self.graph) return s def __repr__(self): s = \"Structure Graph\" s", "to each other, or violate the dimensions of the Lattice.", "GraphViz allows for much easier # control over graph appearance", "v, d[\"to_jimage\"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} else:", "k)) if (new_u, new_v, new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u, new_v,", "v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and", "that the functional group that is substituted will not place", "{\"nodesep\": 10.0, \"dpi\": 300, \"overlap\": \"false\"} # add display options", "given as (from_index, to_index)\" \"tuples\") if props is not None:", "methods to make associating a graph with a given crystallographic", "= StructureGraph.with_empty_graph(structure, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in edges.items():", "Dictionary representing the bonds of the functional group (format: {(u,", "np.int16) if scale_matrix.shape != (3, 3): scale_matrix = np.array(scale_matrix *", "n in range(len(molecule)): if structure is None: neighbors = strategy.get_nn_info(molecule,", "store any kind of information that connects two Sites. \"\"\"", "of StructureGraph with supercell d = { \"@module\": self.__class__.__module__, \"@class\":", "sites.\".format( from_index, to_index ) ) if to_jimage is None: edge_index", "of nodes in graph \"\"\" return len(self.structure) def sort(self, key=None,", "s def __str__(self): s = \"Structure Graph\" s += \"\\nStructure:", "= edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties)", "will be to actually accurately assign charge. NOTE: This function", "NetworkX to restore graph information. \"\"\" s = Structure.from_dict(d[\"structure\"]) return", "del d[\"key\"] # ensure images are tuples (conversion to lists", ":param bonds: list of tuples (from_index, to_index) representing bonds to", "attempting to change it if not existing_edge: raise ValueError( \"Edge", "\"\"\" existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists", "(bool): keep GraphViz .dot file for later visualization :param algo:", "different Structures, with node indices replaced by Species strings, will", "in including: for cycle in unique_cycles: if i in cycle", "for multigraphs (edges are super-imposed on each other). If visualization", "edge exists between those sites.\".format( from_index, to_index ) ) #", "if \"weight\" in alterations[(u, v)]: weight = alterations[(u, v)][\"weight\"] del", "(from_index, to_index) and, failing that, will attempt to break (to_index,", "\"A\" labels = [(label[0], mapping[label[1]]) for label in labels] labels", "species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in graph.edges()]) return new_igraph", "one of a list of strategies defined in pymatgen.analysis.local_env. :param", "supercell new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v, k)) #", "matrices raise NotImplementedError(\"Not tested with 3x3 scaling matrices yet.\") new_lattice", "occurrences of bonds :return: \"\"\" if self.molecule != other.molecule and", "u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart) # now retrieve", "Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param", "defined by edge are expected to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac)", "added to the MoleculeGraph. These edges must include the index", "< u: new_v, new_u, new_d = u, v, d.copy() new_d[\"to_jimage\"]", "len(self.molecule) != len(other.molecule): return False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return", "new style attributes g.edges[u, v, k].update(d) # optionally remove periodic", "\"-T\", extension, basename + \".dot\"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE,", "representing the bonds of the functional group (format: {(u, v):", "specie names with A, B, C, etc. :return: a list", "logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = \"<NAME>, <NAME>, <NAME>\" __version__ = \"0.1\"", "one big graph new_g = nx.MultiDiGraph() for new_graph in new_graphs:", "if isinstance(structure, StructureGraph): # just make a copy from input", "in the MoleculeGraph. :param including: list of site indices. If", "amends self.graph to incorporate the new functional group. NOTE: using", "\"to_image\" in d: to_image = d[\"to_jimage\"] else: to_image = (0,", "appear when removing periodic edges if hide_unconnected_nodes: g = g.subgraph([n", "combinations from operator import itemgetter import networkx as nx import", "if not np.array_equal(neighbor[\"image\"], [0, 0, 0]): continue if n >", "if nodes are not\" \" present in the graph. Please", "data=True)) for u, v, d in out_edges + in_edges: weight", ") new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure = Structure.from_sites(new_sites) # merge", "any operations on the expanded graph could also be done", "self.molecule with a functional group. This method also amends self.graph", "multiply the Structure # *before* generating the StructureGraph, but this", "\"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls,", "MoleculeGraph objects. :return: list of MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph): return", "periodic boundary if v_present is not None: new_u = u", "`with_empty_graph` method or `with_local_env_strategy` method (using an algorithm provided by", "edges if appropriate if to_jimage is None: # assume we", "in new_graphs: new_g = nx.union(new_g, new_graph) edges_to_remove = [] #", "in nodes): raise ValueError( \"Edges cannot be added if nodes", "= d.get(\"weight\", None) if (v, to_jimage) not in connected_site_images: connected_site", "properties[prop] = [prop_set[prop]] # Site properties must be present for", ":return: \"\"\" self.set_node_attributes() neighbors = self.get_connected_sites(index) # If the atom", "indices: list of indices in the current Molecule (and graph)", "each node a \"specie\" and a \"coords\" attribute, updated with", "node_labels (bool): if True, label nodes with species and site", "at index is terminal if len(neighbors) == 1: self.substitute_group( index,", "if properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(from_index, to_index, edge_index)", "the MoleculeGraph. :param including: list of site indices. If including", "duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg @property def name(self): \"\"\" :return:", "edge_properties=props, ) sg.set_node_attributes() return sg @staticmethod def with_local_env_strategy(structure, strategy, weights=False):", "Molecule ordering to graph mapping = {idx: self.molecule.index(site) for idx,", "for u, v, k in red_edges: g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"})", "Heisenberg exchange parameters, etc. :param molecule: Molecule object :param graph_data:", "s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s +=", "\"\"\" Internal function to check if two graph objects are", "edges red that do not exist in diff and edges", "grp_map # Work is simplified if a graph is already", "2017\" ConnectedSite = namedtuple(\"ConnectedSite\", \"site, jimage, index, weight, dist\") def", "don't change behavior of graph, # they're just for book-keeping", "\"\"\" species = {} coords = {} properties = {}", "stay remain # inside the initial image to_jimage = (0,", "extend_structure: a = max(coords[:, 0]) - min(coords[:, 0]) + 100", "s += self._edges_to_string(self.graph) return s def __len__(self): \"\"\" :return: length", "binaries to be in the path.\") # Developer note: NetworkX", "relevant class for their meaning) :return: \"\"\" if not strategy.structures_allowed:", "_igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(),", "= \"August 2017\" ConnectedSite = namedtuple(\"ConnectedSite\", \"site, jimage, index, weight,", "not found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert back to", "MoleculeGraph. :return: \"\"\" species = {} coords = {} properties", "constructed manually, see as_dict method for format) \"\"\" if isinstance(structure,", "in unique_frag_dict[key]: mapping = {e: i for i, e in", "the graph using critic2 from # charge density. # Multiplication", "to # keep the graph in sync with its corresponding", "v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"to_jimage\" in", "values which are a list of weights for those connections", "+= self._edges_to_string(self.graph) return s def __len__(self): \"\"\" :return: length of", "= other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d[\"to_jimage\"])", "neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates = []", "if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls,", "etc. :return: a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)']", "sets of edges. This is returned with key 'dist'. Important", "information: relationships between sites represented by a Graph structure, and", "the Lattice. :param index: Index of atom to substitute. :param", "mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self): \"\"\" Determine if the MoleculeGraph", "True, hide unconnected nodes :param hide_image_edges: if True, do not", "edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) else:", "does not require that weight be altered. As such, by", "# these can appear when removing periodic edges if hide_unconnected_nodes:", "+= \" {}\".format(\"-\" * max([18, len(edge_label)])) else: print_weights = False", "frag_dict: unique_frags = [] for frag in frag_dict[key]: found =", "lengths to be defined as duplicates, otherwise bond lengths can", "min(coords[:, 0]) + 100 b = max(coords[:, 1]) - min(coords[:,", "method for format) \"\"\" if isinstance(structure, StructureGraph): # just make", "= \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" __date__ =", "None: raise ValueError(\"Image must be supplied, to avoid ambiguity.\") if", "= \"from to to_image \" header_line = \"---- ---- ------------\"", "Raised when a molecule graph is failed to split into", "from the MoleculeGraph :param from_index: int :param to_index: int :param", "n: index of Site in Structure :param jimage: lattice vector", "all node indices are in terms of the MoleculeGraph this", "= {} for j in range(len(self.molecule) - 1): if j", "= from_index, to_index to_jimage, from_jimage = from_jimage, to_jimage # constrain", "edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0, 0),", "in f2_nodes: if node[1][\"specie\"] not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1", ") ) def remove_nodes(self, indices): \"\"\" A wrapper for Molecule.remove_sites().", "connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site)", "None): raise ValueError( \"Please specify units associated \" \"with your", "np.array_equal(neighbor[\"image\"], [0, 0, 0]): continue if n > neighbor[\"site_index\"]: from_index", "to_index, to_jimage) ) return # generic container for additional edge", "existing_reverse = None if existing_edge: self.graph.remove_edge(from_index, to_index) else: if allow_reverse:", "the total molecule to a single submolecule. A later effort", "enumerate(cycle): edges.append((cycle[i - 1], e)) cycles_edges.append(edges) return cycles_edges def get_connected_sites(self,", "props = None else: weight = None nodes = mg.graph.nodes", "not in cycles_nodes: cycles_nodes.append(cycle) for cycle in cycles_nodes: edges =", "for i in range(25)] for label in labels: sp =", "return [copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols = list() # Had", "object :return: mg, a MoleculeGraph \"\"\" if not strategy.molecules_allowed: raise", "\"\"\" motifs = set() for idx, site in enumerate(self.structure): centre_sp", "with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' \"\"\"", "weights can be different and StructureGraphs can still be considered", "been deleted red_edges.append((u, v, k)) elif (u, v, d[\"to_jimage\"]) in", "node indices will be the same if the underlying Molecules", "detect all equivalent images and add multiple # edges if", "remove the index site, and connect the nearest neighbor to", "v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image - v_expec_image %", "in self.graph.edges(keys=True, data=True): if v < u: new_v, new_u, new_d", "weight_statistics(self): \"\"\" Extract a statistical summary of edge weights present", "self.diff(diff, strict=True) green_edges = [] red_edges = [] for u,", "break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): \"\"\" Remove an edge from", "dist * 0.01, include_index=True ) for nnsite in equiv_sites: to_jimage", "if d[\"headlabel\"] else \"none\" # optionally color edges using node", "from_image = edge[2] to_image = edge[3] except TypeError: raise ValueError(\"Edges", "[] for i, e in enumerate(cycle): edges.append((cycle[i - 1], e))", "is already in place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order)", "= self * (3, 3, 3) # make undirected to", "rings will be returned. :return: dict {index:cycle}. Each entry will", "graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Molecule.substitute to replace", "edge, props in edges.items(): try: from_index = edge[0] to_index =", "principle, any operations on the expanded graph could also be", "a \"properties\" key. :return: \"\"\" self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian,", "len(edges.union(edges_other)) return { \"self\": edges - edges_other, \"other\": edges_other -", "differently. :param other: MoleculeGraph :param strict: if False, will compare", "in_edges = [(u, v, d, \"in\") for u, v, d", "to be constructed manually, see as_dict method for format) \"\"\"", "red_edges = [] for u, v, k, d in g.edges(keys=True,", "= nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph)", "to separate two molecule fragments, then this function will fail.", "copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is not None: for edge", "two or more new MoleculeGraph objects. :return: list of MoleculeGraphs", "the nearest neighbor site. Defaults to 1. :param graph_dict: Dictionary", "atoms = len(grp) - 1 offset = len(self.structure) - atoms", "= \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__str__()) s += \"\\nGraph:", "# charge density. # Multiplication works by looking for the", "if the graphs of two MoleculeGraphs are isomorphic to one", "the current species and coordinates. :return: \"\"\" species = {}", "/ number of nodes in graph \"\"\" return len(self.molecule) def", "mapping = {n: n + len(new_sites) for n in range(len(self.structure))}", "lattice vector of site :return: list of ConnectedSite tuples, sorted", "= i + offset return grp_map if isinstance(func_grp, Molecule): func_grp", "neighbor to the C atom in CH3. The X-C bond", "of the functional group (format: {(from_index, to_index, from_image, to_image): props},", "return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\" Helper function that", "group in self.molecule with a functional group. This method also", "exists in the # supercell. If it does, the edge", "molecule. There are three options: 1. Providing an actual molecule", "how to distribute charge if 0 in nodes: charge =", "Edge weights can be different and MoleculeGraphs can still be", "index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings =", "diff (StructureGraph): an additional graph to compare with, will color", "mapping[tuple(site.coords)]) edges = {(u, v) for u, v, d in", "for these edges should reflect the MoleculeGraph AFTER the insertion,", "\\n{}\".format(self.structure.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s", "None: for (u, v) in alterations.keys(): if \"weight\" in alterations[(u,", "in neighbors: self.add_edge( from_index=site, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"],", "def with_local_env_strategy(molecule, strategy): \"\"\" Constructor for MoleculeGraph, using a strategy", "graph_data = json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule, edges):", "parameters, etc. :param molecule: Molecule object :param graph_data: dict containing", "any bonds before partition, to avoid remapping if alterations is", "edges, \"both\": edges.intersection(edges_other), \"dist\": jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False): \"\"\"", ":param color_scheme (str): \"VESTA\" or \"JMOL\" :param keep_dot (bool): keep", "that all edges should stay remain # inside the initial", "0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge", "to a single submolecule. A later effort will be to", "interpret, `hide_image_edges` can help, especially in larger graphs. :param filename:", "== n2[\"specie\"] def edge_match(e1, e2): if use_weights: return e1[\"weight\"] ==", "d.copy() new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u,", "u, v, k in red_edges: g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"}) basename,", "are present in both. The Jaccard distance is a simple", "None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self,", "a map of nodes from original graph to its image", "= [chr(66 + i) for i in range(25)] for label", "copy, modifies that, and returns two or more new MoleculeGraph", "return s def __repr__(self): s = \"Structure Graph\" s +=", "len(f2_edges): return False f1_comp_dict = {} f2_comp_dict = {} for", "a MoleculeGraph \"\"\" mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for", "# use np.around to fix issues with finite precision leading", "these can be confusing due to periodic boundaries if hide_image_edges:", "weight=weight, edge_properties=edge_props, ) def replace_group( self, index, func_grp, strategy, bond_order=1,", "structure, and an associated structure object. This class uses the", "node colors to color edges :param node_labels (bool): if True,", "v, str(data.get(\"to_jimage\", (0, 0, 0))), data.get(\"weight\", 0) ) else: for", "+= \"{:4} {:4} {:12} {:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\", (0, 0,", "label[0]) for label in labels] motif = \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif)", "{:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0, 0)))) return s def __str__(self):", "edges = {(u, v, d[\"to_jimage\"]) for u, v, d in", "(edges == edges_other) and (self.structure == other_sorted.structure) def diff(self, other,", "(u, v, d.get(\"to_jimage\", (0, 0, 0))) for u, v, d", "to make associating a graph with a given molecule easier.", "= { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph),", "# molecules (and not, e.g., layers of a 2D crystal)", "these edges should reflect the MoleculeGraph AFTER the insertion, NOT", "or \"eV\" :return (MoleculeGraph): \"\"\" if edge_weight_name and (edge_weight_units is", "node v in # new supercell, and get asgolute Cartesian", "= g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if", "0, 0), # initial version of this class worked even", "Using to_directed() will mean that each cycle always appears twice", "\"\"\" Alters either the weight or the edge_properties of an", "molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return:", "graph. Since physically a 'bond' (or other connection between sites)", "graph \"\"\" return self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self): \"\"\" :return: Units", "automatically determine bonds using one of a list of strategies", "if len(props.items()) == 0: props = None else: weight =", "the # supercell. If it does, the edge is updated.", "representing both site index and periodic image. Here, the #", "origin if not defined if \"to_image\" in d: to_image =", "Species for the new site :param coords: 3x1 array representing", "choose another strategy.\" ) extend_structure = strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule,", "v)][\"weight\"] edge_properties = alterations[(u, v)] if len(alterations[(u, v)]) != 0", "= self.get_connected_sites(index) # If the atom at index is terminal", "(two or more separate molecules). This function does not only", "and edges green that are in diff graph but not", "Structure.from_sites(new_sites) # merge all graphs into one big graph new_g", "specified bond order to calculate the bond length between the", "False if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return", "the edge_properties of an edge in the MoleculeGraph. :param from_index:", "in edge_props.keys(): to_jimage = edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else: # By", "import write_dot from networkx.readwrite import json_graph from scipy.spatial import KDTree", "except TypeError: raise ValueError(\"Edges must be given as (from_index, to_index,\"", "self.graph.add_node(i) self.set_node_attributes() if edges is not None: for edge in", "sg.graph.nodes if not (from_index in nodes and to_index in nodes):", "if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index)", "int(to_index) # check we're not trying to add a duplicate", "enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of", "v, d) in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return", "len(self.graph.edges()) != len(other.graph.edges()): return False return _isomorphic(self.graph, other.graph) def diff(self,", "in diff graph but not in the reference graph :param", "if not any(already_present): unique_subgraphs.append(subgraph) # get Molecule objects for each", "initial version of this class worked even if # from_jimage", "a methyl group substitution, func_grp should be X-CH3, where X", "exchange parameters, etc. :param molecule: Molecule object :param graph_data: dict", "float. :param new_edge_properties: alter_edge does not require that edge_properties be", "this will happen when from_index == to_index, # typically in", "should have a proper __hash__() value, # using its frac_coords", "to_index, to_jimage=to_jimage, **edge_properties) def insert_node( self, i, species, coords, coords_are_cartesian=False,", "relative to original # lattice (keeping original lattice has #", "crystal (a duplicate defined as an isomorphic subgraph). :param use_weights", "class to work, but # just makes it neater if", "through # periodic boundary if v_present is not None: new_u", "fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", ) edges_to_delete = [] #", "structure object. This class uses the NetworkX package to store", "that are present in only one MoleculeGraph ('self' and 'other'),", "[ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g in unique_subgraphs ]", "new_v} not in edges_inside_supercell: # normalize direction if new_v <", "graph :param hide_unconnected_nodes: if True, hide unconnected nodes :param hide_image_edges:", "nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) # get contrasting", "n1[\"specie\"] == n2[\"specie\"] def edge_match(e1, e2): if use_weights: return e1[\"weight\"]", "{ \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), }", "from Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16) if scale_matrix.shape != (3,", "weight=weight, edge_properties=props) mg.set_node_attributes() return mg @staticmethod def with_local_env_strategy(molecule, strategy): \"\"\"", "\"overlap\": \"false\"} # add display options for nodes for n", "to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes() return sg @staticmethod def with_local_env_strategy(structure,", "if g.degree()[n] != 0]) # optionally highlight differences with another", "grp_map[i] = i + offset return grp_map # Work is", "sg.set_node_attributes() return sg @staticmethod def with_local_env_strategy(structure, strategy, weights=False): \"\"\" Constructor", "/ size of the union) of the sets of edges.", "existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data and warn_duplicates: warnings.warn( \"Trying", "3x3 scaling matrix. # code adapted from Structure.__mul__ scale_matrix =", "have the same edges between Sites. Edge weights can be", "if existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise ValueError( \"Edge cannot be", "weight be altered. As such, by default, this is None.", "unique_subgraphs ] if not any(already_present): unique_subgraphs.append(subgraph) # get Molecule objects", "{ (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True)", "another strategy.\" ) extend_structure = strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\",", "= True break if not found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags)", "d, \"in\") for u, v, d in self.graph.in_edges(n, data=True)] for", "# from_site if jimage arg != (0, 0, 0) relative_jimage", "equal Molecules, and have the same edges between Sites. Edge", "v, d in subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add", "\"\"\" m = Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"]) @classmethod def _edges_to_string(cls,", "subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names to", "diff: diff = self.diff(diff, strict=True) green_edges = [] red_edges =", "len(self.structure) n_v = v % len(self.structure) # get fractional co-ordinates", "correspond to Sites in Molecule). :param molecule (Molecule): :param name", "= (0, 0, 0) if \"weight\" in edge_props.keys(): weight =", "sg @staticmethod def with_local_env_strategy(structure, strategy, weights=False): \"\"\" Constructor for StructureGraph,", "and detect all equivalent images and add multiple # edges", "list of site indices. If including is not None, then", "n_v = v % len(self.structure) # get fractional co-ordinates of", "edge # between two sites existing_edge_data = self.graph.get_edge_data(from_index, to_index) if", "allow_reverse=False): \"\"\" Remove an edge from the MoleculeGraph :param from_index:", "\"key\" in d: del d[\"key\"] # ensure images are tuples", "give good outputs :return: \"\"\" if not which(algo): raise RuntimeError(\"StructureGraph", "return # generic container for additional edge properties, # similar", "def edge_weight_unit(self): \"\"\" :return: Units of the edge weight property", "will subgraphs representing crystals molecule_subgraphs = [] for subgraph in", "edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties)", "MoleculeGraph \"\"\" mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge,", "for node in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords", "# of an image node, and seeing if that node", "to_jimage, from_jimage = from_jimage, to_jimage # constrain all from_jimages to", "in the StructureGraph. :param from_index: int :param to_index: int :param", "add display options for edges for u, v, k, d", "True, will warn if trying to add duplicate edges (duplicate", "self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ): \"\"\" Alters either", "if getattr(self, \"_supercell_sg\", None) is None: self._supercell_sg = supercell_sg =", "is None. If weight is to be changed, it should", "== to_jimage: edge_index = i self.graph.remove_edge(from_index, to_index, edge_index) else: if", "color_u = g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v)", "intended to be constructed manually, see as_dict method for format)", "d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\":", "Each dict should at least have a \"to_index\" and \"from_index\"", "= graph_dict[(u, v)] if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"]", "name=name, ) graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod", "+= \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph)", "Structure object :param graph_data: dict containing graph information in dict", "\"site {} to site {} in {}.\".format(from_index, to_index, to_jimage) )", "self.graph[from_index][to_index][0][\"weight\"] = new_weight if new_edge_properties is not None: for prop", "\" \"site {} to site {} in {}.\".format(from_index, to_index, to_jimage)", "1): if j < i: mapping[j] = j else: mapping[j]", "self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) def replace_group( self, index,", "functional group. NOTE: Care must be taken to ensure that", "image node, and seeing if that node exists in the", "n): \"\"\" Returns the number of neighbors of site n.", "added in either case) :param edge_properties (dict): any other information", "is not, separate the MoleculeGraph into different MoleculeGraphs, where each", "in edges_inside_supercell: # normalize direction if new_v < new_u: new_u,", ":param name (str): name of graph, e.g. \"bonds\" :param edge_weight_name", "graph_data: dict containing graph information in dict format (not intended", "it more difficult to # keep the graph in sync", "\"\"\" # Copies self.graph such that all edges (u, v)", "n else: from_index = n to_index = neighbor[\"site_index\"] mg.add_edge( from_index=from_index,", "doesn't specify # will try and detect all equivalent images", "# return new instance of StructureGraph with supercell d =", "g.subgraph([n for n in g.degree() if g.degree()[n] != 0]) #", "new_v}) edges_to_add.append((new_u, new_v, new_d)) else: # want to find new_v", "# graph attributes don't change behavior of graph, # they're", "new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage # use np.around to fix", "__copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two MoleculeGraphs are", "split molecule; \\ MoleculeGraph is still connected.\" ) # alter", "edge properties are to be changed, it should be a", "if to_jimage is None: # assume we want the closest", "actual molecule as the input. The first atom must be", "filetype from extension (any graphviz filetype supported, such as pdf", "k)) # don't show edge directions d[\"arrowhead\"] = \"none\" #", "edges = {(u, v, d.get(\"to_jimage\", (0, 0, 0))) for u,", "by a Graph structure, and an associated structure object. This", "robust approach, but will treat e.g. enantiomers as being duplicates.", "be broken between {} and {};\\ no edge exists between", "edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\",", "on one side of supercell # are connected to nodes", "by functional group # Subtracting 1 because the dummy atom", "# make undirected to find connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph)", "to avoid remapping if alterations is not None: for (u,", "IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare)", "to be changed, it should be a float. :param new_edge_properties:", "a \"to_index\" and \"from_index\" key, and can also have a", "in all_cycles: if sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if", "strategy): \"\"\" Constructor for MoleculeGraph, using a strategy from :Class:", "= \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return sorted(list(motifs)) def as_dict(self): \"\"\" As", "+= \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph)", "edges_to_remove.append((u, v, k)) if (new_u, new_v, new_to_jimage) not in new_periodic_images:", "labels] labels = [\"{}({})\".format(label[1], label[0]) for label in labels] motif", "s += \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s +=", "= {} strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) for", "for i in range(atoms): grp_map[i] = i + offset return", "charge to whatever subgraph has node with index 0 #", "strict: return ValueError(\"Meaningless to compare MoleculeGraphs if \" \"corresponding Molecules", "be (0, 0, 0), # initial version of this class", "ensure that edge exists before attempting to remove it existing_edges", "fail. Currently, this function naively assigns the charge of the", "that contains connection information: relationships between sites represented by a", "connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs =", ":param strict: if False, will compare bonds from different Molecules,", "or the edge_properties of an edge in the MoleculeGraph. :param", "fragment in unique_frag_dict[key]: mapping = {e: i for i, e", "center of mass molecule = molecule.get_centered_molecule() molecules.append(molecule) return molecules class", "\"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v],", "other_sorted.structure) def diff(self, other, strict=True): \"\"\" Compares two StructureGraphs. Returns", "class for their meaning) :return: \"\"\" if not strategy.structures_allowed: raise", "StructureGraph: there is no guarantee the node indices will be", "package to store and operate on the graph itself, but", "= [] # Remove all two-edge cycles all_cycles = [c", "if (v, to_jimage) not in connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage,", "weight_labels (bool): if True, label edges with weights :param image_labels", "obtained from the relevant template in func_groups.json. 3. A MoleculeGraph", "with edges that are present in only one StructureGraph ('self'", "edge[1] except TypeError: raise ValueError(\"Edges must be given as (from_index,", "coords, etc.) in the MoleculeGraph. :return: \"\"\" species = {}", "dictionary with keys specifying the species involved in a connection", "mycomp = \"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey", "position of nearest neighbor. The second atom must be the", "of graph \"\"\" return self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self): \"\"\" :return:", "weights to graph if weight_labels: units = g.graph.get(\"edge_weight_units\", \"\") if", "{ (u, v, d.get(\"to_jimage\", (0, 0, 0))) for u, v,", "list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight = None if \"weight\"", "graphs (two or more separate molecules). This function does not", "self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges()) != len(other.graph.edges()): return", "mg @staticmethod def with_local_env_strategy(molecule, strategy): \"\"\" Constructor for MoleculeGraph, using", "it's important images # are hashable/immutable if \"to_jimage\" in d:", "additional properties are to be specified. :return: sg, a StructureGraph", "compared. :return: bool \"\"\" if len(self.molecule) != len(other.molecule): return False", "be taken to ensure that the functional group that is", "edge_props = fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append(", "v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked edges for", "Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s", "differences with another graph if diff: diff = self.diff(diff, strict=True)", "of edge properties to be changed. :return: \"\"\" existing_edges =", "= func_grp.graph.get_edge_data(u, v)[0] weight = None if \"weight\" in edge_props.keys():", "connected_sites = set() out_edges = list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n,", "in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(from_index,", "v # reduce unnecessary checking if to_jimage != (0, 0,", "in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls, structure, name=\"bonds\",", "not any(already_present): unique_subgraphs.append(subgraph) # get Molecule objects for each subgraph", "[supercell_sg.structure[n].coords for n in subgraph.nodes()] species = [supercell_sg.structure[n].specie for n", "index: Index of atom to substitute. :param func_grp: Substituent molecule.", "= set() for idx, site in enumerate(self.structure): centre_sp = site.species_string", "these can appear when removing periodic edges if hide_unconnected_nodes: g", "idx, site in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) #", "bonds :return: \"\"\" if self.structure != other.structure and strict: return", "case) :param edge_properties (dict): any other information to store on", "structure, weight can be None if not defined. :param n:", "\" \"corresponding Molecules are different.\") if strict: # sort for", "from_jimage from_jimage = np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage, shift) #", "another form site v to site u: this is #", "key=None, reverse=False): \"\"\" Same as Structure.sort(), also remaps nodes in", "self.molecule.charge else: charge = 0 # relabel nodes in graph", "instantiation for k, v in properties.items(): if len(v) != len(species):", "an index, the value will be an empty list. \"\"\"", "if dist == 0: # this will happen when from_index", "retrieve from/to images, set as origin if not defined to_image", "of indices in the current Molecule (and graph) to be", "attached functional group and the nearest neighbor site. Defaults to", ":param from_index: int :param to_index: int :param new_weight: alter_edge does", "connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites def get_coordination_of_site(self,", "g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\" Helper function that converts a networkx", "= Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"]) @classmethod def _edges_to_string(cls, g): header", "parameter is None, and all rings will be returned. :return:", "k)) elif (u, v, d[\"to_jimage\"]) in diff[\"other\"]: # edge has", "species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper", "v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if \"weight\" in", "and \"from_index\" key, and can also have a \"weight\" and", "property of graph \"\"\" return self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self): \"\"\"", "meaning) :return: \"\"\" if not strategy.structures_allowed: raise ValueError( \"Chosen strategy", "equal. :param other: StructureGraph :return (bool): \"\"\" # sort for", "to whatever subgraph has node with index 0 # TODO:", "removing periodic edges if hide_unconnected_nodes: g = g.subgraph([n for n", "\"\"\" :return: length of Molecule / number of nodes in", "+= \" ({})\".format(edge_weight_units) header += \" {}\".format(edge_label) header_line += \"", "group in list. \" \"Provide explicit coordinate instead\") self.molecule.substitute(index, func_grp,", "now present in supercell # and if so, delete old", "= structure.as_dict()[\"graphs\"] self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy", "len(f1_nodes) != len(f2_nodes): return False f2_edges = frag2.edges() if len(f2_edges)", "= any(d[\"to_jimage\"] != (0, 0, 0) for u, v, d", "{ \"all_weights\": all_weights, \"min\": stats.minmax[0], \"max\": stats.minmax[1], \"mean\": stats.mean, \"variance\":", "# find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)]", "from input graph_data = molecule.as_dict()[\"graphs\"] self.molecule = molecule self.graph =", "unique_frags: if _isomorphic(frag, f): found = True break if not", "1 else: f2_comp_dict[node[1][\"specie\"]] += 1 if f1_comp_dict != f2_comp_dict: return", ":param warn_duplicates (bool): if True, will warn if trying to", "of site n. In graph terms, simply returns degree of", "that edge exists before attempting to remove it existing_edges =", "from networkx.readwrite import json_graph from scipy.spatial import KDTree from scipy.stats", "be safely added. :param site_properties: Site properties for Molecule :param", "= {} for ii in range(1, len(self.molecule)): for combination in", "in graph to match mapping new_graph = nx.relabel_nodes(subg, mapping) species", "make a copy from input graph_data = molecule.as_dict()[\"graphs\"] self.molecule =", "break both (from_index, to_index) and, failing that, will attempt to", "continue if n > neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"] to_index =", "value will be an empty list. \"\"\" # Copies self.graph", "images and add multiple # edges if appropriate if to_jimage", "use node colors to color edges :param node_labels (bool): if", "{}\".format(\"-\" * max([18, len(edge_label)])) else: print_weights = False s =", "fragment combinations of the MoleculeGraphs (in other words, all connected", "avoid ambiguity.\") if existing_edges: for i, properties in existing_edges.items(): if", "trying to add a duplicate edge # there should only", ":return (int): \"\"\" number_of_self_loops = sum([1 for n, v in", "molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False) else: structure = None for", "just keeping track of the # which new lattice images", "dummy atom \"X\" func_grp.remove_species(\"X\") if graph_dict is not None: for", "= \"\" if to_image == (0, 0, 0) else \"to", ") sg.set_node_attributes() return sg @staticmethod def with_local_env_strategy(structure, strategy, weights=False): \"\"\"", "object with an empty graph (no edges, only nodes defined", "def get_connected_sites(self, n, jimage=(0, 0, 0)): \"\"\" Returns a named", "d[\"to_jimage\"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges", "to be a chemical bond, but can store any kind", "species = nx.get_node_attributes(new_graph, \"specie\") coords = nx.get_node_attributes(new_graph, \"coords\") raw_props =", "to incorporate the new functional group. TODO: Figure out how", "ever be at most one edge # between two sites", "or more new MoleculeGraph objects. :return: list of MoleculeGraphs \"\"\"", "search in new structure for these atoms # query returns", "on graph edges, similar to Structure's site_properties :return: \"\"\" #", "one side of supercell # are connected to nodes on", "to have the same bond lengths to be defined as", "that lie across *supercell* boundaries # these will subgraphs representing", "\"\"\" Extract a statistical summary of edge weights present in", "d in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.structure", "matrix. # code adapted from Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16)", "== other_sorted.structure) def diff(self, other, strict=True): \"\"\" Compares two StructureGraphs.", "# (site, jimage) pair existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data:", "{}\".format(d[\"weight\"], units) # update edge with our new style attributes", "between those sites.\".format( from_index, to_index ) ) def remove_nodes(self, indices):", ":param filename: filename to output, will detect filetype from extension", "molecules, not any duplicates present in the crystal (a duplicate", "node, and seeing if that node exists in the #", "cannot be broken between {} and {};\\ no edge exists", "failing that, will attempt to break (to_index, from_index). :return: \"\"\"", "in only one MoleculeGraph ('self' and 'other'), and edges that", "node exists in the # supercell. If it does, the", "class StructureGraph(MSONable): \"\"\" This is a class for annotating a", "and operate on the graph itself, but contains a lot", "Defaults to 1. :param graph_dict: Dictionary representing the bonds of", "# By default, assume that all edges should stay remain", "in list. \" \"Provide explicit coordinate instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order)", "= new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0]", "len(self.molecule) - atoms for i in range(atoms): grp_map[i] = i", "edge parameters. :param molecule: Molecule object :param edges: dict representing", "copy=False) self.set_node_attributes() def get_disconnected_fragments(self): \"\"\" Determine if the MoleculeGraph is", "attempt to break (to_index, from_index). :return: \"\"\" # ensure that", "of node v in # new supercell, and get asgolute", "a copy, modifies that, and returns two or more new", "as_dict(self): \"\"\" As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts`", "= nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts, reading to/from", "edge_properties = edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage,", "weight=neighbor[\"weight\"], warn_duplicates=False, ) def get_connected_sites(self, n, jimage=(0, 0, 0)): \"\"\"", "= Structure.from_sites(new_sites) # merge all graphs into one big graph", "choose another strategy.\" ) sg = StructureGraph.with_empty_graph(structure, name=\"bonds\") for n,", "site = PeriodicSite.from_dict(site_d) # from_site if jimage arg != (0,", "= new_v, new_u new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage", "all unique fragments using graph isomorphism unique_frag_dict = {} for", "graph. Please check your\" \" indices.\" ) mg.add_edge(from_index, to_index, weight=weight,", "self.structure.lattice # use k-d tree to match given position to", "of the Lattice. :param index: Index of atom to substitute.", "edge_colors else \"#000000\" # optionally add weights to graph if", "self.set_node_attributes() def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None,", "the origin if image_labels: d[\"headlabel\"] = \"\" if to_image ==", "graph \"\"\" return len(self.molecule) def sort(self, key=None, reverse=False): \"\"\" Same", "could also be done on the original graph, but a", "\"Currently functional group replacement\" \"cannot occur at an atom within", "neighbor[\"site_index\"] to_index = n else: from_index = n to_index =", "another. In order to prevent problems with misdirected edges, both", "edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None),", "in larger graphs. :param filename: filename to output, will detect", "of the total molecule to a single submolecule. A later", "= {idx: self.molecule.index(site) for idx, site in enumerate(old_molecule)} self.graph =", "(0, 0, 0)))) return s def __str__(self): s = \"Molecule", "neighbor in neighbors: # all bonds in molecules should not", "are cartesian. Defaults to False. :param validate_proximity: For Molecule.insert(); if", "for u, v, k, d in new_g.edges(keys=True, data=True): to_jimage =", "300, \"overlap\": \"false\"} # add display options for nodes for", "# prune duplicate subgraphs unique_subgraphs = [] for subgraph in", "to_index ) ) def remove_nodes(self, indices): \"\"\" A wrapper for", "in-built graph drawing methods, but note that this might give", "of neighbors of site n. In graph terms, simply returns", "to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return mg @staticmethod def with_local_env_strategy(molecule, strategy):", "by closest first \"\"\" connected_sites = set() out_edges = list(self.graph.out_edges(n,", "labels] motif = \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return sorted(list(motifs)) def as_dict(self):", "edge_match(e1, e2): if use_weights: return e1[\"weight\"] == e2[\"weight\"] return True", "g.graph = {\"nodesep\": 10.0, \"dpi\": 300, \"overlap\": \"false\"} # add", "for label in labels: sp = label[1] if sp not", "None # check if image sites now present in supercell", "your\" \" indices.\" ) mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return", "as dashed lines) :param color_scheme (str): \"VESTA\" or \"JMOL\" :param", "site :param coords: 3x1 array representing coordinates of the new", "structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts,", "It creates a copy, modifies that, and returns two or", "more new MoleculeGraph objects. :param bonds: list of tuples (from_index,", "> 2] # Using to_directed() will mean that each cycle", "types_of_coordination_environments(self, anonymous=False): \"\"\" Extract information on the different co-ordination environments", "(matplotlib can superimpose multiple edges). g = self.graph.copy() g.graph =", "len(self.structure) def sort(self, key=None, reverse=False): \"\"\" Same as Structure.sort(), also", ":return: bool \"\"\" if len(self.molecule) != len(other.molecule): return False if", "to_jimage=to_jimage, **edge_properties) def insert_node( self, i, species, coords, coords_are_cartesian=False, validate_proximity=False,", "\"Edge between {} and {} cannot be altered;\\ no edge", "to automatically detect.\") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist ==", "not None, then find_rings will only return those rings including", "None if not defined. :param n: index of Site in", "u, v, data in edges: s += \"{:4} {:4} {:12}", "stores information on the graph edges of what lattice image", "edge_weight_name = g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights = [\"weight\"] edge_label =", "from_index: int :param to_index: int :param allow_reverse: If allow_reverse is", "self.find_rings(including=[index]) if len(rings) != 0: raise RuntimeError( \"Currently functional group", "(u, v, attr_dict) # list of new edges inside supercell", "be the same if the underlying Structures are ordered differently.", "connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage))", "generating the StructureGraph, but this isn't # possible when generating", "= edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, ) )", "{(u, v) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return", "len(other.molecule): return False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False if", "{}.\".format(from_index, to_index, to_jimage) ) return # generic container for additional", "1]) + 100 c = max(coords[:, 2]) - min(coords[:, 2])", "graph, but a larger graph can be easier to visualize", "subgraphs: nodes = sorted(list(subg.nodes)) # Molecule indices are essentially list-based,", "for ii in range(1, len(self.molecule)): for combination in combinations(graph.nodes, ii):", "self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0),", "u: this is # harmless, so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0,", "in self.graph.edges(n) if n == v]) return self.graph.degree(n) - number_of_self_loops", "keep = max(sizes, key=lambda x: sizes[x]) for i in sizes.keys():", "return new_igraph def _isomorphic(frag1, frag2): \"\"\" Internal function to check", "Can be \" \"empty string if arbitrary or \" \"dimensionless.\"", "dist=dist) else: site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site =", "= self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for key, d in existing_edge_data.items():", "and (self.molecule == other_sorted.molecule) def isomorphic_to(self, other): \"\"\" Checks if", "can also be drawn with networkx's in-built graph drawing methods,", "draw_graph_to_file( self, filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False,", "in nodes and to_index in nodes): raise ValueError( \"Edges cannot", "the atom at index is terminal if len(neighbors) == 1:", "= np.array(scaling_matrix, np.int16) if scale_matrix.shape != (3, 3): scale_matrix =", "networkx.algorithms.isomorphism as iso import numpy as np from monty.json import", "to store on graph edges, similar to Structure's site_properties :return:", "misdirected edges, both graphs are converted into undirected nx.Graph objects.", "MoleculeGraph AFTER the insertion, NOT before. Each dict should at", "\"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey = mycomp", "0, 0) relative_jimage = np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage)", "Structure \"\"\" # creating a supercell is an easy way", "sufficient bonds to separate two molecule fragments, then this function", "subg in subgraphs: nodes = sorted(list(subg.nodes)) # Molecule indices are", "crystal) # without adding extra logic if getattr(self, \"_supercell_sg\", None)", "from_jimage, to_jimage # constrain all from_jimages to be (0, 0,", "weight. If None, then the algorithm will attempt to automatically", "wrapper around Molecule.insert(), which also incorporates the new site into", "for j in range(len(self.structure) - 1): if j < i:", "be a lot smaller tol = 0.05 for u, v,", "list. \" \"Provide explicit coordinate instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping", "del edge_props[\"to_jimage\"] else: # By default, assume that all edges", "d.get(\"to_jimage\", (0, 0, 0))) for u, v, d in other_sorted.graph.edges(keys=False,", "orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart) # now retrieve position of", "in Structure). :param structure (Structure): :param name (str): name of", "= nx.union(new_g, new_graph) edges_to_remove = [] # tuple of (u,", "- 1 offset = len(self.structure) - atoms for i in", ":param other: StructureGraph :param strict: if False, will compare bonds", "cartesian. Defaults to False. :param validate_proximity: For Molecule.insert(); if True", "jimage: lattice vector of site :return: list of ConnectedSite tuples,", "edges for everyone one we add if {new_u, new_v} not", "# this could probably be a lot smaller tol =", "u, v, d in subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) #", "v) matched by edges (v, u) undirected = self.graph.to_undirected() directed", "`pymatgen.core.Structure` except with using `to_dict_of_dicts` from NetworkX to store graph", "networkx as nx import networkx.algorithms.isomorphism as iso import numpy as", "edges_other = {(u, v) for u, v, d in other_sorted.graph.edges(keys=False,", "attempt to break (to_index, from_index). :return: list of MoleculeGraphs \"\"\"", "edges_to_add = [] # tuple of (u, v, attr_dict) #", "is to be changed, it should be a float. :param", "of mass molecule = molecule.get_centered_molecule() molecules.append(molecule) return molecules class MolGraphSplitError(Exception):", "label nodes with species and site index :param weight_labels (bool):", "options: 1. Providing an actual molecule as the input. The", "types from_jimage, to_jimage = ( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), )", "return False if len(self.graph.edges()) != len(other.graph.edges()): return False return _isomorphic(self.graph,", "self.graph.edges(data=True): label = get_label(u, v) types[label].append(d[\"weight\"]) return dict(types) @property def", "[0, 0, 1] dists = [] for image in images:", "f1_comp_dict = {} f2_comp_dict = {} for node in f1_nodes:", "site: mapping[tuple(site.coords)]) edges = {(u, v) for u, v, d", "from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Molecule` except restoring graphs", "= None for n in range(len(molecule)): if structure is None:", "be 0 because there should only be one edge between", "collections import defaultdict, namedtuple from itertools import combinations from operator", "edge[1] from_image = edge[2] to_image = edge[3] except TypeError: raise", "Molecule objects for each subgraph molecules = [] for subgraph", "ValueError(\"Edges must be given as (from_index, to_index)\" \"tuples\") if props", ":param other: MoleculeGraph :return (bool): \"\"\" # sort for consistent", "('self' and 'other'), and edges that are present in both.", "props is a dictionary of properties, including weight. Props should", "for use with molecules! \" \"Please choose another strategy.\" )", "properties in existing_reverse.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i", "should be a dictionary of edge properties to be changed.", "to be changed following the split. :param allow_reverse: If allow_reverse", "new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d)) else: # want to", "site index :param weight_labels (bool): if True, label edges with", "not count atoms = len(grp) - 1 offset = len(self.structure)", "the expected position # of an image node, and seeing", "def isomorphic_to(self, other): \"\"\" Checks if the graphs of two", "None nodes = sg.graph.nodes if not (from_index in nodes and", "unique_cycles.append(cycle) if including is None: cycles_nodes = unique_cycles else: for", "to_jimage) not in connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight,", "# discount subgraphs that lie across *supercell* boundaries # these", "another graph if diff: diff = self.diff(diff, strict=True) green_edges =", "if anonymous, will replace specie names with A, B, C,", "went through # periodic boundary if v_present is not None:", "entry will be a ring (cycle, in graph theory terms)", "edge_label += \" ({})\".format(edge_weight_units) header += \" {}\".format(edge_label) header_line +=", "u, v, k in green_edges: g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"}) for", "None: self._supercell_sg = supercell_sg = self * (3, 3, 3)", "or more new MoleculeGraph objects. :param bonds: list of tuples", "subgraphs unique_subgraphs = [] for subgraph in molecule_subgraphs: already_present =", "unique fragments using graph isomorphism unique_frag_dict = {} for key", "self.graph.graph[\"name\"] @property def edge_weight_name(self): \"\"\" :return: Name of the edge", "b = max(coords[:, 1]) - min(coords[:, 1]) + 100 c", "(using an algorithm provided by the `local_env` module, such as", "ValueError( \"Edge between {} and {} cannot be altered;\\ no", "in enumerate(self.structure): s = PeriodicSite( site.species, site.coords + v, new_lattice,", "image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ): \"\"\" Draws graph using GraphViz.", "0, 0)))) return s def __str__(self): s = \"Structure Graph\"", "d, dir in out_edges + in_edges: to_jimage = d[\"to_jimage\"] if", "multigraphs (edges are super-imposed on each other). If visualization is", "control over graph appearance and also correctly displays # mutli-graphs", "jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get(\"weight\", None) if", "for neighbor in neighbors: # all bonds in molecules should", "note: all node indices are in terms of the MoleculeGraph", "this is not necessary for the class to work, but", "neighbors = strat.get_nn_info(self.structure, site) for neighbor in neighbors: self.add_edge( from_index=site,", "of MoleculeGraphs \"\"\" self.set_node_attributes() original = copy.deepcopy(self) for bond in", "TODO: Figure out how to replace into a ring structure.", "alterations[(u, v)][\"weight\"] edge_properties = alterations[(u, v)] if len(alterations[(u, v)]) !=", "number of occurrences of bonds :return: \"\"\" if self.molecule !=", "checking if to_jimage != (0, 0, 0): # get index", "= (0, 0, 0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d))", "object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object", "of deprecation # of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for c", "f1_nodes = frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes):", "to break (to_index, from_index). :return: \"\"\" # ensure that edge", "before attempting to remove it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse", "g.edges[u, v, k].update(d) # optionally remove periodic image edges, #", "including weight and/or edge properties to be changed following the", "from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, ) def get_connected_sites(self,", "n): \"\"\" Returns a named tuple of neighbors of site", "even if # from_jimage != (0, 0, 0), but making", "from the relevant template in func_groups.json. 3. A MoleculeGraph object.", "in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.molecule ==", "to_jimage = d[\"to_jimage\"] # for node v # reduce unnecessary", "n2[\"specie\"] def edge_match(e1, e2): if use_weights: return e1[\"weight\"] == e2[\"weight\"]", "dictionary of edge properties to be changed. :return: \"\"\" existing_edges", "weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return list sorted by", "str(len(subgraph.edges())) if mykey not in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else:", "edge is updated. This is more # computationally expensive than", "\"\"\" :return: length of Structure / number of nodes in", "from_index=site, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, ) def", "exited with return code {}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename", "dictionary of keyword arguments for strategy. If None, default parameters", "# optionally color edges using node colors color_u = g.node[u][\"fillcolor\"]", "sanitize types from_jimage, to_jimage = ( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)),", "for additional edge properties, # similar to site properties edge_properties", "Exception: raise RuntimeError(\"Can't find functional group in list. \" \"Provide", ":param diff (StructureGraph): an additional graph to compare with, will", "= d.copy() new_to_jimage = tuple(map(int, v_expec_image)) # normalize direction if", "molecule graph is failed to split into two disconnected subgraphs", "d[\"style\"] = \"solid\" if to_image != (0, 0, 0): d[\"style\"]", "before partition, to avoid remapping if alterations is not None:", "from_index = edge[0] to_index = edge[1] except TypeError: raise ValueError(\"Edges", "return (edges == edges_other) and (self.molecule == other_sorted.molecule) def isomorphic_to(self,", "using node colors color_u = g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"]", "opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage #", "s def __len__(self): \"\"\" :return: length of Molecule / number", "trying to add duplicate edges (duplicate edges will not be", "KDTree from scipy.stats import describe from pymatgen.core import Lattice, Molecule,", "position of node v in # new supercell, and get", "MoleculeGraphs. Returns dict with keys 'self', 'other', 'both' with edges", "to_index, to_jimage=None, allow_reverse=False): \"\"\" Remove an edge from the StructureGraph.", "to_index)\" \"tuples\") if props is not None: if \"weight\" in", "in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, to_jimage=None,", "if edges have the same weights. Typically, this means molecules", "func_grp: Substituent molecule. There are three options: 1. Providing an", "that went through # periodic boundary if v_present is not", "is None: cycles_nodes = unique_cycles else: for i in including:", "optionally remove periodic image edges, # these can be confusing", "= molecule.cart_coords if extend_structure: a = max(coords[:, 0]) - min(coords[:,", "to substitute. :param func_grp: Substituent molecule. There are two options:", "self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight, dist=dist)", "a duplicate edge # there should only ever be at", "this class manually, use the `with_empty_graph` method or `with_local_env_strategy` method", "a DummySpecies X, indicating the position of nearest neighbor. The", "bond order to calculate the bond length between the attached", "also has methods for drawing # graphs using matplotlib, these", "\" \"trying to automatically detect.\") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if", "\"Provide explicit coordinate instead\") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp)", "all_subgraphs: intersects_boundary = any(d[\"to_jimage\"] != (0, 0, 0) for u,", "cycles_nodes: edges = [] for i, e in enumerate(cycle): edges.append((cycle[i", "will attempt to automatically determine bonds using one of a", "to be changed. :return: \"\"\" existing_edges = self.graph.get_edge_data(from_index, to_index) #", "GraphViz. The networkx graph object itself can also be drawn", "strategy.\" ) sg = StructureGraph.with_empty_graph(structure, name=\"bonds\") for n, neighbors in", "defined. :param n: index of Site in Molecule :param jimage:", "\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), } sg", "of nodes in graph \"\"\" return len(self.molecule) def sort(self, key=None,", "c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs = [] for", "new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing {} edges, adding {}", "string if arbitrary or \" \"dimensionless.\" ) # construct graph", "if v < u: new_v, new_u, new_d = u, v,", "tuples (from_index, to_index) representing bonds to be broken to split", "= min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist * 0.01,", "`pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore", "methods, but note that this might give misleading results for", "k, d in g.edges(keys=True, data=True): # retrieve from/to images, set", "= {e: i for i, e in enumerate(sorted(fragment.nodes))} remapped =", "Module for graph representations of crystals. \"\"\" import copy import", "not, e.g., layers of a 2D crystal) # without adding", "if warn_duplicates: warnings.warn( \"Trying to add an edge that already", "in self.graph.edges(keys=False, data=True)} edges_other = {(u, v) for u, v,", "print_weights = False s = header + \"\\n\" + header_line", "from_jimage = np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage, shift) # automatic", "edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: self.graph.add_edge(u, v,", "0, 1] dists = [] for image in images: dists.append(", "d in g.edges(keys=True, data=True): # retrieve from/to images, set as", "fractional co-ordinates of where atoms defined # by edge are", "warn_duplicates=False, ) return sg @property def name(self): \"\"\" :return: Name", "def with_local_env_strategy(structure, strategy, weights=False): \"\"\" Constructor for StructureGraph, using a", "= supercell_sg = self * (3, 3, 3) # make", "sizes[x]) for i in sizes.keys(): if i != keep: to_remove.add(i)", "3x1 array representing coordinates of the new site :param coords_are_cartesian:", "reverse=False): \"\"\" Same as Structure.sort(), also remaps nodes in graph.", "such as pdf or png) :param diff (StructureGraph): an additional", "deleted red_edges.append((u, v, k)) elif (u, v, d[\"to_jimage\"]) in diff[\"other\"]:", "new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing {} edges, adding {} new", "weight property of graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self,", "= ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) #", "len(alterations[(u, v)]) != 0 else None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties)", "place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule)", "self.graph.edges(keys=False, data=True)} edges_other = {(u, v, d[\"to_jimage\"]) for u, v,", "int :param to_index: int :param to_jimage: tuple :param allow_reverse: If", "MoleculeGraph is connected. If it is not, separate the MoleculeGraph", "debugging, edges to periodic images always appear as dashed lines)", "unique_sorted = [] unique_cycles = [] for cycle in all_cycles:", "self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls, d):", "second site. What the code will do is to remove", "from_index = n to_index = neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"],", "site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0,", "place atoms to close to each other, or violate the", "{} to site {} in {}.\".format(from_index, to_index, to_jimage) ) return", "rings = self.find_rings(including=[index]) if len(rings) != 0: raise RuntimeError( \"Currently", "not in connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist)", "in connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site)", "for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure)))", "approach, but will treat e.g. enantiomers as being duplicates. :return:", "name of graph, e.g. \"bonds\" :param edge_weight_name (str): name of", ".dot file for later visualization :param algo: any graphviz algo,", "added green_edges.append((u, v, k)) for u, v, k in green_edges:", "i2): \"\"\" Helper function called by isomorphic to ensure comparison", "\"\"\" Two MoleculeGraphs are equal if they have equal Molecules,", "visualize and reason about. :param scaling_matrix: same as Structure.__mul__ :return:", "class (consult relevant class for their meaning) :return: \"\"\" if", "edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked edges", "scaling_matrix): \"\"\" Replicates the graph, creating a supercell, intelligently joining", "as a convenient key mapping = {tuple(site.frac_coords): self.structure.index(site) for site", "import itemgetter import networkx as nx import networkx.algorithms.isomorphism as iso", "corresponding to site n. :param n: index of site :return", "edges # will remove two edges for everyone one we", "(format: {(u, v): props}, where props is a dictionary of", "edge between any two nodes if new_weight is not None:", "https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\" if 1 - (c[0] * 0.299", "self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d", "for this include storing bonding information, NMR J-couplings, Heisenberg exchange", "# convert color to hex string color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1],", "so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"]", "- 1) self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) def replace_group(", "labels: sp = label[1] if sp not in mapping: mapping[sp]", "e1[\"weight\"] == e2[\"weight\"] return True # prune duplicate subgraphs unique_subgraphs", "bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. :param molecule:", "substituted will not place atoms to close to each other,", "index should always be 0 because there should only be", "atom in self.molecule with a functional group. This method also", "periodic images always appear as dashed lines) :param color_scheme (str):", "using its frac_coords as a convenient key mapping = {tuple(site.frac_coords):", "all_weights, \"min\": stats.minmax[0], \"max\": stats.minmax[1], \"mean\": stats.mean, \"variance\": stats.variance, }", "species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(", ") if to_jimage is None: edge_index = 0 else: for", "storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. :param", "is available and networkx if it is not. \"\"\" f1_nodes", "count number of occurrences of bonds :return: \"\"\" if self.molecule", "with full 3x3 scaling matrices raise NotImplementedError(\"Not tested with 3x3", "edge weights present in the graph. :return: A dict with", "strategy is not designed for use with molecules! \" \"Please", "mapping = {} for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] =", "in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge(", "all node indices are in terms of the StructureGraph this", "for key in frag_dict: unique_frags = [] for frag in", "site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) # create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data))", "= np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image - v_expec_image % 1", "reference, # get relative Cartesian co-ordinates of where # atoms", "Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"]) def __mul__(self, scaling_matrix): \"\"\" Replicates the", "the functional group that is substituted will not place atoms", "want to find new_v such that we have # full", "# information for u, v, k, d in self.graph.edges(keys=True, data=True):", "that do not exist in diff and edges green that", "# get relative Cartesian co-ordinates of where # atoms defined", ") graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod def", "from_index: to_index, from_index = from_index, to_index # sanitize types from_index,", "other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.molecule == other_sorted.molecule)", ") else: if strategy_params is None: strategy_params = {} strat", "v)] if len(alterations[(u, v)]) != 0 else None original.alter_edge(u, v,", "# Broadly, it would be easier to multiply the Structure", "Structures are different.\") if strict: # sort for consistent node", "chemical bond, but can store any kind of information that", "go through periodic boundaries :param edge_colors (bool): if True, use", "reverse=True) if anonymous: mapping = {centre_sp: \"A\"} available_letters = [chr(66", "mg, a MoleculeGraph \"\"\" mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\")", "# only add labels for images that are not the", "neighbor in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes,", "added if nodes are not\" \" present in the graph.", "weight=weight, edge_properties=props, ) sg.set_node_attributes() return sg @staticmethod def with_local_env_strategy(structure, strategy,", "(str): name of graph, e.g. \"bonds\" :param edge_weight_name (str): name", "(no edges, only nodes defined that correspond to Sites in", "be broken to split the MoleculeGraph. :param alterations: a dict", "# optionally add weights to graph if weight_labels: units =", "mutli-graphs (matplotlib can superimpose multiple edges). g = self.graph.copy() g.graph", "nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is not None:", "is the first site and C is the second site.", "with keys specifying the species involved in a connection in", "convert color to hex string color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2])", "dissimilarity between two MoleculeGraphs (ignoring edge weights), and is defined", "= [] for u, v, k, d in g.edges(keys=True, data=True):", "key=key, reverse=reverse) # apply Molecule ordering to graph mapping =", "in range(len(self.structure))} for idx, site in enumerate(self.structure): s = PeriodicSite(", "output, will detect filetype from extension (any graphviz filetype supported,", "for i, n in enumerate(nodes): mapping[n] = i # just", "jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return list", "scipy.spatial import KDTree from scipy.stats import describe from pymatgen.core import", "out_edges = [(u, v, d, \"out\") for u, v, d", "(str): \"VESTA\" or \"JMOL\" :param keep_dot (bool): keep GraphViz .dot", "# https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\" if 1 - (c[0] *", "new_v, new_d)) else: # want to find new_v such that", "+ \" E\" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return", "(0, 0, 0): d[\"style\"] = \"dashed\" if hide_image_edges: edges_to_delete.append((u, v,", "origin if not defined to_image = d[\"to_jimage\"] # set edge", "in self.graph.out_edges(n, data=True)] in_edges = [(u, v, d, \"in\") for", "# using the position of node u as a reference,", "to_index, key in remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index,", "still be considered equal. :param other: StructureGraph :return (bool): \"\"\"", "edge with our new style attributes g.edges[u, v, k].update(d) #", "magic numbers account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor =", "designed for use with molecules! \" \"Please choose another strategy.\"", "== to_jimage: if warn_duplicates: warnings.warn( \"Trying to add an edge", "edge_index = 0 else: for i, properties in existing_edges.items(): if", "strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights:", "= None nodes = mg.graph.nodes if not (from_index in nodes", "site in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges", "indices replaced by Species strings, will not count number of", "in self.graph.edges(keys=False, data=True)} edges_other = { (u, v, d.get(\"to_jimage\", (0,", "def __mul__(self, scaling_matrix): \"\"\" Replicates the graph, creating a supercell,", "does not necessarily have to be a chemical bond, but", "len(self.structure) - atoms for i in range(atoms): grp_map[i] = i", "other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.structure == other_sorted.structure)", "be changed. :return: \"\"\" existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure", "< 0.5 else \"#ffffff\" # convert color to hex string", "graph indices have different indexing u, v = (u -", "new_u = u new_v = v_present new_d = d.copy() new_to_jimage", "@property def edge_weight_name(self): \"\"\" :return: Name of the edge weight", "not None: for (u, v) in graph_dict.keys(): edge_props = graph_dict[(u,", "= self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before attempting", "[0, 0, 0]) # get contrasting font color # magic", "for (u, v, d) in edges_to_add: self.graph.add_edge(u, v, **d) def", "color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else", "CH3. The X-C bond indicates the directionality to connect the", "from_index, to_index ) ) # Third index should always be", "discount subgraphs that lie across *supercell* boundaries # these will", "of new edges inside supercell # for duplicate checking edges_inside_supercell", "add if {new_u, new_v} not in edges_inside_supercell: # normalize direction", "have a direction, from_index, from_jimage can be swapped with to_index,", "# get fractional co-ordinates of where atoms defined # by", "a given crystallographic structure easier. Use cases for this include", "and len(edges_other) == 0: jaccard_dist = 0 # by definition", "len(rings) != 0: raise RuntimeError( \"Currently functional group replacement\" \"cannot", "__hash__() value, # using its frac_coords as a convenient key", "# similar to site properties edge_properties = edge_properties or {}", "for u, v, k, d in g.edges(keys=True, data=True): if (u,", "'both' with edges that are present in only one StructureGraph", "terms of the StructureGraph this method is called from, not", "color edges using node colors color_u = g.node[u][\"fillcolor\"] color_v =", "0 else: for i, properties in existing_edges.items(): if properties[\"to_jimage\"] ==", "should hopefully be # easier to extend to a general", "second atom must be the next nearest atom. For example,", "\"\"\" Split MoleculeGraph into two or more MoleculeGraphs by breaking", "parameters, etc. For periodic graphs, class stores information on the", "and another # (site, jimage) pair existing_edge_data = self.graph.get_edge_data(from_index, to_index)", "before attempting to change it if not existing_edge: raise ValueError(", "should be X-CH3, where X is the first site and", "make undirected to find connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) #", "= None if existing_edge: self.graph.remove_edge(from_index, to_index) else: if allow_reverse: existing_reverse", "object. This class uses the NetworkX package to store and", "# create a map of nodes from original graph to", "list. \" \"Provide explicit coordinate instead\") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping", "# they're just for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units,", "and is defined by 1 - (size of the intersection", "in g.nodes(): # get label by species name label =", "self.graph to incorporate the new functional group. NOTE: Care must", "# a dedicated tool like GraphViz allows for much easier", "# edges if appropriate if to_jimage is None: # assume", "v == n: site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site", "# Multiplication works by looking for the expected position #", "= len(grp) - 1 offset = len(self.structure) - atoms for", "= (0, 0, 0) edges_to_remove.append((u, v, k)) # make sure", "= new_structure[u].coords + v_rel # now search in new structure", "in raw_props.values(): for prop in prop_set.keys(): if prop in properties:", "len(grp) - 1 offset = len(self.molecule) - atoms for i", "= 0.05 for u, v, k, d in new_g.edges(keys=True, data=True):", "== 0: props = None else: weight = None nodes", ":param edge_properties (dict): any other information to store on graph", "# so that nodes on one side of supercell #", "allow_reverse is True, then break_edge will attempt to break both", "taken to ensure that the functional group that is substituted", "v_label = self.structure[v].species_string return \"-\".join(sorted((u_label, v_label))) types = defaultdict(list) for", "if that node exists in the # supercell. If it", "nodes with species and site index :param weight_labels (bool): if", "None: strategy_params = {} strat = strategy(**strategy_params) for site in", "origin if image_labels: d[\"headlabel\"] = \"\" if to_image == (0,", "connections (e.g. bond lengths). \"\"\" def get_label(u, v): u_label =", "def build_unique_fragments(self): \"\"\" Find all possible fragment combinations of the", "to_image = d[\"to_jimage\"] else: to_image = (0, 0, 0) #", "this is None. If any edge properties are to be", "if to_image == (0, 0, 0) else \"to {}\".format((to_image)) d[\"arrowhead\"]", "display options for edges for u, v, k, d in", "image edges, # these can be confusing due to periodic", "def get_label(u, v): u_label = self.structure[u].species_string v_label = self.structure[v].species_string return", "in diff[\"other\"]: # edge has been added green_edges.append((u, v, k))", "edge in the MoleculeGraph. :param from_index: int :param to_index: int", "connected_sites def get_coordination_of_site(self, n): \"\"\" Returns the number of neighbors", "strategy.get_nn_info(structure, n) for neighbor in neighbors: # all bonds in", "(edges == edges_other) and (self.molecule == other_sorted.molecule) def isomorphic_to(self, other):", "with to_index, to_jimage. However, images will always always be shifted", "properties are to be specified. :return: mg, a MoleculeGraph \"\"\"", "used. :return: \"\"\" self.set_node_attributes() neighbors = self.get_connected_sites(index) # If the", "are equal if they have equal Molecules, and have the", "initial image to_jimage = (0, 0, 0) if \"weight\" in", "Structure. This # approach has many benefits, but made it", "== (0, 0, 0) else \"to {}\".format((to_image)) d[\"arrowhead\"] = \"normal\"", "True, only treat subgraphs as isomorphic if edges have the", "{} for ii in range(1, len(self.molecule)): for combination in combinations(graph.nodes,", "and {} cannot be altered;\\ no edge exists between those", "edge exists between those sites.\".format( from_index, to_index ) ) def", "connection in alphabetical order (e.g. string 'Fe-O') and values which", "g): header = \"from to to_image \" header_line = \"----", "simplifies logic later if not np.array_equal(from_jimage, (0, 0, 0)): shift", "= strat.get_nn_info(self.structure, site) for neighbor in neighbors: self.add_edge( from_index=site, from_jimage=(0,", "unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is None: cycles_nodes = unique_cycles else:", "molecule easier. Use cases for this include storing bonding information,", "molecule: Molecule object :param edges: dict representing the bonds of", "an # existing Site in Structure kd_tree = KDTree(new_structure.cart_coords) #", "coords[node] = self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph,", "tuple(map(int, v_expec_image)) # normalize direction if new_v < new_u: new_u,", "self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node(", "a ring structure. :param index: Index of atom to substitute.", "of information that connects two Sites. \"\"\" def __init__(self, molecule,", "are present in only one MoleculeGraph ('self' and 'other'), and", "{index:cycle}. Each entry will be a ring (cycle, in graph", "u) undirected = self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes = []", "self.graph.edges(keys=False, data=True) } edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for u,", "from_index = from_index, to_index to_jimage, from_jimage = from_jimage, to_jimage #", "nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge( self, from_index, to_index, to_jimage=None, new_weight=None,", "This class uses the NetworkX package to store and operate", "# this will happen when from_index == to_index, # typically", "weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ): \"\"\" Draws graph using", "= tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod", "MoleculeGraph. :param alterations: a dict {(from_index, to_index): alt}, where alt", "0 because there should only be one edge between any", "offset return grp_map if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else:", "v, k, d in new_g.edges(keys=True, data=True): to_jimage = d[\"to_jimage\"] #", "n to_index = neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, )", "the dissimilarity between two StructureGraphs (ignoring edge weights), and is", "an algorithm provided by the `local_env` module, such as O'Keeffe).", "from different Molecules, with node indices replaced by Species strings,", "site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d.get(\"to_jimage\", (0, 0, 0)))", "def set_node_attributes(self): \"\"\" Replicates molecule site properties (specie, coords, etc.)", "self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0: # this will happen when", "use standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0,", "(0, 0, 0))), data.get(\"weight\", 0) ) else: for u, v,", "index is terminal if len(neighbors) == 1: self.substitute_group( index, func_grp,", "neighbor. The second atom must be the next nearest atom.", "bond information, stored in the form of a graph. A", "edges_to_remove = [] # tuple of (u, v, k) edges_to_add", "None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if new_edge_properties is not None: for", "attributes g.edges[u, v, k].update(d) # optionally remove periodic image edges,", "del alterations[(u, v)][\"weight\"] edge_properties = alterations[(u, v)] if len(alterations[(u, v)])", "is simplified if a graph is already in place if", "os.remove(basename + \".dot\") def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Molecule`", "in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in", "key=lambda x: sizes[x]) for i in sizes.keys(): if i !=", "retrieve position of node v in # new supercell, and", "will not count number of occurrences of bonds :return: \"\"\"", "new site :param species: Species for the new site :param", "RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\" Gives each node", "v_label))) types = defaultdict(list) for u, v, d in self.graph.edges(data=True):", "correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self): \"\"\" Determine if", "style=\"filled\", shape=\"circle\", ) edges_to_delete = [] # add display options", "properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure =", "edge style d[\"style\"] = \"solid\" if to_image != (0, 0,", "duplicates # information for u, v, k, d in self.graph.edges(keys=True,", "edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d in", "{} if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index,", "new site :param coords_are_cartesian: Whether coordinates are cartesian. Defaults to", "except TypeError: raise ValueError(\"Edges must be given as (from_index, to_index)\"", "directionality to connect the atoms. 2. A string name. The", "{(u, v, d[\"to_jimage\"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)}", "} def get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve subgraphs as molecules, useful", "other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d.get(\"to_jimage\", (0, 0,", "namedtuple from itertools import combinations from operator import itemgetter import", "violate the dimensions of the Lattice. :param index: Index of", "+ 100 c = max(coords[:, 2]) - min(coords[:, 2]) +", ":return: Name of graph \"\"\" return self.graph.graph[\"name\"] @property def edge_weight_name(self):", "summary of edge weights present in the graph. :return: A", "dedicated tool like GraphViz allows for much easier # control", "graph. :param key: :param reverse: :return: \"\"\" old_molecule = self.molecule.copy()", "edges_to_delete.append((u, v, k)) # don't show edge directions d[\"arrowhead\"] =", "v, d[\"to_jimage\"]) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other", "return (edges == edges_other) and (self.structure == other_sorted.structure) def diff(self,", "func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings = self.find_rings(including=[index])", "where props is a dictionary of properties, including weight. Props", "most one edge # between a given (site, jimage) pair", "# tuple of (u, v, attr_dict) # list of new", "from_jimages to be (0, 0, 0), # initial version of", "we're not trying to add a duplicate edge # there", "image_labels (bool): if True, label edges with their periodic images", "header += \" {}\".format(edge_label) header_line += \" {}\".format(\"-\" * max([18,", "def with_edges(structure, edges): \"\"\" Constructor for MoleculeGraph, using pre-existing or", "Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional", "coords = molecule.cart_coords if extend_structure: a = max(coords[:, 0]) -", "d[\"arrowhead\"] = \"normal\" if d[\"headlabel\"] else \"none\" # optionally color", "d[\"arrowhead\"] = \"none\" # only add labels for images that", "new_structure[u].coords + v_rel # now search in new structure for", "d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None,", "to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else: if strategy_params is None: strategy_params", "= sorted(labels, reverse=True) if anonymous: mapping = {centre_sp: \"A\"} available_letters", "= 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { \"self\": edges", "those sites.\".format( from_index, to_index ) ) if to_jimage is None:", "`from_dict_of_dicts` from NetworkX to restore graph information. \"\"\" m =", "present in the graph. :param anonymous: if anonymous, will replace", "dir in out_edges + in_edges: to_jimage = d[\"to_jimage\"] if dir", "v_expec_image - v_expec_image % 1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec", "iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): \"\"\" This", "StructureGraph. :param from_index: int :param to_index: int :param to_jimage: tuple", "to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes() return sg @staticmethod", "import igraph IGRAPH_AVAILABLE = True except ImportError: IGRAPH_AVAILABLE = False", "__mul__ with full 3x3 scaling matrices raise NotImplementedError(\"Not tested with", "prevent problems with misdirected edges, both graphs are converted into", "new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure = Structure.from_sites(new_sites) # merge all graphs", "Molecules. If the bonds parameter does not include sufficient bonds", "will attempt to break (to_index, from_index). :return: list of MoleculeGraphs", "{ (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True)", "graph edges, similar to Structure's site_properties :return: \"\"\" # this", "lists happens # when serializing back from json), it's important", "shape=\"circle\", ) edges_to_delete = [] # add display options for", "x: sizes[x]) for i in sizes.keys(): if i != keep:", "from_index, to_index, new_weight=None, new_edge_properties=None): \"\"\" Alters either the weight or", "do not exist in diff and edges green that are", "# get index in original site n_u = u %", "defined by edge # are expected to be v_expec =", "is at center of mass molecule = molecule.get_centered_molecule() molecules.append(molecule) return", "edge properties to be changed. :return: \"\"\" existing_edge = self.graph.get_edge_data(from_index,", "# must be remapped, incrementing from 0 mapping = {}", "data=True): # retrieve from/to images, set as origin if not", "sg = StructureGraph.with_empty_graph(structure, name=\"bonds\") for n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for", "cycles_edges = [] # Remove all two-edge cycles all_cycles =", "data=True)} return (edges == edges_other) and (self.structure == other_sorted.structure) def", "other.structure and strict: return ValueError(\"Meaningless to compare StructureGraphs if \"", "site # graph attributes don't change behavior of graph, #", "should not count atoms = len(grp) - 1 offset =", "periodic image. Here, the # number of nodes != number", "return grp_map # Work is simplified if a graph is", "position # of an image node, and seeing if that", "\"Production\" __date__ = \"August 2017\" ConnectedSite = namedtuple(\"ConnectedSite\", \"site, jimage,", "new_graphs: new_g = nx.union(new_g, new_graph) edges_to_remove = [] # tuple", "style d[\"style\"] = \"solid\" if to_image != (0, 0, 0):", "C is the second site. What the code will do", "returns (distance, index) v_present = kd_tree.query(v_expec) v_present = v_present[1] if", "= np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords # using the position", "edge weight property of graph \"\"\" return self.graph.graph[\"edge_weight_name\"] @property def", "dir == \"in\": u, v = v, u to_jimage =", "automatically detect.\") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0:", "Use cases for this include storing bonding information, NMR J-couplings,", "d[\"to_jimage\"] == (0, 0, 0)] new_periodic_images = [] orig_lattice =", "MoleculeGraph. :param i: Index at which to insert the new", "in all_subgraphs: intersects_boundary = any(d[\"to_jimage\"] != (0, 0, 0) for", "underlying Molecules. If the bonds parameter does not include sufficient", "return e1[\"weight\"] == e2[\"weight\"] return True # prune duplicate subgraphs", "edges, only nodes defined that correspond to Sites in Molecule).", "your edge weights. Can be \" \"empty string if arbitrary", "__len__(self): \"\"\" :return: length of Structure / number of nodes", "including: list of site indices. If including is not None,", "g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\" #", "self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight, dist=dist)", ":return: A dictionary with keys specifying the species involved in", "this could probably be a lot smaller tol = 0.05", "\"\"\" if not which(algo): raise RuntimeError(\"StructureGraph graph drawing requires \"", "nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph, \"specie\") coords = nx.get_node_attributes(new_graph, \"coords\")", "molecule; \\ MoleculeGraph is still connected.\" ) # alter any", "be a float. :param new_edge_properties: alter_edge does not require that", "print_weights: for u, v, data in edges: s += \"{:4}", "'maximum', 'median', 'mean', 'std_dev' \"\"\" all_weights = [d.get(\"weight\", None) for", "[\"weight\"] edge_label = g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label", "_igraph_from_nxgraph(graph): \"\"\" Helper function that converts a networkx graph object", "that are in diff graph but not in the reference", "for site in other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])", "of site :return (int): \"\"\" number_of_self_loops = sum([1 for n,", "if \"key\" in d: del d[\"key\"] # ensure images are", "\"weight\" in props.keys(): weight = props[\"weight\"] del props[\"weight\"] else: weight", "incorporate the new functional group. TODO: Figure out how to", "tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), ) from_index, to_index = int(from_index), int(to_index)", "\"\"\" Find ring structures in the MoleculeGraph. :param including: list", "in other_sorted.graph.edges(keys=False, data=True)} else: edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for", "= \"---- ---- ------------\" edge_weight_name = g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights", "of the edge weight property of graph \"\"\" return self.graph.graph[\"edge_weight_units\"]", "\"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls,", "be used. :return: \"\"\" def map_indices(grp): grp_map = {} #", "for v in c_lat: # create a map of nodes", "If any edge properties are to be changed, it should", "be obtained from the relevant template in func_groups.json. :param strategy:", "to_jimage = d[\"to_jimage\"] if dir == \"in\": u, v =", "v, d[\"to_jimage\"]) in diff[\"other\"]: # edge has been added green_edges.append((u,", "# Developer note: a different approach was also trialed, using", "n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors: # local_env", "iso import numpy as np from monty.json import MSONable from", "0, 0], [0, 1, 0], [0, 0, 1] dists =", "bonds, allow_reverse=False, alterations=None): \"\"\" Split MoleculeGraph into two or more", "molecules class MolGraphSplitError(Exception): \"\"\" Raised when a molecule graph is", "If there is no cycle including an index, the value", "\"\"\" number_of_self_loops = sum([1 for n, v in self.graph.edges(n) if", "else: weight = None nodes = mg.graph.nodes if not (from_index", "also work here. However, # a dedicated tool like GraphViz", "breaking a set of bonds. This function uses MoleculeGraph.break_edge repeatedly", "position of node u as a reference, # get relative", "# by edge are expected to be, relative to original", "to substitute. :param func_grp: Substituent molecule. There are three options:", "in mapping: mapping[sp] = available_letters.pop(0) centre_sp = \"A\" labels =", "into different MoleculeGraphs, where each resulting MoleculeGraph is a disconnected", "if d.get(\"weight\"): d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"], units) # update edge", "different approach was also trialed, using # a simple Graph", "StructureGraph(MSONable): \"\"\" This is a class for annotating a Structure", "Cartesian # co-ordinates of where atoms defined by edge #", "tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\"", "graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data =", "Structure / number of nodes in graph \"\"\" return len(self.structure)", "\"\"\" connected_sites = set() out_edges = list(self.graph.out_edges(n, data=True)) in_edges =", "site u: this is # harmless, so warn_duplicates=False sg.add_edge( from_index=n,", "the same weights. Typically, this means molecules will need to", "range(len(molecule)): if structure is None: neighbors = strategy.get_nn_info(molecule, n) else:", "data=True)} else: edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v,", "failing that, will attempt to break (to_index, from_index). :return: list", "write_dot from networkx.readwrite import json_graph from scipy.spatial import KDTree from", "= max(coords[:, 2]) - min(coords[:, 2]) + 100 structure =", "v)[0] weight = None if \"weight\" in edge_props.keys(): weight =", "remapped = nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped, \"specie\") coords =", "dist, dist * 0.01, include_index=True ) for nnsite in equiv_sites:", "[prop_set[prop]] # Site properties must be present for all atoms", "have equal Structures, and have the same edges between Sites.", "creating a supercell is an easy way to extract #", "important images # are hashable/immutable if \"to_jimage\" in d: d[\"to_jimage\"]", "= header + \"\\n\" + header_line + \"\\n\" edges =", "for annotating a Structure with bond information, stored in the", "i, and all indices used for these edges should reflect", "information. \"\"\" d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\":", "is a simple measure of the dissimilarity between two MoleculeGraphs", "KDTree(new_structure.cart_coords) # tolerance in Å for sites to be considered", "break (to_index, from_index). :return: \"\"\" # ensure that edge exists", "to_jimage. However, images will always always be shifted so that", "vector of site :return: list of ConnectedSite tuples, sorted by", "= _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\", \"ERROR\") return", "weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node( self, i,", "periodic boundaries. In principle, any operations on the expanded graph", "= g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if", "\"\" if to_image == (0, 0, 0) else \"to {}\".format((to_image))", "So, we must also remove duplicates unique_sorted = [] unique_cycles", "of crystals. \"\"\" import copy import logging import os.path import", "\"coords\" attribute, updated with the current species and coordinates. :return:", "always appears twice # So, we must also remove duplicates", "Site in Structure :param jimage: lattice vector of site :return:", "mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is not None: for", "other words, all connected induced subgraphs) :return: \"\"\" self.set_node_attributes() graph", "= i if new_weight is not None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight", "from_index: to_index, from_index = from_index, to_index to_jimage, from_jimage = from_jimage,", "and MoleculeGraphs can still be considered equal. :param other: MoleculeGraph", "edges must include the index of the new site i,", "edges inside supercell # for duplicate checking edges_inside_supercell = [{u,", "nx.is_connected(subgraph): mykey = mycomp + str(len(subgraph.edges())) if mykey not in", "data=True)] for u, v, d, dir in out_edges + in_edges:", "\"bonds\" :param edge_weight_name (str): name of edge weights, e.g. \"bond_length\"", ") # Third index should always be 0 because there", "give charge to whatever subgraph has node with index 0", "images always appear as dashed lines) :param color_scheme (str): \"VESTA\"", "length :param warn_duplicates (bool): if True, will warn if trying", "be used. :return: \"\"\" self.set_node_attributes() neighbors = self.get_connected_sites(index) # If", "Molecule as the input. The first atom must be a", "not include sufficient bonds to separate two molecule fragments, then", "indices.\" ) mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return mg @staticmethod", ":param strategy_params: dictionary of keyword arguments for strategy. If None,", "self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls, d):", "using critic2 from # charge density. # Multiplication works by", "but this isn't # possible when generating the graph using", "remove it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if", "tuple :param allow_reverse: If allow_reverse is True, then break_edge will", "number of neighbors of site n. In graph terms, simply", "0.01, include_index=True ) for nnsite in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords,", "{(from_index, to_index, from_image, to_image): props}, where props is a dictionary", "to_jimage # use np.around to fix issues with finite precision", "from_index < to_index and from_jimage becomes (0, 0, 0). :param", "closest site warnings.warn(\"Please specify to_jimage to be unambiguous, \" \"trying", "else: if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp", "two StructureGraphs. Returns dict with keys 'self', 'other', 'both' with", "more crowded graphs) usually give good outputs :return: \"\"\" if", "to make associating a graph with a given crystallographic structure", "defined that correspond to Sites in Structure). :param structure (Structure):", "from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Structure` except restoring graphs", "neighbors of site n: periodic_site, jimage, index, weight. Index is", "existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: for i, properties in", "\"\"\" # creating a supercell is an easy way to", "check if image sites now present in supercell # and", "offset = len(self.structure) - atoms for i in range(atoms): grp_map[i]", "twice # So, we must also remove duplicates unique_sorted =", "it would be easier to multiply the Structure # *before*", "with a functional group. This method also amends self.graph to", "class MoleculeGraph(MSONable): \"\"\" This is a class for annotating a", "of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for", "json_graph from scipy.spatial import KDTree from scipy.stats import describe from", "graphs of two MoleculeGraphs are isomorphic to one another. In", "or \"fdp\" (for more crowded graphs) usually give good outputs", "is # harmless, so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0, 0),", "+= self._edges_to_string(self.graph) return s def __repr__(self): s = \"Molecule Graph\"", "color edges using node colors color_u = g.nodes[u][\"fillcolor\"] color_v =", "\"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge( self,", "# construct graph with one node per site # graph", "(0, 0, 0))) for u, v, d in other_sorted.graph.edges(keys=False, data=True)", "reason about. :param scaling_matrix: same as Structure.__mul__ :return: \"\"\" #", "(ignoring edge weights), and is defined by 1 - (size", "neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes, key=lambda x:", "compare StructureGraphs if \" \"corresponding Structures are different.\") if strict:", "for prop_set in raw_props.values(): for prop in prop_set.keys(): if prop", "be # easier to extend to a general 3x3 scaling", "= self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight,", "for the class to work, but # just makes it", "there is no cycle including an index, the value will", "sort for consistent node indices # PeriodicSite should have a", "already exists from \" \"site {} to site {}.\".format(from_index, to_index)", "label by species name label = \"{}({})\".format(str(self.molecule[n].specie), n) if node_labels", "species, coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j", "restore graph information. \"\"\" s = Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"])", "0 not in list(graph.graph.nodes()): # If graph indices have different", "Currently, this function naively assigns the charge of the total", "import os.path import subprocess import warnings from collections import defaultdict,", "u, v = (u - 1), (v - 1) self.add_edge(", "with our new style attributes g.edges[u, v, k].update(d) # optionally", "self.graph.to_undirected() # find all possible fragments, aka connected induced subgraphs", "d in other_sorted.graph.edges(keys=False, data=True) } else: edges = { (str(self.molecule[u].specie),", ") sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes()", "track of the # which new lattice images present, but", "diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\",", "edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError: raise", "including an index, the value will be an empty list.", "v)]) != 0 else None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else:", "relevant template in func_groups.json. 3. A MoleculeGraph object. :param strategy:", "ConnectedSite tuples, sorted by closest first \"\"\" connected_sites = set()", "= [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all unique fragments", "in subgraph.nodes()] species = [supercell_sg.structure[n].specie for n in subgraph.nodes()] molecule", "0)))) return s def __str__(self): s = \"Molecule Graph\" s", "nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols = list() #", "to output, will detect filetype from extension (any graphviz filetype", ":param from_index: int :param to_index: int :param to_jimage: tuple :param", "str(data.get(\"to_jimage\", (0, 0, 0)))) return s def __str__(self): s =", "defined # by edge are expected to be, relative to", "mg.set_node_attributes() return mg @staticmethod def with_local_env_strategy(molecule, strategy): \"\"\" Constructor for", "self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before attempting to", "using GraphViz. The networkx graph object itself can also be", "that nodes on one side of supercell # are connected", "ring structures in the MoleculeGraph. :param including: list of site", "= map_indices(func_grp) # Remove dummy atom \"X\" func_grp.remove_species(\"X\") if graph_dict", "else \"#000000\" # optionally add weights to graph if weight_labels:", "self.graph.remove_nodes_from(indices) mapping = {} for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current]", "!= (0, 0, 0) for u, v, d in subgraph.edges(data=True))", "per site # graph attributes don't change behavior of graph,", "strict: if False, will compare bonds from different Structures, with", "functional group in list. \" \"Provide explicit coordinate instead\") self.structure.substitute(index,", "edge_props = func_grp.graph.get_edge_data(u, v)[0] weight = None if \"weight\" in", "if \" \"corresponding Structures are different.\") if strict: # sort", "mapping) species = nx.get_node_attributes(new_graph, \"specie\") coords = nx.get_node_attributes(new_graph, \"coords\") raw_props", "store graph information. \"\"\" d = { \"@module\": self.__class__.__module__, \"@class\":", "({})\".format(edge_weight_units) header += \" {}\".format(edge_label) header_line += \" {}\".format(\"-\" *", "color to hex string color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node(", "between those sites.\".format( from_index, to_index ) ) # Third index", "calculate the bond length between the attached functional group and", "a convenient key mapping = {tuple(site.frac_coords): self.molecule.index(site) for site in", "edges - edges_other, \"other\": edges_other - edges, \"both\": edges.intersection(edges_other), \"dist\":", "an empty graph (no edges, only nodes defined that correspond", "TypeError: raise ValueError(\"Edges must be given as (from_index, to_index,\" \"", "group replacement\" \"cannot occur at an atom within a ring\"", "# edge has been added green_edges.append((u, v, k)) for u,", "u to_jimage = np.multiply(-1, to_jimage) to_jimage = tuple(map(int, np.add(to_jimage, jimage)))", "(0, 0, 0)))) return s def __str__(self): s = \"Structure", "not keep_dot: os.remove(basename + \".dot\") def as_dict(self): \"\"\" As in", "self.set_node_attributes() neighbors = self.get_connected_sites(index) # If the atom at index", "= nx.get_node_attributes(new_graph, \"properties\") properties = {} for prop_set in raw_props.values():", "= mycomp + str(len(subgraph.edges())) if mykey not in frag_dict: frag_dict[mykey]", "structure: a Structure object :param graph_data: dict containing graph information", "only one StructureGraph ('self' and 'other'), and edges that are", "node[1][\"specie\"] not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1 else: f1_comp_dict[node[1][\"specie\"]] +=", "def break_edge(self, from_index, to_index, allow_reverse=False): \"\"\" Remove an edge from", "properties are to be changed, it should be a dictionary", "\"specie\" and a \"coords\" attribute, updated with the current species", "graphs. :param filename: filename to output, will detect filetype from", "n in subgraph.nodes()] molecule = Molecule(species, coords) # shift so", "int :param to_index: int :param new_weight: alter_edge does not require", "identities. \"\"\" return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\" Helper", "(v, to_jimage) not in connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v,", "site_d[\"abc\"] = np.add(site_d[\"abc\"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d) # from_site if", "mapping new_graph = nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph, \"specie\") coords", "index :param weight_labels (bool): if True, label edges with weights", "add specie names to graph to be able to test", "edge_props = graph_dict[(u, v)] if \"to_jimage\" in edge_props.keys(): to_jimage =", "weight=weight, edge_properties=edge_props, ) else: if strategy_params is None: strategy_params =", "in only one StructureGraph ('self' and 'other'), and edges that", "molecules.append(molecule) return molecules class MolGraphSplitError(Exception): \"\"\" Raised when a molecule", "sites) doesn't have a direction, from_index, from_jimage can be swapped", "MoleculeGraph: there is no guarantee the node indices will be", "for any one bond, one from site u to site", ") ) if to_jimage is None: edge_index = 0 else:", "f1_comp_dict[node[1][\"specie\"]] += 1 for node in f2_nodes: if node[1][\"specie\"] not", "1, 0], [0, 0, 1] dists = [] for image", "(artificial) periodic boundaries if not np.array_equal(neighbor[\"image\"], [0, 0, 0]): continue", "[] for sp in set(connected_species): count = connected_species.count(sp) labels.append((count, sp))", "By default, assume that all edges should stay remain #", "the MoleculeGraph into different MoleculeGraphs, where each resulting MoleculeGraph is", "IGRAPH_AVAILABLE = True except ImportError: IGRAPH_AVAILABLE = False logger =", "strict=True): \"\"\" Compares two MoleculeGraphs. Returns dict with keys 'self',", "sg def __rmul__(self, other): return self.__mul__(other) @classmethod def _edges_to_string(cls, g):", "present in only one StructureGraph ('self' and 'other'), and edges", "and values which are a list of weights for those", "NetworkX to restore graph information. \"\"\" m = Molecule.from_dict(d[\"molecule\"]) return", "nearest neighbor site. Defaults to 1. :param graph_dict: Dictionary representing", "from 0 mapping = {} for i, n in enumerate(nodes):", "this might give misleading results for multigraphs (edges are super-imposed", "else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all unique fragments using graph", "isomorphism unique_frag_dict = {} for key in frag_dict: unique_frags =", "attr dicts, reading to/from json duplicates # information for u,", "pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk import", "len(f2_edges) != len(f2_edges): return False f1_comp_dict = {} f2_comp_dict =", "ambiguity.\") if existing_edges: for i, properties in existing_edges.items(): if properties[\"to_jimage\"]", "supercell # for duplicate checking edges_inside_supercell = [{u, v} for", "def __repr__(self): s = \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__repr__())", "as molecules, useful for extracting molecules from periodic crystals. Will", "mapping, copy=False) self.set_node_attributes() def substitute_group( self, index, func_grp, strategy, bond_order=1,", "empty list. \"\"\" # Copies self.graph such that all edges", "duplicate checking edges_inside_supercell = [{u, v} for u, v, d", "combination in combinations(graph.nodes, ii): mycomp = [] for idx in", "v)][\"weight\"] del alterations[(u, v)][\"weight\"] edge_properties = alterations[(u, v)] if len(alterations[(u,", "from scipy.stats import describe from pymatgen.core import Lattice, Molecule, PeriodicSite,", "idx, site in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) #", "graph, # they're just for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name,", "coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(self, from_index, to_index, new_weight=None,", "k in red_edges: g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"}) basename, extension =", "+ v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping,", "1)) if print_weights: for u, v, data in edges: s", "a dictionary including weight and/or edge properties to be changed", "alt}, where alt is a dictionary including weight and/or edge", "visualization is difficult to interpret, `hide_image_edges` can help, especially in", "not\" \" present in the graph. Please check your\" \"", "\"\"\" Retrieve subgraphs as molecules, useful for extracting molecules from", "dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist = min(dists) equiv_sites = self.structure.get_neighbors_in_shell(", "include storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc.", "the bonds of the functional group (format: {(u, v): props},", "work, but # just makes it neater if to_index <", "v)] if \"to_jimage\" in edge_props.keys(): to_jimage = edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"]", "different MoleculeGraphs, where each resulting MoleculeGraph is a disconnected subgraph", "names to graph to be able to test for isomorphism", "in range(atoms): grp_map[i] = i + offset return grp_map #", "itemgetter import networkx as nx import networkx.algorithms.isomorphism as iso import", "u, v, d in self.graph.edges(keys=False, data=True) } edges_other = {", "any edge properties are to be changed, it should be", "index found in the Molecule. If there is no cycle", "as duplicates, otherwise bond lengths can differ. This is a", "a dictionary of edge properties to be changed. :return: \"\"\"", "weights present in the graph. :return: A dict with an", "will always try to add two edges # for any", "no cycle including an index, the value will be an", "edges_to_add = [] for u, v, k, d in self.graph.edges(keys=True,", "new_v, new_u, new_d = u, v, d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1,", "one we add if {new_u, new_v} not in edges_inside_supercell: #", "to_jimage if user doesn't specify # will try and detect", "site. What the code will do is to remove the", "the types and weights of edges in the graph. :return:", "return code {}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + \".dot\")", "image the edge belongs to. :param structure: a Structure object", "function does not modify the original MoleculeGraph. It creates a", "func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError(\"Can't find functional group", "# optionally highlight differences with another graph if diff: diff", "modify the original MoleculeGraph. It creates a copy, modifies that,", "and {};\\ no edge exists between those sites.\".format( from_index, to_index", "optionally color edges using node colors color_u = g.node[u][\"fillcolor\"] color_v", "of strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword", "else \"to {}\".format((to_image)) d[\"arrowhead\"] = \"normal\" if d[\"headlabel\"] else \"none\"", "only used for debugging, edges to periodic images always appear", "(c) Pymatgen Development Team. # Distributed under the terms of", "able to test for isomorphism for subgraph in molecule_subgraphs: for", "This is a fairly robust approach, but will treat e.g.", "= {} coords = {} properties = {} for node", "a graph with a given crystallographic structure easier. Use cases", "representations of crystals. \"\"\" import copy import logging import os.path", "number of sites in the Structure. This # approach has", "Retrieve subgraphs as molecules, useful for extracting molecules from periodic", "0, 0) for u, v, d in subgraph.edges(data=True)) if not", "to be specified. :return: sg, a StructureGraph \"\"\" sg =", "\"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, from_jimage=(0, 0,", "properties[\"to_jimage\"] == to_jimage: edge_index = i if new_weight is not", "in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg @property def", "site connecting to :param weight (float): e.g. bond length :param", "cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule, edges): \"\"\" Constructor for MoleculeGraph,", "so that nodes on one side of supercell # are", "as np from monty.json import MSONable from monty.os.path import which", "operate on the graph itself, but contains a lot of", "also be done on the original graph, but a larger", "+= \"{:4} {:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0, 0)))) return", "from_index) if existing_reverse: for i, properties in existing_reverse.items(): if properties[\"to_jimage\"]", "centre_sp = site.species_string connected_sites = self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for", "edges edges_to_remove = [] edges_to_add = [] for u, v,", "larger graph can be easier to visualize and reason about.", "uses the NetworkX package to store and operate on the", "using # a simple Graph (instead of MultiDiGraph), with node", "to be removed. :return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {}", "book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data", "are ordered differently. :param other: MoleculeGraph :param strict: if False,", "partition, to avoid remapping if alterations is not None: for", "to_index: int :param to_jimage: tuple :param allow_reverse: If allow_reverse is", "d[\"to_jimage\"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} else: edges", "separate the MoleculeGraph into different MoleculeGraphs, where each resulting MoleculeGraph", "types_and_weights_of_connections(self): \"\"\" Extract a dictionary summarizing the types and weights", "os.path import subprocess import warnings from collections import defaultdict, namedtuple", "supercell # are connected to nodes on opposite side v_expec_frac", "d[\"to_jimage\"]) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other =", "be the same if the underlying Molecules are ordered differently.", "image is given, this method will fail. :param from_index: int", "the initial image to_jimage = (0, 0, 0) if \"weight\"", "creates a copy, modifies that, and returns two or more", "vector of image :param weight (float): e.g. bond length :param", "3x3 scaling matrices yet.\") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat =", "self.set_node_attributes() def get_disconnected_fragments(self): \"\"\" Determine if the MoleculeGraph is connected.", "unique_frag_dict[key]: mapping = {e: i for i, e in enumerate(sorted(fragment.nodes))}", "edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, ) ) frag_key", "0.299 + c[1] * 0.587 + c[2] * 0.114) /", "equivalent images and add multiple # edges if appropriate if", "not in new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing", "MoleculeGraph.substitute_group to replace a functional group in self.molecule with a", "Remove dummy atom \"X\" func_grp.remove_species(\"X\") if graph_dict is not None:", "There are two options: 1. Providing an actual Molecule as", "relationships between sites represented by a Graph structure, and an", "prune duplicate subgraphs unique_subgraphs = [] for subgraph in molecule_subgraphs:", "to_jimage != (0, 0, 0): # get index in original", "dict {(from_index, to_index): alt}, where alt is a dictionary including", ":param image_labels (bool): if True, label edges with their periodic", "an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights: if", "def get_disconnected_fragments(self): \"\"\" Determine if the MoleculeGraph is connected. If", "jimage=image)[0] ) dist = min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist,", "old_structure = self.structure.copy() # sort Structure self.structure._sites = sorted(self.structure._sites, key=key,", "ensure that edge exists before attempting to remove it existing_edge", "return connected_sites def get_coordination_of_site(self, n): \"\"\" Returns the number of", "MoleculeGraph is still connected.\" ) # alter any bonds before", "if nx.is_connected(subgraph): mykey = mycomp + str(len(subgraph.edges())) if mykey not", "{}.\".format(from_index, to_index) ) return # generic container for additional edge", "props is a dictionary of properties, including weight. If None,", "of nodes != number of sites in the Structure. This", "igraph if if is available and networkx if it is", "the index of the corresponding site in the original structure,", "d: del d[\"id\"] if \"key\" in d: del d[\"key\"] #", "\"\"\" f1_nodes = frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if len(f1_nodes) !=", "expected to be, relative to original # lattice (keeping original", "or str (when not using graph_dict). :param index: Index of", "will warn if trying to add duplicate edges (duplicate edges", "dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0: # this", "are expected to be v_expec = new_structure[u].coords + v_rel #", "MoleculeGraphs (ignoring edge weights), and is defined by 1 -", "a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs", ":return: \"\"\" # Developer note: a different approach was also", "bond in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError(", "StructureGraphs. Returns dict with keys 'self', 'other', 'both' with edges", ":param from_index: index of site connecting from :param to_index: index", "for i in sizes.keys(): if i != keep: to_remove.add(i) self.remove_nodes(list(to_remove))", "self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if new_edge_properties is not None: for prop", "self.graph such that all edges (u, v) matched by edges", "connected_site_images = set() out_edges = [(u, v, d, \"out\") for", "site_properties :return: \"\"\" # this is not necessary for the", "relative Cartesian co-ordinates of where # atoms defined by edge", "be altered;\\ no edge exists between those sites.\".format( from_index, to_index", "u new_v = v_present new_d = d.copy() # node now", "Team. # Distributed under the terms of the MIT License.", "v, u to_jimage = np.multiply(-1, to_jimage) to_jimage = tuple(map(int, np.add(to_jimage,", "of the intersection / size of the union) of the", "def __len__(self): \"\"\" :return: length of Structure / number of", "str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list)", "generating the graph using critic2 from # charge density. #", "raise RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\" Gives each", "matched by edges (v, u) undirected = self.graph.to_undirected() directed =", "for new_graph in new_graphs: new_g = nx.union(new_g, new_graph) edges_to_remove =", "subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c)", "if True (default False), distance will be checked to ensure", "types[label].append(d[\"weight\"]) return dict(types) @property def weight_statistics(self): \"\"\" Extract a statistical", ":param n: index of Site in Molecule :param jimage: lattice", "= tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes()", "in func_groups.json. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A", "not defined. :param n: index of Site in Structure :param", "mapping[v], weight=weight, edge_properties=edge_props, ) else: if strategy_params is None: strategy_params", "!= len(f2_edges): return False f1_comp_dict = {} f2_comp_dict = {}", "have the same bond lengths to be defined as duplicates,", "a float. :param new_edge_properties: alter_edge does not require that edge_properties", "By default, this parameter is None, and all rings will", "off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group", "v, k)) for u, v, k in green_edges: g.edges[u, v,", "exists before attempting to remove it existing_edge = self.graph.get_edge_data(from_index, to_index)", "import logging import os.path import subprocess import warnings from collections", "!= (0, 0, 0) relative_jimage = np.subtract(to_jimage, jimage) dist =", "as nx import networkx.algorithms.isomorphism as iso import numpy as np", "if True, label nodes with species and site index :param", "lie on periodic boundaries. In principle, any operations on the", "If None, default parameters will be used. :return: \"\"\" def", "of site indices. If including is not None, then find_rings", "in the MoleculeGraph. :return: \"\"\" species = {} coords =", "are ordered differently. :param other: StructureGraph :param strict: if False,", "= nx.get_node_attributes(remapped, \"coords\") edges = {} for from_index, to_index, key", "# convert back to molecule graphs unique_mol_graph_dict = {} for", "Compares two StructureGraphs. Returns dict with keys 'self', 'other', 'both'", "@property def edge_weight_unit(self): \"\"\" :return: Units of the edge weight", "already in place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping", "v, d.copy() new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v, k))", "\\ MoleculeGraph is still connected.\" ) # alter any bonds", "i, e in enumerate(cycle): edges.append((cycle[i - 1], e)) cycles_edges.append(edges) return", "indices used for these edges should reflect the MoleculeGraph AFTER", "names with A, B, C, etc. :return: a list of", "str(self.structure[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) } edges_other", "\"from_index\" key, and can also have a \"weight\" and a", "!= f2_comp_dict: return False if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2", "# now search in new structure for these atoms #", "diff[\"self\"]: # edge has been deleted red_edges.append((u, v, k)) elif", "from extension (any graphviz filetype supported, such as pdf or", "by edges (v, u) undirected = self.graph.to_undirected() directed = undirected.to_directed()", "bonds in molecules should not cross # (artificial) periodic boundaries", "\"{:4} {:4} {:12} {:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\", (0, 0, 0))),", "frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): \"\"\" This is a class for", "raise RuntimeError( \"Currently functional group replacement\" \"cannot occur at an", "sizes.keys(): if i != keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp,", "np.array_equal(from_jimage, (0, 0, 0)): shift = from_jimage from_jimage = np.subtract(from_jimage,", ":param coords_are_cartesian: Whether coordinates are cartesian. Defaults to False. :param", "None. If weight is to be changed, it should be", "nx.get_node_attributes(remapped, \"specie\") coords = nx.get_node_attributes(remapped, \"coords\") edges = {} for", "string 'Fe-O') and values which are a list of weights", "scaling matrices yet.\") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix)", ":return: \"\"\" self.molecule.insert( i, species, coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping", "connected_sites.sort(key=lambda x: x.dist) return connected_sites def get_coordination_of_site(self, n): \"\"\" Returns", "return s def __str__(self): s = \"Structure Graph\" s +=", "return { \"all_weights\": all_weights, \"min\": stats.minmax[0], \"max\": stats.minmax[1], \"mean\": stats.mean,", "None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self,", "two sites existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data and warn_duplicates:", "+ header_line + \"\\n\" edges = list(g.edges(data=True)) # sort edges", "\".dot\") def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Molecule` except with", "get Molecule objects for each subgraph molecules = [] for", "'other' MoleculeGraph: there is no guarantee the node indices will", "to site {} in {}.\".format(from_index, to_index, to_jimage) ) return #", "connecting to :param from_jimage (tuple of ints): lattice vector of", "+ \".dot\") @property def types_and_weights_of_connections(self): \"\"\" Extract a dictionary summarizing", "but a larger graph can be easier to visualize and", "u, v, d in other_sorted.graph.edges(keys=False, data=True)} else: edges = {", "restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information.", "coordinates. :return: \"\"\" species = {} coords = {} properties", "self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None,", "else: if strategy_params is None: strategy_params = {} strat =", "of graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index,", "which are a list of weights for those connections (e.g.", "( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] =", "= alterations[(u, v)] if len(alterations[(u, v)]) != 0 else None", "\"\") if d.get(\"weight\"): d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"], units) # update", "copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group( self, index, func_grp, strategy, bond_order=1,", "else: edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d", "mg.graph.nodes if not (from_index in nodes and to_index in nodes):", "- (size of the intersection / size of the union)", "graph) to be removed. :return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping =", "data=True)} edges_other = { (u, v, d.get(\"to_jimage\", (0, 0, 0)))", "just makes it neater if to_index < from_index: to_index, from_index", "\"dimensionless.\" ) # construct graph with one node per site", "storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. For", "if len(neighbors) == 1: self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict,", "= tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None):", "0, 0]) # get contrasting font color # magic numbers", "defined by 1 - (size of the intersection / size", "\"\"\" s = Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"]) def __mul__(self, scaling_matrix):", "nx.connected_components(supercell_sg.graph)] # discount subgraphs that lie across *supercell* boundaries #", "value, # using its frac_coords as a convenient key try:", "to replace a functional group in self.molecule with a functional", "use k-d tree to match given position to an #", "self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\": json_graph.adjacency_data(new_g), } sg =", "# computationally expensive than just keeping track of the #", "0) ) else: for u, v, data in edges: s", "\"from to to_image \" header_line = \"---- ---- ------------\" edge_weight_name", "0 mapping = {} for i, n in enumerate(nodes): mapping[n]", "map_indices(func_grp) # Remove dummy atom \"X\" func_grp.remove_species(\"X\") if graph_dict is", "in other.molecule} except ValueError: return False other_sorted = other.__copy__() other_sorted.sort(key=lambda", "to nodes on opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find", "be considered equal # this could probably be a lot", "with node indices # representing both site index and periodic", "including: for cycle in unique_cycles: if i in cycle and", "/ number of nodes in graph \"\"\" return len(self.structure) def", "= \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph:", "mapping = {idx: self.structure.index(site) for idx, site in enumerate(old_structure)} self.graph", ":param structure: a Structure object :param graph_data: dict containing graph", "has # significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac =", "shift) # automatic detection of to_jimage if user doesn't specify", ":param molecule: Molecule object :param strategy: an instance of a", "to avoid ambiguity.\") if existing_edges: for i, properties in existing_edges.items():", "frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all", "for u, v, d in subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph))", "color edges red that do not exist in diff and", "a fairly robust approach, but will treat e.g. enantiomers as", "molecules will need to have the same bond lengths to", "for u, v, d, dir in out_edges + in_edges: to_jimage", "new_v, new_to_jimage)) logger.debug(\"Removing {} edges, adding {} new edges.\".format(len(edges_to_remove), len(edges_to_add)))", "it is not, separate the MoleculeGraph into different MoleculeGraphs, where", "as origin if not defined to_image = d[\"to_jimage\"] # set", "the graph information, but also changes the underlying Molecules. If", "or png) :param diff (StructureGraph): an additional graph to compare", "g.edges(keys=True, data=True): if (u, v, d[\"to_jimage\"]) in diff[\"self\"]: # edge", "if hide_unconnected_nodes: g = g.subgraph([n for n in g.degree() if", "done on the original graph, but a larger graph can", "equal if they have equal Molecules, and have the same", "periodic boundaries if not np.array_equal(neighbor[\"image\"], [0, 0, 0]): continue if", "color_scheme (str): \"VESTA\" or \"JMOL\" :param keep_dot (bool): keep GraphViz", "to be considered equal # this could probably be a", "\"\"\" Builds off of Molecule.substitute to replace an atom in", "weight is to be changed, it should be a float.", "if it is not. \"\"\" f1_nodes = frag1.nodes(data=True) f2_nodes =", "**edge_properties) def insert_node( self, i, species, coords, validate_proximity=False, site_properties=None, edges=None,", "import combinations from operator import itemgetter import networkx as nx", "(self.molecule == other_sorted.molecule) def isomorphic_to(self, other): \"\"\" Checks if the", "treat subgraphs as isomorphic if edges have the same weights.", "\"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] if 0", "two Sites. \"\"\" def __init__(self, molecule, graph_data=None): \"\"\" If constructing", "relevant template in func_groups.json. :param strategy: Class from pymatgen.analysis.local_env. :param", "# of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)]", "A MoleculeGraph object. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order:", "\"#ff0000\"}) basename, extension = os.path.splitext(filename) extension = extension[1:] write_dot(g, basename", "edge[2] to_image = edge[3] except TypeError: raise ValueError(\"Edges must be", "changed following the split. :param allow_reverse: If allow_reverse is True,", "returns degree of node corresponding to site n. :param n:", "s def __repr__(self): s = \"Molecule Graph\" s += \"\\nMolecule:", "site v to site u: this is # harmless, so", "self.molecule != other.molecule and strict: return ValueError(\"Meaningless to compare MoleculeGraphs", ":param algo: any graphviz algo, \"neato\" (for simple graphs) or", "boundaries if not np.array_equal(neighbor[\"image\"], [0, 0, 0]): continue if n", "not modify the original MoleculeGraph. It creates a copy, modifies", "ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight, dist=dist) else: site =", "weights. Can be \" \"empty string if arbitrary or \"", "graph mapping = {idx: self.molecule.index(site) for idx, site in enumerate(old_molecule)}", "in molecules should not cross # (artificial) periodic boundaries if", "self._edges_to_string(self.graph) return s def __len__(self): \"\"\" :return: length of Molecule", "to graph to be able to test for isomorphism for", "check we're not trying to add a duplicate edge #", "using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object", "form site v to site u: this is # harmless,", "if dir == \"in\": u, v = v, u to_jimage", "by default, this is None. If weight is to be", "(0, 0, 0)] new_periodic_images = [] orig_lattice = self.structure.lattice #", "= None else: weight = None nodes = mg.graph.nodes if", "units associated \" \"with your edge weights. Can be \"", "one bond, one from site u to site v #", "): \"\"\" Add edge to graph. Since physically a 'bond'", "easy way to extract # molecules (and not, e.g., layers", "Copyright (c) Pymatgen Development Team. # Distributed under the terms", "in range(atoms): grp_map[i] = i + offset return grp_map if", "alter the graph information, but also changes the underlying Molecules.", "for key in unique_frag_dict: unique_mol_graph_list = [] for fragment in", "\"\"\" Constructor for StructureGraph, returns a StructureGraph object with an", "v} for u, v, d in new_g.edges(data=True) if d[\"to_jimage\"] ==", "allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: for i, properties", "edges.sort(key=itemgetter(0, 1)) if print_weights: for u, v, data in edges:", "easier to visualize and reason about. :param scaling_matrix: same as", "isinstance(structure, StructureGraph): # just make a copy from input graph_data", "self.graph.edges(n) if n == v]) return self.graph.degree(n) - number_of_self_loops def", "the closest site warnings.warn(\"Please specify to_jimage to be unambiguous, \"", "properties, \"properties\") def alter_edge( self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None,", "path.\") # Developer note: NetworkX also has methods for drawing", "= other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d.get(\"to_jimage\",", "edges_inside_supercell = [{u, v} for u, v, d in new_g.edges(data=True)", "between two StructureGraphs (ignoring edge weights), and is defined by", "i in cycle and cycle not in cycles_nodes: cycles_nodes.append(cycle) for", "molecule_subgraphs = [] for subgraph in all_subgraphs: intersects_boundary = any(d[\"to_jimage\"]", "graph theory terms) including the index found in the Molecule.", "using a strategy from :Class: `pymatgen.analysis.local_env`. :param structure: Structure object", "'both' with edges that are present in only one MoleculeGraph", "def sort(self, key=None, reverse=False): \"\"\" Same as Structure.sort(), also remaps", "v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords # using the", "not exist in diff and edges green that are in", "weight=weight, dist=dist) else: site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site", "n == v]) return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self,", "\"GraphViz binaries to be in the path.\") # Developer note:", "dict representing the bonds of the functional group (format: {(from_index,", "compare bonds from different Structures, with node indices replaced by", "The molecule will be obtained from the relevant template in", "Returns the number of neighbors of site n. In graph", "new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug(\"Removing {} edges,", "to store and operate on the graph itself, but contains", "to be defined as duplicates, otherwise bond lengths can differ.", "in Structure :param jimage: lattice vector of site :return: list", "v, k in red_edges: g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"}) basename, extension", "do not draw edges that go through periodic boundaries :param", "node indices are in terms of the StructureGraph this method", "json), it's important images # are hashable/immutable if \"to_jimage\" in", "exists between those sites.\".format( from_index, to_index ) ) if to_jimage", "that is substituted will not place atoms to close to", "be different and MoleculeGraphs can still be considered equal. :param", "v in self.graph.edges(n) if n == v]) return self.graph.degree(n) -", "= [] for u, v, k, d in self.graph.edges(keys=True, data=True):", "index 0 # TODO: actually figure out how to distribute", "int :param to_jimage: tuple :param new_weight: alter_edge does not require", "MoleculeGraph :return (bool): \"\"\" # sort for consistent node indices", "nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) # get contrasting", "help, especially in larger graphs. :param filename: filename to output,", "edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], weight=weight,", "in Structure kd_tree = KDTree(new_structure.cart_coords) # tolerance in Å for", "using `from_dict_of_dicts` from NetworkX to restore graph information. \"\"\" m", "self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self): \"\"\" :return: Units of the edge", "str(other.structure[v].specie)) for u, v, d in other.graph.edges(keys=False, data=True) } if", "edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self,", "# Remove dummy atom \"X\" func_grp.remove_species(\"X\") if graph_dict is not", "True break if not found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) #", "= Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"]) def __mul__(self, scaling_matrix): \"\"\" Replicates", "close to each other, or violate the dimensions of the", "in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1 else: f2_comp_dict[node[1][\"specie\"]] += 1 if", "in unique_frag_dict: unique_mol_graph_list = [] for fragment in unique_frag_dict[key]: mapping", "# local_env will always try to add two edges #", "{:4} {:12} {:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\", (0, 0, 0))), data.get(\"weight\",", "graph (no edges, only nodes defined that correspond to Sites", "work here. However, # a dedicated tool like GraphViz allows", "\"\"\" if not strategy.structures_allowed: raise ValueError( \"Chosen strategy is not", "disconnected subgraphs \"\"\" pass class MoleculeGraph(MSONable): \"\"\" This is a", ":param to_index: int :param to_jimage: tuple :param new_weight: alter_edge does", "): \"\"\" Builds off of Molecule.substitute to replace an atom", "+ offset return grp_map # Work is simplified if a", "fontcolor = \"#000000\" if 1 - (c[0] * 0.299 +", "produce a different graph compared with using a Molecule or", "differ. This is a fairly robust approach, but will treat", "in the form of a graph. A \"bond\" does not", "return len(self.structure) def sort(self, key=None, reverse=False): \"\"\" Same as Structure.sort(),", "def replace_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ):", "the new functional group. TODO: Figure out how to replace", "d[\"graphs\"]) @classmethod def _edges_to_string(cls, g): header = \"from to to_image", "if _isomorphic(frag, f): found = True break if not found:", "(format: {(from_index, to_index, from_image, to_image): props}, where props is a", "nodes, # these can appear when removing periodic edges if", "nodes if new_weight is not None: self.graph[from_index][to_index][0][\"weight\"] = new_weight if", "as an isomorphic subgraph). :param use_weights (bool): If True, only", "is to remove the index site, and connect the nearest", "self.graph.remove_edge(from_index, to_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if", "duplicate subgraphs unique_subgraphs = [] for subgraph in molecule_subgraphs: already_present", "no image is given, this method will fail. :param from_index:", "graph object into an igraph graph object. \"\"\" nodes =", "substitute. :param func_grp: Substituent molecule. There are two options: 1.", "expected to be v_expec = new_structure[u].coords + v_rel # now", "edges). g = self.graph.copy() g.graph = {\"nodesep\": 10.0, \"dpi\": 300,", "in # new supercell, and get asgolute Cartesian # co-ordinates", "can differ. This is a fairly robust approach, but will", "to_index,\" \" from_image, to_image) tuples\") if props is not None:", "strategy.structures_allowed: raise ValueError( \"Chosen strategy is not designed for use", "give misleading results for multigraphs (edges are super-imposed on each", "logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = \"<NAME>, <NAME>, <NAME>\" __version__", "with another graph if diff: diff = self.diff(diff, strict=True) green_edges", "from monty.json import MSONable from monty.os.path import which from networkx.drawing.nx_agraph", "copy=True)) new_structure = Structure.from_sites(new_sites) # merge all graphs into one", "- min(coords[:, 1]) + 100 c = max(coords[:, 2]) -", "v, d in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy=\"omit\") return {", "coords: 3x1 array representing coordinates of the new site :param", "= alterations[(u, v)][\"weight\"] del alterations[(u, v)][\"weight\"] edge_properties = alterations[(u, v)]", "strings, will not count number of occurrences of bonds :return:", "{} if weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index,", "1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present =", "A string name. The molecule will be obtained from the", "edges_to_delete = [] # add display options for edges for", "from_site if jimage arg != (0, 0, 0) relative_jimage =", "@classmethod def with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for", "fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species,", "sp in set(connected_species): count = connected_species.count(sp) labels.append((count, sp)) labels =", "by species name label = \"{}({})\".format(str(self.structure[n].specie), n) if node_labels else", "nx.weakly_connected_components(original.graph)] for subg in subgraphs: nodes = sorted(list(subg.nodes)) # Molecule", "failed to split into two disconnected subgraphs \"\"\" pass class", "in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to", "order to calculate the bond length between the attached functional", "<NAME>, <NAME>\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\" __email__ =", "to_index, edge_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if", "\"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod", "list of strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of", "drawn with networkx's in-built graph drawing methods, but note that", "to_jimage = edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else: # By default, assume", "if edges is not None: for edge in edges: try:", "simple Graph (instead of MultiDiGraph), with node indices # representing", "Structure.__mul__ :return: \"\"\" # Developer note: a different approach was", "return n1[\"specie\"] == n2[\"specie\"] def edge_match(e1, e2): if use_weights: return", "n: periodic_site, jimage, index, weight. Index is the index of", "\"Å\" or \"eV\" :return (StructureGraph): \"\"\" if edge_weight_name and (edge_weight_units", "int :param allow_reverse: If allow_reverse is True, then break_edge will", "present, but should hopefully be # easier to extend to", "(str): name of edge weights, e.g. \"bond_length\" or \"exchange_constant\" :param", "use with structures! \" \"Please choose another strategy.\" ) sg", "= copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group( self, index, func_grp, strategy,", "if i != keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy,", "__rmul__(self, other): return self.__mul__(other) @classmethod def _edges_to_string(cls, g): header =", "allow_reverse=False): \"\"\" Remove an edge from the StructureGraph. If no", "from_image, to_image) tuples\") if props is not None: if \"weight\"", "None: if \"weight\" in props.keys(): weight = props[\"weight\"] del props[\"weight\"]", "# If graph indices have different indexing u, v =", "\"dashed\" if hide_image_edges: edges_to_delete.append((u, v, k)) # don't show edge", "!= (0, 0, 0): # get index in original site", "instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph", "the MoleculeGraph :param from_index: int :param to_index: int :param allow_reverse:", "weight = None nodes = mg.graph.nodes if not (from_index in", "= nx.MultiDiGraph() for new_graph in new_graphs: new_g = nx.union(new_g, new_graph)", "to_index = edge[1] except TypeError: raise ValueError(\"Edges must be given", "networkx.drawing.nx_agraph import write_dot from networkx.readwrite import json_graph from scipy.spatial import", "to_index: int :param to_jimage: tuple :param new_weight: alter_edge does not", "into a ring structure. :param index: Index of atom to", "connects two Sites. \"\"\" def __init__(self, structure, graph_data=None): \"\"\" If", "connecting to :param weight (float): e.g. bond length :param warn_duplicates", "self.structure[v].species_string return \"-\".join(sorted((u_label, v_label))) types = defaultdict(list) for u, v,", "Name of graph \"\"\" return self.graph.graph[\"name\"] @property def edge_weight_name(self): \"\"\"", "enumerate(self.structure): centre_sp = site.species_string connected_sites = self.get_connected_sites(idx) connected_species = [connected_site.site.species_string", "edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d in", "at most one edge # between two sites existing_edge_data =", "molecule.get_centered_molecule() molecules.append(molecule) return molecules class MolGraphSplitError(Exception): \"\"\" Raised when a", "\" \"site {} to site {}.\".format(from_index, to_index) ) return #", "functional group that is substituted will not place atoms to", "= \"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ =", "from \" \"site {} to site {} in {}.\".format(from_index, to_index,", "be easier to visualize and reason about. :param scaling_matrix: same", "graph_dict). :param index: Index of atom to substitute. :param func_grp:", "graph in sync with its corresponding Structure. # Broadly, it", "- 1), (v - 1) self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props,", "will compare bonds from different Molecules, with node indices replaced", "replace specie names with A, B, C, etc. :return: a", "be None if no additional properties are to be specified.", "properties in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i", "= get_label(u, v) types[label].append(d[\"weight\"]) return dict(types) @property def weight_statistics(self): \"\"\"", "alter any bonds before partition, to avoid remapping if alterations", "= i # just give charge to whatever subgraph has", "from_index, from_jimage can be swapped with to_index, to_jimage. However, images", "of a graph. A \"bond\" does not necessarily have to", "strict=True): \"\"\" Compares two StructureGraphs. Returns dict with keys 'self',", "(3, 3, 3) # make undirected to find connected subgraphs", "an atom in self.structure with a functional group. This method", "!= (0, 0, 0): d[\"style\"] = \"dashed\" if hide_image_edges: edges_to_delete.append((u,", "strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg,", "= v_present[1] if v_present[0] <= tol else None # check", "does not modify the original MoleculeGraph. It creates a copy,", "None: new_u = u new_v = v_present new_d = d.copy()", "d in out_edges + in_edges: weight = d.get(\"weight\", None) if", "from_index, to_index ) ) def remove_nodes(self, indices): \"\"\" A wrapper", "new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in graph.edges()]) return", "if two graph objects are isomorphic, using igraph if if", "and edges that are present in both. The Jaccard distance", "is a class for annotating a Structure with bond information,", "if self.molecule != other.molecule and strict: return ValueError(\"Meaningless to compare", "to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index,", "edges should stay remain # inside the initial image to_jimage", "this class worked even if # from_jimage != (0, 0,", "be given as (from_index, to_index)\" \"tuples\") if props is not", "considered equal. :param other: MoleculeGraph :return (bool): \"\"\" # sort", "not, separate the MoleculeGraph into different MoleculeGraphs, where each resulting", "make associating a graph with a given crystallographic structure easier.", "The networkx graph object itself can also be drawn with", "in red_edges: g.edges[u, v, k].update({\"color_uv\": \"#ff0000\"}) basename, extension = os.path.splitext(filename)", "strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy:", "\"cannot occur at an atom within a ring\" \"structure.\" )", "graph. :param key: :param reverse: :return: \"\"\" old_structure = self.structure.copy()", "many benefits, but made it more difficult to # keep", "make a copy from input graph_data = structure.as_dict()[\"graphs\"] self.structure =", ") def replace_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None,", "indices # representing both site index and periodic image. Here,", "duplicates present in the crystal (a duplicate defined as an", "intelligently joining together edges that lie on periodic boundaries. In", "given, this method will fail. :param from_index: int :param to_index:", "edge_weight_unit(self): \"\"\" :return: Units of the edge weight property of", "itertools import combinations from operator import itemgetter import networkx as", "in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v],", "in unique_frags: if _isomorphic(frag, f): found = True break if", "of sites in the Structure. This # approach has many", "!= 0: raise RuntimeError(\"{} exited with return code {}.\".format(algo, rs.returncode))", "total molecule to a single submolecule. A later effort will", "keep_dot: os.remove(basename + \".dot\") def as_dict(self): \"\"\" As in :Class:", "mapping = {} for j in range(len(self.molecule) - 1): if", "for strategy. If None, default parameters will be used. :return:", "(conversion to lists happens # when serializing back from json),", "altered;\\ no edge exists between those sites.\".format( from_index, to_index )", "to_index, new_weight=None, new_edge_properties=None): \"\"\" Alters either the weight or the", "to_jimage=to_jimage, to_index=nnsite.index, ) return # sanitize types from_jimage, to_jimage =", "**edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def insert_node( self, i,", "cycle and cycle not in cycles_nodes: cycles_nodes.append(cycle) for cycle in", "nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def", "existing_edges.items(): if properties[\"to_jimage\"] == to_jimage: edge_index = i if new_weight", "measure of the dissimilarity between two MoleculeGraphs (ignoring edge weights),", "get label by species name label = \"{}({})\".format(str(self.molecule[n].specie), n) if", "(int): \"\"\" number_of_self_loops = sum([1 for n, v in self.graph.edges(n)", "in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule,", "= len(self.structure) - atoms for i in range(atoms): grp_map[i] =", "[1, 0, 0], [0, 1, 0], [0, 0, 1] dists", "between those sites.\".format( from_index, to_index ) ) if to_jimage is", "mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else: if strategy_params is None:", "underlying Molecules are ordered differently. :param other: MoleculeGraph :param strict:", "def as_dict(self): \"\"\" As in :Class: `pymatgen.core.Molecule` except with using", "= g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label += \" ({})\".format(edge_weight_units) header +=", "a class for annotating a Molecule with bond information, stored", "using the position of node u as a reference, #", "v, d in self.graph.edges(keys=False, data=True)} edges_other = { (u, v,", "list of ConnectedSite tuples, sorted by closest first \"\"\" connected_sites", "lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS try: import igraph IGRAPH_AVAILABLE =", "get contrasting font color # magic numbers account for perceived", "[algo, \"-T\", extension, basename + \".dot\"] rs = subprocess.Popen(args, stdout=f,", "= \"A\" labels = [(label[0], mapping[label[1]]) for label in labels]", "if \"to_jimage\" in edge_props.keys(): to_jimage = edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else:", "= \"solid\" if to_image != (0, 0, 0): d[\"style\"] =", "edge_props[\"weight\"] del edge_props[\"weight\"] if 0 not in list(graph.graph.nodes()): # If", "u to site v # and another form site v", "is None: edge_index = 0 else: for i, properties in", "in Molecule :param jimage: lattice vector of site :return: list", "compare bonds from different Molecules, with node indices replaced by", "dict format (not intended to be constructed manually, see as_dict", "apply Molecule ordering to graph mapping = {idx: self.molecule.index(site) for", "raise RuntimeError(\"{} exited with return code {}.\".format(algo, rs.returncode)) if not", "graph if weight_labels: units = g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"): d[\"label\"]", "= EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) # get contrasting font color", "1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { \"self\": edges -", "in cycles_nodes: cycles_nodes.append(cycle) for cycle in cycles_nodes: edges = []", "v, d in other_sorted.graph.edges(keys=False, data=True)} else: edges = { (str(self.structure[u].specie),", "= edge[0] to_index = edge[1] except TypeError: raise ValueError(\"Edges must", "np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords # using the position of", "the StructureGraph. If no image is given, this method will", "0]) # optionally highlight differences with another graph if diff:", "g.graph[\"edge_weight_name\"] edge_weight_units = g.graph[\"edge_weight_units\"] if edge_weight_units: edge_label += \" ({})\".format(edge_weight_units)", "a MoleculeGraph \"\"\" if not strategy.molecules_allowed: raise ValueError( \"Chosen strategy", "submolecule. A later effort will be to actually accurately assign", "v, d in out_edges + in_edges: weight = d.get(\"weight\", None)", "is more # computationally expensive than just keeping track of", "10.0, \"dpi\": 300, \"overlap\": \"false\"} # add display options for", "original MoleculeGraph. It creates a copy, modifies that, and returns", "a general 3x3 scaling matrix. # code adapted from Structure.__mul__", "# easier to extend to a general 3x3 scaling matrix.", "`to_dict_of_dicts` from NetworkX to store graph information. \"\"\" d =", "= sorted(self.structure._sites, key=key, reverse=reverse) # apply Structure ordering to graph", "of tuples (from_index, to_index) representing bonds to be broken to", "v_present[1] if v_present[0] <= tol else None if v_present is", "from pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS try: import", "edge_weight_name and (edge_weight_units is None): raise ValueError( \"Please specify units", "can store any kind of information that connects two Sites.", "{}\".format((to_image)) d[\"arrowhead\"] = \"normal\" if d[\"headlabel\"] else \"none\" # optionally", "site in mapping.values(): neighbors = strat.get_nn_info(self.structure, site) for neighbor in", "= [supercell_sg.structure[n].coords for n in subgraph.nodes()] species = [supercell_sg.structure[n].specie for", "str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group( self,", "before attempting to remove it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse", "label = \"{}({})\".format(str(self.structure[n].specie), n) if node_labels else \"\" # use", "0, 0) # set edge style d[\"style\"] = \"solid\" if", "max(coords[:, 2]) - min(coords[:, 2]) + 100 structure = molecule.get_boxed_structure(a,", "hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ): \"\"\"", "full 3x3 scaling matrices raise NotImplementedError(\"Not tested with 3x3 scaling", "tool like GraphViz allows for much easier # control over", "number_of_self_loops = sum([1 for n, v in self.graph.edges(n) if n", "edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, )", "None) for u, v, d in self.graph.edges(data=True)] stats = describe(all_weights,", "co-ordinates of where atoms defined # by edge are expected", "by species name label = \"{}({})\".format(str(self.molecule[n].specie), n) if node_labels else", "Same as Molecule.sort(), also remaps nodes in graph. :param key:", "to restore graph information. \"\"\" s = Structure.from_dict(d[\"structure\"]) return cls(s,", "template in func_groups.json. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order:", "= props[\"weight\"] del props[\"weight\"] else: weight = None if len(props.items())", "self.graph to incorporate the new functional group. NOTE: using a", "= new_edge_properties[prop] def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): \"\"\" Remove", "graphviz algo, \"neato\" (for simple graphs) or \"fdp\" (for more", "when a molecule graph is failed to split into two", "molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts,", "instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights: if True,", "strat) for (u, v) in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0]", "species and site index :param weight_labels (bool): if True, label", "Graph structure, and an associated structure object. This class uses", "to_index: index of site connecting to :param weight (float): e.g.", "apply Structure ordering to graph mapping = {idx: self.structure.index(site) for", "== to_jimage: edge_index = i self.graph.remove_edge(to_index, from_index, edge_index) else: raise", "from :param to_index: index of site connecting to :param weight", "As in :Class: `pymatgen.core.Structure` except with using `to_dict_of_dicts` from NetworkX", "graph) to be removed. :return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping =", "None else: weight = None nodes = sg.graph.nodes if not", "are invalid.\") def set_node_attributes(self): \"\"\" Gives each node a \"specie\"", "(new_u, new_v, new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u,", "else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\"", "be to actually accurately assign charge. NOTE: This function does", "g.nodes(): # get label by species name label = \"{}({})\".format(str(self.molecule[n].specie),", "from_index, to_index to_jimage, from_jimage = from_jimage, to_jimage # constrain all", "else: print_weights = False s = header + \"\\n\" +", "structures in the MoleculeGraph. :param including: list of site indices.", "edge_weight_units (str): name of edge weight units e.g. \"Å\" or", "# don't show edge directions d[\"arrowhead\"] = \"none\" # only", "construct graph with one node per site # graph attributes", "tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod", "from_jimage)), tuple(map(int, to_jimage)), ) from_index, to_index = int(from_index), int(to_index) #", "in :Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from NetworkX", "Species strings, will not count number of occurrences of bonds", ":return (bool): \"\"\" # sort for consistent node indices #", "Sites in Structure). :param structure (Structure): :param name (str): name", "create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self, bonds,", "map_indices(grp): grp_map = {} # Get indices now occupied by", "in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( \"Cannot", "v, d.get(\"to_jimage\", (0, 0, 0))) for u, v, d in", "from_index: int :param to_index: int :param to_jimage: tuple :param new_weight:", "be removed. :return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for", "of an image node, and seeing if that node exists", "s def __repr__(self): s = \"Structure Graph\" s += \"\\nStructure:", "different and MoleculeGraphs can still be considered equal. :param other:", "molecule. There are two options: 1. Providing an actual Molecule", "with using `to_dict_of_dicts` from NetworkX to store graph information. \"\"\"", "in d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"]", "atom to substitute. :param func_grp: Substituent molecule. There are three", "bonds to be broken to split the MoleculeGraph. :param alterations:", "mapping[n] = i # just give charge to whatever subgraph", "extension = os.path.splitext(filename) extension = extension[1:] write_dot(g, basename + \".dot\")", "is returned with key 'dist'. Important note: all node indices", "from the relevant template in func_groups.json. :param strategy: Class from", "else: # want to find new_v such that we have", "(self.structure == other_sorted.structure) def diff(self, other, strict=True): \"\"\" Compares two", "to_jimage = (0, 0, 0) if \"weight\" in edge_props.keys(): weight", "to_index = neighbor[\"site_index\"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates", "= np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index, )", "weight=weight, dist=dist) connected_sites.add(connected_site) # return list sorted by closest sites", "site, and connect the nearest neighbor to the C atom", "self.graph.remove_edge(to_index, from_index) else: raise ValueError( \"Edge cannot be broken between", "Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except", "all atoms in the molecule # in order to be", "edges.\".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked edges for edges_to_remove in edges_to_remove:", "\\n{}\".format(self.molecule.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s", "100 structure = molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False) else: structure", "color = \"#{:02x}{:02x}{:02x}\".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label,", "= MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in edges.items():", "Please check your\" \" indices.\" ) mg.add_edge(from_index, to_index, weight=weight, edge_properties=props)", "# add/delete marked edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for", "self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node] = self.molecule[node].properties", "properties, including weight. If None, then the algorithm will attempt", "- len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { \"self\": edges - edges_other,", "edges_other, \"other\": edges_other - edges, \"both\": edges.intersection(edges_other), \"dist\": jaccard_dist, }", "connected_site in connected_sites] labels = [] for sp in set(connected_species):", "These edges must include the index of the new site", "crystals molecule_subgraphs = [] for subgraph in all_subgraphs: intersects_boundary =", "v) in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight = None", "for u, v, d in out_edges + in_edges: weight =", "\"\"\" if not strategy.molecules_allowed: raise ValueError( \"Chosen strategy is not", "include_index=True ) for nnsite in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords)", "all connected induced subgraphs) :return: \"\"\" self.set_node_attributes() graph = self.graph.to_undirected()", "diff(self, other, strict=True): \"\"\" Compares two MoleculeGraphs. Returns dict with", "be given as (from_index, to_index,\" \" from_image, to_image) tuples\") if", "bonds from different Structures, with node indices replaced by Species", "for site in other.molecule} except ValueError: return False other_sorted =", "alter_edge( self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ): \"\"\" Alters", "mapping[j] = j + 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes()", "def __len__(self): \"\"\" :return: length of Molecule / number of", "key. :return: \"\"\" self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties,", "separate molecules). This function does not only alter the graph", "contains a lot of helper methods to make associating a", "= sg.graph.nodes if not (from_index in nodes and to_index in", "= v_present[1] if v_present[0] <= tol else None if v_present", "MolGraphSplitError(Exception): \"\"\" Raised when a molecule graph is failed to", "accurately assign charge. NOTE: This function does not modify the", "\"\"\" if isinstance(structure, StructureGraph): # just make a copy from", "terms of the MoleculeGraph this method is called from, not", "= edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else: if", "will be the same if the underlying Structures are ordered", "- 1], e)) cycles_edges.append(edges) return cycles_edges def get_connected_sites(self, n): \"\"\"", "def __repr__(self): s = \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__())", "graph. A \"bond\" does not necessarily have to be a", "k].update({\"color_uv\": \"#ff0000\"}) basename, extension = os.path.splitext(filename) extension = extension[1:] write_dot(g,", "keep GraphViz .dot file for later visualization :param algo: any", "{} for prop_set in raw_props.values(): for prop in prop_set.keys(): if", "= tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u, v, k)) if", "in enumerate(cycle): edges.append((cycle[i - 1], e)) cycles_edges.append(edges) return cycles_edges def", "= copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise", "Site properties for Molecule :param edges: List of dicts representing", "and (edge_weight_units is None): raise ValueError( \"Please specify units associated", "from_index). :return: list of MoleculeGraphs \"\"\" self.set_node_attributes() original = copy.deepcopy(self)", "= v_expec_image - v_expec_image % 1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image)", "bonds to separate two molecule fragments, then this function will", "used for Molecule instantiation for k, v in properties.items(): if", "crystals. Will only return unique molecules, not any duplicates present", "try: import igraph IGRAPH_AVAILABLE = True except ImportError: IGRAPH_AVAILABLE =", "from collections import defaultdict, namedtuple from itertools import combinations from", "u_label = self.structure[u].species_string v_label = self.structure[v].species_string return \"-\".join(sorted((u_label, v_label))) types", "are tuples (conversion to lists happens # when serializing back", "graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data =", "also correctly displays # mutli-graphs (matplotlib can superimpose multiple edges).", "if existing_edge: self.graph.remove_edge(from_index, to_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index,", "if strict: # sort for consistent node indices # PeriodicSite", "(v, u) undirected = self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes =", "is None: # assume we want the closest site warnings.warn(\"Please", "not in edges_inside_supercell: # normalize direction if new_v < new_u:", "get_label(u, v) types[label].append(d[\"weight\"]) return dict(types) @property def weight_statistics(self): \"\"\" Extract", "v, k in green_edges: g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"}) for u,", "a MoleculeGraph will generally produce a different graph compared with", "= i + offset return grp_map # Work is simplified", "g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"] def _igraph_from_nxgraph(graph): \"\"\" Helper function that converts", "Alters either the weight or the edge_properties of an edge", "d: del d[\"key\"] # ensure images are tuples (conversion to", "lot smaller tol = 0.05 for u, v, k, d", "s = PeriodicSite( site.species, site.coords + v, new_lattice, properties=site.properties, coords_are_cartesian=True,", "edges that lie on periodic boundaries. In principle, any operations", "the graph edges of what lattice image the edge belongs", "two StructureGraphs (ignoring edge weights), and is defined by 1", "site i, and all indices used for these edges should", "\" {}\".format(edge_label) header_line += \" {}\".format(\"-\" * max([18, len(edge_label)])) else:", "if edge[2] != 0: duplicates.append(edge) for duplicate in duplicates: mg.graph.remove_edge(duplicate[0],", "else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def insert_node( self, i, species,", "!= (0, 0, 0), but making this # assumption simplifies", "return grp_map if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try:", "not strategy.structures_allowed: raise ValueError( \"Chosen strategy is not designed for", "in graph \"\"\" return len(self.structure) def sort(self, key=None, reverse=False): \"\"\"", "if not strategy.molecules_allowed: raise ValueError( \"Chosen strategy is not designed", "in the # supercell. If it does, the edge is", "both. The Jaccard distance is a simple measure of the", "coords, validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper around Molecule.insert(),", "# normalize directions of edges edges_to_remove = [] edges_to_add =", "is None, and all rings will be returned. :return: dict", "else \"\" # use standard color scheme for nodes c", "site :return: list of ConnectedSite tuples, sorted by closest first", "set() out_edges = list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n, data=True)) for", "is a dictionary including weight and/or edge properties to be", "s += \"{:4} {:4} {:12} {:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\", (0,", "the StructureGraph, but this isn't # possible when generating the", "= {(u, v, d.get(\"to_jimage\", (0, 0, 0))) for u, v,", "[(label[0], mapping[label[1]]) for label in labels] labels = [\"{}({})\".format(label[1], label[0])", "\"solid\" if to_image != (0, 0, 0): d[\"style\"] = \"dashed\"", "len(props.items()) == 0: props = None else: weight = None", "considered equal. :param other: StructureGraph :return (bool): \"\"\" # sort", "3) # make undirected to find connected subgraphs supercell_sg.graph =", "code will do is to remove the index site, and", "\"properties\" key. :return: \"\"\" self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity,", "swapped with to_index, to_jimage. However, images will always always be", "of site :return: list of ConnectedSite tuples, sorted by closest", "which to insert the new site :param species: Species for", "(0, 0, 0) if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"]", "operator import itemgetter import networkx as nx import networkx.algorithms.isomorphism as", "colors to color edges :param node_labels (bool): if True, label", "the new site :param validate_proximity: For Molecule.insert(); if True (default", "= self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist * 0.01, include_index=True ) for", "old edge that went through # periodic boundary if v_present", "bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. For periodic", "func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self, including=None): \"\"\"", "unique_subgraphs.append(subgraph) # get Molecule objects for each subgraph molecules =", "guarantee the node indices will be the same if the", "= copy.deepcopy(self) for bond in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if", "graph information. \"\"\" s = Structure.from_dict(d[\"structure\"]) return cls(s, d[\"graphs\"]) def", "distribute charge if 0 in nodes: charge = self.molecule.charge else:", "with supercell d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\":", "of what lattice image the edge belongs to. :param structure:", "properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph,", "self.structure[u].species_string v_label = self.structure[v].species_string return \"-\".join(sorted((u_label, v_label))) types = defaultdict(list)", "are expected to be, relative to original # lattice (keeping", "= [supercell_sg.structure[n].specie for n in subgraph.nodes()] molecule = Molecule(species, coords)", "name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor classes only (generally) work with", "matrices yet.\") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat", "including is None: cycles_nodes = unique_cycles else: for i in", "crowded graphs) usually give good outputs :return: \"\"\" if not", "cannot be added if nodes are not\" \" present in", "v, d in other_sorted.graph.edges(keys=False, data=True) } else: edges = {", "(StructureGraph): an additional graph to compare with, will color edges", "return \"-\".join(sorted((u_label, v_label))) types = defaultdict(list) for u, v, d", ":return (MoleculeGraph): \"\"\" if edge_weight_name and (edge_weight_units is None): raise", "a = max(coords[:, 0]) - min(coords[:, 0]) + 100 b", "ii): mycomp = [] for idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp", "summarizing the types and weights of edges in the graph.", "def map_indices(grp): grp_map = {} # Get indices now occupied", "Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s", "directed = undirected.to_directed() cycles_nodes = [] cycles_edges = [] #", "have the same weights. Typically, this means molecules will need", "a Molecule or str (when not using graph_dict). :param index:", "\" \"Provide explicit coordinate instead\") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping =", "normalize direction if new_v < new_u: new_u, new_v = new_v,", "if they have equal Molecules, and have the same edges", "to Sites in Molecule). :param molecule (Molecule): :param name (str):", "{(u, v, d.get(\"to_jimage\", (0, 0, 0))) for u, v, d", "n_u = u % len(self.structure) n_v = v % len(self.structure)", "n. In graph terms, simply returns degree of node corresponding", "for label in labels] motif = \"{}-{}\".format(centre_sp, \",\".join(labels)) motifs.add(motif) return", "in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None),", "properties[\"to_jimage\"] == to_jimage: edge_index = i self.graph.remove_edge(to_index, from_index, edge_index) else:", "networkx's in-built graph drawing methods, but note that this might", "on the expanded graph could also be done on the", "\"all_weights\": all_weights, \"min\": stats.minmax[0], \"max\": stats.minmax[1], \"mean\": stats.mean, \"variance\": stats.variance,", "tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete", "np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage, shift) # automatic detection of", "0]): continue if n > neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"] to_index", "edges_inside_supercell: # normalize direction if new_v < new_u: new_u, new_v", "connected. If it is not, separate the MoleculeGraph into different", "of Structure / number of nodes in graph \"\"\" return", "graph using GraphViz. The networkx graph object itself can also", "species name label = \"{}({})\".format(str(self.structure[n].specie), n) if node_labels else \"\"", "# full periodic boundary conditions # so that nodes on", "None: self.graph[from_index][to_index][0][\"weight\"] = new_weight if new_edge_properties is not None: for", "== 0: jaccard_dist = 0 # by definition else: jaccard_dist", "the graph. :return: A dict with an 'all_weights' list, 'minimum',", "Pymatgen Development Team. # Distributed under the terms of the", "sites represented by a Graph structure, and an associated structure", "the nearest neighbor to the C atom in CH3. The", "(to_index, from_index). :return: list of MoleculeGraphs \"\"\" self.set_node_attributes() original =", "= self.molecule.copy() # sort Molecule self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse)", "by isomorphic to ensure comparison of node identities. \"\"\" return", "molecule will be obtained from the relevant template in func_groups.json.", "also have a \"weight\" and a \"properties\" key. :return: \"\"\"", "the MoleculeGraph. :param from_index: int :param to_index: int :param new_weight:", "!= 0 else None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u,", "existing_edge_data and warn_duplicates: warnings.warn( \"Trying to add an edge that", "100 b = max(coords[:, 1]) - min(coords[:, 1]) + 100", "edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else: # By default, assume that all", "present in the crystal (a duplicate defined as an isomorphic", "raise RuntimeError(\"Some edges are invalid.\") def set_node_attributes(self): \"\"\" Replicates molecule", "edge_properties=props) mg.set_node_attributes() return mg @staticmethod def with_local_env_strategy(molecule, strategy): \"\"\" Constructor", "class uses the NetworkX package to store and operate on", "sorted(self.structure._sites, key=key, reverse=reverse) # apply Structure ordering to graph mapping", "any graphviz algo, \"neato\" (for simple graphs) or \"fdp\" (for", "# this is not necessary for the class to work,", "return ValueError(\"Meaningless to compare StructureGraphs if \" \"corresponding Structures are", "edge_properties=edge_props, ) def replace_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None,", "supercell_sg = self * (3, 3, 3) # make undirected", "\"\"\" Constructor for MoleculeGraph, using pre-existing or pre-defined edges with", "v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments()", ":param func_grp: Substituent molecule. There are two options: 1. Providing", "data.get(\"weight\", 0) ) else: for u, v, data in edges:", "weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge to graph. Since", ":param edge_weight_units (str): name of edge weight units e.g. \"Å\"", ":return: \"\"\" self.set_node_attributes() graph = self.graph.to_undirected() # find all possible", "n in subgraph.nodes()] species = [supercell_sg.structure[n].specie for n in subgraph.nodes()]", "or \" \"dimensionless.\" ) # construct graph with one node", "of the functional group (format: {(u, v): props}, where props", "# there should only ever be at most one edge", "measure of the dissimilarity between two StructureGraphs (ignoring edge weights),", "for g in unique_subgraphs ] if not any(already_present): unique_subgraphs.append(subgraph) #", "[] for idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp)) subgraph", "= np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0,", "unnecessary checking if to_jimage != (0, 0, 0): # get", "else: charge = 0 # relabel nodes in graph to", "\"\" # use standard color scheme for nodes c =", "of Site in Structure :param jimage: lattice vector of site", "json duplicates # information for u, v, k, d in", "edges_other) and (self.structure == other_sorted.structure) def diff(self, other, strict=True): \"\"\"", "a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights: if True, use weights", "two disconnected subgraphs \"\"\" pass class MoleculeGraph(MSONable): \"\"\" This is", "MoleculeGraph ('self' and 'other'), and edges that are present in", "the MoleculeGraph. :param alterations: a dict {(from_index, to_index): alt}, where", "including weight. If None, then the algorithm will attempt to", "@property def weight_statistics(self): \"\"\" Extract a statistical summary of edge", "new_mol = Molecule(species, coords, charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) #", "raise ValueError( \"Chosen strategy is not designed for use with", "to the C atom in CH3. The X-C bond indicates", "graphs using matplotlib, these also work here. However, # a", "!= (3, 3): scale_matrix = np.array(scale_matrix * np.eye(3), np.int16) else:", "\"_supercell_sg\", None) is None: self._supercell_sg = supercell_sg = self *", "strategy_params=None, ): \"\"\" Builds off of Structure.substitute to replace an", "else None # check if image sites now present in", "mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure} other_sorted =", "connection information: relationships between sites represented by a Graph structure,", "such, by default, this is None. If any edge properties", "self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge", "into one big graph new_g = nx.MultiDiGraph() for new_graph in", "for idx, site in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True)", ":param graph_data: dict containing graph information in dict format (not", "a Molecule with bond information, stored in the form of", "species and coordinates. :return: \"\"\" species = {} coords =", "= v % len(self.structure) # get fractional co-ordinates of where", "new site :param coords: 3x1 array representing coordinates of the", "in graph.edges()]) return new_igraph def _isomorphic(frag1, frag2): \"\"\" Internal function", "property of graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index,", "two MoleculeGraphs are isomorphic to one another. In order to", "called from, not the 'other' MoleculeGraph: there is no guarantee", "e.g. bond length :param warn_duplicates (bool): if True, will warn", "(a duplicate defined as an isomorphic subgraph). :param use_weights (bool):", "as iso import numpy as np from monty.json import MSONable", "to be in the path.\") # Developer note: NetworkX also", ":param to_jimage: tuple :param new_weight: alter_edge does not require that", "if print_weights: for u, v, data in edges: s +=", "\"\"\" Raised when a molecule graph is failed to split", "nnsite in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int)", "types and weights of edges in the graph. :return: A", "u, v, d in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy=\"omit\") return", "1 because the dummy atom X should not count atoms", "for u, v, k, d in self.graph.edges(keys=True, data=True): if \"id\"", "the weight or the edge_properties of an edge in the", "ConnectedSite = namedtuple(\"ConnectedSite\", \"site, jimage, index, weight, dist\") def _compare(g1,", "0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return list sorted by", "numpy as np from monty.json import MSONable from monty.os.path import", "u_cart) # now retrieve position of node v in #", "{} for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph,", "\"\"\" return self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self): \"\"\" :return: Units of", "a class for annotating a Structure with bond information, stored", "a \"coords\" attribute, updated with the current species and coordinates.", "for the expected position # of an image node, and", "f): found = True break if not found: unique_frags.append(frag) unique_frag_dict[key]", "e.g. \"bond_length\" or \"exchange_constant\" :param edge_weight_units (str): name of edge", "index of site connecting from :param to_index: index of site", "like GraphViz allows for much easier # control over graph", "data=True)} edges_other = {(u, v) for u, v, d in", "atom at index is terminal if len(neighbors) == 1: self.substitute_group(", "copy.deepcopy(self) for bond in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph):", "= (u - 1), (v - 1) self.add_edge( mapping[u], mapping[v],", "= [d.get(\"weight\", None) for u, v, d in self.graph.edges(data=True)] stats", "\"{:.2f} {}\".format(d[\"weight\"], units) # update edge with our new style", "\"\"\" :return: Units of the edge weight property of graph", "two MoleculeGraphs (ignoring edge weights), and is defined by 1", "scaling matrices raise NotImplementedError(\"Not tested with 3x3 scaling matrices yet.\")", "if v == n: site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u])", "repeatedly to create disjoint graphs (two or more separate molecules).", "here. However, # a dedicated tool like GraphViz allows for", "specify # will try and detect all equivalent images and", "# set edge style d[\"style\"] = \"solid\" if to_image !=", "for neighbor in neighbors: self.add_edge( from_index=site, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"],", "in range(1, len(self.molecule)): for combination in combinations(graph.nodes, ii): mycomp =", "color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else", "remove it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if", "will be an empty list. \"\"\" # Copies self.graph such", "all bonds in molecules should not cross # (artificial) periodic", "name (str): name of graph, e.g. \"bonds\" :param edge_weight_name (str):", "include sufficient bonds to separate two molecule fragments, then this", "# node now inside supercell new_d[\"to_jimage\"] = (0, 0, 0)", "self.graph.get_edge_data(to_index, from_index) if existing_reverse: for i, properties in existing_reverse.items(): if", "scaling matrix. # code adapted from Structure.__mul__ scale_matrix = np.array(scaling_matrix,", "to be able to test for isomorphism for subgraph in", "supercell d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(),", "key in frag_dict: unique_frags = [] for frag in frag_dict[key]:", "f1_nodes: if node[1][\"specie\"] not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]] = 1 else:", "marked edges for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v,", "= label[1] if sp not in mapping: mapping[sp] = available_letters.pop(0)", "= {} properties = {} for node in self.graph.nodes(): species[node]", "new functional group. NOTE: Care must be taken to ensure", "Molecule.remove_sites(). :param indices: list of indices in the current Molecule", "harmless, so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"],", "`pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance of", "cycle including an index, the value will be an empty", "number_of_self_loops def draw_graph_to_file( self, filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False,", "\"\"\" Helper function that converts a networkx graph object into", "+ c[2] * 0.114) / 255 < 0.5 else \"#ffffff\"", "# return list sorted by closest sites first connected_sites =", "Sites. Edge weights can be different and MoleculeGraphs can still", "import networkx as nx import networkx.algorithms.isomorphism as iso import numpy", "manually, use the `with_empty_graph` method or `with_local_env_strategy` method (using an", "def __str__(self): s = \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__str__())", "the same if the underlying Structures are ordered differently. :param", "in remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)] =", "are isomorphic to one another. In order to prevent problems", "alphabetical order (e.g. string 'Fe-O') and values which are a", "properties = {} for node in self.graph.nodes(): species[node] = self.structure[node].specie.symbol", "Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16) if scale_matrix.shape != (3, 3):", ":param scaling_matrix: same as Structure.__mul__ :return: \"\"\" # Developer note:", "so that from_index < to_index and from_jimage becomes (0, 0,", "properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph,", "species = [supercell_sg.structure[n].specie for n in subgraph.nodes()] molecule = Molecule(species,", "nodes = graph.nodes(data=True) new_igraph = igraph.Graph() for node in nodes:", "new_v, new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v,", "theory terms) including the index found in the Molecule. If", "MoleculeGraph into different MoleculeGraphs, where each resulting MoleculeGraph is a", "for u, v, k in green_edges: g.edges[u, v, k].update({\"color_uv\": \"#00ff00\"})", "basename, extension = os.path.splitext(filename) extension = extension[1:] write_dot(g, basename +", "d in self.graph.edges(keys=False, data=True)} edges_other = { (u, v, d.get(\"to_jimage\",", "k) edges_to_add = [] # tuple of (u, v, attr_dict)", "0): d[\"style\"] = \"dashed\" if hide_image_edges: edges_to_delete.append((u, v, k)) #", "d): \"\"\" As in :Class: `pymatgen.core.Molecule` except restoring graphs using", "specie=str(supercell_sg.structure[n].specie)) # now define how we test for isomorphism def", "u, v, d in self.graph.in_edges(n, data=True)] for u, v, d,", "= j + 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if", "2]) + 100 structure = molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False)", "in the graph. :return: A dictionary with keys specifying the", "def edge_weight_name(self): \"\"\" :return: Name of the edge weight property", "return True # prune duplicate subgraphs unique_subgraphs = [] for", "in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist = min(dists) equiv_sites", "self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\",", "is connected. If it is not, separate the MoleculeGraph into", "each other). If visualization is difficult to interpret, `hide_image_edges` can", "graph drawing requires \" \"GraphViz binaries to be in the", "# graphs using matplotlib, these also work here. However, #", "original = copy.deepcopy(self) for bond in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse)", "that this might give misleading results for multigraphs (edges are", "of (u, v, attr_dict) # list of new edges inside", "atom \"X\" func_grp.remove_species(\"X\") if graph_dict is not None: for (u,", "_isomorphic(self.graph, other.graph) def diff(self, other, strict=True): \"\"\" Compares two MoleculeGraphs.", "site :return (int): \"\"\" number_of_self_loops = sum([1 for n, v", "pre-defined edges with optional edge parameters. :param molecule: Molecule object", "bond length between the attached functional group and the nearest", "\"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls, d): \"\"\"", "MoleculeGraph object. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A", "from_index == to_index, # typically in primitive single-atom lattices images", "if to_jimage is None: raise ValueError(\"Image must be supplied, to", "where # atoms defined by edge are expected to be", "\"\"\" Replicates the graph, creating a supercell, intelligently joining together", "images are tuples (conversion to lists happens # when serializing", "self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return d @classmethod def", "= self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species,", "and a \"coords\" attribute, updated with the current species and", "as (from_index, to_index)\" \"tuples\") if props is not None: if", "self.add_edge( edge[\"from_index\"], edge[\"to_index\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError:", ":param edge_colors (bool): if True, use node colors to color", "edges: dict representing the bonds of the functional group (format:", "None), ) except KeyError: raise RuntimeError(\"Some edges are invalid.\") def", "weight, dist\") def _compare(g1, g2, i1, i2): \"\"\" Helper function", "2. A string name. The molecule will be obtained from", "a named tuple of neighbors of site n: periodic_site, jimage,", "!= keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict,", "keyword arguments for strategy. If None, default parameters will be", "u, v, d in out_edges + in_edges: weight = d.get(\"weight\",", "jimage=(0, 0, 0), index=u, weight=weight, dist=dist) else: site = self.molecule[v]", "a dictionary of properties, including weight. If None, then the", "Molecule instantiation for k, v in properties.items(): if len(v) !=", "new_edge_properties[prop] def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): \"\"\" Remove an", "igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1]))", "are to be changed, it should be a dictionary of", "will not place atoms to close to each other, or", "deprecation # of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for c in", "stats.mean, \"variance\": stats.variance, } def types_of_coordination_environments(self, anonymous=False): \"\"\" Extract information", "for the new site :param coords: 3x1 array representing coordinates", "occupied by functional group # Subtracting 1 because the dummy", "(or other connection between sites) doesn't have a direction, from_index,", "by Species strings, will not count number of occurrences of", "[supercell_sg.structure[n].specie for n in subgraph.nodes()] molecule = Molecule(species, coords) #", "to_jimage is None: # assume we want the closest site", "edge attr dicts, reading to/from json duplicates # information for", "node in f2_nodes: if node[1][\"specie\"] not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] =", "and an associated structure object. This class uses the NetworkX", "sanitize types from_index, to_index = int(from_index), int(to_index) # check we're", "0) relative_jimage = np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight", "(0, 0, 0) for u, v, d in subgraph.edges(data=True)) if", "hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected", "graph with a given molecule easier. Use cases for this", "as pdf or png) :param diff (StructureGraph): an additional graph", "the MIT License. \"\"\" Module for graph representations of crystals.", "from NetworkX to restore graph information. \"\"\" s = Structure.from_dict(d[\"structure\"])", "{} for i, n in enumerate(nodes): mapping[n] = i #", "site :param species: Species for the new site :param coords:", "if properties[\"to_jimage\"] == to_jimage: edge_index = i if new_weight is", "results for multigraphs (edges are super-imposed on each other). If", "orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart) # now", "Structure.sort(), also remaps nodes in graph. :param key: :param reverse:", "using igraph if if is available and networkx if it", "for i, properties in existing_reverse.items(): if properties[\"to_jimage\"] == to_jimage: edge_index", "k].update({\"color_uv\": \"#00ff00\"}) for u, v, k in red_edges: g.edges[u, v,", "representing bonds to be broken to split the MoleculeGraph. :param", "for frag in frag_dict[key]: found = False for f in", "different.\") if strict: # sort for consistent node indices #", "\"\"\" if len(self.molecule) != len(other.molecule): return False if self.molecule.composition.alphabetical_formula !=", "g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", ) edges_to_delete", "unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is None: cycles_nodes = unique_cycles", "stats.variance, } def types_of_coordination_environments(self, anonymous=False): \"\"\" Extract information on the", "the intersection / size of the union) of the sets", "0: raise RuntimeError( \"Currently functional group replacement\" \"cannot occur at", "= int(from_index), int(to_index) # check we're not trying to add", "will color edges red that do not exist in diff", "g.degree()[n] != 0]) # optionally highlight differences with another graph", "in the current Molecule (and graph) to be removed. :return:", "MoleculeGraph. It creates a copy, modifies that, and returns two", "d.copy() # node now inside supercell new_d[\"to_jimage\"] = (0, 0,", "0, 0))) for u, v, d in other_sorted.graph.edges(keys=False, data=True) }", "get fractional co-ordinates of where atoms defined # by edge", "an actual Molecule as the input. The first atom must", "= [] orig_lattice = self.structure.lattice # use k-d tree to", "(0, 0, 0) edges_to_remove.append((u, v, k)) # make sure we", "0), index=u, weight=weight, dist=dist) else: site = self.molecule[v] dist =", "method also amends self.graph to incorporate the new functional group.", "graph_dict[(u, v)] if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del", "helper methods to make associating a graph with a given", "= dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index) for neighbor in neighbors:", "detect filetype from extension (any graphviz filetype supported, such as", "of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights: if True, use", "new_g.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: new_g.add_edge(u, v, **d)", "edge[3] except TypeError: raise ValueError(\"Edges must be given as (from_index,", "into an igraph graph object. \"\"\" nodes = graph.nodes(data=True) new_igraph", "instance of StructureGraph with supercell d = { \"@module\": self.__class__.__module__,", "to add a duplicate edge # there should only ever", "visualization :param algo: any graphviz algo, \"neato\" (for simple graphs)", "site :param validate_proximity: For Molecule.insert(); if True (default False), distance", "have different indexing u, v = (u - 1), (v", "one StructureGraph ('self' and 'other'), and edges that are present", "in cycles_nodes: edges = [] for i, e in enumerate(cycle):", "existing_edge: self.graph.remove_edge(from_index, to_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index)", "nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey = mycomp + str(len(subgraph.edges())) if", "__mul__(self, scaling_matrix): \"\"\" Replicates the graph, creating a supercell, intelligently", "and strict: return ValueError(\"Meaningless to compare MoleculeGraphs if \" \"corresponding", "break_edge will attempt to break both (from_index, to_index) and, failing", "other, strict=True): \"\"\" Compares two MoleculeGraphs. Returns dict with keys", "= {\"nodesep\": 10.0, \"dpi\": 300, \"overlap\": \"false\"} # add display", "if scale_matrix.shape != (3, 3): scale_matrix = np.array(scale_matrix * np.eye(3),", "and if so, delete old edge that went through #", "{} strat = strategy(**strategy_params) for site in mapping.values(): neighbors =", "considered equal # this could probably be a lot smaller", "from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ):", "molecules from periodic crystals. Will only return unique molecules, not", "properties to be changed following the split. :param allow_reverse: If", "= [1, 0, 0], [0, 1, 0], [0, 0, 1]", "len(self.molecule) def sort(self, key=None, reverse=False): \"\"\" Same as Molecule.sort(), also", "1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is not", "atom must be a DummySpecies X, indicating the position of", "simple graphs) or \"fdp\" (for more crowded graphs) usually give", "a chemical bond, but can store any kind of information", "= self.graph.to_undirected() disconnected.remove_node(index) for neighbor in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected,", "edges between Sites. Edge weights can be different and MoleculeGraphs", "raise ValueError(\"Image must be supplied, to avoid ambiguity.\") if existing_edges:", "to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel =", "that correspond to Sites in Structure). :param structure (Structure): :param", "self.add_edge( from_index=site, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, )", "be unambiguous, \" \"trying to automatically detect.\") dist, to_jimage =", "# get label by species name label = \"{}({})\".format(str(self.structure[n].specie), n)", ":param weight (float): e.g. bond length :param warn_duplicates (bool): if", "i: Index at which to insert the new site :param", "for images that are not the origin if image_labels: d[\"headlabel\"]", "least have a \"to_index\" and \"from_index\" key, and can also", "disconnected = self.graph.to_undirected() disconnected.remove_node(index) for neighbor in neighbors: sizes[neighbor[2]] =", "the terms of the MIT License. \"\"\" Module for graph", "lattice has # significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac", "molecule = molecule.get_centered_molecule() molecules.append(molecule) return molecules class MolGraphSplitError(Exception): \"\"\" Raised", "a Structure object :param graph_data: dict containing graph information in", "graph mapping = {idx: self.structure.index(site) for idx, site in enumerate(old_structure)}", "disconnected subgraph of the original. Currently, this function naively assigns", "a simple measure of the dissimilarity between two MoleculeGraphs (ignoring", "cls(m, d[\"graphs\"]) @classmethod def _edges_to_string(cls, g): header = \"from to", "0.587 + c[2] * 0.114) / 255 < 0.5 else", "if rs.returncode != 0: raise RuntimeError(\"{} exited with return code", "for Molecule instantiation for k, v in properties.items(): if len(v)", "will try and detect all equivalent images and add multiple", "this method is called from, not the 'other' StructureGraph: there", "d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule, name=\"bonds\", edge_weight_name=None,", "data in edges: s += \"{:4} {:4} {:12} {:.3e}\\n\".format( u,", "of bonds :return: \"\"\" if self.structure != other.structure and strict:", "self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping =", "new supercell, and get asgolute Cartesian # co-ordinates of where", "of an edge in the MoleculeGraph. :param from_index: int :param", "cycle in all_cycles: if sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle)", "def with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor for StructureGraph,", "edge_properties=edge_props) else: if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try:", "edges with optional edge parameters. :param molecule: Molecule object :param", "edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add:", "raise ValueError( \"Please specify units associated \" \"with your edge", "not None: self.graph[from_index][to_index][edge_index][\"weight\"] = new_weight if new_edge_properties is not None:", "for node in f1_nodes: if node[1][\"specie\"] not in f1_comp_dict: f1_comp_dict[node[1][\"specie\"]]", ":return: \"\"\" if not which(algo): raise RuntimeError(\"StructureGraph graph drawing requires", "there is no guarantee the node indices will be the", "their periodic images (usually only used for debugging, edges to", "x: x.dist) return connected_sites def get_coordination_of_site(self, n): \"\"\" Returns the", "the graph in sync with its corresponding Structure. # Broadly,", "0]) + 100 b = max(coords[:, 1]) - min(coords[:, 1])", "weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props,", "= { (u, v, d.get(\"to_jimage\", (0, 0, 0))) for u,", "be defined as duplicates, otherwise bond lengths can differ. This", "unique_cycles = [] for cycle in all_cycles: if sorted(cycle) not", "(and graph) to be removed. :return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping", "attempt to break both (from_index, to_index) and, failing that, will", "png) :param diff (StructureGraph): an additional graph to compare with,", "[d.get(\"weight\", None) for u, v, d in self.graph.edges(data=True)] stats =", "= {(u, v) for u, v, d in self.graph.edges(keys=False, data=True)}", "MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule", "any one bond, one from site u to site v", "we test for isomorphism def node_match(n1, n2): return n1[\"specie\"] ==", "edges green that are in diff graph but not in", "= {} strat = strategy(**strategy_params) for site in mapping.values(): neighbors", "to site {}.\".format(from_index, to_index) ) return # generic container for", "charge=self.molecule.charge), edges, ) ) frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \"", "warn_duplicates: warnings.warn( \"Trying to add an edge that already exists", "validate_proximity=False, site_properties=None, edges=None, ): \"\"\" A wrapper around Molecule.insert(), which", "NMR J-couplings, Heisenberg exchange parameters, etc. For periodic graphs, class", "match given position to an # existing Site in Structure", "0: duplicates.append(edge) for duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes()", "new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in graph.edges()]) return new_igraph def _isomorphic(frag1,", "del properties[k] new_mol = Molecule(species, coords, charge=charge, site_properties=properties) graph_data =", "optionally add weights to graph if weight_labels: units = g.graph.get(\"edge_weight_units\",", "0, 0) if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del", "edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\",", "np.multiply(-1, to_jimage) to_jimage = tuple(map(int, np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict()", "copy=False) self.set_node_attributes() def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None,", "ensure comparison of node identities. \"\"\" return g1.vs[i1][\"species\"] == g2.vs[i2][\"species\"]", "this # assumption simplifies logic later if not np.array_equal(from_jimage, (0,", "molecules (and not, e.g., layers of a 2D crystal) #", "and another form site v to site u: this is", "lattices images = [1, 0, 0], [0, 1, 0], [0,", "= {} for node in self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node]", "return False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges())", "belongs to. :param structure: a Structure object :param graph_data: dict", "self.molecule.copy() # sort Molecule self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse) #", "+= 1 if f1_comp_dict != f2_comp_dict: return False if IGRAPH_AVAILABLE:", "edge_props[\"weight\"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else: if", "\"graphs\": json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d) return sg def __rmul__(self,", "nodes in graph. :param key: :param reverse: :return: \"\"\" old_molecule", "nodes != number of sites in the Structure. This #", "Get indices now occupied by functional group # Subtracting 1", "Remove an edge from the StructureGraph. If no image is", "enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped, \"specie\") coords", "have to be boxed first coords = molecule.cart_coords if extend_structure:", "graph information, but also changes the underlying Molecules. If the", "Molecule.insert(), which also incorporates the new site into the MoleculeGraph.", "of the original. Currently, this function naively assigns the charge", "new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def build_unique_fragments(self):", "= {centre_sp: \"A\"} available_letters = [chr(66 + i) for i", "is a simple measure of the dissimilarity between two StructureGraphs", "the expanded graph could also be done on the original", "\"\"\" Gives each node a \"specie\" and a \"coords\" attribute,", "match mapping new_graph = nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph, \"specie\")", "\"\"\" As in :Class: `pymatgen.core.Structure` except with using `to_dict_of_dicts` from", "units) # update edge with our new style attributes g.edges[u,", "nodes are not\" \" present in the graph. Please check", "the graph. :param anonymous: if anonymous, will replace specie names", "= [algo, \"-T\", extension, basename + \".dot\"] rs = subprocess.Popen(args,", "s = \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__str__()) s +=", "confusing due to periodic boundaries if hide_image_edges: for edge_to_delete in", "1: self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else:", "be checked to ensure that site can be safely added.", "charge = 0 # relabel nodes in graph to match", "self.graph.add_edge(u, v, **d) def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other):", "\"site {} to site {}.\".format(from_index, to_index) ) return # generic", "a disconnected subgraph of the original. Currently, this function naively", "class that contains connection information: relationships between sites represented by", "edge are expected to be, relative to original # lattice", "A wrapper for Molecule.remove_sites(). :param indices: list of indices in", "None, then find_rings will only return those rings including the", "subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define how we test for", "DummySpecies X, indicating the position of nearest neighbor. The second", "in_edges: weight = d.get(\"weight\", None) if v == n: site", "graph \"\"\" return len(self.structure) def sort(self, key=None, reverse=False): \"\"\" Same", "np.subtract(to_jimage, shift) # automatic detection of to_jimage if user doesn't", "graph information. \"\"\" m = Molecule.from_dict(d[\"molecule\"]) return cls(m, d[\"graphs\"]) @classmethod", "StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): \"\"\" Two StructureGraphs are equal if", "be done on the original graph, but a larger graph", "i, species, coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for", "from pymatgen.core import Lattice, Molecule, PeriodicSite, Structure from pymatgen.core.structure import", "Draws graph using GraphViz. The networkx graph object itself can", "e in enumerate(cycle): edges.append((cycle[i - 1], e)) cycles_edges.append(edges) return cycles_edges", "f_lat = lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs", "enumerate(nodes): mapping[n] = i # just give charge to whatever", "easier. Use cases for this include storing bonding information, NMR", "to calculate the bond length between the attached functional group", "v, attr_dict) # list of new edges inside supercell #", "sorted(list(subg.nodes)) # Molecule indices are essentially list-based, so node indices", "returns two or more new MoleculeGraph objects. :return: list of", "s += \"\\nStructure: \\n{}\".format(self.structure.__str__()) s += \"\\nGraph: {}\\n\".format(self.name) s +=", "list(g.edges(data=True)) # sort edges for consistent ordering edges.sort(key=itemgetter(0, 1)) if", "== other_sorted.molecule) def isomorphic_to(self, other): \"\"\" Checks if the graphs", "have a \"weight\" and a \"properties\" key. :return: \"\"\" self.molecule.insert(", "assume we want the closest site warnings.warn(\"Please specify to_jimage to", "more new MoleculeGraph objects. :return: list of MoleculeGraphs \"\"\" if", "len(new_sites) for n in range(len(self.structure))} for idx, site in enumerate(self.structure):", "= os.path.splitext(filename) extension = extension[1:] write_dot(g, basename + \".dot\") with", "removed. :return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct,", "ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm)", "Extract a statistical summary of edge weights present in the", "a given molecule easier. Use cases for this include storing", "into two or more MoleculeGraphs by breaking a set of", "\"\"\" nodes = graph.nodes(data=True) new_igraph = igraph.Graph() for node in", "# shift so origin is at center of mass molecule", "c in nx.simple_cycles(directed) if len(c) > 2] # Using to_directed()", "f2_comp_dict: return False if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 =", "= [] red_edges = [] for u, v, k, d", "v_expec_image = v_expec_image - v_expec_image % 1 v_expec_frac = np.subtract(v_expec_frac,", "involved in a connection in alphabetical order (e.g. string 'Fe-O')", "As in :Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from", "graph_data = molecule.as_dict()[\"graphs\"] self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) #", "u, v, d in new_g.edges(data=True) if d[\"to_jimage\"] == (0, 0,", "from_index: index of site connecting from :param to_index: index of", "that lie on periodic boundaries. In principle, any operations on", "direction :param to_jimage (tuple of ints): lattice vector of image", "seeing if that node exists in the # supercell. If", "[] cycles_edges = [] # Remove all two-edge cycles all_cycles", "new_edge_properties is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] =", "\"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge( mapping[u],", "between sites represented by a Graph structure, and an associated", "remapped, incrementing from 0 mapping = {} for i, n", "new_g = nx.MultiDiGraph() for new_graph in new_graphs: new_g = nx.union(new_g,", "\"\"\" Constructor for MoleculeGraph, returns a MoleculeGraph object with an", "Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, ) ) frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula)", "as (from_index, to_index,\" \" from_image, to_image) tuples\") if props is", "new_u, new_v = new_v, new_u new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"]", "Replicates the graph, creating a supercell, intelligently joining together edges", "\" ({})\".format(edge_weight_units) header += \" {}\".format(edge_label) header_line += \" {}\".format(\"-\"", "= nx.get_node_attributes(remapped, \"specie\") coords = nx.get_node_attributes(remapped, \"coords\") edges = {}", "other, strict=True): \"\"\" Compares two StructureGraphs. Returns dict with keys", "functional group (format: {(from_index, to_index, from_image, to_image): props}, where props", "safely added. :param site_properties: Site properties for Molecule :param edges:", "font color # magic numbers account for perceived luminescence #", "for everyone one we add if {new_u, new_v} not in", "edge_properties of an edge in the StructureGraph. :param from_index: int", "= [] new_graphs = [] for v in c_lat: #", "= [\"{}({})\".format(label[1], label[0]) for label in labels] motif = \"{}-{}\".format(centre_sp,", "new_weight: alter_edge does not require that weight be altered. As", "template in func_groups.json. 3. A MoleculeGraph object. :param strategy: Class", ":return: Name of the edge weight property of graph \"\"\"", "new_graph in new_graphs: new_g = nx.union(new_g, new_graph) edges_to_remove = []", "sites existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data and warn_duplicates: warnings.warn(", "to use nx.weakly_connected_components because of deprecation # of nx.weakly_connected_component_subgraphs subgraphs", "string name. The molecule will be obtained from the relevant", "PeriodicSite should have a proper __hash__() value, # using its", "from the StructureGraph. If no image is given, this method", "else: properties[prop] = [prop_set[prop]] # Site properties must be present", "0, 0), to_jimage=edge[\"to_jimage\"], weight=edge.get(\"weight\", None), edge_properties=edge.get(\"properties\", None), ) except KeyError:", "\"\"\" Determine if the MoleculeGraph is connected. If it is", "the dissimilarity between two MoleculeGraphs (ignoring edge weights), and is", "# ensure images are tuples (conversion to lists happens #", "index and periodic image. Here, the # number of nodes", "return False if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2)", "try: from_index = edge[0] to_index = edge[1] from_image = edge[2]", "\"\"\" def __init__(self, molecule, graph_data=None): \"\"\" If constructing this class", "of MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original = copy.deepcopy(self)", "both graphs are converted into undirected nx.Graph objects. :param other:", "disconnected.remove_node(index) for neighbor in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep", "from/to images, set as origin if not defined to_image =", "return mg @staticmethod def with_local_env_strategy(molecule, strategy): \"\"\" Constructor for MoleculeGraph,", "connection between sites) doesn't have a direction, from_index, from_jimage can", "[] for cycle in all_cycles: if sorted(cycle) not in unique_sorted:", "in new_g.edges(keys=True, data=True): to_jimage = d[\"to_jimage\"] # for node v", "of graph, e.g. \"bonds\" :param edge_weight_name (str): name of edge", "works by looking for the expected position # of an", "each resulting MoleculeGraph is a disconnected subgraph of the original.", "dissimilarity between two StructureGraphs (ignoring edge weights), and is defined", "d[\"to_jimage\"] if dir == \"in\": u, v = v, u", "edge exists before attempting to change it if not existing_edge:", "and strict: return ValueError(\"Meaningless to compare StructureGraphs if \" \"corresponding", "out how to distribute charge if 0 in nodes: charge", "= {tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule} other_sorted = other.__copy__()", "periodic edges if hide_unconnected_nodes: g = g.subgraph([n for n in", "if image sites now present in supercell # and if", "self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): \"\"\"", "an associated structure object. This class uses the NetworkX package", "either the weight or the edge_properties of an edge in", "other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v,", "\" E\" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict", "mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in", "exists between those sites.\".format( from_index, to_index ) ) # Third", "be considered equal. :param other: MoleculeGraph :return (bool): \"\"\" #", "reverse=False): \"\"\" Same as Molecule.sort(), also remaps nodes in graph.", "for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1][\"specie\"], coords=node[1][\"coords\"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for", "for i, e in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping) species", "for i in including: for cycle in unique_cycles: if i", "different graph compared with using a Molecule or str (when", "dict with keys 'self', 'other', 'both' with edges that are", ":param structure: Structure object :param strategy: an instance of a", "{} coords = {} properties = {} for node in", "networkx graph object into an igraph graph object. \"\"\" nodes", "existing_edge_data.items(): if d[\"to_jimage\"] == to_jimage: if warn_duplicates: warnings.warn( \"Trying to", "options for edges for u, v, k, d in g.edges(keys=True,", "node corresponding to site n. :param n: index of site", "ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm", "anonymous: mapping = {centre_sp: \"A\"} available_letters = [chr(66 + i)", "extension = extension[1:] write_dot(g, basename + \".dot\") with open(filename, \"w\")", "those connections (e.g. bond lengths). \"\"\" def get_label(u, v): u_label", "and site index :param weight_labels (bool): if True, label edges", "\"\"\" Helper function called by isomorphic to ensure comparison of", "representing coordinates of the new site :param validate_proximity: For Molecule.insert();", "will be obtained from the relevant template in func_groups.json. 3.", "exists from \" \"site {} to site {} in {}.\".format(from_index,", "n in g.nodes(): # get label by species name label", "all from_jimages to be (0, 0, 0), # initial version", "from_index, to_index ) ) if to_jimage is None: edge_index =", "edge exists before attempting to change it if not existing_edges:", "graph is failed to split into two disconnected subgraphs \"\"\"", "cycles all_cycles = [c for c in nx.simple_cycles(directed) if len(c)", "the corresponding site in the original structure, weight can be", "reading to/from json duplicates # information for u, v, k,", "= [] # tuple of (u, v, attr_dict) # list", "in subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names", "representing crystals molecule_subgraphs = [] for subgraph in all_subgraphs: intersects_boundary", "and, failing that, will attempt to break (to_index, from_index). :return:", "actual Molecule as the input. The first atom must be", "(specie, coords, etc.) in the MoleculeGraph. :return: \"\"\" species =", "are different.\") if strict: # sort for consistent node indices", "GraphViz .dot file for later visualization :param algo: any graphviz", "0), to_jimage=to_jimage, to_index=nnsite.index, ) return # sanitize types from_jimage, to_jimage", "n) if node_labels else \"\" # use standard color scheme", "\"\"\" As in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts`", "for n, v in self.graph.edges(n) if n == v]) return", "necessarily have to be a chemical bond, but can store", "determine bonds using one of a list of strategies defined", "later visualization :param algo: any graphviz algo, \"neato\" (for simple", "hide unconnected nodes :param hide_image_edges: if True, do not draw", "as a convenient key mapping = {tuple(site.frac_coords): self.molecule.index(site) for site", "for edge, props in edges.items(): try: from_index = edge[0] to_index", "any other information to store on graph edges, similar to", "to_jimage = ( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), ) from_index, to_index", ":param to_index: int :param new_weight: alter_edge does not require that", "= namedtuple(\"ConnectedSite\", \"site, jimage, index, weight, dist\") def _compare(g1, g2,", "site) for neighbor in neighbors: self.add_edge( from_index=site, from_jimage=(0, 0, 0),", "If it does, the edge is updated. This is more", "from local_env class (consult relevant class for their meaning) :return:", ":return: length of Structure / number of nodes in graph", "i, e in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping) species =", "see as_dict method for format) \"\"\" if isinstance(structure, StructureGraph): #", "strategy, bond_order=1, graph_dict=None, strategy_params=None, ): \"\"\" Builds off of Molecule.substitute", "from_jimage (tuple of ints): lattice vector of periodic image, e.g.", "atom in CH3. The X-C bond indicates the directionality to", "other_sorted.graph.edges(keys=False, data=True)} else: edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for u,", "other.molecule} except ValueError: return False other_sorted = other.__copy__() other_sorted.sort(key=lambda site:", "\"\"\" Same as Structure.sort(), also remaps nodes in graph. :param", "\"site, jimage, index, weight, dist\") def _compare(g1, g2, i1, i2):", "neater if to_index < from_index: to_index, from_index = from_index, to_index", "+= \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def __len__(self):", "Returns dict with keys 'self', 'other', 'both' with edges that", "if len(edges) == 0 and len(edges_other) == 0: jaccard_dist =", "= edge_props[\"to_jimage\"] del edge_props[\"to_jimage\"] else: # By default, assume that", "int :param to_jimage: tuple :param allow_reverse: If allow_reverse is True,", "broken between {} and {};\\ no edge exists between those", "good outputs :return: \"\"\" if not which(algo): raise RuntimeError(\"StructureGraph graph", "return cls(m, d[\"graphs\"]) @classmethod def _edges_to_string(cls, g): header = \"from", "where X is the first site and C is the", "list() # Had to use nx.weakly_connected_components because of deprecation #", "[] for u, v, k, d in self.graph.edges(keys=True, data=True): if", "the C atom in CH3. The X-C bond indicates the", "be able to test for isomorphism for subgraph in molecule_subgraphs:", "mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else: if strategy_params is", "of the MoleculeGraph this method is called from, not the", ":return: \"\"\" if not strategy.structures_allowed: raise ValueError( \"Chosen strategy is", "super-imposed on each other). If visualization is difficult to interpret,", "= edge[0] to_index = edge[1] from_image = edge[2] to_image =", "out_edges + in_edges: weight = d.get(\"weight\", None) if v ==", "edge # there should only ever be at most one", "\"Provide explicit coordinate instead\") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp)", "object :param graph_data: dict containing graph information in dict format", "): \"\"\" Builds off of Structure.substitute to replace an atom", "including is not None, then find_rings will only return those", "new_d[\"to_jimage\"] = (0, 0, 0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v,", "= [prop_set[prop]] # Site properties must be present for all", "mapping = {idx: self.molecule.index(site) for idx, site in enumerate(old_molecule)} self.graph", "of the new site i, and all indices used for", "are in diff graph but not in the reference graph", "self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self, filename=\"graph\", diff=None, hide_unconnected_nodes=False, hide_image_edges=True,", "np.array(scale_matrix * np.eye(3), np.int16) else: # TODO: test __mul__ with", "associating a graph with a given crystallographic structure easier. Use", "header_line = \"---- ---- ------------\" edge_weight_name = g.graph[\"edge_weight_name\"] if edge_weight_name:", "if \" \"corresponding Molecules are different.\") if strict: # sort", "else: mapping[j] = j + 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i)", "that are present in both. The Jaccard distance is a", "\"Chosen strategy is not designed for use with molecules! \"", "add duplicate edges # will remove two edges for everyone", "json_graph.adjacency_data(new_graph) # create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def", "actually accurately assign charge. NOTE: This function does not modify", "atoms = len(grp) - 1 offset = len(self.molecule) - atoms", "= tuple(map(int, np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict() site_d[\"abc\"] = np.add(site_d[\"abc\"],", "of supercell # are connected to nodes on opposite side", "to_index ) ) if to_jimage is None: edge_index = 0", "if not keep_dot: os.remove(basename + \".dot\") def as_dict(self): \"\"\" As", "else: for i, properties in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage:", "combinations of the MoleculeGraphs (in other words, all connected induced", "other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges = {(u, v) for u, v,", "to Structure's site_properties :return: \"\"\" # this is not necessary", "indices have different indexing u, v = (u - 1),", "the new functional group. NOTE: using a MoleculeGraph will generally", "from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index, ) return # sanitize types", "data=True): if \"id\" in d: del d[\"id\"] if \"key\" in", "edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d)) else: # want to find", "edge weights. Can be \" \"empty string if arbitrary or", "True # prune duplicate subgraphs unique_subgraphs = [] for subgraph", "also trialed, using # a simple Graph (instead of MultiDiGraph),", "because the dummy atom X should not count atoms =", ":param to_index: int :param allow_reverse: If allow_reverse is True, then", "with open(filename, \"w\") as f: args = [algo, \"-T\", extension,", "X-C bond indicates the directionality to connect the atoms. 2.", "by 1 - (size of the intersection / size of", "= v, u to_jimage = np.multiply(-1, to_jimage) to_jimage = tuple(map(int,", "MoleculeGraph into two or more MoleculeGraphs by breaking a set", "for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = \"#000000\" if 1", "k].update(d) # optionally remove periodic image edges, # these can", "graph isomorphism unique_frag_dict = {} for key in frag_dict: unique_frags", "else: for u, v, data in edges: s += \"{:4}", "i in sizes.keys(): if i != keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group(", "information in dict format (not intended to be constructed manually,", "same bond lengths to be defined as duplicates, otherwise bond", "new_d = d.copy() new_to_jimage = tuple(map(int, v_expec_image)) # normalize direction", "from_index) else: raise ValueError( \"Edge cannot be broken between {}", "None, then the algorithm will attempt to automatically determine bonds", "} return d @classmethod def from_dict(cls, d): \"\"\" As in", "relabel nodes in graph to match mapping new_graph = nx.relabel_nodes(subg,", "open(filename, \"w\") as f: args = [algo, \"-T\", extension, basename", "statistical summary of edge weights present in the graph. :return:", "edges for consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for u,", "for f in unique_frags: if _isomorphic(frag, f): found = True", "in the MoleculeGraph. :param from_index: int :param to_index: int :param", "def with_edges(molecule, edges): \"\"\" Constructor for MoleculeGraph, using pre-existing or", "an actual molecule as the input. The first atom must", "mapping, copy=True) # normalize directions of edges edges_to_remove = []", "we have # full periodic boundary conditions # so that", "expanded graph could also be done on the original graph,", "v, d in new_g.edges(data=True) if d[\"to_jimage\"] == (0, 0, 0)]", "atom must be the next nearest atom. For example, for", "in self.molecule with a functional group. This method also amends", "designed for use with structures! \" \"Please choose another strategy.\"", "unique_mol_graph_dict = {} for key in unique_frag_dict: unique_mol_graph_list = []", "if v_present[0] <= tol else None # check if image", "drawing requires \" \"GraphViz binaries to be in the path.\")", "the relevant template in func_groups.json. :param strategy: Class from pymatgen.analysis.local_env.", "provided by the `local_env` module, such as O'Keeffe). This class", "# normalize direction if new_v < new_u: new_u, new_v =", ":param key: :param reverse: :return: \"\"\" old_molecule = self.molecule.copy() #", "v) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges", "simple measure of the dissimilarity between two MoleculeGraphs (ignoring edge", "In principle, any operations on the expanded graph could also", "json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule, edges): \"\"\" Constructor", "{}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def __repr__(self): s =", "j else: mapping[j] = j + 1 nx.relabel_nodes(self.graph, mapping, copy=False)", "Helper function called by isomorphic to ensure comparison of node", "= graph_dict[(u, v)] if \"to_jimage\" in edge_props.keys(): to_jimage = edge_props[\"to_jimage\"]", "set_node_attributes(self): \"\"\" Replicates molecule site properties (specie, coords, etc.) in", "from networkx.drawing.nx_agraph import write_dot from networkx.readwrite import json_graph from scipy.spatial", "is no cycle including an index, the value will be", "# harmless, so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"],", "new_u = u new_v = v_present new_d = d.copy() #", "strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor classes", "between two sites existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data and", "v]) return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self, filename=\"graph\", diff=None,", "algorithm provided by the `local_env` module, such as O'Keeffe). This", "\"{:4} {:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0, 0)))) return s", "(Molecule): :param name (str): name of graph, e.g. \"bonds\" :param", "= fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append( self.with_edges(", "[] for subgraph in molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph, g,", "work with structures # molecules have to be boxed first", "= g.nodes[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\"", "d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u, v, k)) if (new_u, new_v,", "that, and returns two or more new MoleculeGraph objects. :param", "List of dicts representing edges to be added to the", "return { \"self\": edges - edges_other, \"other\": edges_other - edges,", "# are expected to be v_expec = new_structure[u].coords + v_rel", "describe from pymatgen.core import Lattice, Molecule, PeriodicSite, Structure from pymatgen.core.structure", "the graph. Please check your\" \" indices.\" ) mg.add_edge(from_index, to_index,", "in unique_subgraphs ] if not any(already_present): unique_subgraphs.append(subgraph) # get Molecule", "pair and another # (site, jimage) pair existing_edge_data = self.graph.get_edge_data(from_index,", "etc. For periodic graphs, class stores information on the graph", "to_index = int(from_index), int(to_index) # check we're not trying to", "the value will be an empty list. \"\"\" # Copies", "fragments, aka connected induced subgraphs frag_dict = {} for ii", "hide_image_edges: if True, do not draw edges that go through", "should reflect the MoleculeGraph AFTER the insertion, NOT before. Each", "from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ): \"\"\" Alters either the", "an igraph graph object. \"\"\" nodes = graph.nodes(data=True) new_igraph =", "be drawn with networkx's in-built graph drawing methods, but note", "use with molecules! \" \"Please choose another strategy.\" ) extend_structure", "unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert back to molecule graphs", "serializing back from json), it's important images # are hashable/immutable", "types = defaultdict(list) for u, v, d in self.graph.edges(data=True): label", "len(edges_other) == 0: jaccard_dist = 0 # by definition else:", "1), (v - 1) self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, )", "to be added to the MoleculeGraph. These edges must include", "new_d = u, v, d.copy() new_d[\"to_jimage\"] = (0, 0, 0)", "constrain all from_jimages to be (0, 0, 0), # initial", "= {} for j in range(len(self.structure) - 1): if j", "fillcolor=color, fontcolor=fontcolor, label=label, fontname=\"Helvetica-bold\", style=\"filled\", shape=\"circle\", ) edges_to_delete = []", "self._edges_to_string(self.graph) return s def __len__(self): \"\"\" :return: length of Structure", "new_weight=None, new_edge_properties=None, ): \"\"\" Alters either the weight or the", "except ValueError: return False other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)])", "periodic image in +x direction :param to_jimage (tuple of ints):", "int :param to_index: int :param allow_reverse: If allow_reverse is True,", "probably be a lot smaller tol = 0.05 for u,", "\" \"GraphViz binaries to be in the path.\") # Developer", "other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u,", "Structure self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse) # apply Structure ordering", "make associating a graph with a given molecule easier. Use", "for edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"], from_jimage=(0, 0,", "from_index=n, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights else", "+= \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph)", "the current Molecule (and graph) to be removed. :return: \"\"\"", "0)] new_periodic_images = [] orig_lattice = self.structure.lattice # use k-d", "tuple of (u, v, k) edges_to_add = [] # tuple", "self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings", "now occupied by functional group # Subtracting 1 because the", "species = {} coords = {} properties = {} for", "and get asgolute Cartesian # co-ordinates of where atoms defined", "c in nx.weakly_connected_components(original.graph)] for subg in subgraphs: nodes = sorted(list(subg.nodes))", "StructureGraph :return (bool): \"\"\" # sort for consistent node indices", "we don't try to add duplicate edges # will remove", "for Molecule.remove_sites(). :param indices: list of indices in the current", "if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp =", "coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed", "def __init__(self, structure, graph_data=None): \"\"\" If constructing this class manually,", "v) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other =", "prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index,", "the bond length between the attached functional group and the", "assign charge. NOTE: This function does not modify the original", "any(already_present): unique_subgraphs.append(subgraph) # get Molecule objects for each subgraph molecules", "no additional properties are to be specified. :return: sg, a", "for u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {", "no_cross=True, reorder=False) else: structure = None for n in range(len(molecule)):", "added. :param site_properties: Site properties for Molecule :param edges: List", "node_match=node_match, edge_match=edge_match) for g in unique_subgraphs ] if not any(already_present):", "if node[1][\"specie\"] not in f2_comp_dict: f2_comp_dict[node[1][\"specie\"]] = 1 else: f2_comp_dict[node[1][\"specie\"]]", "break_edge(self, from_index, to_index, allow_reverse=False): \"\"\" Remove an edge from the", "to Sites in Structure). :param structure (Structure): :param name (str):", "warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge to graph. Since physically", "0, 0) for periodic image in +x direction :param to_jimage", "it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if to_jimage", "indicates the directionality to connect the atoms. 2. A string", "and coordinates. :return: \"\"\" species = {} coords = {}", "@property def types_and_weights_of_connections(self): \"\"\" Extract a dictionary summarizing the types", "dists = [] for image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0]", ":param allow_reverse: If allow_reverse is True, then break_edge will attempt", "for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self, from_index,", "of Site in Molecule :param jimage: lattice vector of site", "will mean that each cycle always appears twice # So,", "if d[\"to_jimage\"] == to_jimage: if warn_duplicates: warnings.warn( \"Trying to add", "test __mul__ with full 3x3 scaling matrices raise NotImplementedError(\"Not tested", "jimage arg != (0, 0, 0) relative_jimage = np.subtract(to_jimage, jimage)", "key=key, reverse=reverse) # apply Structure ordering to graph mapping =", "combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination) if", "d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"])", "len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes, key=lambda x: sizes[x]) for i", "the algorithm will attempt to automatically determine bonds using one", "in cycle and cycle not in cycles_nodes: cycles_nodes.append(cycle) for cycle", "other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d.get(\"to_jimage\", (0,", "(bool): If True, only treat subgraphs as isomorphic if edges", "A \"bond\" does not necessarily have to be a chemical", "in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: self.graph.add_edge(u,", "name label = \"{}({})\".format(str(self.structure[n].specie), n) if node_labels else \"\" #", "from input graph_data = structure.as_dict()[\"graphs\"] self.structure = structure self.graph =", "or \"eV\" :return (StructureGraph): \"\"\" if edge_weight_name and (edge_weight_units is", "from_index, to_index, to_jimage=None, allow_reverse=False): \"\"\" Remove an edge from the", "from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights else None,", "\"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"molecule\": self.molecule.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), } return", "functional group in self.molecule with a functional group. This method", "information on the different co-ordination environments present in the graph.", "function does not only alter the graph information, but also", "NOTE: Care must be taken to ensure that the functional", "\"A\"} available_letters = [chr(66 + i) for i in range(25)]", "\"\"\" import copy import logging import os.path import subprocess import", "v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart)", "weights can be different and MoleculeGraphs can still be considered", "(from_index, to_index,\" \" from_image, to_image) tuples\") if props is not", "for subgraph in unique_subgraphs: coords = [supercell_sg.structure[n].coords for n in", ":return: list of MoleculeGraphs \"\"\" if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original", "get_disconnected_fragments(self): \"\"\" Determine if the MoleculeGraph is connected. If it", "site n. :param n: index of site :return (int): \"\"\"", "= nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for c", "edge_properties of an edge in the MoleculeGraph. :param from_index: int", "just give charge to whatever subgraph has node with index", "Structure with bond information, stored in the form of a", "necessary for the class to work, but # just makes", "edge_index) else: raise ValueError( \"Edge cannot be broken between {}", "store and operate on the graph itself, but contains a", "This class that contains connection information: relationships between sites represented", "already exists from \" \"site {} to site {} in", "\"\"\" self.set_node_attributes() original = copy.deepcopy(self) for bond in bonds: original.break_edge(bond[0],", "get_coordination_of_site(self, n): \"\"\" Returns the number of neighbors of site", "This function does not modify the original MoleculeGraph. It creates", "edge in the StructureGraph. :param from_index: int :param to_index: int", "MoleculeGraph. :param including: list of site indices. If including is", "Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites =", ") return # sanitize types from_jimage, to_jimage = ( tuple(map(int,", "site in the original structure, weight can be None if", "[\"{}({})\".format(label[1], label[0]) for label in labels] motif = \"{}-{}\".format(centre_sp, \",\".join(labels))", "sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is None:", "bond, one from site u to site v # and", "be swapped with to_index, to_jimage. However, images will always always", "g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors", "# add/delete marked edges for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for", "(for simple graphs) or \"fdp\" (for more crowded graphs) usually", "(u - 1), (v - 1) self.add_edge( mapping[u], mapping[v], weight=weight,", "problems with misdirected edges, both graphs are converted into undirected", "all equivalent images and add multiple # edges if appropriate", "True, label edges with weights :param image_labels (bool): if True,", ":return: \"\"\" species = {} coords = {} properties =", "cls(s, d[\"graphs\"]) def __mul__(self, scaling_matrix): \"\"\" Replicates the graph, creating", "mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg @property def name(self): \"\"\"", "requires \" \"GraphViz binaries to be in the path.\") #", "images present, but should hopefully be # easier to extend", "as the input. The first atom must be a DummySpecies", "new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <=", "for MoleculeGraph, returns a MoleculeGraph object with an empty graph", "for (u, v) in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight", "pdf or png) :param diff (StructureGraph): an additional graph to", "return self.graph.graph[\"name\"] @property def edge_weight_name(self): \"\"\" :return: Name of the", "Molecule or str (when not using graph_dict). :param index: Index", "False, will compare bonds from different Structures, with node indices", "= ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + \" E\" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key]", ":param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return:", "MoleculeGraph.break_edge repeatedly to create disjoint graphs (two or more separate", "such as O'Keeffe). This class that contains connection information: relationships", "arg != (0, 0, 0) relative_jimage = np.subtract(to_jimage, jimage) dist", "color_scheme=\"VESTA\", keep_dot=False, algo=\"fdp\", ): \"\"\" Draws graph using GraphViz. The", "graphs) usually give good outputs :return: \"\"\" if not which(algo):", "for much easier # control over graph appearance and also", "+= 1 for node in f2_nodes: if node[1][\"specie\"] not in", "v, d, \"in\") for u, v, d in self.graph.in_edges(n, data=True)]", "edges_to_remove.append((u, v, k)) # make sure we don't try to", "if False, will compare bonds from different Structures, with node", "label = \"{}({})\".format(str(self.molecule[n].specie), n) if node_labels else \"\" # use", "ValueError( \"Edge cannot be broken between {} and {};\\ no", "graphs unique_mol_graph_dict = {} for key in unique_frag_dict: unique_mol_graph_list =", "be present for all atoms in the molecule # in", "charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) # create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol,", "Two MoleculeGraphs are equal if they have equal Molecules, and", "must be the next nearest atom. For example, for a", "difficult to # keep the graph in sync with its", "split into two disconnected subgraphs \"\"\" pass class MoleculeGraph(MSONable): \"\"\"", "other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d[\"to_jimage\"]) for u,", "add/delete marked edges for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u,", "sort Molecule self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse) # apply Molecule", "with_edges(molecule, edges): \"\"\" Constructor for MoleculeGraph, using pre-existing or pre-defined", "site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0,", "to_jimage: tuple :param allow_reverse: If allow_reverse is True, then break_edge", "with networkx's in-built graph drawing methods, but note that this", "# alter any bonds before partition, to avoid remapping if", "= {(u, v, d[\"to_jimage\"]) for u, v, d in other_sorted.graph.edges(keys=False,", "new_edge_properties=None, ): \"\"\" Alters either the weight or the edge_properties", "object itself can also be drawn with networkx's in-built graph", "key, d in existing_edge_data.items(): if d[\"to_jimage\"] == to_jimage: if warn_duplicates:", "from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise ValueError( \"Edge cannot", "{}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + \".dot\") @property def", "== edges_other) and (self.structure == other_sorted.structure) def diff(self, other, strict=True):", "= self.graph.copy() g.graph = {\"nodesep\": 10.0, \"dpi\": 300, \"overlap\": \"false\"}", "periodic images (usually only used for debugging, edges to periodic", "properties to be changed. :return: \"\"\" existing_edge = self.graph.get_edge_data(from_index, to_index)", "to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def insert_node(", "MoleculeGraph objects. :param bonds: list of tuples (from_index, to_index) representing", "None: cycles_nodes = unique_cycles else: for i in including: for", "graph_data = json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure, edges):", "effort will be to actually accurately assign charge. NOTE: This", "[(u, v, d, \"in\") for u, v, d in self.graph.in_edges(n,", "(edge_weight_units is None): raise ValueError( \"Please specify units associated \"", "\"to_index\" and \"from_index\" key, and can also have a \"weight\"", "weights=False): \"\"\" Constructor for StructureGraph, using a strategy from :Class:", "method is called from, not the 'other' MoleculeGraph: there is", "in alphabetical order (e.g. string 'Fe-O') and values which are", "f2_comp_dict = {} for node in f1_nodes: if node[1][\"specie\"] not", "\"\"\" self.molecule.insert( i, species, coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping =", "conditions # so that nodes on one side of supercell", "that correspond to Sites in Molecule). :param molecule (Molecule): :param", "cycles_nodes = [] cycles_edges = [] # Remove all two-edge", "be supplied, to avoid ambiguity.\") if existing_edges: for i, properties", "len(c) > 2] # Using to_directed() will mean that each", "contains connection information: relationships between sites represented by a Graph", "add display options for nodes for n in g.nodes(): #", "default, this is None. If weight is to be changed,", "nodes in graph. :param key: :param reverse: :return: \"\"\" old_structure", "namedtuple(\"ConnectedSite\", \"site, jimage, index, weight, dist\") def _compare(g1, g2, i1,", "for c in nx.connected_components(supercell_sg.graph)] # discount subgraphs that lie across", "represented by a Graph structure, and an associated structure object.", "None, and all rings will be returned. :return: dict {index:cycle}.", "to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"], warn_duplicates=False, ) def get_connected_sites(self, n, jimage=(0, 0,", "information. \"\"\" d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\":", "= self.graph.get_edge_data(from_index, to_index) existing_reverse = None if existing_edge: self.graph.remove_edge(from_index, to_index)", "basename + \".dot\") with open(filename, \"w\") as f: args =", "d in self.graph.edges(keys=False, data=True) } edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie))", "# use standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol),", "for edge in graph.edges()]) return new_igraph def _isomorphic(frag1, frag2): \"\"\"", "edges=None, ): \"\"\" A wrapper around Molecule.insert(), which also incorporates", "tuple of (u, v, attr_dict) # list of new edges", "u, v, k, d in self.graph.edges(keys=True, data=True): if \"id\" in", "# automatic detection of to_jimage if user doesn't specify #", "each other, or violate the dimensions of the Lattice. :param", "def from_dict(cls, d): \"\"\" As in :Class: `pymatgen.core.Molecule` except restoring", "raw_props.values(): for prop in prop_set.keys(): if prop in properties: properties[prop].append(prop_set[prop])", "is None: neighbors = strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure,", "connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v,", ":Class: `pymatgen.core.Structure` except with using `to_dict_of_dicts` from NetworkX to store", "properties[k] new_mol = Molecule(species, coords, charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph)", "v)]) return original.get_disconnected_fragments() def build_unique_fragments(self): \"\"\" Find all possible fragment", "mycomp + str(len(subgraph.edges())) if mykey not in frag_dict: frag_dict[mykey] =", "in Structure \"\"\" # creating a supercell is an easy", "n in range(len(self.structure))} for idx, site in enumerate(self.structure): s =", "self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist = min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords,", "functional group replacement\" \"cannot occur at an atom within a", "= \"<NAME>, <NAME>, <NAME>\" __version__ = \"0.1\" __maintainer__ = \"<NAME>\"", "weight property of graph \"\"\" return self.graph.graph[\"edge_weight_name\"] @property def edge_weight_unit(self):", "by closest first \"\"\" connected_sites = set() connected_site_images = set()", ":return: \"\"\" def map_indices(grp): grp_map = {} # Get indices", "self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None,", "as Structure.sort(), also remaps nodes in graph. :param key: :param", "else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError(\"Can't find", ":param reverse: :return: \"\"\" old_structure = self.structure.copy() # sort Structure", "for u, v, d in self.graph.edges(keys=False, data=True) } edges_other =", "g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"): d[\"label\"] = \"{:.2f} {}\".format(d[\"weight\"], units) #", "to a general 3x3 scaling matrix. # code adapted from", "either case) :param edge_properties (dict): any other information to store", "supported, such as pdf or png) :param diff (StructureGraph): an", "everyone one we add if {new_u, new_v} not in edges_inside_supercell:", "(0, 0, 0))) for u, v, d in self.graph.edges(keys=False, data=True)}", "strict: # sort for consistent node indices # PeriodicSite should", "(3, 3): scale_matrix = np.array(scale_matrix * np.eye(3), np.int16) else: #", "index in original site n_u = u % len(self.structure) n_v", "graph_dict[(u, v)] if \"to_jimage\" in edge_props.keys(): to_jimage = edge_props[\"to_jimage\"] del", "edges_to_add.append((new_u, new_v, new_d)) # add/delete marked edges for edges_to_remove in", "self.graph.copy() g.graph = {\"nodesep\": 10.0, \"dpi\": 300, \"overlap\": \"false\"} #", "with structures! \" \"Please choose another strategy.\" ) sg =", "convenient key mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure}", "essentially list-based, so node indices # must be remapped, incrementing", "from_index, to_index, allow_reverse=False): \"\"\" Remove an edge from the MoleculeGraph", "def diff(self, other, strict=True): \"\"\" Compares two MoleculeGraphs. Returns dict", "if \"from_jimage\" in d: d[\"from_jimage\"] = tuple(d[\"from_jimage\"]) self.set_node_attributes() @classmethod def", "= StructureGraph.from_dict(d) return sg def __rmul__(self, other): return self.__mul__(other) @classmethod", "be changed, it should be a dictionary of edge properties", "coords = nx.get_node_attributes(new_graph, \"coords\") raw_props = nx.get_node_attributes(new_graph, \"properties\") properties =", "for u, v, d in other_sorted.graph.edges(keys=False, data=True)} else: edges =", "through periodic boundaries :param edge_colors (bool): if True, use node", "from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates = [] for edge", "graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule,", "function naively assigns the charge of the total molecule to", "np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get(\"weight\", None)", "new_u new_to_jimage = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) new_d[\"to_jimage\"] = new_to_jimage edges_to_remove.append((u, v,", "to close to each other, or violate the dimensions of", "mapping[sp] = available_letters.pop(0) centre_sp = \"A\" labels = [(label[0], mapping[label[1]])", "try to add duplicate edges # will remove two edges", "break if not found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert", "__str__(self): s = \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s", "node colors color_u = g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"] d[\"color_uv\"] =", "equal if they have equal Structures, and have the same", "\"0.1\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\"", "func_grp.graph.get_edge_data(u, v)[0] weight = None if \"weight\" in edge_props.keys(): weight", "cases for this include storing bonding information, NMR J-couplings, Heisenberg", "edges, both graphs are converted into undirected nx.Graph objects. :param", "(tuple of ints): lattice vector of image :param weight (float):", "first \"\"\" connected_sites = set() connected_site_images = set() out_edges =", "'Fe-O') and values which are a list of weights for", "representing coordinates of the new site :param coords_are_cartesian: Whether coordinates", "in sizes.keys(): if i != keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index,", "the same bond lengths to be defined as duplicates, otherwise", "named tuple of neighbors of site n: periodic_site, jimage, index,", "scale_matrix = np.array(scale_matrix * np.eye(3), np.int16) else: # TODO: test", "to_index: int :param new_weight: alter_edge does not require that weight", "# number of nodes != number of sites in the", "edges.intersection(edges_other), \"dist\": jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False): \"\"\" Retrieve subgraphs", "# ensure that edge exists before attempting to change it", "with key 'dist'. Important note: all node indices are in", "edges, only nodes defined that correspond to Sites in Structure).", "makes it neater if to_index < from_index: to_index, from_index =", "strategy_params=None, ): \"\"\" Builds off of Molecule.substitute and MoleculeGraph.substitute_group to", "between a given (site, jimage) pair and another # (site,", "for drawing # graphs using matplotlib, these also work here.", "the # which new lattice images present, but should hopefully", "mapping = {} for j in range(len(self.structure) - 1): if", "is called from, not the 'other' StructureGraph: there is no", "NMR J-couplings, Heisenberg exchange parameters, etc. :param molecule: Molecule object", "the MoleculeGraph this method is called from, not the 'other'", "graph could also be done on the original graph, but", "if new_weight is not None: self.graph[from_index][to_index][0][\"weight\"] = new_weight if new_edge_properties", "what lattice image the edge belongs to. :param structure: a", "Molecules in Structure \"\"\" # creating a supercell is an", "weights), and is defined by 1 - (size of the", "u: new_v, new_u, new_d = u, v, d.copy() new_d[\"to_jimage\"] =", "= frag2.edges() if len(f2_edges) != len(f2_edges): return False f1_comp_dict =", "list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight = None if \"weight\"", "g.graph[\"edge_weight_name\"] if edge_weight_name: print_weights = [\"weight\"] edge_label = g.graph[\"edge_weight_name\"] edge_weight_units", "= [{u, v} for u, v, d in new_g.edges(data=True) if", "does, the edge is updated. This is more # computationally", "labels = [\"{}({})\".format(label[1], label[0]) for label in labels] motif =", "from :param to_index: index of site connecting to :param from_jimage", "information to store on graph edges, similar to Structure's site_properties", "in nodes: charge = self.molecule.charge else: charge = 0 #", "edge_props = graph_dict[(u, v)] if \"weight\" in edge_props.keys(): weight =", "parameters will be used. :return: \"\"\" def map_indices(grp): grp_map =", "3. A MoleculeGraph object. :param strategy: Class from pymatgen.analysis.local_env. :param", "stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode != 0: raise RuntimeError(\"{}", "{:4} {:12}\\n\".format(u, v, str(data.get(\"to_jimage\", (0, 0, 0)))) return s def", "for isomorphism def node_match(n1, n2): return n1[\"specie\"] == n2[\"specie\"] def", "If it is not, separate the MoleculeGraph into different MoleculeGraphs,", "its frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.structure.index(site)", "for u, v, d in self.graph.out_edges(n, data=True)] in_edges = [(u,", ":return: \"\"\" self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current", "units e.g. \"Å\" or \"eV\" :return (StructureGraph): \"\"\" if edge_weight_name", "specify units associated \" \"with your edge weights. Can be", "red that do not exist in diff and edges green", "of nodes from original graph to its image mapping =", "= \"none\" # only add labels for images that are", "set of bonds. This function uses MoleculeGraph.break_edge repeatedly to create", "MoleculeGraphs \"\"\" self.set_node_attributes() original = copy.deepcopy(self) for bond in bonds:", "0) for u, v, d in subgraph.edges(data=True)) if not intersects_boundary:", "= self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for connected_site in connected_sites] labels", "converts a networkx graph object into an igraph graph object.", "if len(c) > 2] # Using to_directed() will mean that", "return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match(\"specie\", \"ERROR\") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(),", "= np.subtract(to_jimage, shift) # automatic detection of to_jimage if user", "d) in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return StructureGraph.from_dict(self.as_dict())", "This is returned with key 'dist'. Important note: all node", "d in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy=\"omit\") return { \"all_weights\":", "in +x direction :param to_jimage (tuple of ints): lattice vector", "\"\"\" Two StructureGraphs are equal if they have equal Structures,", "to add duplicate edges (duplicate edges will not be added", "for subgraph in molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match,", "None for n in range(len(molecule)): if structure is None: neighbors", "[] # tuple of (u, v, k) edges_to_add = []", "associated \" \"with your edge weights. Can be \" \"empty", "+ i) for i in range(25)] for label in labels:", "mapping = map_indices(func_grp.molecule) for (u, v) in list(func_grp.graph.edges()): edge_props =", "for n in g.nodes(): # get label by species name", "expensive than just keeping track of the # which new", "for (u, v) in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight", "if \"to_image\" in d: to_image = d[\"to_jimage\"] else: to_image =", "for format) \"\"\" if isinstance(molecule, MoleculeGraph): # just make a", "find_rings will only return those rings including the specified sites.", "pre-existing or pre-defined edges with optional edge parameters. :param molecule:", "json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d) return sg def __rmul__(self, other):", "order to prevent problems with misdirected edges, both graphs are", "d[\"id\"] if \"key\" in d: del d[\"key\"] # ensure images", "for idx, site in enumerate(self.structure): centre_sp = site.species_string connected_sites =", "to connect the atoms. 2. A string name. The molecule", "The X-C bond indicates the directionality to connect the atoms.", "# approach has many benefits, but made it more difficult", "u, v, d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k))", "neighbor[\"site_index\"]: from_index = neighbor[\"site_index\"] to_index = n else: from_index =", "v_expec_image)) # normalize direction if new_v < new_u: new_u, new_v", "multiple edges). g = self.graph.copy() g.graph = {\"nodesep\": 10.0, \"dpi\":", "first atom must be a DummySpecies X, indicating the position", "is a class for annotating a Molecule with bond information,", "\"\\n\" edges = list(g.edges(data=True)) # sort edges for consistent ordering", "from_index, to_index, key in remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index, key=key)", "site in enumerate(self.structure): s = PeriodicSite( site.species, site.coords + v,", "defined that correspond to Sites in Molecule). :param molecule (Molecule):", "bonds from different Molecules, with node indices replaced by Species", "\"exchange_constant\" :param edge_weight_units (str): name of edge weight units e.g.", "to_index, **edge_properties) def insert_node( self, i, species, coords, validate_proximity=False, site_properties=None,", "more MoleculeGraphs by breaking a set of bonds. This function", "edge_weight_units=\"\") for edge, props in edges.items(): try: from_index = edge[0]", "weight = None nodes = sg.graph.nodes if not (from_index in", "Structure :param jimage: lattice vector of site :return: list of", "be X-CH3, where X is the first site and C", "not designed for use with structures! \" \"Please choose another", "periodic image edges, # these can be confusing due to", "other_sorted.graph.edges(keys=False, data=True) } else: edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for", "= sorted(list(subg.nodes)) # Molecule indices are essentially list-based, so node", "= None if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del", "0), but making this # assumption simplifies logic later if", "edges using node colors color_u = g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"]", "key mapping = {tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule} other_sorted", "can be safely added. :param site_properties: Site properties for Molecule", "on opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage", "from_jimage = from_jimage, to_jimage # constrain all from_jimages to be", "edges using node colors color_u = g.nodes[u][\"fillcolor\"] color_v = g.nodes[v][\"fillcolor\"]", "duplicates. :return: list of unique Molecules in Structure \"\"\" #", "= g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u, color_v) if edge_colors else \"#000000\"", "As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX", "0, 0))) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other", "node indices are in terms of the MoleculeGraph this method", "# TODO: actually figure out how to distribute charge if", "in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def", "= { (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d in other.graph.edges(keys=False,", "edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data)", "similar to site properties edge_properties = edge_properties or {} if", "in range(len(self.structure) - 1): if j < i: mapping[j] =", "len(edge_label)])) else: print_weights = False s = header + \"\\n\"", ":Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from NetworkX to", "atoms. 2. A string name. The molecule will be obtained", "underlying Structures are ordered differently. :param other: StructureGraph :param strict:", "in graph theory terms) including the index found in the", "other): \"\"\" Two StructureGraphs are equal if they have equal", "0 # relabel nodes in graph to match mapping new_graph", "stats.minmax[0], \"max\": stats.minmax[1], \"mean\": stats.mean, \"variance\": stats.variance, } def types_of_coordination_environments(self,", "such that we have # full periodic boundary conditions #", "an easy way to extract # molecules (and not, e.g.,", "duplicates.append(edge) for duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return", "Molecule. If there is no cycle including an index, the", "objects for each subgraph molecules = [] for subgraph in", "pass class MoleculeGraph(MSONable): \"\"\" This is a class for annotating", "finite precision leading to incorrect image v_expec_image = np.around(v_expec_frac, decimals=3)", "weight=neighbor[\"weight\"] if weights else None, warn_duplicates=False, ) return sg @property", "key. :return: \"\"\" self.molecule.insert( i, species, coords, validate_proximity=validate_proximity, properties=site_properties, )", "between the attached functional group and the nearest neighbor site.", "that site can be safely added. :param site_properties: Site properties", "graph \"\"\" return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, weight=None,", "all_weights = [d.get(\"weight\", None) for u, v, d in self.graph.edges(data=True)]", "= \"dashed\" if hide_image_edges: edges_to_delete.append((u, v, k)) # don't show", "find all possible fragments, aka connected induced subgraphs frag_dict =", "= [] for idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = \"\".join(sorted(mycomp))", "0)))) return s def __str__(self): s = \"Structure Graph\" s", "3, 3) # make undirected to find connected subgraphs supercell_sg.graph", "mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor[\"weight\"], warn_duplicates=False, ) duplicates = [] for", "\"to_jimage\" in d: d[\"to_jimage\"] = tuple(d[\"to_jimage\"]) if \"from_jimage\" in d:", "a convenient key try: mapping = {tuple(site.coords): self.molecule.index(site) for site", "Multiplication works by looking for the expected position # of", "scale_matrix = np.array(scaling_matrix, np.int16) if scale_matrix.shape != (3, 3): scale_matrix", "to_jimage: edge_index = i self.graph.remove_edge(to_index, from_index, edge_index) else: raise ValueError(", "note: a different approach was also trialed, using # a", "d = { \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": new_structure.as_dict(), \"graphs\":", "for each subgraph molecules = [] for subgraph in unique_subgraphs:", "can be different and StructureGraphs can still be considered equal.", "v, d.copy() new_d[\"to_jimage\"] = tuple(np.multiply(-1, d[\"to_jimage\"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u,", "\"Å\" or \"eV\" :return (MoleculeGraph): \"\"\" if edge_weight_name and (edge_weight_units", "\"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__str__()) s += \"\\nGraph: {}\\n\".format(self.name)", "in unique_subgraphs: coords = [supercell_sg.structure[n].coords for n in subgraph.nodes()] species", "= nx.get_node_attributes(new_graph, \"coords\") raw_props = nx.get_node_attributes(new_graph, \"properties\") properties = {}", "is None. If any edge properties are to be changed,", "of unique Molecules in Structure \"\"\" # creating a supercell", "scheme for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) #", "neighbors: # local_env will always try to add two edges", "[] # tuple of (u, v, attr_dict) # list of", "add multiple # edges if appropriate if to_jimage is None:", "Same as Structure.sort(), also remaps nodes in graph. :param key:", "the sets of edges. This is returned with key 'dist'.", "= max(coords[:, 1]) - min(coords[:, 1]) + 100 c =", "weight = alterations[(u, v)][\"weight\"] del alterations[(u, v)][\"weight\"] edge_properties = alterations[(u,", "on each other). If visualization is difficult to interpret, `hide_image_edges`", "import warnings from collections import defaultdict, namedtuple from itertools import", "tuple(d[\"from_jimage\"]) @classmethod def with_empty_graph(cls, structure, name=\"bonds\", edge_weight_name=None, edge_weight_units=None): \"\"\" Constructor", "returned. :return: dict {index:cycle}. Each entry will be a ring", "creating a supercell, intelligently joining together edges that lie on", "in prop_set.keys(): if prop in properties: properties[prop].append(prop_set[prop]) else: properties[prop] =", "Extract a dictionary summarizing the types and weights of edges", "dist\") def _compare(g1, g2, i1, i2): \"\"\" Helper function called", "units e.g. \"Å\" or \"eV\" :return (MoleculeGraph): \"\"\" if edge_weight_name", "self.graph.out_edges(n, data=True)] in_edges = [(u, v, d, \"in\") for u,", "different Molecules, with node indices replaced by Species strings, will", "'mean', 'std_dev' \"\"\" all_weights = [d.get(\"weight\", None) for u, v,", "other: MoleculeGraph :return (bool): \"\"\" # sort for consistent node", "the different co-ordination environments present in the graph. :param anonymous:", ":return: \"\"\" # ensure that edge exists before attempting to", "s = \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s +=", "for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d) in", "node in self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node]", "be None if not defined. :param n: index of Site", "in enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors: # local_env will always", "if weight_labels: units = g.graph.get(\"edge_weight_units\", \"\") if d.get(\"weight\"): d[\"label\"] =", "There are three options: 1. Providing an actual molecule as", "new to_jimage # use np.around to fix issues with finite", "in_edges = list(self.graph.in_edges(n, data=True)) for u, v, d in out_edges", "StructureGraphs (ignoring edge weights), and is defined by 1 -", "modifies that, and returns two or more new MoleculeGraph objects.", "dictionary of properties, including weight. If None, then the algorithm", "not None: self.graph[from_index][to_index][0][\"weight\"] = new_weight if new_edge_properties is not None:", "name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") for edge, props in edges.items(): try: from_index", "s = \"Molecule Graph\" s += \"\\nMolecule: \\n{}\".format(self.molecule.__repr__()) s +=", "# Subtracting 1 because the dummy atom X should not", "g in unique_subgraphs ] if not any(already_present): unique_subgraphs.append(subgraph) # get", "= np.multiply(-1, to_jimage) to_jimage = tuple(map(int, np.add(to_jimage, jimage))) site_d =", "a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param", "show edge directions d[\"arrowhead\"] = \"none\" # only add labels", "else: jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return {", "dist=dist) connected_sites.add(connected_site) # return list sorted by closest sites first", "also be drawn with networkx's in-built graph drawing methods, but", "ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for u, v, data in", "= nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph, \"specie\") coords = nx.get_node_attributes(new_graph,", "to distribute charge if 0 in nodes: charge = self.molecule.charge", "StructureGraph, returns a StructureGraph object with an empty graph (no", "d[\"graphs\"]) def __mul__(self, scaling_matrix): \"\"\" Replicates the graph, creating a", "# Using to_directed() will mean that each cycle always appears", "of this class worked even if # from_jimage != (0,", "This is a class for annotating a Structure with bond", "pymatgen.core import Lattice, Molecule, PeriodicSite, Structure from pymatgen.core.structure import FunctionalGroups", "sorted(labels, reverse=True) if anonymous: mapping = {centre_sp: \"A\"} available_letters =", "to site v # and another form site v to", "k, d in g.edges(keys=True, data=True): if (u, v, d[\"to_jimage\"]) in", "(c[0] * 0.299 + c[1] * 0.587 + c[2] *", "d) in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict())", "boundaries :param edge_colors (bool): if True, use node colors to", "\"\"\" if isinstance(molecule, MoleculeGraph): # just make a copy from", "if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"] self.add_edge(", "of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] \"\"\" motifs = set()", "= molecule.get_centered_molecule() molecules.append(molecule) return molecules class MolGraphSplitError(Exception): \"\"\" Raised when", "not None: for edge in edges: try: self.add_edge( edge[\"from_index\"], edge[\"to_index\"],", "mycomp = [] for idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp =", "index of site connecting to :param weight (float): e.g. bond", "that go through periodic boundaries :param edge_colors (bool): if True,", "to split into two disconnected subgraphs \"\"\" pass class MoleculeGraph(MSONable):", "edge has been added green_edges.append((u, v, k)) for u, v,", "for subgraph in molecule_subgraphs: for n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie))", "\"specie\") coords = nx.get_node_attributes(remapped, \"coords\") edges = {} for from_index,", "copy.deepcopy(self) sub_mols = list() # Had to use nx.weakly_connected_components because", "code adapted from Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16) if scale_matrix.shape", "not existing_edge: raise ValueError( \"Edge between {} and {} cannot", "the edge is updated. This is more # computationally expensive", "return ValueError(\"Meaningless to compare MoleculeGraphs if \" \"corresponding Molecules are", "with using a Molecule or str (when not using graph_dict).", "it should be a float. :param new_edge_properties: alter_edge does not", "__maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Production\" __date__", "will generally produce a different graph compared with using a", "of site connecting to :param from_jimage (tuple of ints): lattice", "range(atoms): grp_map[i] = i + offset return grp_map # Work", "standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0,", "(bool): if True, use node colors to color edges :param", "be an empty list. \"\"\" # Copies self.graph such that", "__date__ = \"August 2017\" ConnectedSite = namedtuple(\"ConnectedSite\", \"site, jimage, index,", "structures # molecules have to be boxed first coords =", "classes only (generally) work with structures # molecules have to", "\"properties\") properties = {} for prop_set in raw_props.values(): for prop", "None: strategy_params = {} strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp,", "list(self.graph.in_edges(n, data=True)) for u, v, d in out_edges + in_edges:", "* max([18, len(edge_label)])) else: print_weights = False s = header", "# If the atom at index is terminal if len(neighbors)", "intersection / size of the union) of the sets of", "a StructureGraph object with an empty graph (no edges, only", "'other', 'both' with edges that are present in only one", "be the next nearest atom. For example, for a methyl", "colors color_u = g.node[u][\"fillcolor\"] color_v = g.node[v][\"fillcolor\"] d[\"color_uv\"] = \"{};0.5:{};0.5\".format(color_u,", "by edge are expected to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart", "self.molecule.index(site) for site in other.molecule} except ValueError: return False other_sorted", ") mapping = {} for j in range(len(self.molecule) - 1):", "= self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise ValueError(", "idx, site in enumerate(self.structure): s = PeriodicSite( site.species, site.coords +", "that edge exists before attempting to change it if not", "and reason about. :param scaling_matrix: same as Structure.__mul__ :return: \"\"\"", "will be checked to ensure that site can be safely", "atoms to close to each other, or violate the dimensions", "in order to be used for Molecule instantiation for k,", "(keeping original lattice has # significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords,", "in edges: s += \"{:4} {:4} {:12} {:.3e}\\n\".format( u, v,", "group. NOTE: using a MoleculeGraph will generally produce a different", "sg.add_edge( from_index=n, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if weights", "node_match(n1, n2): return n1[\"specie\"] == n2[\"specie\"] def edge_match(e1, e2): if", "from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes() return sg @staticmethod def", "bond length :param warn_duplicates (bool): if True, will warn if", "position to an # existing Site in Structure kd_tree =", "image v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image - v_expec_image", "coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j in", "edge_properties=edge_props, ) else: if strategy_params is None: strategy_params = {}", "# Work is simplified if a graph is already in", "# create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self,", "molecules = [] for subgraph in unique_subgraphs: coords = [supercell_sg.structure[n].coords", "of the edge weight property of graph \"\"\" return self.graph.graph[\"edge_weight_name\"]", "new_igraph def _isomorphic(frag1, frag2): \"\"\" Internal function to check if", "not existing_edges: raise ValueError( \"Edge between {} and {} cannot", "equal. :param other: MoleculeGraph :return (bool): \"\"\" # sort for", "= [(u, v, d, \"in\") for u, v, d in", "not require that weight be altered. As such, by default,", "two nodes if new_weight is not None: self.graph[from_index][to_index][0][\"weight\"] = new_weight", "not keep_dot: os.remove(basename + \".dot\") @property def types_and_weights_of_connections(self): \"\"\" Extract", "fairly robust approach, but will treat e.g. enantiomers as being", "self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0),", "in the crystal (a duplicate defined as an isomorphic subgraph).", "= \"Structure Graph\" s += \"\\nStructure: \\n{}\".format(self.structure.__repr__()) s += \"\\nGraph:", "undirected nx.Graph objects. :param other: MoleculeGraph object to be compared.", "reference graph :param hide_unconnected_nodes: if True, hide unconnected nodes :param", "0, 0) else \"to {}\".format((to_image)) d[\"arrowhead\"] = \"normal\" if d[\"headlabel\"]", "will only return those rings including the specified sites. By", "subgraphs as molecules, useful for extracting molecules from periodic crystals.", "\"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return s def __repr__(self): s", "uses MoleculeGraph.break_edge repeatedly to create disjoint graphs (two or more", "d.get(\"weight\", None) if (v, to_jimage) not in connected_site_images: connected_site =", "method for format) \"\"\" if isinstance(molecule, MoleculeGraph): # just make", "in c_lat: # create a map of nodes from original", "for combination in combinations(graph.nodes, ii): mycomp = [] for idx", "= [] # tuple of (u, v, k) edges_to_add =", "lattice images present, but should hopefully be # easier to", "range(len(self.molecule) - 1): if j < i: mapping[j] = j", "v)] if \"weight\" in edge_props.keys(): weight = edge_props[\"weight\"] del edge_props[\"weight\"]", "(usually only used for debugging, edges to periodic images always", "of MultiDiGraph), with node indices # representing both site index", "< to_index and from_jimage becomes (0, 0, 0). :param from_index:", "Class from pymatgen.analysis.local_env. :param bond_order: A specified bond order to", "drawing # graphs using matplotlib, these also work here. However,", "= 0 else: for i, properties in existing_edges.items(): if properties[\"to_jimage\"]", "edges to periodic images always appear as dashed lines) :param", "direction, from_index, from_jimage can be swapped with to_index, to_jimage. However,", "\"\\nStructure: \\n{}\".format(self.structure.__repr__()) s += \"\\nGraph: {}\\n\".format(self.name) s += self._edges_to_string(self.graph) return", "in other_sorted.graph.edges(keys=False, data=True) } else: edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie))", "If constructing this class manually, use the `with_empty_graph` method or", "or `with_local_env_strategy` method (using an algorithm provided by the `local_env`", "in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy=\"omit\") return { \"all_weights\": all_weights,", "args = [algo, \"-T\", extension, basename + \".dot\"] rs =", "change behavior of graph, # they're just for book-keeping graph", "[] for fragment in unique_frag_dict[key]: mapping = {e: i for", "graph new_g = nx.MultiDiGraph() for new_graph in new_graphs: new_g =", "e)) cycles_edges.append(edges) return cycles_edges def get_connected_sites(self, n): \"\"\" Returns a", "* np.eye(3), np.int16) else: # TODO: test __mul__ with full", "= [] for subgraph in molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph,", "between two MoleculeGraphs (ignoring edge weights), and is defined by", "What the code will do is to remove the index", "max([18, len(edge_label)])) else: print_weights = False s = header +", "constructing this class manually, use the `with_empty_graph` method or `with_local_env_strategy`", "However, # a dedicated tool like GraphViz allows for much", "nodes = sg.graph.nodes if not (from_index in nodes and to_index", "ensure that site can be safely added. :param site_properties: Site", "from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None, ): \"\"\" Add edge to", "a functional group. This method also amends self.graph to incorporate", "for site in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])", "edges (u, v) matched by edges (v, u) undirected =", "subgraphs frag_dict = {} for ii in range(1, len(self.molecule)): for", "\"bond\" does not necessarily have to be a chemical bond,", "return new instance of StructureGraph with supercell d = {", "of node u as a reference, # get relative Cartesian", "= strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name=\"bonds\", edge_weight_name=\"weight\", edge_weight_units=\"\") # NearNeighbor", "v_present new_d = d.copy() # node now inside supercell new_d[\"to_jimage\"]", "i + offset return grp_map # Work is simplified if", "coords[node] = self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species, \"specie\") nx.set_node_attributes(self.graph,", "using a Molecule or str (when not using graph_dict). :param", "return self.graph.graph[\"edge_weight_units\"] def add_edge( self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None,", "other.graph.edges(keys=False, data=True) } if len(edges) == 0 and len(edges_other) ==", "incrementing from 0 mapping = {} for i, n in", ":return: \"\"\" self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current", "if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: for i,", "insertion, NOT before. Each dict should at least have a", "with return code {}.\".format(algo, rs.returncode)) if not keep_dot: os.remove(basename +", "if not (from_index in nodes and to_index in nodes): raise", "generally produce a different graph compared with using a Molecule", "a supercell, intelligently joining together edges that lie on periodic", "to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node( self,", "{ \"@module\": self.__class__.__module__, \"@class\": self.__class__.__name__, \"structure\": self.structure.as_dict(), \"graphs\": json_graph.adjacency_data(self.graph), }", "be added to the MoleculeGraph. These edges must include the", "original. Currently, this function naively assigns the charge of the", "# Get indices now occupied by functional group # Subtracting", "lengths). \"\"\" def get_label(u, v): u_label = self.structure[u].species_string v_label =", "self.graph.to_undirected() disconnected.remove_node(index) for neighbor in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2]))", "mapping[tuple(site.frac_coords)]) edges = {(u, v, d.get(\"to_jimage\", (0, 0, 0))) for", "existing_edges: for i, properties in existing_edges.items(): if properties[\"to_jimage\"] == to_jimage:", "\"variance\": stats.variance, } def types_of_coordination_environments(self, anonymous=False): \"\"\" Extract information on", "else None if v_present is not None: new_u = u", "j < i: mapping[j] = j else: mapping[j] = j", "if len(self.molecule) != len(other.molecule): return False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula:", "{:.3e}\\n\".format( u, v, str(data.get(\"to_jimage\", (0, 0, 0))), data.get(\"weight\", 0) )", "} def types_of_coordination_environments(self, anonymous=False): \"\"\" Extract information on the different", "0, 0): d[\"style\"] = \"dashed\" if hide_image_edges: edges_to_delete.append((u, v, k))", "be altered. As such, by default, this is None. If", "(e.g. string 'Fe-O') and values which are a list of", "single submolecule. A later effort will be to actually accurately", "images = [1, 0, 0], [0, 1, 0], [0, 0,", "to original # lattice (keeping original lattice has # significant", "and the nearest neighbor site. Defaults to 1. :param graph_dict:", "coords_are_cartesian: Whether coordinates are cartesian. Defaults to False. :param validate_proximity:", "not trying to add a duplicate edge # there should", "if user doesn't specify # will try and detect all", "are three options: 1. Providing an actual molecule as the", "Determine if the MoleculeGraph is connected. If it is not,", "strict: if False, will compare bonds from different Molecules, with", "so origin is at center of mass molecule = molecule.get_centered_molecule()", "a copy from input graph_data = molecule.as_dict()[\"graphs\"] self.molecule = molecule", "if {new_u, new_v} not in edges_inside_supercell: # normalize direction if", "= new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs = [] for v", "Typically, this means molecules will need to have the same", "# apply Molecule ordering to graph mapping = {idx: self.molecule.index(site)", "if f1_comp_dict != f2_comp_dict: return False if IGRAPH_AVAILABLE: ifrag1 =", "one from site u to site v # and another", "resulting MoleculeGraph is a disconnected subgraph of the original. Currently,", "for isomorphism for subgraph in molecule_subgraphs: for n in subgraph:", "test for isomorphism for subgraph in molecule_subgraphs: for n in", "prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index,", "As such, by default, this is None. If any edge", "for format) \"\"\" if isinstance(structure, StructureGraph): # just make a", "of the dissimilarity between two StructureGraphs (ignoring edge weights), and", "in the graph. :param anonymous: if anonymous, will replace specie", "cycles_nodes = unique_cycles else: for i in including: for cycle", "# are connected to nodes on opposite side v_expec_frac =", "= copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError(\"Can't find functional group in", "subgraph in unique_subgraphs: coords = [supercell_sg.structure[n].coords for n in subgraph.nodes()]", "0, 0)] new_periodic_images = [] orig_lattice = self.structure.lattice # use", "edge_weight_name (str): name of edge weights, e.g. \"bond_length\" or \"exchange_constant\"", "(from_index, to_index)\" \"tuples\") if props is not None: if \"weight\"", "label = get_label(u, v) types[label].append(d[\"weight\"]) return dict(types) @property def weight_statistics(self):", "found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert back to molecule", "other: StructureGraph :param strict: if False, will compare bonds from", "nx.set_node_attributes(self.graph, coords, \"coords\") nx.set_node_attributes(self.graph, properties, \"properties\") def alter_edge(self, from_index, to_index,", "return False other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges =", "use_weights (bool): If True, only treat subgraphs as isomorphic if", "self.graph.get_edge_data(from_index, to_index) existing_reverse = None if to_jimage is None: raise", "other). If visualization is difficult to interpret, `hide_image_edges` can help,", "becomes (0, 0, 0). :param from_index: index of site connecting", "Add edge to graph. Since physically a 'bond' (or other", "# relabel nodes in graph to match mapping new_graph =", "be added if nodes are not\" \" present in the", "replacement\" \"cannot occur at an atom within a ring\" \"structure.\"", "in d: to_image = d[\"to_jimage\"] else: to_image = (0, 0,", "edges with their periodic images (usually only used for debugging,", "neighbor[2])) keep = max(sizes, key=lambda x: sizes[x]) for i in", "warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0, 0), to_index=neighbor[\"site_index\"], to_jimage=neighbor[\"image\"], weight=neighbor[\"weight\"] if", ") dist = min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist", "using one of a list of strategies defined in pymatgen.analysis.local_env.", "diff(self, other, strict=True): \"\"\" Compares two StructureGraphs. Returns dict with", "check if two graph objects are isomorphic, using igraph if", "for node in self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node] = self.structure[node].coords", "as_dict method for format) \"\"\" if isinstance(molecule, MoleculeGraph): # just", "in nx.weakly_connected_components(original.graph)] for subg in subgraphs: nodes = sorted(list(subg.nodes)) #", "): \"\"\" A wrapper around Molecule.insert(), which also incorporates the", "Molecules are ordered differently. :param other: MoleculeGraph :param strict: if", "strategy_params is None: strategy_params = {} strat = strategy(**strategy_params) graph", "the graph. :return: A dictionary with keys specifying the species", "key=key) edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge),", "graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings = self.find_rings(including=[index]) if len(rings) !=", "sp not in mapping: mapping[sp] = available_letters.pop(0) centre_sp = \"A\"", "1 else: f1_comp_dict[node[1][\"specie\"]] += 1 for node in f2_nodes: if" ]
[ "from . import image from . import container from .", ". import image from . import container from . import", "import image from . import container from . import system" ]
[ "Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): #", "return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): # return", "= Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\") def article_create(request):", "if form.is_valid(): #save article to DB instance = form.save(commit=False) instance.author", "{'article': article}) @login_required(login_url=\"/accounts/login\") def article_create(request): if request.method == 'POST': form", "Articles(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def", "form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save article to DB", "form.is_valid(): #save article to DB instance = form.save(commit=False) instance.author =", "instance.author = request.user instance.save( ) return redirect ('articles:list') else: form", "return render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\") def article_create(request): if request.method", "= forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save article to DB instance", "DB instance = form.save(commit=False) instance.author = request.user instance.save( ) return", "{'articles': articles}) def article_detail(request, slug): # return HttpResponse(slug) article =", "render, redirect from django.http import HttpResponse from .models import Article", ") return redirect ('articles:list') else: form = forms.CreateArticle() return render(request,", "article_detail(request, slug): # return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request,", "import login_required from . import forms def Articles(request): articles =", "return redirect ('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html',", "forms def Articles(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles':", ". import forms def Articles(request): articles = Article.objects.all().order_by('date') return render(request,", "request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save", "# return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article':", "Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\") def article_create(request): if", "django.contrib.auth.decorators import login_required from . import forms def Articles(request): articles", "from django.http import HttpResponse from .models import Article from django.contrib.auth.decorators", "Article from django.contrib.auth.decorators import login_required from . import forms def", "login_required from . import forms def Articles(request): articles = Article.objects.all().order_by('date')", "= Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug):", "def article_detail(request, slug): # return HttpResponse(slug) article = Article.objects.get(slug=slug) return", "articles}) def article_detail(request, slug): # return HttpResponse(slug) article = Article.objects.get(slug=slug)", "@login_required(login_url=\"/accounts/login\") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST,", "'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\") def article_create(request): if request.method == 'POST':", "to DB instance = form.save(commit=False) instance.author = request.user instance.save( )", "def Articles(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles})", "'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save article to", "import render, redirect from django.http import HttpResponse from .models import", "HttpResponse from .models import Article from django.contrib.auth.decorators import login_required from", "render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\") def article_create(request): if request.method ==", "redirect ('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', {'form':form})", "= form.save(commit=False) instance.author = request.user instance.save( ) return redirect ('articles:list')", "if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid():", "django.shortcuts import render, redirect from django.http import HttpResponse from .models", "article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\") def", "return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article': article})", "from django.shortcuts import render, redirect from django.http import HttpResponse from", "== 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save article", "render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): # return HttpResponse(slug)", "def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES)", "request.user instance.save( ) return redirect ('articles:list') else: form = forms.CreateArticle()", "import forms def Articles(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html',", "article to DB instance = form.save(commit=False) instance.author = request.user instance.save(", "import Article from django.contrib.auth.decorators import login_required from . import forms", "article}) @login_required(login_url=\"/accounts/login\") def article_create(request): if request.method == 'POST': form =", "article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if", "from django.contrib.auth.decorators import login_required from . import forms def Articles(request):", "django.http import HttpResponse from .models import Article from django.contrib.auth.decorators import", "from . import forms def Articles(request): articles = Article.objects.all().order_by('date') return", ".models import Article from django.contrib.auth.decorators import login_required from . import", "articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request,", "instance.save( ) return redirect ('articles:list') else: form = forms.CreateArticle() return", "= request.user instance.save( ) return redirect ('articles:list') else: form =", "request.FILES) if form.is_valid(): #save article to DB instance = form.save(commit=False)", "instance = form.save(commit=False) instance.author = request.user instance.save( ) return redirect", "HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url=\"/accounts/login\")", "redirect from django.http import HttpResponse from .models import Article from", "form.save(commit=False) instance.author = request.user instance.save( ) return redirect ('articles:list') else:", "import HttpResponse from .models import Article from django.contrib.auth.decorators import login_required", "slug): # return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html',", "from .models import Article from django.contrib.auth.decorators import login_required from .", "forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save article to DB instance =", "#save article to DB instance = form.save(commit=False) instance.author = request.user", "'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): # return HttpResponse(slug) article" ]
[ "sifter.grammar from sifter.grammar.lexer import tokens import sifter.handler import logging __all__", "RFC 5228 unless stated otherwise. import ply.yacc import sifter.grammar from", "%d must come before any \" \"other non-REQUIRE commands\" %", "p[0].insert(0, p[1]) def p_stringlist_single(p): \"\"\"stringlist : string\"\"\" p[0] = [", ": \"\"\" p[0] = sifter.grammar.CommandList() def p_command(p): \"\"\"command : IDENTIFIER", "can't be in the block of another command if any(command.RULE_IDENTIFIER", "')'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in test list that", "is None: log = logging.getLogger(\"sifter\") log.error((\"No handler registered for command", "] def p_argument_stringlist(p): \"\"\"argument : '[' stringlist ']'\"\"\" p[0] =", "def p_commands_list(p): \"\"\"commands : commands command\"\"\" p[0] = p[1] #", "stringlist ']'\"\"\" p[0] = p[2] def p_argument_string(p): \"\"\"argument : string\"\"\"", "(p[1], p.lineno(1)))) raise SyntaxError def p_block(p): \"\"\"block : '{' commands", "= p[3] else: p[0]['tests'] = [ p[2] ] def p_testlist_error(p):", "%d\" % (p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests,", "stringlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def p_stringlist_single(p): \"\"\"stringlist :", "# which means it can't be in the block of", "logging.getLogger(\"sifter\") log.error((\"Syntax error in command block that starts on line", "logging.getLogger(\"sifter\") log.error((\"REQUIRE command on line %d must come before any", "3.2: REQUIRE command must come before any other commands, #", "line %d\" % p.lineno(1))) raise SyntaxError def p_stringlist_list(p): \"\"\"stringlist :", "must come before any \" \"other non-REQUIRE commands\" % p.lineno(2)))", "that starts on line %d\" % p.lineno(1))) raise SyntaxError def", "',' testlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def p_testlist_single(p): \"\"\"testlist", "in command block that starts on line %d\" % (p.lineno(1),)))", "| argumentlist '(' testlist ')'\"\"\" p[0] = { 'args' :", "def p_arguments(p): \"\"\"arguments : argumentlist | argumentlist test | argumentlist", "any other commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER !=", "None: log = logging.getLogger(\"sifter\") log.error((\"No handler registered for command '%s'", "on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError p[0] =", "on line %d\" % p.lineno(1))) raise SyntaxError def p_stringlist_list(p): \"\"\"stringlist", "commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for", "if any(command.RULE_IDENTIFIER != 'REQUIRE' for command in p[0].commands): log =", "before any other commands, # which means it can't be", "p.lineno(2))) raise SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands : \"\"\" p[0]", "the block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for", "logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on line %d must follow an IF/ELSIF", "string ',' stringlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def p_stringlist_single(p):", "= logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on line %d must follow an", "argument\"\"\" p[0] = p[1] p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\"", "= p[1] p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\" p[0] =", "p[0].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command on line %d must", "before any other commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER", "def p_stringlist_error(p): \"\"\"argument : '[' error ']'\"\"\" log = logging.getLogger(\"sifter\")", "len(p) > 2: if p[2] == '(': p[0]['tests'] = p[3]", "p[2] ] def p_testlist_error(p): \"\"\"arguments : argumentlist '(' error ')'\"\"\"", "line %d must follow an IF/ELSIF \" \"command\" % p.lineno(2)))", "come before any other commands, # which means it can't", "= handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p): \"\"\"testlist : test ',' testlist\"\"\"", "must come before any other commands, # which means it", "log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command block that starts", ": commands command\"\"\" p[0] = p[1] # section 3.2: REQUIRE", "\"\"\"command : IDENTIFIER error ';' | IDENTIFIER error block\"\"\" log", "log.error((\"Syntax error in command definition after %s on line %d\"", "%d)\" % (p.lineno(2)))) raise SyntaxError p[0] = p[2] def p_block_error(p):", "command on line %d must come before any \" \"other", "registered for command '%s' on line %d\" % (p[1], p.lineno(1))))", "p[0] = p[1] p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\" p[0]", "raise SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist : argumentlist argument\"\"\" p[0] =", "p_argument_tag(p): \"\"\"argument : TAG\"\"\" p[0] = sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument", "sections in RFC 5228 unless stated otherwise. import ply.yacc import", "in command definition after %s on line %d\" % (p[1],", "p_argument_stringlist(p): \"\"\"argument : '[' stringlist ']'\"\"\" p[0] = p[2] def", "('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'): log =", "p[0] = p[3] p[0].insert(0, p[1]) def p_testlist_single(p): \"\"\"testlist : test\"\"\"", "p[0]['tests'] = p[3] else: p[0]['tests'] = [ p[2] ] def", "log.error((\"Syntax error in command block that starts on line %d\"", "\"\"\"block : '{' commands '}' \"\"\" # section 3.2: REQUIRE", "IDENTIFIER arguments ';' | IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\", p[1], p[2],", "2: if p[2] == '(': p[0]['tests'] = p[3] else: p[0]['tests']", "sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument : '[' error ']'\"\"\" log =", "[ p[1] ] def p_argument_stringlist(p): \"\"\"argument : '[' stringlist ']'\"\"\"", "',' stringlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def p_stringlist_single(p): \"\"\"stringlist", "% (p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests) def", "<gh_stars>0 # Parser based on RFC 5228, especially the grammar", "ply.yacc import sifter.grammar from sifter.grammar.lexer import tokens import sifter.handler import", ": test\"\"\" p[0] = [ p[1] ] def p_argument_stringlist(p): \"\"\"argument", "means it can't be in the block of another command", "handler = sifter.handler.get('test', p[1]) if handler is None: log =", "SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands : \"\"\" p[0] = sifter.grammar.CommandList()", "p[2]) tests = p[2].get('tests') handler = sifter.handler.get('test', p[1]) if handler", "p[0] = p[1] def p_argument_tag(p): \"\"\"argument : TAG\"\"\" p[0] =", "import sifter.grammar from sifter.grammar.lexer import tokens import sifter.handler import logging", "IDENTIFIER error block\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command", "in p[2].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command not allowed inside", "error ';' | IDENTIFIER error block\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax", "treat all single strings as a string list p[0] =", "== 'REQUIRE' for command in p[2].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE", "[] def p_test(p): \"\"\"test : IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1], p[2])", "= logging.getLogger(\"sifter\") log.error((\"Syntax error in test list that starts on", "\"\"\" # section 3.2: REQUIRE command must come before any", "!= ';': block = p[3] handler = sifter.handler.get('command', p[1]) if", "not in ('IF', 'ELSIF'): log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on", "command on line %d must follow an IF/ELSIF \" \"command\"", "another ELSIF elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not", "p[1] ] def p_argument_number(p): \"\"\"argument : NUMBER\"\"\" p[0] = p[1]", "';' | IDENTIFIER error block\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error", "p_command(p): \"\"\"command : IDENTIFIER arguments ';' | IDENTIFIER arguments block\"\"\"", "| argumentlist test | argumentlist '(' testlist ')'\"\"\" p[0] =", "')'\"\"\" p[0] = { 'args' : p[1], } if len(p)", "\" \"command\" % p.lineno(2))) raise SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands", "% (p.lineno(2)))) raise SyntaxError p[0] = p[2] def p_block_error(p): \"\"\"block", "SyntaxError # section 3.1: ELSIF and ELSE must follow IF", "starts on line %d\" % (p.lineno(1),))) raise SyntaxError def p_arguments(p):", "command not allowed inside of a block (line %d)\" %", ": NUMBER\"\"\" p[0] = p[1] def p_argument_tag(p): \"\"\"argument : TAG\"\"\"", "p[1]) if handler is None: log = logging.getLogger(\"sifter\") log.error((\"No handler", "SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p): \"\"\"testlist : test", "if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'): log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE", "'REQUIRE' for command in p[0].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command", "REQUIRE command must come before any other commands, # which", "command must come before any other commands, # which means", "log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on line %d must follow", "must follow IF or another ELSIF elif p[2].RULE_IDENTIFIER in ('ELSIF',", ": test ',' testlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def", "% (p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests, block=block)", "log.error((\"REQUIRE command not allowed inside of a block (line %d)\"", ": string ',' stringlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def", "= [ p[1] ] def p_argument_stringlist(p): \"\"\"argument : '[' stringlist", "in RFC 5228 unless stated otherwise. import ply.yacc import sifter.grammar", "command block that starts on line %d\" % (p.lineno(1),))) raise", "p_block(p): \"\"\"block : '{' commands '}' \"\"\" # section 3.2:", "3.2: REQUIRE command must come before any other commands if", "% (p.lineno(1),))) raise SyntaxError def p_arguments(p): \"\"\"arguments : argumentlist |", "'args' : p[1], } if len(p) > 2: if p[2]", "NUMBER\"\"\" p[0] = p[1] def p_argument_tag(p): \"\"\"argument : TAG\"\"\" p[0]", "{ 'args' : p[1], } if len(p) > 2: if", "'REQUIRE' for command in p[2].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command", "p[1], p[2]) tests = p[2].get('tests') handler = sifter.handler.get('test', p[1]) if", "defined in section 8. All # references are to sections", "None: log = logging.getLogger(\"sifter\") log.error((\"No handler registered for test '%s'", "single strings as a string list p[0] = [ p[1]", "tests = p[2].get('tests') block = None if p[3] != ';':", "\"\"\"test : IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1], p[2]) tests = p[2].get('tests')", "def p_command_error(p): \"\"\"command : IDENTIFIER error ';' | IDENTIFIER error", "# for simplicity, we treat all single strings as a", "def p_command(p): \"\"\"command : IDENTIFIER arguments ';' | IDENTIFIER arguments", "non-REQUIRE commands\" % p.lineno(2))) raise SyntaxError # section 3.1: ELSIF", "%s on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError def", "block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command", "handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p): \"\"\"testlist : test ',' testlist\"\"\" p[0]", "raise SyntaxError # section 3.1: ELSIF and ELSE must follow", "p[3]) tests = p[2].get('tests') block = None if p[3] !=", "logging.getLogger(\"sifter\") log.error((\"Syntax error in test list that starts on line", "% p.lineno(2))) raise SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands : \"\"\"", "= p[3] handler = sifter.handler.get('command', p[1]) if handler is None:", "= p[3] p[0].insert(0, p[1]) def p_stringlist_single(p): \"\"\"stringlist : string\"\"\" p[0]", "p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p): \"\"\"testlist", "p[0] = [ p[1] ] def p_argument_number(p): \"\"\"argument : NUMBER\"\"\"", ": '{' commands '}' \"\"\" # section 3.2: REQUIRE command", "log.error((\"ELSIF/ELSE command on line %d must follow an IF/ELSIF \"", "p_command_error(p): \"\"\"command : IDENTIFIER error ';' | IDENTIFIER error block\"\"\"", "based on RFC 5228, especially the grammar as defined in", "def p_stringlist_list(p): \"\"\"stringlist : string ',' stringlist\"\"\" p[0] = p[3]", "p[3] != ';': block = p[3] handler = sifter.handler.get('command', p[1])", "test ',' testlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def p_testlist_single(p):", "logging.getLogger(\"sifter\") log.error((\"REQUIRE command not allowed inside of a block (line", ": IDENTIFIER error ';' | IDENTIFIER error block\"\"\" log =", "p[1] ] def p_argument_stringlist(p): \"\"\"argument : '[' stringlist ']'\"\"\" p[0]", "']'\"\"\" p[0] = p[2] def p_argument_string(p): \"\"\"argument : string\"\"\" #", "(p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p):", "'{' error '}'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command", "ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands : commands command\"\"\" p[0] = p[1]", "section 3.1: ELSIF and ELSE must follow IF or another", "ELSIF and ELSE must follow IF or another ELSIF elif", "stated otherwise. import ply.yacc import sifter.grammar from sifter.grammar.lexer import tokens", "log.error((\"Syntax error in test list that starts on line %d\"", "'%s' on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError p[0]", "%d must follow an IF/ELSIF \" \"command\" % p.lineno(2))) raise", "for command in p[0].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command on", "def p_testlist_list(p): \"\"\"testlist : test ',' testlist\"\"\" p[0] = p[3]", "'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'): log = logging.getLogger(\"sifter\")", "'ELSIF'): log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on line %d must", "(p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) def", "p_testlist_list(p): \"\"\"testlist : test ',' testlist\"\"\" p[0] = p[3] p[0].insert(0,", "other commands, # which means it can't be in the", "(line %d)\" % (p.lineno(2)))) raise SyntaxError p[0] = p[2] def", "= logging.getLogger(\"sifter\") log.error((\"REQUIRE command on line %d must come before", ": argumentlist argument\"\"\" p[0] = p[1] p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist", "tokens import sifter.handler import logging __all__ = ('parser',) def parser(**kwargs):", "p[2] def p_block_error(p): \"\"\"block : '{' error '}'\"\"\" log =", "p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for command in", "\"\"\"arguments : argumentlist '(' error ')'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax", "any \" \"other non-REQUIRE commands\" % p.lineno(2))) raise SyntaxError #", "']'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in string list that", "block\"\"\" #print(\"COMMAND:\", p[1], p[2], p[3]) tests = p[2].get('tests') block =", "\"\"\"block : '{' error '}'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error", "a block (line %d)\" % (p.lineno(2)))) raise SyntaxError p[0] =", "log = logging.getLogger(\"sifter\") log.error((\"No handler registered for test '%s' on", "in p[0].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command on line %d", "%d\" % p.lineno(1))) raise SyntaxError def p_stringlist_list(p): \"\"\"stringlist : string", "= sifter.handler.get('command', p[1]) if handler is None: log = logging.getLogger(\"sifter\")", "if len(p) > 2: if p[2] == '(': p[0]['tests'] =", "\"\"\" p[0] = [] def p_test(p): \"\"\"test : IDENTIFIER arguments\"\"\"", "all single strings as a string list p[0] = [", "def p_argument_number(p): \"\"\"argument : NUMBER\"\"\" p[0] = p[1] def p_argument_tag(p):", "= p[2].get('tests') handler = sifter.handler.get('test', p[1]) if handler is None:", "commands\" % p.lineno(2))) raise SyntaxError # section 3.1: ELSIF and", "p[3] handler = sifter.handler.get('command', p[1]) if handler is None: log", "simplicity, we treat all single strings as a string list", "on RFC 5228, especially the grammar as defined in section", "it can't be in the block of another command if", "test\"\"\" p[0] = [ p[1] ] def p_argument_stringlist(p): \"\"\"argument :", "p[0] = [] def p_test(p): \"\"\"test : IDENTIFIER arguments\"\"\" #print(\"TEST:\",", "arguments ';' | IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\", p[1], p[2], p[3])", "p[0] = sifter.grammar.CommandList() def p_command(p): \"\"\"command : IDENTIFIER arguments ';'", "def parser(**kwargs): return ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands : commands command\"\"\"", "= logging.getLogger(\"sifter\") log.error((\"No handler registered for test '%s' on line", "if p[2] == '(': p[0]['tests'] = p[3] else: p[0]['tests'] =", "SyntaxError def p_arguments(p): \"\"\"arguments : argumentlist | argumentlist test |", "error '}'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command block", "in test list that starts on line %d\" % p.lineno(2)))", "= [] def p_test(p): \"\"\"test : IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1],", "or another ELSIF elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER", "= logging.getLogger(\"sifter\") log.error((\"Syntax error in string list that starts on", "p[1] ] def p_string(p): \"\"\"string : QUOTED_STRING\"\"\" p[0] = sifter.grammar.String(p[1])", "p[0] = sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument : '[' error ']'\"\"\"", "are to sections in RFC 5228 unless stated otherwise. import", "\"\"\" p[0] = sifter.grammar.CommandList() def p_command(p): \"\"\"command : IDENTIFIER arguments", "handler is None: log = logging.getLogger(\"sifter\") log.error((\"No handler registered for", "list that starts on line %d\" % p.lineno(2))) raise SyntaxError", "string list p[0] = [ p[1] ] def p_argument_number(p): \"\"\"argument", "p[1]) def p_testlist_single(p): \"\"\"testlist : test\"\"\" p[0] = [ p[1]", "(p.lineno(1),))) raise SyntaxError def p_arguments(p): \"\"\"arguments : argumentlist | argumentlist", "p.lineno(1))) raise SyntaxError def p_stringlist_list(p): \"\"\"stringlist : string ',' stringlist\"\"\"", "block = None if p[3] != ';': block = p[3]", "follow an IF/ELSIF \" \"command\" % p.lineno(2))) raise SyntaxError p[0].commands.append(p[2])", "line %d\" % p.lineno(2))) raise SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist :", "';': block = p[3] handler = sifter.handler.get('command', p[1]) if handler", "list p[0] = [ p[1] ] def p_argument_number(p): \"\"\"argument :", "p[3] p[0].insert(0, p[1]) def p_testlist_single(p): \"\"\"testlist : test\"\"\" p[0] =", "of another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in", "p_argument_string(p): \"\"\"argument : string\"\"\" # for simplicity, we treat all", "= p[1] # section 3.2: REQUIRE command must come before", "command in p[2].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command not allowed", "def p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\" p[0] = [] def p_test(p):", "\"\"\"commands : commands command\"\"\" p[0] = p[1] # section 3.2:", "commands command\"\"\" p[0] = p[1] # section 3.2: REQUIRE command", "be in the block of another command if any(command.RULE_IDENTIFIER ==", "for test '%s' on line %d\" % (p[1], p.lineno(1)))) raise", "in string list that starts on line %d\" % p.lineno(1)))", "logging.getLogger(\"sifter\") log.error((\"Syntax error in string list that starts on line", "= p[1] def p_argument_tag(p): \"\"\"argument : TAG\"\"\" p[0] = sifter.grammar.Tag(p[1])", "p[0] = [ p[1] ] def p_string(p): \"\"\"string : QUOTED_STRING\"\"\"", "= p[2] def p_argument_string(p): \"\"\"argument : string\"\"\" # for simplicity,", "\"\"\"testlist : test\"\"\" p[0] = [ p[1] ] def p_argument_stringlist(p):", "def p_argument_string(p): \"\"\"argument : string\"\"\" # for simplicity, we treat", "\"other non-REQUIRE commands\" % p.lineno(2))) raise SyntaxError # section 3.1:", "test '%s' on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError", "testlist\"\"\" p[0] = p[3] p[0].insert(0, p[1]) def p_testlist_single(p): \"\"\"testlist :", "any other commands, # which means it can't be in", "p_stringlist_list(p): \"\"\"stringlist : string ',' stringlist\"\"\" p[0] = p[3] p[0].insert(0,", "logging __all__ = ('parser',) def parser(**kwargs): return ply.yacc.yacc(**kwargs) def p_commands_list(p):", "in section 8. All # references are to sections in", "return ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands : commands command\"\"\" p[0] =", "% (p[1], p.lineno(1)))) raise SyntaxError def p_block(p): \"\"\"block : '{'", "if handler is None: log = logging.getLogger(\"sifter\") log.error((\"No handler registered", "raise SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands : \"\"\" p[0] =", "testlist ')'\"\"\" p[0] = { 'args' : p[1], } if", "TAG\"\"\" p[0] = sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument : '[' error", "= None if p[3] != ';': block = p[3] handler", "\"\"\"testlist : test ',' testlist\"\"\" p[0] = p[3] p[0].insert(0, p[1])", "= [ p[2] ] def p_testlist_error(p): \"\"\"arguments : argumentlist '('", "8. All # references are to sections in RFC 5228", "unless stated otherwise. import ply.yacc import sifter.grammar from sifter.grammar.lexer import", "p[0] = p[1] # section 3.2: REQUIRE command must come", "\"\"\"stringlist : string\"\"\" p[0] = [ p[1] ] def p_string(p):", "def p_commands_empty(p): \"\"\"commands : \"\"\" p[0] = sifter.grammar.CommandList() def p_command(p):", "= sifter.grammar.CommandList() def p_command(p): \"\"\"command : IDENTIFIER arguments ';' |", "ELSE must follow IF or another ELSIF elif p[2].RULE_IDENTIFIER in", "log.error((\"No handler registered for test '%s' on line %d\" %", ": \"\"\" p[0] = [] def p_test(p): \"\"\"test : IDENTIFIER", "block = p[3] handler = sifter.handler.get('command', p[1]) if handler is", "\"\"\"commands : \"\"\" p[0] = sifter.grammar.CommandList() def p_command(p): \"\"\"command :", ": p[1], } if len(p) > 2: if p[2] ==", "section 8. All # references are to sections in RFC", "test list that starts on line %d\" % p.lineno(2))) raise", "sifter.handler.get('command', p[1]) if handler is None: log = logging.getLogger(\"sifter\") log.error((\"No", "p.lineno(2))) raise SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist : argumentlist argument\"\"\" p[0]", "error ']'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in string list", "\"\"\"stringlist : string ',' stringlist\"\"\" p[0] = p[3] p[0].insert(0, p[1])", "raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) def p_command_error(p): \"\"\"command", "== 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for command in p[0].commands):", "an IF/ELSIF \" \"command\" % p.lineno(2))) raise SyntaxError p[0].commands.append(p[2]) def", "allowed inside of a block (line %d)\" % (p.lineno(2)))) raise", "come before any other commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if", "especially the grammar as defined in section 8. All #", ": '[' error ']'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in", "if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): log =", "[ p[1] ] def p_string(p): \"\"\"string : QUOTED_STRING\"\"\" p[0] =", "%d\" % (p[1], p.lineno(1)))) raise SyntaxError def p_block(p): \"\"\"block :", ": IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1], p[2]) tests = p[2].get('tests') handler", "'(' error ')'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in test", "# section 3.1: ELSIF and ELSE must follow IF or", "starts on line %d\" % p.lineno(1))) raise SyntaxError def p_stringlist_list(p):", "p[1] # section 3.2: REQUIRE command must come before any", "import tokens import sifter.handler import logging __all__ = ('parser',) def", "sifter.handler.get('test', p[1]) if handler is None: log = logging.getLogger(\"sifter\") log.error((\"No", "p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'):", "p[2].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command not allowed inside of", "% p.lineno(1))) raise SyntaxError def p_stringlist_list(p): \"\"\"stringlist : string ','", "line %d\" % (p[1], p.lineno(1)))) raise SyntaxError def p_block(p): \"\"\"block", "'(' testlist ')'\"\"\" p[0] = { 'args' : p[1], }", "on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError def p_block(p):", "p_arguments(p): \"\"\"arguments : argumentlist | argumentlist test | argumentlist '('", "command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): log", "block that starts on line %d\" % (p.lineno(1),))) raise SyntaxError", ": string\"\"\" # for simplicity, we treat all single strings", "handler(arguments=p[2]['args'], tests=tests, block=block) def p_command_error(p): \"\"\"command : IDENTIFIER error ';'", "other commands if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE'", "__all__ = ('parser',) def parser(**kwargs): return ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands", "sifter.grammar.lexer import tokens import sifter.handler import logging __all__ = ('parser',)", "any(command.RULE_IDENTIFIER != 'REQUIRE' for command in p[0].commands): log = logging.getLogger(\"sifter\")", "error in string list that starts on line %d\" %", "block\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command definition after", "p_testlist_error(p): \"\"\"arguments : argumentlist '(' error ')'\"\"\" log = logging.getLogger(\"sifter\")", "command in p[0].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command on line", "argumentlist | argumentlist test | argumentlist '(' testlist ')'\"\"\" p[0]", "line %d\" % (p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'],", "handler registered for test '%s' on line %d\" % (p[1],", "= sifter.handler.get('test', p[1]) if handler is None: log = logging.getLogger(\"sifter\")", "grammar as defined in section 8. All # references are", "# references are to sections in RFC 5228 unless stated", "IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1], p[2]) tests = p[2].get('tests') handler =", "command\"\"\" p[0] = p[1] # section 3.2: REQUIRE command must", "= logging.getLogger(\"sifter\") log.error((\"Syntax error in command definition after %s on", "p_commands_list(p): \"\"\"commands : commands command\"\"\" p[0] = p[1] # section", "raise SyntaxError def p_arguments(p): \"\"\"arguments : argumentlist | argumentlist test", "as a string list p[0] = [ p[1] ] def", "('IF', 'ELSIF'): log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on line %d", "log = logging.getLogger(\"sifter\") log.error((\"No handler registered for command '%s' on", "[ p[1] ] def p_argument_number(p): \"\"\"argument : NUMBER\"\"\" p[0] =", "p_commands_empty(p): \"\"\"commands : \"\"\" p[0] = sifter.grammar.CommandList() def p_command(p): \"\"\"command", "error ')'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in test list", "raise SyntaxError def p_block(p): \"\"\"block : '{' commands '}' \"\"\"", "log.error((\"Syntax error in string list that starts on line %d\"", "p[2] == '(': p[0]['tests'] = p[3] else: p[0]['tests'] = [", "p_stringlist_error(p): \"\"\"argument : '[' error ']'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax", "p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) def p_command_error(p):", "= logging.getLogger(\"sifter\") log.error((\"REQUIRE command not allowed inside of a block", "\"\"\"command : IDENTIFIER arguments ';' | IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\",", "to sections in RFC 5228 unless stated otherwise. import ply.yacc", "we treat all single strings as a string list p[0]", "definition after %s on line %d\" % (p[1], p.lineno(1)))) raise", "from sifter.grammar.lexer import tokens import sifter.handler import logging __all__ =", "for command in p[2].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command not", "%d\" % (p.lineno(1),))) raise SyntaxError def p_arguments(p): \"\"\"arguments : argumentlist", "# section 3.2: REQUIRE command must come before any other", "p[1]) def p_stringlist_single(p): \"\"\"stringlist : string\"\"\" p[0] = [ p[1]", "SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) def p_command_error(p): \"\"\"command :", "any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands): log = logging.getLogger(\"sifter\")", "p[2].get('tests') handler = sifter.handler.get('test', p[1]) if handler is None: log", "section 3.2: REQUIRE command must come before any other commands", "line %d\" % (p.lineno(1),))) raise SyntaxError def p_arguments(p): \"\"\"arguments :", "error block\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command definition", "p[0] = { 'args' : p[1], } if len(p) >", "p[1] def p_argument_tag(p): \"\"\"argument : TAG\"\"\" p[0] = sifter.grammar.Tag(p[1]) def", "block (line %d)\" % (p.lineno(2)))) raise SyntaxError p[0] = p[2]", "registered for test '%s' on line %d\" % (p[1], p.lineno(1))))", "tests = p[2].get('tests') handler = sifter.handler.get('test', p[1]) if handler is", "\"\"\"argument : '[' error ']'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error", "\" \"other non-REQUIRE commands\" % p.lineno(2))) raise SyntaxError # section", "IF/ELSIF \" \"command\" % p.lineno(2))) raise SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p):", "%d\" % p.lineno(2))) raise SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist : argumentlist", "'}'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command block that", ": IDENTIFIER arguments ';' | IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\", p[1],", "\"\"\"argument : NUMBER\"\"\" p[0] = p[1] def p_argument_tag(p): \"\"\"argument :", "!= 'REQUIRE' for command in p[0].commands): log = logging.getLogger(\"sifter\") log.error((\"REQUIRE", "IF or another ELSIF elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'): if", "p[2].get('tests') block = None if p[3] != ';': block =", "= sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument : '[' error ']'\"\"\" log", "\"\"\"argumentlist : \"\"\" p[0] = [] def p_test(p): \"\"\"test :", "sifter.handler import logging __all__ = ('parser',) def parser(**kwargs): return ply.yacc.yacc(**kwargs)", "p[0] = handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p): \"\"\"testlist : test ','", "'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for command in p[0].commands): log", "block=block) def p_command_error(p): \"\"\"command : IDENTIFIER error ';' | IDENTIFIER", "come before any \" \"other non-REQUIRE commands\" % p.lineno(2))) raise", "\"\"\"argumentlist : argumentlist argument\"\"\" p[0] = p[1] p[0].append(p[2]) def p_argumentlist_empty(p):", "which means it can't be in the block of another", "p[0] = handler(arguments=p[2]['args'], tests=tests, block=block) def p_command_error(p): \"\"\"command : IDENTIFIER", "'{' commands '}' \"\"\" # section 3.2: REQUIRE command must", "log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command not allowed inside of a", "p[3] else: p[0]['tests'] = [ p[2] ] def p_testlist_error(p): \"\"\"arguments", "log.error((\"No handler registered for command '%s' on line %d\" %", "def p_stringlist_single(p): \"\"\"stringlist : string\"\"\" p[0] = [ p[1] ]", "argumentlist argument\"\"\" p[0] = p[1] p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist :", "error in command block that starts on line %d\" %", "5228, especially the grammar as defined in section 8. All", "the grammar as defined in section 8. All # references", "#print(\"COMMAND:\", p[1], p[2], p[3]) tests = p[2].get('tests') block = None", "must follow an IF/ELSIF \" \"command\" % p.lineno(2))) raise SyntaxError", "references are to sections in RFC 5228 unless stated otherwise.", "p[1] p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\" p[0] = []", "def p_argumentlist_list(p): \"\"\"argumentlist : argumentlist argument\"\"\" p[0] = p[1] p[0].append(p[2])", "p_block_error(p): \"\"\"block : '{' error '}'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax", "p_argumentlist_list(p): \"\"\"argumentlist : argumentlist argument\"\"\" p[0] = p[1] p[0].append(p[2]) def", "p.lineno(1)))) raise SyntaxError def p_block(p): \"\"\"block : '{' commands '}'", "log = logging.getLogger(\"sifter\") log.error((\"REQUIRE command on line %d must come", "p[0].append(p[2]) def p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\" p[0] = [] def", "'[' stringlist ']'\"\"\" p[0] = p[2] def p_argument_string(p): \"\"\"argument :", "Parser based on RFC 5228, especially the grammar as defined", "if p[2].RULE_IDENTIFIER == 'REQUIRE': if any(command.RULE_IDENTIFIER != 'REQUIRE' for command", "p[1], } if len(p) > 2: if p[2] == '(':", "= handler(arguments=p[2]['args'], tests=tests, block=block) def p_command_error(p): \"\"\"command : IDENTIFIER error", "] def p_testlist_error(p): \"\"\"arguments : argumentlist '(' error ')'\"\"\" log", "sifter.grammar.CommandList() def p_command(p): \"\"\"command : IDENTIFIER arguments ';' | IDENTIFIER", "tests=tests) def p_testlist_list(p): \"\"\"testlist : test ',' testlist\"\"\" p[0] =", "arguments block\"\"\" #print(\"COMMAND:\", p[1], p[2], p[3]) tests = p[2].get('tests') block", "elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not in ('IF',", "\"\"\"argument : TAG\"\"\" p[0] = sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument :", "otherwise. import ply.yacc import sifter.grammar from sifter.grammar.lexer import tokens import", "def p_testlist_single(p): \"\"\"testlist : test\"\"\" p[0] = [ p[1] ]", "raise SyntaxError p[0] = p[2] def p_block_error(p): \"\"\"block : '{'", "def p_block(p): \"\"\"block : '{' commands '}' \"\"\" # section", "handler registered for command '%s' on line %d\" % (p[1],", "a string list p[0] = [ p[1] ] def p_argument_number(p):", "import ply.yacc import sifter.grammar from sifter.grammar.lexer import tokens import sifter.handler", "log = logging.getLogger(\"sifter\") log.error((\"Syntax error in string list that starts", "None if p[3] != ';': block = p[3] handler =", "argumentlist '(' error ')'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in", "= { 'args' : p[1], } if len(p) > 2:", "raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests) def p_testlist_list(p): \"\"\"testlist :", "%d\" % (p[1], p.lineno(1)))) raise SyntaxError p[0] = handler(arguments=p[2]['args'], tests=tests)", "in the block of another command if any(command.RULE_IDENTIFIER == 'REQUIRE'", "that starts on line %d\" % p.lineno(2))) raise SyntaxError def", "p_test(p): \"\"\"test : IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1], p[2]) tests =", "in ('IF', 'ELSIF'): log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command on line", "that starts on line %d\" % (p.lineno(1),))) raise SyntaxError def", "parser(**kwargs): return ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands : commands command\"\"\" p[0]", "= [ p[1] ] def p_string(p): \"\"\"string : QUOTED_STRING\"\"\" p[0]", "strings as a string list p[0] = [ p[1] ]", "p[0].insert(0, p[1]) def p_testlist_single(p): \"\"\"testlist : test\"\"\" p[0] = [", "(p.lineno(2)))) raise SyntaxError p[0] = p[2] def p_block_error(p): \"\"\"block :", "tests=tests, block=block) def p_command_error(p): \"\"\"command : IDENTIFIER error ';' |", "if p[3] != ';': block = p[3] handler = sifter.handler.get('command',", "= p[2] def p_block_error(p): \"\"\"block : '{' error '}'\"\"\" log", "= p[2].get('tests') block = None if p[3] != ';': block", "string\"\"\" p[0] = [ p[1] ] def p_string(p): \"\"\"string :", "] def p_argument_number(p): \"\"\"argument : NUMBER\"\"\" p[0] = p[1] def", "p_argument_number(p): \"\"\"argument : NUMBER\"\"\" p[0] = p[1] def p_argument_tag(p): \"\"\"argument", "\"\"\"argument : '[' stringlist ']'\"\"\" p[0] = p[2] def p_argument_string(p):", "of a block (line %d)\" % (p.lineno(2)))) raise SyntaxError p[0]", "p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'): log = logging.getLogger(\"sifter\") log.error((\"ELSIF/ELSE command", "IDENTIFIER error ';' | IDENTIFIER error block\"\"\" log = logging.getLogger(\"sifter\")", "on line %d\" % p.lineno(2))) raise SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist", "p[0] = p[2] def p_block_error(p): \"\"\"block : '{' error '}'\"\"\"", "#print(\"TEST:\", p[1], p[2]) tests = p[2].get('tests') handler = sifter.handler.get('test', p[1])", "p[0] = p[2] def p_argument_string(p): \"\"\"argument : string\"\"\" # for", "p[3] p[0].insert(0, p[1]) def p_stringlist_single(p): \"\"\"stringlist : string\"\"\" p[0] =", "p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands : \"\"\" p[0] = sifter.grammar.CommandList() def", "('parser',) def parser(**kwargs): return ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands : commands", "on line %d must follow an IF/ELSIF \" \"command\" %", "REQUIRE command must come before any other commands if p[2].RULE_IDENTIFIER", "def p_testlist_error(p): \"\"\"arguments : argumentlist '(' error ')'\"\"\" log =", "string\"\"\" # for simplicity, we treat all single strings as", "\"\"\"arguments : argumentlist | argumentlist test | argumentlist '(' testlist", "before any \" \"other non-REQUIRE commands\" % p.lineno(2))) raise SyntaxError", "% p.lineno(2))) raise SyntaxError # section 3.1: ELSIF and ELSE", "section 3.2: REQUIRE command must come before any other commands,", "raise SyntaxError def p_stringlist_list(p): \"\"\"stringlist : string ',' stringlist\"\"\" p[0]", "on line %d must come before any \" \"other non-REQUIRE", "logging.getLogger(\"sifter\") log.error((\"No handler registered for command '%s' on line %d\"", "'[' error ']'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in string", "not allowed inside of a block (line %d)\" % (p.lineno(2))))", "SyntaxError def p_stringlist_list(p): \"\"\"stringlist : string ',' stringlist\"\"\" p[0] =", "else: p[0]['tests'] = [ p[2] ] def p_testlist_error(p): \"\"\"arguments :", "% p.lineno(2))) raise SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist : argumentlist argument\"\"\"", "p[0] = [ p[1] ] def p_argument_stringlist(p): \"\"\"argument : '['", "argumentlist test | argumentlist '(' testlist ')'\"\"\" p[0] = {", ": string\"\"\" p[0] = [ p[1] ] def p_string(p): \"\"\"string", "logging.getLogger(\"sifter\") log.error((\"Syntax error in command definition after %s on line", "'}' \"\"\" # section 3.2: REQUIRE command must come before", "def p_argument_stringlist(p): \"\"\"argument : '[' stringlist ']'\"\"\" p[0] = p[2]", "is None: log = logging.getLogger(\"sifter\") log.error((\"No handler registered for test", "for command '%s' on line %d\" % (p[1], p.lineno(1)))) raise", "line %d must come before any \" \"other non-REQUIRE commands\"", "import sifter.handler import logging __all__ = ('parser',) def parser(**kwargs): return", "3.1: ELSIF and ELSE must follow IF or another ELSIF", "for simplicity, we treat all single strings as a string", "def p_argument_tag(p): \"\"\"argument : TAG\"\"\" p[0] = sifter.grammar.Tag(p[1]) def p_stringlist_error(p):", "error in test list that starts on line %d\" %", "command must come before any other commands if p[2].RULE_IDENTIFIER ==", "ELSIF elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not in", "logging.getLogger(\"sifter\") log.error((\"No handler registered for test '%s' on line %d\"", "list that starts on line %d\" % p.lineno(1))) raise SyntaxError", "p_stringlist_single(p): \"\"\"stringlist : string\"\"\" p[0] = [ p[1] ] def", "SyntaxError def p_argumentlist_list(p): \"\"\"argumentlist : argumentlist argument\"\"\" p[0] = p[1]", "as defined in section 8. All # references are to", "p[2], p[3]) tests = p[2].get('tests') block = None if p[3]", ": argumentlist | argumentlist test | argumentlist '(' testlist ')'\"\"\"", "follow IF or another ELSIF elif p[2].RULE_IDENTIFIER in ('ELSIF', 'ELSE'):", "arguments\"\"\" #print(\"TEST:\", p[1], p[2]) tests = p[2].get('tests') handler = sifter.handler.get('test',", "= [ p[1] ] def p_argument_number(p): \"\"\"argument : NUMBER\"\"\" p[0]", "after %s on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError", "p[2] def p_argument_string(p): \"\"\"argument : string\"\"\" # for simplicity, we", "argumentlist '(' testlist ')'\"\"\" p[0] = { 'args' : p[1],", "[ p[2] ] def p_testlist_error(p): \"\"\"arguments : argumentlist '(' error", "test | argumentlist '(' testlist ')'\"\"\" p[0] = { 'args'", "commands, # which means it can't be in the block", "log = logging.getLogger(\"sifter\") log.error((\"Syntax error in test list that starts", "error in command definition after %s on line %d\" %", "\"\"\"argument : string\"\"\" # for simplicity, we treat all single", "# Parser based on RFC 5228, especially the grammar as", "> 2: if p[2] == '(': p[0]['tests'] = p[3] else:", "in ('ELSIF', 'ELSE'): if p[0].commands[-1].RULE_IDENTIFIER not in ('IF', 'ELSIF'): log", "log = logging.getLogger(\"sifter\") log.error((\"Syntax error in command definition after %s", "on line %d\" % (p.lineno(1),))) raise SyntaxError def p_arguments(p): \"\"\"arguments", "= logging.getLogger(\"sifter\") log.error((\"No handler registered for command '%s' on line", "inside of a block (line %d)\" % (p.lineno(2)))) raise SyntaxError", "5228 unless stated otherwise. import ply.yacc import sifter.grammar from sifter.grammar.lexer", "SyntaxError p[0] = p[2] def p_block_error(p): \"\"\"block : '{' error", "commands '}' \"\"\" # section 3.2: REQUIRE command must come", "command '%s' on line %d\" % (p[1], p.lineno(1)))) raise SyntaxError", "} if len(p) > 2: if p[2] == '(': p[0]['tests']", ": TAG\"\"\" p[0] = sifter.grammar.Tag(p[1]) def p_stringlist_error(p): \"\"\"argument : '['", "and ELSE must follow IF or another ELSIF elif p[2].RULE_IDENTIFIER", "p.lineno(2))) raise SyntaxError # section 3.1: ELSIF and ELSE must", "def p_block_error(p): \"\"\"block : '{' error '}'\"\"\" log = logging.getLogger(\"sifter\")", "starts on line %d\" % p.lineno(2))) raise SyntaxError def p_argumentlist_list(p):", "another command if any(command.RULE_IDENTIFIER == 'REQUIRE' for command in p[2].commands):", "p[1], p[2], p[3]) tests = p[2].get('tests') block = None if", "log.error((\"REQUIRE command on line %d must come before any \"", "p[0] = p[3] p[0].insert(0, p[1]) def p_stringlist_single(p): \"\"\"stringlist : string\"\"\"", "string list that starts on line %d\" % p.lineno(1))) raise", "| IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\", p[1], p[2], p[3]) tests =", "command definition after %s on line %d\" % (p[1], p.lineno(1))))", ": '[' stringlist ']'\"\"\" p[0] = p[2] def p_argument_string(p): \"\"\"argument", ": argumentlist '(' error ')'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error", "== '(': p[0]['tests'] = p[3] else: p[0]['tests'] = [ p[2]", "All # references are to sections in RFC 5228 unless", "= p[3] p[0].insert(0, p[1]) def p_testlist_single(p): \"\"\"testlist : test\"\"\" p[0]", "= ('parser',) def parser(**kwargs): return ply.yacc.yacc(**kwargs) def p_commands_list(p): \"\"\"commands :", "import logging __all__ = ('parser',) def parser(**kwargs): return ply.yacc.yacc(**kwargs) def", "'(': p[0]['tests'] = p[3] else: p[0]['tests'] = [ p[2] ]", "IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\", p[1], p[2], p[3]) tests = p[2].get('tests')", "';' | IDENTIFIER arguments block\"\"\" #print(\"COMMAND:\", p[1], p[2], p[3]) tests", "must come before any other commands if p[2].RULE_IDENTIFIER == 'REQUIRE':", "= logging.getLogger(\"sifter\") log.error((\"Syntax error in command block that starts on", ": '{' error '}'\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in", "\"command\" % p.lineno(2))) raise SyntaxError p[0].commands.append(p[2]) def p_commands_empty(p): \"\"\"commands :", "def p_test(p): \"\"\"test : IDENTIFIER arguments\"\"\" #print(\"TEST:\", p[1], p[2]) tests", "p[0]['tests'] = [ p[2] ] def p_testlist_error(p): \"\"\"arguments : argumentlist", "SyntaxError def p_block(p): \"\"\"block : '{' commands '}' \"\"\" #", "handler = sifter.handler.get('command', p[1]) if handler is None: log =", "p_argumentlist_empty(p): \"\"\"argumentlist : \"\"\" p[0] = [] def p_test(p): \"\"\"test", "| IDENTIFIER error block\"\"\" log = logging.getLogger(\"sifter\") log.error((\"Syntax error in", "p_testlist_single(p): \"\"\"testlist : test\"\"\" p[0] = [ p[1] ] def", "RFC 5228, especially the grammar as defined in section 8." ]
[ "from sklearn.cross_validation import Bootstrap from sklearn.naive_bayes import MultinomialNB from sklearn.grid_search", "Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42) mnb_gv = GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores", "X.shape # sklearn's grid search parameters = { 'alpha': np.logspace(-100,0,10)}", "myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) # CV with ShuffleSpit", "Select Features via Bag of Words approach without stop words", "from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation", "= plt.bar(ind+0.3, res, width, color='y') p3 = plt.bar(ind+0.6, com, width,", "= cross_val_score(mnb_gv, X, y, cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params = mnb_gv.best_params_.values()[0]", "Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb, X, y, cv=bv)", "ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0) test_scores = cross_val_score(mnb, X, y, cv=cv)", "import GridSearchCV from scipy.stats import sem from pprint import pprint", "via Bag of Words approach without stop words #X =", "color='r') p2 = plt.bar(ind+0.3, res, width, color='y') p3 = plt.bar(ind+0.6,", "CV with ShuffleSpit ''' cv = ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0)", "= mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print mnb_gv_best_params # CV with Bootstrap", "com = np.array(com_list) ind = np.arange(N) # the x locations", "'Improvement')) plt.show() rand_baseline = list() test_results = list() sem_results =", "location = \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with open(os.path.join(sub_dir, location),", "mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb, X, y, cv=bv) print", "docs.data, docs.target baseline = 1/float(len(list(np.unique(y)))) # Select Features via Bag", "os import time as tm sub_dir = \"Results/\" location =", "n_iter=100, test_size=0.2, random_state=0) test_scores = cross_val_score(mnb, X, y, cv=cv) print", "= CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X) X = TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char',", "the bars: can also be len(x) sequence #fig, ax =", "cross_val_score from sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation import Bootstrap from", "plt.legend( (p1[0], p2[0], p3[0]), ('Baseline', 'Algorithm', 'Improvement')) plt.show() rand_baseline =", "''' cv = ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0) test_scores = cross_val_score(mnb,", "np.array(com_list) ind = np.arange(N) # the x locations for the", "with open(os.path.join(sub_dir, location), 'w') as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\")", "baseline) / baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list, results_list,", "mean_sem(boot_scores) improvement = (mnb_gv.best_score_ - baseline) / baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_])", "rand_baseline = list() test_results = list() sem_results = list() com_results", "cross_val_score(mnb, X, y, cv=bv) print mean_sem(boot_scores) improvement = (mnb_gv.best_score_ -", "= plt.bar(ind, base, width, color='r') p2 = plt.bar(ind+0.3, res, width,", "cross_val_score(mnb_gv, X, y, cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params = mnb_gv.best_params_.values()[0] print", "graph(base_list, results_list, com_list, arange): N=arange base=np.array(base_list) res=np.array(results_list) com = np.array(com_list)", "print X_train.shape print y_train.shape print X_test.shape print y_test.shape mnb =", "sem(scores)) def test_docs(dir): # Load documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X,", "ShuffleSplit from sklearn.cross_validation import Bootstrap from sklearn.naive_bayes import MultinomialNB from", "for the groups width = 0.3 # the width of", "GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores = cross_val_score(mnb_gv, X, y, cv=bv) mnb_gv.fit(X,", "import Bootstrap from sklearn.naive_bayes import MultinomialNB from sklearn.grid_search import GridSearchCV", "the scores with the standard deviation def mean_sem(scores): return (\"Mean", "Words approach without stop words #X = CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode',", "X, y, cv=cv) print np.mean(test_scores) ''' # Single run through", "cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params = mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print mnb_gv_best_params", "import numpy as np import pylab as pl import string", "X, y, cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params = mnb_gv.best_params_.values()[0] print mnb_gv.best_score_", "\"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with open(os.path.join(sub_dir, location), 'w') as", "deviation def mean_sem(scores): return (\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def", "mean of the scores with the standard deviation def mean_sem(scores):", "= np.arange(N) # the x locations for the groups width", "import train_test_split from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import ShuffleSplit", "as np import pylab as pl import string import matplotlib.pyplot", "# Load documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y = docs.data,", "base=np.array(base_list) res=np.array(results_list) com = np.array(com_list) ind = np.arange(N) # the", "np.logspace(-100,0,10)} bv = Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42) mnb_gv = GridSearchCV(MultinomialNB(),", "the standard deviation def mean_sem(scores): return (\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores),", "print mean_sem(boot_scores) improvement = (mnb_gv.best_score_ - baseline) / baseline rand_baseline.append(baseline)", "= \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with open(os.path.join(sub_dir, location), 'w')", "approach without stop words #X = CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X)", "import sem from pprint import pprint import numpy as np", "#test_docs(\"problemA\") for i in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os import", "width = 0.3 # the width of the bars: can", "docs.target baseline = 1/float(len(list(np.unique(y)))) # Select Features via Bag of", "the x locations for the groups width = 0.3 #", "as pl import string import matplotlib.pyplot as plt # Calculates", "# CV with ShuffleSpit ''' cv = ShuffleSplit(n_samples, n_iter=100, test_size=0.2,", "X_train.shape print y_train.shape print X_test.shape print y_test.shape mnb = MultinomialNB().fit(X_train,", "strip_accents='unicode', ).fit_transform(X) X = TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True,", "width, color='r') p2 = plt.bar(ind+0.3, res, width, color='y') p3 =", "run through ''' X_train, X_test, y_train, y_test = train_test_split(X, y,", "test_size=0.2, random_state=0) test_scores = cross_val_score(mnb, X, y, cv=cv) print np.mean(test_scores)", "plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0],", "#X = CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X) X = TfidfVectorizer(charset_error='ignore', stop_words='english',", "#plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0], p3[0]), ('Baseline', 'Algorithm', 'Improvement')) plt.show() rand_baseline", "+ tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with open(os.path.join(sub_dir, location), 'w') as myFile:", "10, 7.5 plt.rcParams['axes.grid'] = True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy')", "plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0], p3[0]),", "X_test, y_train, y_test = train_test_split(X, y, random_state=0) print X_train.shape print", "''' # Single run through ''' X_train, X_test, y_train, y_test", "True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend(", "# sklearn's grid search parameters = { 'alpha': np.logspace(-100,0,10)} bv", "= \"Results/\" location = \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with", "words #X = CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X) X = TfidfVectorizer(charset_error='ignore',", "random_state=0) test_scores = cross_val_score(mnb, X, y, cv=cv) print np.mean(test_scores) '''", "plt.show() rand_baseline = list() test_results = list() sem_results = list()", "standard deviation def mean_sem(scores): return (\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores))", "N=arange base=np.array(base_list) res=np.array(results_list) com = np.array(com_list) ind = np.arange(N) #", "import pprint import numpy as np import pylab as pl", "print X_test.shape print y_test.shape mnb = MultinomialNB().fit(X_train, y_train) print mnb.score(X_test,", "= list() com_results = list() #test_docs(\"problemA\") for i in string.uppercase[:13]:", "test_scores = cross_val_score(mnb, X, y, cv=cv) print np.mean(test_scores) ''' #", "sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features = X.shape # sklearn's grid search", "tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with open(os.path.join(sub_dir, location), 'w') as myFile: myFile.write(str(rand_baseline))", "list() sem_results = list() com_results = list() #test_docs(\"problemA\") for i", "bv = Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42) mnb_gv = GridSearchCV(MultinomialNB(), parameters,", "groups width = 0.3 # the width of the bars:", "sklearn import datasets from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import", "ax = plt.sublots() p1 = plt.bar(ind, base, width, color='r') p2", "baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list, results_list, com_list, arange):", "scores with the standard deviation def mean_sem(scores): return (\"Mean score:", "= docs.data, docs.target baseline = 1/float(len(list(np.unique(y)))) # Select Features via", "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) print X_train.shape", "sklearn.grid_search import GridSearchCV from scipy.stats import sem from pprint import", "return (\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir): # Load", "test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os import time as tm sub_dir =", "numpy as np import pylab as pl import string import", "y = docs.data, docs.target baseline = 1/float(len(list(np.unique(y)))) # Select Features", "= MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb, X, y, cv=bv) print mean_sem(boot_scores)", "from sklearn import datasets from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text", "sem_results = list() com_results = list() #test_docs(\"problemA\") for i in", "import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import train_test_split", "from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation", "pylab as pl import string import matplotlib.pyplot as plt #", "sequence #fig, ax = plt.sublots() p1 = plt.bar(ind, base, width,", "TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features =", "p3[0]), ('Baseline', 'Algorithm', 'Improvement')) plt.show() rand_baseline = list() test_results =", "'alpha': np.logspace(-100,0,10)} bv = Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42) mnb_gv =", "print mnb_gv_best_params # CV with Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores", "parameters, cv=bv,) #scores = cross_val_score(mnb_gv, X, y, cv=bv) mnb_gv.fit(X, y)", "Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0], p3[0]), ('Baseline', 'Algorithm',", "of the bars: can also be len(x) sequence #fig, ax", "= cross_val_score(mnb, X, y, cv=cv) print np.mean(test_scores) ''' # Single", "sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import", "rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list, results_list, com_list, arange): N=arange", "p1 = plt.bar(ind, base, width, color='r') p2 = plt.bar(ind+0.3, res,", "y, cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params = mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print", "y_train.shape print X_test.shape print y_test.shape mnb = MultinomialNB().fit(X_train, y_train) print", "parameters = { 'alpha': np.logspace(-100,0,10)} bv = Bootstrap(n_samples, n_iter=10, test_size=0.3,", "cross_val_score(mnb, X, y, cv=cv) print np.mean(test_scores) ''' # Single run", "= np.array(com_list) ind = np.arange(N) # the x locations for", "sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import", "without stop words #X = CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X) X", "MultinomialNB from sklearn.grid_search import GridSearchCV from scipy.stats import sem from", "# Single run through ''' X_train, X_test, y_train, y_test =", "X, y, cv=bv) print mean_sem(boot_scores) improvement = (mnb_gv.best_score_ - baseline)", "of Words approach without stop words #X = CountVectorizer(charset_error='ignore', stop_words='english',", "CV with Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb, X,", "= ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0) test_scores = cross_val_score(mnb, X, y,", "\".txt\" with open(os.path.join(sub_dir, location), 'w') as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results))", "('Baseline', 'Algorithm', 'Improvement')) plt.show() rand_baseline = list() test_results = list()", "the groups width = 0.3 # the width of the", "p2 = plt.bar(ind+0.3, res, width, color='y') p3 = plt.bar(ind+0.6, com,", "color='y') p3 = plt.bar(ind+0.6, com, width, color='b') plt.rcParams['figure.figsize'] = 10,", "import datasets from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer", "{ 'alpha': np.logspace(-100,0,10)} bv = Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42) mnb_gv", "Bootstrap from sklearn.naive_bayes import MultinomialNB from sklearn.grid_search import GridSearchCV from", "print y_test.shape mnb = MultinomialNB().fit(X_train, y_train) print mnb.score(X_test, y_test) '''", "n_iter=10, test_size=0.3, random_state=42) mnb_gv = GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores =", "plt.bar(ind+0.3, res, width, color='y') p3 = plt.bar(ind+0.6, com, width, color='b')", "list() com_results = list() #test_docs(\"problemA\") for i in string.uppercase[:13]: test_docs(\"problem\"+i)", "string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os import time as tm sub_dir", "mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print mnb_gv_best_params # CV with Bootstrap mnb", "documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y = docs.data, docs.target baseline", "import ShuffleSplit from sklearn.cross_validation import Bootstrap from sklearn.naive_bayes import MultinomialNB", "(p1[0], p2[0], p3[0]), ('Baseline', 'Algorithm', 'Improvement')) plt.show() rand_baseline = list()", "as tm sub_dir = \"Results/\" location = \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\")", "= list() test_results = list() sem_results = list() com_results =", "np.mean(test_scores) ''' # Single run through ''' X_train, X_test, y_train,", "com_list, arange): N=arange base=np.array(base_list) res=np.array(results_list) com = np.array(com_list) ind =", "Load documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y = docs.data, docs.target", "cv = ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0) test_scores = cross_val_score(mnb, X,", "color='b') plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid'] = True plt.gray() plt.ylabel('Accuracy')", "test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list, results_list, com_list, arange): N=arange base=np.array(base_list)", "the mean of the scores with the standard deviation def", "mnb_gv = GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores = cross_val_score(mnb_gv, X, y,", "from pprint import pprint import numpy as np import pylab", "n_samples, n_features = X.shape # sklearn's grid search parameters =", "sklearn's grid search parameters = { 'alpha': np.logspace(-100,0,10)} bv =", "X, y = docs.data, docs.target baseline = 1/float(len(list(np.unique(y)))) # Select", "= X.shape # sklearn's grid search parameters = { 'alpha':", "X = TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples,", "y) mnb_gv_best_params = mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print mnb_gv_best_params # CV", "sklearn.naive_bayes import MultinomialNB from sklearn.grid_search import GridSearchCV from scipy.stats import", "import time as tm sub_dir = \"Results/\" location = \"multiDoc\"", "the width of the bars: can also be len(x) sequence", "myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) # CV with ShuffleSpit ''' cv", "com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list, results_list, com_list, arange): N=arange base=np.array(base_list) res=np.array(results_list)", "= plt.bar(ind+0.6, com, width, color='b') plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid']", "plt.rcParams['axes.grid'] = True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13))", "'w') as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results))", "sklearn.cross_validation import Bootstrap from sklearn.naive_bayes import MultinomialNB from sklearn.grid_search import", "can also be len(x) sequence #fig, ax = plt.sublots() p1", "grid search parameters = { 'alpha': np.logspace(-100,0,10)} bv = Bootstrap(n_samples,", "from sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation import Bootstrap from sklearn.naive_bayes", "open(os.path.join(sub_dir, location), 'w') as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results))", "= 1/float(len(list(np.unique(y)))) # Select Features via Bag of Words approach", "also be len(x) sequence #fig, ax = plt.sublots() p1 =", "time as tm sub_dir = \"Results/\" location = \"multiDoc\" +", "random_state=0) print X_train.shape print y_train.shape print X_test.shape print y_test.shape mnb", "import pylab as pl import string import matplotlib.pyplot as plt", "print np.mean(test_scores) ''' # Single run through ''' X_train, X_test,", "width, color='y') p3 = plt.bar(ind+0.6, com, width, color='b') plt.rcParams['figure.figsize'] =", "plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0], p3[0]), ('Baseline', 'Algorithm', 'Improvement')) plt.show()", "random_state=42) mnb_gv = GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores = cross_val_score(mnb_gv, X,", "boot_scores = cross_val_score(mnb, X, y, cv=bv) print mean_sem(boot_scores) improvement =", "ind = np.arange(N) # the x locations for the groups", "results_list, com_list, arange): N=arange base=np.array(base_list) res=np.array(results_list) com = np.array(com_list) ind", "y_test = train_test_split(X, y, random_state=0) print X_train.shape print y_train.shape print", "in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os import time as tm", "#graph(rand_baseline,test_results,com_results,13) import os import time as tm sub_dir = \"Results/\"", "#fig, ax = plt.sublots() p1 = plt.bar(ind, base, width, color='r')", "width of the bars: can also be len(x) sequence #fig,", "matplotlib.pyplot as plt # Calculates the mean of the scores", "x locations for the groups width = 0.3 # the", "MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb, X, y, cv=bv) print mean_sem(boot_scores) improvement", "plt # Calculates the mean of the scores with the", "myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) # CV with", "= TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features", "# the width of the bars: can also be len(x)", "ShuffleSpit ''' cv = ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0) test_scores =", "import MultinomialNB from sklearn.grid_search import GridSearchCV from scipy.stats import sem", "y_train, y_test = train_test_split(X, y, random_state=0) print X_train.shape print y_train.shape", "def graph(base_list, results_list, com_list, arange): N=arange base=np.array(base_list) res=np.array(results_list) com =", "sub_dir = \"Results/\" location = \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\"", "sem from pprint import pprint import numpy as np import", "myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) # CV with ShuffleSpit '''", "with Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb, X, y,", "train_test_split from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import ShuffleSplit from", "(\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir): # Load documents", "improvement = (mnb_gv.best_score_ - baseline) / baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement)", "X_test.shape print y_test.shape mnb = MultinomialNB().fit(X_train, y_train) print mnb.score(X_test, y_test)", "= 10, 7.5 plt.rcParams['axes.grid'] = True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem", "= train_test_split(X, y, random_state=0) print X_train.shape print y_train.shape print X_test.shape", "(mnb_gv.best_score_ - baseline) / baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def", ").fit_transform(X) X = TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X)", "np import pylab as pl import string import matplotlib.pyplot as", "mnb_gv_best_params # CV with Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores =", "com_results = list() #test_docs(\"problemA\") for i in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13)", "{0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir): # Load documents docs =", "1/float(len(list(np.unique(y)))) # Select Features via Bag of Words approach without", "def mean_sem(scores): return (\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir):", "(+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir): # Load documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir)", "= Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42) mnb_gv = GridSearchCV(MultinomialNB(), parameters, cv=bv,)", "cv=bv) print mean_sem(boot_scores) improvement = (mnb_gv.best_score_ - baseline) / baseline", "pprint import pprint import numpy as np import pylab as", "Calculates the mean of the scores with the standard deviation", "+ \".txt\" with open(os.path.join(sub_dir, location), 'w') as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\")", "test_size=0.3, random_state=42) mnb_gv = GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores = cross_val_score(mnb_gv,", "Single run through ''' X_train, X_test, y_train, y_test = train_test_split(X,", "as plt # Calculates the mean of the scores with", "0.3 # the width of the bars: can also be", "plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0], p3[0]), ('Baseline', 'Algorithm', 'Improvement'))", "pl import string import matplotlib.pyplot as plt # Calculates the", "#scores = cross_val_score(mnb_gv, X, y, cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params =", "res=np.array(results_list) com = np.array(com_list) ind = np.arange(N) # the x", "= { 'alpha': np.logspace(-100,0,10)} bv = Bootstrap(n_samples, n_iter=10, test_size=0.3, random_state=42)", "sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import train_test_split from sklearn.cross_validation import", "plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0],", "baseline = 1/float(len(list(np.unique(y)))) # Select Features via Bag of Words", "from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import train_test_split from sklearn.cross_validation", "mnb_gv.best_score_ print mnb_gv_best_params # CV with Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params)", "<gh_stars>1-10 from sklearn import datasets from sklearn.feature_extraction.text import TfidfVectorizer from", "plt.bar(ind, base, width, color='r') p2 = plt.bar(ind+0.3, res, width, color='y')", "as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) #", "print mnb_gv.best_score_ print mnb_gv_best_params # CV with Bootstrap mnb =", "train_test_split(X, y, random_state=0) print X_train.shape print y_train.shape print X_test.shape print", "mnb_gv.fit(X, y) mnb_gv_best_params = mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print mnb_gv_best_params #", "plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid'] = True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC", "CountVectorizer from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from", "test_docs(dir): # Load documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y =", "stop words #X = CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X) X =", "myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) # CV with ShuffleSpit ''' cv =", "np.arange(N) # the x locations for the groups width =", "len(x) sequence #fig, ax = plt.sublots() p1 = plt.bar(ind, base,", "i in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os import time as", "= True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M'))", "max_df=0.5).fit_transform(X) n_samples, n_features = X.shape # sklearn's grid search parameters", "CountVectorizer(charset_error='ignore', stop_words='english', strip_accents='unicode', ).fit_transform(X) X = TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4),", "score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir): # Load documents docs", "y, cv=cv) print np.mean(test_scores) ''' # Single run through '''", "import string import matplotlib.pyplot as plt # Calculates the mean", "- baseline) / baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list,", "from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score from sklearn.cross_validation", "myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\") myFile.write(str(com_results)) # CV", "com, width, color='b') plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid'] = True", "be len(x) sequence #fig, ax = plt.sublots() p1 = plt.bar(ind,", "myFile.write(str(com_results)) # CV with ShuffleSpit ''' cv = ShuffleSplit(n_samples, n_iter=100,", "= datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y = docs.data, docs.target baseline = 1/float(len(list(np.unique(y))))", "location), 'w') as myFile: myFile.write(str(rand_baseline)) myFile.write(\"\\n\") myFile.write(str(test_results)) myFile.write(\"\\n\") myFile.write(str(sem_results)) myFile.write(\"\\n\")", "= list() #test_docs(\"problemA\") for i in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import", "datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y = docs.data, docs.target baseline = 1/float(len(list(np.unique(y)))) #", "analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features = X.shape #", "''' X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) print", "res, width, color='y') p3 = plt.bar(ind+0.6, com, width, color='b') plt.rcParams['figure.figsize']", "mean_sem(scores): return (\"Mean score: {0:.3f} (+/-{1:.3f})\").format(np.mean(scores), sem(scores)) def test_docs(dir): #", "p2[0], p3[0]), ('Baseline', 'Algorithm', 'Improvement')) plt.show() rand_baseline = list() test_results", "cv=bv,) #scores = cross_val_score(mnb_gv, X, y, cv=bv) mnb_gv.fit(X, y) mnb_gv_best_params", "# Select Features via Bag of Words approach without stop", "# the x locations for the groups width = 0.3", "from sklearn.grid_search import GridSearchCV from scipy.stats import sem from pprint", "datasets from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from", "docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y = docs.data, docs.target baseline =", "base, width, color='r') p2 = plt.bar(ind+0.3, res, width, color='y') p3", "def test_docs(dir): # Load documents docs = datasets.load_files(container_path=\"../../sklearn_data/\"+dir) X, y", "sklearn.cross_validation import cross_val_score from sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation import", "width, color='b') plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid'] = True plt.gray()", "Bag of Words approach without stop words #X = CountVectorizer(charset_error='ignore',", "y, cv=bv) print mean_sem(boot_scores) improvement = (mnb_gv.best_score_ - baseline) /", "TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import train_test_split from", "scipy.stats import sem from pprint import pprint import numpy as", "list() test_results = list() sem_results = list() com_results = list()", "pprint import numpy as np import pylab as pl import", "test_results = list() sem_results = list() com_results = list() #test_docs(\"problemA\")", "n_features = X.shape # sklearn's grid search parameters = {", "/ baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores)) def graph(base_list, results_list, com_list,", "cv=cv) print np.mean(test_scores) ''' # Single run through ''' X_train,", "strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features = X.shape # sklearn's grid", "with the standard deviation def mean_sem(scores): return (\"Mean score: {0:.3f}", "list() #test_docs(\"problemA\") for i in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os", "bars: can also be len(x) sequence #fig, ax = plt.sublots()", "y, random_state=0) print X_train.shape print y_train.shape print X_test.shape print y_test.shape", "Features via Bag of Words approach without stop words #X", "GridSearchCV from scipy.stats import sem from pprint import pprint import", "= (mnb_gv.best_score_ - baseline) / baseline rand_baseline.append(baseline) test_results.append([mnb_gv.best_score_]) com_results.append(improvement) sem_results.append(sem(boot_scores))", "mnb_gv_best_params = mnb_gv.best_params_.values()[0] print mnb_gv.best_score_ print mnb_gv_best_params # CV with", "import matplotlib.pyplot as plt # Calculates the mean of the", "sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation import Bootstrap from sklearn.naive_bayes import", "tm sub_dir = \"Results/\" location = \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") +", "stop_words='english', strip_accents='unicode', ).fit_transform(X) X = TfidfVectorizer(charset_error='ignore', stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode',", "import CountVectorizer from sklearn.cross_validation import train_test_split from sklearn.cross_validation import cross_val_score", "p3 = plt.bar(ind+0.6, com, width, color='b') plt.rcParams['figure.figsize'] = 10, 7.5", "import os import time as tm sub_dir = \"Results/\" location", "from scipy.stats import sem from pprint import pprint import numpy", "locations for the groups width = 0.3 # the width", "arange): N=arange base=np.array(base_list) res=np.array(results_list) com = np.array(com_list) ind = np.arange(N)", "with ShuffleSpit ''' cv = ShuffleSplit(n_samples, n_iter=100, test_size=0.2, random_state=0) test_scores", "= cross_val_score(mnb, X, y, cv=bv) print mean_sem(boot_scores) improvement = (mnb_gv.best_score_", "plt.bar(ind+0.6, com, width, color='b') plt.rcParams['figure.figsize'] = 10, 7.5 plt.rcParams['axes.grid'] =", "myFile.write(\"\\n\") myFile.write(str(com_results)) # CV with ShuffleSpit ''' cv = ShuffleSplit(n_samples,", "plt.sublots() p1 = plt.bar(ind, base, width, color='r') p2 = plt.bar(ind+0.3,", "string import matplotlib.pyplot as plt # Calculates the mean of", "= plt.sublots() p1 = plt.bar(ind, base, width, color='r') p2 =", "import cross_val_score from sklearn.cross_validation import ShuffleSplit from sklearn.cross_validation import Bootstrap", "through ''' X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)", "Problem Accuracy') plt.yticks(np.arange(0,3,30)) plt.xticks(np.arange(0,13,13)) #plt.set_xticks(('A','B','C','D','E','F','G','H','I','J','K','L','M')) plt.legend( (p1[0], p2[0], p3[0]), ('Baseline',", "for i in string.uppercase[:13]: test_docs(\"problem\"+i) #graph(rand_baseline,test_results,com_results,13) import os import time", "sem_results.append(sem(boot_scores)) def graph(base_list, results_list, com_list, arange): N=arange base=np.array(base_list) res=np.array(results_list) com", "print y_train.shape print X_test.shape print y_test.shape mnb = MultinomialNB().fit(X_train, y_train)", "= list() sem_results = list() com_results = list() #test_docs(\"problemA\") for", "'Algorithm', 'Improvement')) plt.show() rand_baseline = list() test_results = list() sem_results", "stop_words='english', analyzer='char', ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features = X.shape", "ngram_range=(2,4), strip_accents='unicode', sublinear_tf=True, max_df=0.5).fit_transform(X) n_samples, n_features = X.shape # sklearn's", "# Calculates the mean of the scores with the standard", "\"Results/\" location = \"multiDoc\" + tm.strftime(\"%Y%m%d-%H%M%S\") + \".txt\" with open(os.path.join(sub_dir,", "of the scores with the standard deviation def mean_sem(scores): return", "search parameters = { 'alpha': np.logspace(-100,0,10)} bv = Bootstrap(n_samples, n_iter=10,", "from sklearn.naive_bayes import MultinomialNB from sklearn.grid_search import GridSearchCV from scipy.stats", "= 0.3 # the width of the bars: can also", "= GridSearchCV(MultinomialNB(), parameters, cv=bv,) #scores = cross_val_score(mnb_gv, X, y, cv=bv)", "# CV with Bootstrap mnb = MultinomialNB(alpha=mnb_gv_best_params) boot_scores = cross_val_score(mnb,", "7.5 plt.rcParams['axes.grid'] = True plt.gray() plt.ylabel('Accuracy') plt.title('AAAC Problem Accuracy') plt.yticks(np.arange(0,3,30))" ]
[ "io import * from fast import * from spreadsheet import", "utils import * from web import * __all__ = []", "import * from spreadsheet import * from tab import *", "from fast import * from spreadsheet import * from tab", "fast import * from spreadsheet import * from tab import", "* from utils import * from web import * __all__", "import * from web import * __all__ = [] __all__.extend(io.__all__)", "* from tab import * from utils import * from", "spreadsheet import * from tab import * from utils import", "from web import * __all__ = [] __all__.extend(io.__all__) __all__.extend(fast.__all__) __all__.extend(spreadsheet.__all__)", "web from io import * from fast import * from", "spreadsheet import tab import utils import web from io import", "tab import * from utils import * from web import", "import spreadsheet import tab import utils import web from io", "import * from fast import * from spreadsheet import *", "* from fast import * from spreadsheet import * from", "from utils import * from web import * __all__ =", "import * from utils import * from web import *", "import * __all__ = [] __all__.extend(io.__all__) __all__.extend(fast.__all__) __all__.extend(spreadsheet.__all__) __all__.extend(tab.__all__) __all__.extend(utils.__all__)", "from io import * from fast import * from spreadsheet", "import * from tab import * from utils import *", "from spreadsheet import * from tab import * from utils", "fast import spreadsheet import tab import utils import web from", "* from web import * __all__ = [] __all__.extend(io.__all__) __all__.extend(fast.__all__)", "utils import web from io import * from fast import", "* __all__ = [] __all__.extend(io.__all__) __all__.extend(fast.__all__) __all__.extend(spreadsheet.__all__) __all__.extend(tab.__all__) __all__.extend(utils.__all__) __all__.extend(web.__all__)", "import web from io import * from fast import *", "import tab import utils import web from io import *", "import utils import web from io import * from fast", "import io import fast import spreadsheet import tab import utils", "from tab import * from utils import * from web", "web import * __all__ = [] __all__.extend(io.__all__) __all__.extend(fast.__all__) __all__.extend(spreadsheet.__all__) __all__.extend(tab.__all__)", "io import fast import spreadsheet import tab import utils import", "tab import utils import web from io import * from", "* from spreadsheet import * from tab import * from", "import fast import spreadsheet import tab import utils import web" ]
[ "be tested) TargetID = Column(Integer(11), primary_key=True) IPAddress = Column(String(15), nullable=False)", "('Principal', 12, str)), ('Credential', ('Credential', 12, str)), ('CimomVersion', ('CimomVersion', 15,", "for this table activate_flag (:class:`py:bool`): Next state that will be", "# return ('Targetdata db_type %s, rep count=%s' % # #", "Column(String(10), nullable=False) \"\"\" # TODO change ip_address to hostname where", "exist ' 'in local directory or config directory %s' %", "Protocol = Column(String(10), default='http') Port = Column(String(10), nullable=False) \"\"\" #", "= Column(String(12), nullable=False) ScanEnabled = Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol =", "2.0 (the \"License\"); # you may not use this file", "Exception as ex: self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s", "\"\"\" if not isinstance(targetid, six.integer_types): targetid = int(targetid) return self.data_dict[targetid]", "hdr def get_notifyusers(self, targetid): \"\"\" Get list of entries in", "(db_type). Currently the types sql and csv are supported. Returns", "'SMIVersion', 'Product', 'Principal', 'Credential', 'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol',", "to the value defined by the activate_flag Parameters: targetid (:term:`py:integer`):", "legal report output formats. If not provided, the default is", "the common definition of all targets bases including field names,", "is db_dict. Elsewhere it is db_info companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type,", "12, str)), ('InteropNamespace', ('Interop', 8, str)), ('Notify', ('Notify', 12, str)),", "val == 'disabled': return True ValueError('ScanEnabled field must contain \"Enabled\"", "test generates an exception, KeyError if a field in fields", "this target id disabled Exceptions: KeyError if target_id not in", "input file into a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format)", "'Credential': \"User password to access target\", 'CimomVersion': \"Version of CIMOM\",", "= self.connection.cursor() # dynamically build the update sql based on", "count=%s' % # # # (self.db_type, len(self.data_dict))) def test_fieldnames(self, fields):", "names in the list \"\"\" total_width = 0 for name", "into the table. There is one entry in the dictionary", "input_file: reader = csv.DictReader(input_file) # create dictionary (id = key)", "= db_dict['targetsfilename'] self.filename = fn # If the filename is", "Changes: %s Exception: %s', targetid, sql, changes, ex) raise ex", "fn) if not os.path.isfile(full_fn): ValueError('CSV file %s does not exist", "companies table. Move the companyName into the targets table TODO", "Name in table %r error %s' % (self.db_dict, ex)) def", "multiple of these. See get dict_for_host,get_hostid_list def get_targets_host(self, host_data): \"\"\"", "table TODO we should not be doing this in this", "detailed info is displayed on the processing of the TargetData", "record for `host_data` exists return that record, otherwise return None.", "and return the list of integers representing the userids. This", "that record, otherwise return None. There may be multiple ipaddress,", "in the local directory or the same directory as the", "\"\"\"Initialize the abstract Targets instance. This controls all other target", "Returns instance object of the defined provider type. \"\"\" inst", "Returns: (:class:`py:bool`) True if this target id disabled Exceptions: KeyError", "Principal that represents the unique combination of both. The result", "%r error %s' % (self.db_dict, ex)) def update_fields(self, targetid, changes):", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set scanEnabled to %s', targetid, enabled_kw)", "max_width = fmt_value[1] field_type = fmt_value[2] if isinstance(field_type, six.string_types) and", "subclass of TargetsTable process targets infromation from an sql database.", "all the column headers from the record_list.\"\"\" hdr = []", "the defined database type. \"\"\" table_name = 'Targets' key_field =", "{} for row in reader: key = int(row['TargetID']) if key", "including field names, and common methods. Parameters: db_dict (:term: `dictionary')", "and re.match(ip_filter, value['IPAddress']): rtn[key] = value if company_name_filter and \\", "primary_key=True) IPAddress = Column(String(15), nullable=False) CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace", "dbtype, verbose, output_format): \"\"\"Pass through to SQL\"\"\" if verbose: print('SQL", "failed SQL update. ' 'SQL: %s Changes: %s Exception: %s',", "Does not include port right now. \"\"\" output_list = []", "as mysqlerror from ._dbtablebase import DBTableBase from ._mysqldbmixin import MySQLDBMixin", "if os.path.isfile(fn): self.filename = fn else: full_fn = os.path.join(db_dict['directory'], fn)", "ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close() def insert(self,", "fields will be folded if their width is greater than", "dictionary \"\"\" if not isinstance(targetid, six.integer_types): targetid = int(targetid) return", "License for the specific language governing permissions and # limitations", "%s ( %s ) VALUES ( %s )\" % (self.table_name,", "as string of integers separated by commas. Returns None if", "k] for k, v in creds.items()]) unique_keys = dict([[v, k]", "self.db_dict @classmethod def factory(cls, db_dict, db_type, verbose, output_format='simple'): \"\"\"Factory method", "record_list.\"\"\" hdr = [] for name in record_list: value =", "database. Generate the targetstable from the sql database targets table", "return None. There may be multiple ipaddress, port entries for", "Inc. # All Rights Reserved # # Licensed under the", "the targets base. Returns list of IP addresses:port entries. TODO:", "dbtype, verbose, output_format) fn = db_dict['targetsfilename'] self.filename = fn #", "activate_flag (:class:`py:bool`): Next state that will be set into the", "new record to the database containing the fields defined in", "not in database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list): \"\"\" Get", "target_id. This is alternate to using [id] directly. It does", "entry defined by the targetid parameter to the value defined", "Duplicate Id in table: %s\\nrow=%s' % (key, row)) raise ValueError('Input", "in the db. Return list of targetIDs that represent unique", "verbose=%s' % (db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connection", "of a table from the column names in the list", "is no data in NotifyUsers. \"\"\" notify_users = self[targetid]['NotifyUsers'] if", "try: # set the companyname into the targets table for", "definition of all targets bases including field names, and common", "Targets WHERE TargetID=%s\" try: # pylint: disable=unused-variable mydata = cursor.execute(sql,", "def __str__(self): # # # TODO this and __repr__ do", "of display name and length for name.\"\"\" return self.table_format_dict[name] def", "and companyname filter if they exist and return list of", "Exceptions: KeyError if target not in targets dictionary \"\"\" if", "display name and max width for the record table_format_dict =", "cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s added. %s', new_targetid,", "table_format_dict = OrderedDict([ ('TargetID', ('ID', 2, int)), ('CompanyName', ('CompanyName', 12,", "for match of ip_filter and companyname filter if they exist", "total_width def get_unique_creds(self): \"\"\" Get the set of Credentials and", "targetid parameter to the value defined by the activate_flag Parameters:", "target_record = self.get_target(targetid) for change in changes: original_data[change] = target_record[change]", "sql + \" WHERE TargetID=%s\" # Record the original data", "from ._logging import AUDIT_LOGGER_NAME, get_logger from ._companiestable import CompaniesTable __all__", "self.data_dict.items()} ucreds = dict([[v, k] for k, v in creds.items()])", "if key in result: # duplicate row handling print('ERROR. Duplicate", "parameters to open the database defined by the db_dict attribute.", "('Notify', 12, str)), ('NotifyUsers', ('NotifyUsers', 12, str)), ('Protocol', ('Prot', 5,", "import six from mysql.connector import Error as mysqlerror from ._dbtablebase", "(v['Principal'], v['Credential']) for k, v in self.data_dict.items()} ucreds = dict([[v,", "k, v in ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k", "default='Disabled') NotifyUsers = Column(String(12), nullable=False) ScanEnabled = Column(Enum('Enabled', 'Disabled'), default='Enabled')", "\"\"\" total_width = 0 for name in col_list: value =", "line def disabled_target(self, target_record): # pylint: disable=no-self-use \"\"\" If target_record", "combination of both. The result could be used to test", "Targets \" + set_names # append targetid component sql =", "in notify_users_list] return notify_users_list return None def format_record(self, record_id, fields,", "= 'UPDATE Targets SET ScanEnabled = %s WHERE TargetID =", "targetid)) # noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId", "[(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k in unique_keys] return unique_creds class SQLTargetsTable(TargetsTable):", "(key, row)) raise ValueError('Input Error. duplicate Id') else: result[key] =", "fields + join_fields hints = { 'IPAddress': \"Host name or", "or config directory %s' % (fn, db_dict['directory'])) else: self.filename =", "column names in the list \"\"\" total_width = 0 for", "# noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s", "% (v['Principal'], v['Credential']) for k, v in self.data_dict.items()} ucreds =", "fn) else: self.filename = fn else: if os.path.isfile(fn): self.filename =", "db_dict, db_type, verbose, output_format='simple'): \"\"\"Factory method to select subclass based", "list of IP addresses:port entries. TODO: Does not include port", "def get_disabled_targetids(self): \"\"\"Get list of target ids that are marked", "in the format_dictionary and fold=True \"\"\" # TODO can we", "The Name is the database name for the property #", "name.\"\"\" return self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get list of target ids", "ex) raise ex finally: self._load_table() self._load_joins() cursor.close() def activate(self, targetid,", "true, else return false. \"\"\" val = target_record['ScanEnabled'].lower() if val", "multiple ipaddress, port entries for a single ipaddress, port in", "= True set_names = set_names + \"{0} = %s\".format(key) values.append(value)", "for change in changes: original_data[change] = target_record[change] try: cursor.execute(sql, tuple(values))", "Server ipaddresses in the targets base. Returns list of IP", "OF ANY KIND, either express or implied. # See the", "else: if os.path.isfile(fn): self.filename = fn else: full_fn = os.path.join(db_dict['directory'],", "of company\", 'Namespace': \"User namespace\", 'SMIVersion': \"SMI version\", 'Product': \"Product", "the companies table, by mapping the data to the dictionary", "See the License for the specific language governing permissions and", "This controls all other target bases. This defines the common", "disable=unused-variable mydata = cursor.execute(sql, (targetid,)) # noqa F841 self.connection.commit() audit_logger", "Values form of the Target base.\"\"\" def __init__(self, db_dict, dbtype,", "return list(self.table_format_dict) def get_format_dict(self, name): \"\"\"Return tuple of display name", "defined in field_list for the record_id in display format. String", "'Disabled'), default='Disabled') NotifyUsers = Column(String(12), nullable=False) ScanEnabled = Column(Enum('Enabled', 'Disabled'),", "row self.data_dict = result def write_updated_record(self, record_id): \"\"\"Backup the existing", "to in writing, software # distributed under the License is", "Credential \"\"\" creds = {k: '%s%s' % (v['Principal'], v['Credential']) for", "rtn[key] = value if company_name_filter and \\ re.match(value['CompanyName'], company_name_filter): rtn[key]", "None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This subclass of TargetsTable process", "activate_flag Parameters: targetid (:term:`py:integer`): The database key property for this", "targetid, changes, original_data) except Exception as ex: self.connection.rollback() audit_logger =", "if not os.path.isfile(fn): ValueError('CSV file %s does not exist '", "= self[targetid] return get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def get_hostid_list(self, ip_filter=None, company_name_filter=None):", "in smipyping name is db_dict. Elsewhere it is db_info companies_tbl", "or agreed to in writing, software # distributed under the", "PY 3 return_list = [] for key, value in self.data_dict.items():", "('Enabled', 6, str)), ]) # noqa: E123 def __init__(self, db_dict,", "where each item is an entry in the target record.", "columns = ', '.join(fields.keys()) sql = \"INSERT INTO %s (", "TargetId %s,set scanEnabled to %s', targetid, enabled_kw) except mysqlerror as", "ip address\", 'CompanyID': \"DB id of company\", 'Namespace': \"User namespace\",", "= cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s added. %s',", "if value[\"IPAddress\"] == host_data[0] and int(port) == host_data[1]: return_list.append(key) return", "the same as the original value. \"\"\" cursor = self.connection.cursor()", "\"\"\"Get string for the db_dict\"\"\" return '%s' % self.db_dict @classmethod", "TargetID = Column(Integer(11), primary_key=True) IPAddress = Column(String(15), nullable=False) CompanyID =", "hdr.append(value[0]) return hdr def get_notifyusers(self, targetid): \"\"\" Get list of", "db as string of integers separated by commas. Returns None", "data for the audit log. original_data = {} target_record =", "the update sql based on the changes dictionary set_names =", "creds = {k: '%s%s' % (v['Principal'], v['Credential']) for k, v", "the Target_Tableue . Returns: (:class:`py:bool`) True if this target id", "+= value[1] return total_width def get_unique_creds(self): \"\"\" Get the set", "Move the companyName into the targets table TODO we should", "full_fn with open(self.filename) as input_file: reader = csv.DictReader(input_file) # create", "the string representing the url for targetid. Gets the Protocol,", "be set into the database for this target. Since the", "compliance with the License. # You may obtain a copy", "= self.connection.cursor() placeholders = ', '.join(['%s'] * len(fields)) columns =", "Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol = Column(String(10), default='http') Port = Column(String(10),", "db_dict (:term: `dictionary') Dictionary containing all of the parameters to", "open the database defined by the db_dict attribute. db_type (:term:", "check for correct type for target_id Returns: target as dictionary", "the local directory or the same directory as the #", "(i.e. systems to be tested) TargetID = Column(Integer(11), primary_key=True) IPAddress", "% \\ target['CompanyID'] except Exception as ex: raise ValueError('Error: putting", "= full_fn with open(self.filename) as input_file: reader = csv.DictReader(input_file) #", "cursor.execute(sql, (targetid,)) # noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable", "str)), ('InteropNamespace', ('Interop', 8, str)), ('Notify', ('Notify', 12, str)), ('NotifyUsers',", "(:term:`string`) String defining one of the legal report output formats.", "representing the url for targetid. Gets the Protocol, IPaddress and", "int)), ('CompanyName', ('CompanyName', 12, str)), ('Namespace', ('Namespace', 12, str)), ('SMIVersion',", "return inst def get_field_list(self): \"\"\"Return a list of the base", "ex finally: self._load_table() self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values", "The factory method should be used to construct a new", "names in the order defined.\"\"\" return list(self.table_format_dict) def get_format_dict(self, name):", "target['IPAddress'], target['Port']) def get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\" Get all WBEM", "nullable=False) \"\"\" # TODO change ip_address to hostname where host", "raise ex finally: self._load_table() self._load_joins() def delete(self, targetid): \"\"\" Delete", "if verbose: print('targetdata factory datafile %s dbtype %s verbose %s'", "hdr = [] for name in record_list: value = self.get_format_dict(name)", "True set_names = set_names + \"{0} = %s\".format(key) values.append(value) values.append(targetid)", "SQL update. SQL=%s. ' 'data=%s. Exception %s: %s', sql, fields,", "duplicate Id') else: result[key] = row self.data_dict = result def", "report format. \"\"\" super(TargetsTable, self).__init__(db_dict, db_type, verbose) self.output_format = output_format", "result = {} for row in reader: key = int(row['TargetID'])", "not use this file except in compliance with the License.", "self.data_dict if not self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get list of target", "%s' % (fn, db_dict['directory'])) else: self.filename = full_fn with open(self.filename)", "[ 'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion', 'Product', 'Principal', 'Credential', 'CimomVersion', 'InteropNamespace',", "data in NotifyUsers. \"\"\" notify_users = self[targetid]['NotifyUsers'] if notify_users: notify_users_list", "# set the companyname into the targets table for target_key", "the allowed database types for the target database. verbose (:class:`py:bool`)", "% (value,)) output_list.append(value['IPAddress']) return output_list def tbl_hdr(self, record_list): \"\"\"Return a", "information on the targets, host systems, etc. in the environment.", "('Targetdata db_type %s, rep count=%s' % # # # (self.db_type,", "= [] for name in record_list: value = self.get_format_dict(name) hdr.append(value[0])", "you may not use this file except in compliance with", "Otherwise return True Parameters: target_id(:term:`integer`) Valid target Id for the", "except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s", "get_dbdict(self): \"\"\"Get string for the db_dict\"\"\" return '%s' % self.db_dict", "a std cvt function. target = self.get_target(record_id) line = []", "to test with all Principals/Credentials knows in the db. Return", "target_record disabled, return true, else return false. \"\"\" val =", "factory db_type %s' % db_type) if verbose: print('Resulting targets factory", "an exception, KeyError if a field in fields is not", "record_list: value = self.get_format_dict(name) hdr.append(value[0]) return hdr def get_notifyusers(self, targetid):", "._logging import AUDIT_LOGGER_NAME, get_logger from ._companiestable import CompaniesTable __all__ =", "# If the filename is not a full directory, the", "disabled_target_id(self, targetid): \"\"\" Return True if target recorded for this", "There is one entry in the dictionary for each field", "sql = 'UPDATE Targets SET ScanEnabled = %s WHERE TargetID", "notified of issues, else \" \"'Disabled'\", 'NotifyUsers': \"List of UserIDs", "= Column(String(10), default='http') Port = Column(String(10), nullable=False) \"\"\" # TODO", "\" values = [] comma = False for key, value", "one entry in the dictionary for each field to be", "%s Deleted', targetid) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME)", "company_name_filter): rtn[key] = value return rtn def build_url(self, targetid): \"\"\"Get", "or \"Disabled' ' string. %s is invalid.' % val) def", "# # TODO this and __repr__ do not really match.", "# TODO does this cover directories/clean up for possible exceptions.", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "by commas. Returns None if there is no data in", "%s does not exist ' 'in local directory or config", "and the companies table, by mapping the data to the", "database record defined by targetid with the dictionary of items", "build the update sql based on the changes dictionary set_names", "original data for the audit log. original_data = {} target_record", "target\", 'CimomVersion': \"Version of CIMOM\", 'InteropNamespace': \"Interop Namespace name\", 'Notify':", "def format_record(self, record_id, fields, fold=False): \"\"\"Return the fields defined in", "TargetID: %s failed SQL update. ' 'SQL: %s Changes: %s", "('SMIVersion', 12, str)), ('Product', ('Product', 15, str)), ('Principal', ('Principal', 12,", "if ip_filter and re.match(ip_filter, value['IPAddress']): rtn[key] = value if company_name_filter", "'Notify': \"'Enabled' if users to be notified of issues, else", "ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed SQL update. SQL=%s.", "audit_logger.error('TargetTable INSERT failed SQL update. SQL=%s. ' 'data=%s. Exception %s:", "value is the same as the original value. \"\"\" cursor", "whole file back \"\"\" backfile = '%s.bak' % self.filename #", "'ScanEnabled', 'Protocol', 'Port'] # All fields in each record. fields", "This defines the common definition of all targets bases including", "line = [] for field_name in fields: field_value = target[field_name]", "manner but with a join. \"\"\" # Get companies table", "that are marked enabled.\"\"\" return [x for x in self.data_dict", "Column(String(15), nullable=False) Product = Column(String(30), nullable=False) Principal = Column(String(30), nullable=False)", "\"\"\" for field in fields: self.table_format_dict[field] # pylint: disable=pointless-statement def", "knows in the db. Return list of targetIDs that represent", "sql = \"Update Targets \" + set_names # append targetid", "field_name in fields: field_value = target[field_name] fmt_value = self.get_format_dict(field_name) max_width", "= fn # If the filename is not a full", "be inserted. Exceptions: \"\"\" cursor = self.connection.cursor() placeholders = ',", "%s', targetid, changes, original_data) except Exception as ex: self.connection.rollback() audit_logger", "[int(userid) for userid in notify_users_list] return notify_users_list return None def", "UserIDs to notify\", 'ScanEnabled': \"Enabled if this target to be", "unique_keys] return unique_creds class SQLTargetsTable(TargetsTable): \"\"\" Subclass of Targets data", "port right now. \"\"\" output_list = [] # TODO clean", "inst = MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format) else: ValueError('Invalid targets factory", "targets that match. The filters are regex strings. \"\"\" rtn", "the column names in the list \"\"\" total_width = 0", "sql, enabled_kw, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins()", "targetid, enabled_kw) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable", "targetid, sql, changes, ex) raise ex finally: self._load_table() self._load_joins() cursor.close()", "targetid, changes): \"\"\" Update the database record defined by targetid", "String defining one of the legal report output formats. If", "nullable=False) CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30), nullable=False) SMIVersion", "rep count=%s' % # # # (self.db_type, len(self.data_dict))) def test_fieldnames(self,", "% (self.table_name, columns, placeholders) try: cursor.execute(sql, fields.values()) self.connection.commit() new_targetid =", "# The value tuple is display name and max width", "of Principal and Credential \"\"\" creds = {k: '%s%s' %", "there is no data in NotifyUsers. \"\"\" notify_users = self[targetid]['NotifyUsers']", "insert into targets table: # TODO in smipyping name is", "Inactive strings into the field \"\"\" cursor = self.connection.cursor() enabled_kw", "in companies_tbl: company = companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName'] else: target['CompanyName']", "defined by the activate_flag Parameters: targetid (:term:`py:integer`): The database key", "def get_output_width(self, col_list): \"\"\" Get the width of a table", "entry in the dictionary for each field to be inserted.", "self.connection.cursor() placeholders = ', '.join(['%s'] * len(fields)) columns = ',", "disabled, return true, else return false. \"\"\" val = target_record['ScanEnabled'].lower()", "Exception as ex: raise ValueError('Error: putting Company Name in table", "\"INSERT INTO %s ( %s ) VALUES ( %s )\"", "ScanEnabled = Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol = Column(String(10), default='http') Port", "def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Pass through to SQL\"\"\"", "by mapping the data to the dictionary defined for targets", "len=%s' % (self.db_type, self.get_dbdict(), # # # len(self.data_dict))) # def", "= target_record[change] try: cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable", "OrderedDict from textwrap import wrap import six from mysql.connector import", "defines the common definition of all targets bases including field", "does NOT test if the new value is the same", "InteropNamespace = Column(String(30), nullable=False) Notify = Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers", "+ required_fields join_fields = ['CompanyName'] all_fields = fields + join_fields", "= cursor.execute(sql, (targetid,)) # noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME)", "self.get_target(record_id) line = [] for field_name in fields: field_value =", "DBTableBase from ._mysqldbmixin import MySQLDBMixin from ._common import get_url_str from", "filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\" Filter for match of ip_filter and", "\"\"\" If target_record disabled, return true, else return false. \"\"\"", "Credential = Column(String(30), nullable=False) CimomVersion = Column(String(30), nullable=False) InteropNamespace =", "% field_value) else: line.append('%s' % field_value) return line def disabled_target(self,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "named file.\"\"\" with open(file_name, 'wb') as f: writer = csv.DictWriter(f,", "self.data_dict.items(): if self.verbose: print('get_hostid_list value %s' % (value,)) output_list.append(value['IPAddress']) return", "filename is config file name, not actual file name. def", "ex: self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s failed SQL", "record_id in display format. String fields will be folded if", "target ids that are marked disabled\"\"\" return [x for x", "report output formats. If not provided, the default is a", "commas. Returns None if there is no data in NotifyUsers.", "exception, KeyError if a field in fields is not in", "_load_joins(self): \"\"\" Load the tables that would normally be joins.", "name or ip address\", 'CompanyID': \"DB id of company\", 'Namespace':", "the notify users field and split into python list and", "value if company_name_filter and \\ re.match(value['CompanyName'], company_name_filter): rtn[key] = value", "the changes dictionary set_names = \"SET \" values = []", "to create a string. Port info is included only if", "for field in fields: self.table_format_dict[field] # pylint: disable=pointless-statement def get_dbdict(self):", "both. The result could be used to test with all", "original value. \"\"\" cursor = self.connection.cursor() # dynamically build the", "re.match(ip_filter, value['IPAddress']): rtn[key] = value if company_name_filter and \\ re.match(value['CompanyName'],", "the input. Parameters: field_data () Dictionary of fields to be", "self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values form of the Target", "list of targetdata keys \"\"\" # TODO clean up for", "file except in compliance with the License. # You may", "the defined provider type. \"\"\" inst = None if verbose:", "= self.get_target(targetid) for change in changes: original_data[change] = target_record[change] try:", "now. \"\"\" output_list = [] # TODO clean up for", "rtn[key] = value return rtn def build_url(self, targetid): \"\"\"Get the", "list of targetIDs that represent unique sets of Principal and", "dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connectdb(db_dict, verbose) self._load_table() self._load_joins()", "\"Enabled if this target to be scanned\", 'Protocol': '\"http\" or", "not os.path.isfile(fn): ValueError('CSV file %s does not exist ' %", "record_list): \"\"\"Return a list of all the column headers from", "the table entry defined by the targetid parameter to the", "marked enabled.\"\"\" return [x for x in self.data_dict if not", "the record_id in display format. String fields will be folded", "and fold=True \"\"\" # TODO can we make this a", "bases. This defines the common definition of all targets bases", "to %s', targetid, enabled_kw) except mysqlerror as ex: audit_logger =", "all Principals/Credentials knows in the db. Return list of targetIDs", "%s exception %s: %s', targetid, sql, enabled_kw, ex.__class__.__name__, ex) self.connection.rollback()", "\"\"\" cursor = self.connection.cursor() sql = \"DELETE FROM Targets WHERE", "the input file into a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose,", "full directory, the data file must be # either in", "we have multiple of these. See get dict_for_host,get_hostid_list def get_targets_host(self,", "value = self.get_format_dict(name) hdr.append(value[0]) return hdr def get_notifyusers(self, targetid): \"\"\"", "instance. This controls all other target bases. This defines the", "= set_names + \", \" else: comma = True set_names", "the companies table. Move the companyName into the targets table", "integers representing the userids. This list stored in db as", "12, str)), ('SMIVersion', ('SMIVersion', 12, str)), ('Product', ('Product', 15, str)),", "smipyping name is db_dict. Elsewhere it is db_info companies_tbl =", "sql databases. \"\"\" def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Pass", "property # # The value tuple is display name and", "of Credentials and Principal that represents the unique combination of", "output_format) self.connection = None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This subclass", "if not isinstance(targetid, six.integer_types): targetid = int(targetid) return self.data_dict[targetid] def", "string for the db_dict\"\"\" return '%s' % self.db_dict @classmethod def", "ex: raise ValueError('Error: putting Company Name in table %r error", "collections import OrderedDict from textwrap import wrap import six from", "KIND, either express or implied. # See the License for", "[] for field_name in fields: field_value = target[field_name] fmt_value =", "to open the database defined by the db_dict attribute. db_type", "comma: set_names = set_names + \", \" else: comma =", "k] for k, v in ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential'])", "= \"INSERT INTO %s ( %s ) VALUES ( %s", "# create dictionary (id = key) with dictionary for #", "(fn, db_dict['directory'])) else: self.filename = full_fn with open(self.filename) as input_file:", "Dictionary containing all of the parameters to open the database", "infromation from an sql database. Generate the targetstable from the", "# Record the original data for the audit log. original_data", "CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format) elif db_type == ('mysql'): inst =", "self._load_table() self._load_joins() def delete(self, targetid): \"\"\" Delete the target in", "self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s Deleted', targetid) except", "with open(self.filename) as input_file: reader = csv.DictReader(input_file) # create dictionary", "TODO does this cover directories/clean up for possible exceptions. if", "= OrderedDict() for key, value in self.data_dict.items(): if ip_filter and", "split into python list and return the list of integers", "target id disabled Exceptions: KeyError if target_id not in database", "is an entry in the target record. Update does NOT", "db_dict. Elsewhere it is db_info companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type, self.verbose)", "'in local directory or config directory %s' % (fn, db_dict['directory']))", "(the \"License\"); # you may not use this file except", "TargetsTable(DBTableBase): \"\"\" Class representing the targets db table. This base", "record_id, fields, fold=False): \"\"\"Return the fields defined in field_list for", "Exceptions: KeyError if target_id not in database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def", "of both. The result could be used to test with", "one of the allowed database types for the target database.", "and __repr__ do not really match. # # \"\"\"String info", "be scanned\", 'Protocol': '\"http\" or \"https\"', 'Port': \"Integer defining WBEM", "on the targets, host systems, etc. in the environment. The", "self.data_dict[target_key] if target['CompanyID'] in companies_tbl: company = companies_tbl[target['CompanyID']] target['CompanyName'] =", "db_type %s' % db_type) if verbose: print('Resulting targets factory inst", "# # Unless required by applicable law or agreed to", "table field names in the order defined.\"\"\" return list(self.table_format_dict) def", "port.\"} # # Defines each record for the data base", "'%s.bak' % self.filename # TODO does this cover directories/clean up", "be joins. In this case it is the companies table.", "in the table \"\"\" for field in fields: self.table_format_dict[field] #", "format_dictionary and fold=True \"\"\" # TODO can we make this", "field must contain \"Enabled\" or \"Disabled' ' string. %s is", "= Column(String(30), nullable=False) Credential = Column(String(30), nullable=False) CimomVersion = Column(String(30),", "\"Product name\", 'Principal': \"User Name to access target\", 'Credential': \"User", "\"\"\"Write the current Target base to the named file.\"\"\" with", "'Namespace': \"User namespace\", 'SMIVersion': \"SMI version\", 'Product': \"Product name\", 'Principal':", "self._load_joins() self.connection.close() def insert(self, fields): \"\"\" Write a new record", ". Returns: (:class:`py:bool`) True if this target id disabled Exceptions:", "`string`) String defining one of the allowed database types for", "the width of a table from the column names in", "tested) TargetID = Column(Integer(11), primary_key=True) IPAddress = Column(String(15), nullable=False) CompanyID", "Column(String(10), default='http') Port = Column(String(10), nullable=False) \"\"\" # TODO change", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed SQL update. SQL=%s. ' 'data=%s.", "db_type) if verbose: print('Resulting targets factory inst %r' % inst)", "str)), ('Principal', ('Principal', 12, str)), ('Credential', ('Credential', 12, str)), ('CimomVersion',", "implied. # See the License for the specific language governing", "list of integers representing the userids. This list stored in", "% self.filename # TODO does this cover directories/clean up for", "file back \"\"\" backfile = '%s.bak' % self.filename # TODO", "this cover directories/clean up for possible exceptions. if os.path.isfile(backfile): os.remove(backfile)", "added. %s', new_targetid, fields) except mysqlerror as ex: audit_logger =", "in db as string of integers separated by commas. Returns", "their width is greater than the specification in the format_dictionary", "Name is the database name for the property # #", "\"\"\" Activate or deactivate the table entry defined by the", "(targetid,)) # noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s, update fields: %s, '", "unique combination of both. The result could be used to", "row in reader: key = int(row['TargetID']) if key in result:", "result[key] = row self.data_dict = result def write_updated_record(self, record_id): \"\"\"Backup", "Elsewhere it is db_info companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try:", "\"'Enabled' if users to be notified of issues, else \"", "\"\"\" val = target_record['ScanEnabled'].lower() if val == 'enabled': return False", "= csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader() for key, value in sorted(self.data_dict.items()): writer.writerow(value)", "the target database. verbose (:class:`py:bool`) Boolean. If true detailed info", "'%s' % self.db_dict @classmethod def factory(cls, db_dict, db_type, verbose, output_format='simple'):", "field to be inserted. Exceptions: \"\"\" cursor = self.connection.cursor() placeholders", "nullable=False) SMIVersion = Column(String(15), nullable=False) Product = Column(String(30), nullable=False) Principal", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s, update fields: %s, ' 'original", "= [] for key, value in self.data_dict.items(): port = value[\"Port\"]", "[] # TODO clean up for python 3 for _id,", "defined by the targetid parameter to the value defined by", "import MySQLDBMixin from ._common import get_url_str from ._logging import AUDIT_LOGGER_NAME,", "types for the target database. verbose (:class:`py:bool`) Boolean. If true", "\"\"\"Rep of target data\"\"\" # # return ('Targetdata db_type %s,", "the fields defined in field_list for the record_id in display", "if notify_users: notify_users_list = notify_users.split(',') notify_users_list = [int(userid) for userid", "== 'disabled': return True ValueError('ScanEnabled field must contain \"Enabled\" or", "key, value in self.data_dict.items(): if ip_filter and re.match(ip_filter, value['IPAddress']): rtn[key]", "'TargetID' # Fields that are required to create new records", "enabled_kw) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid", "format_record(self, record_id, fields, fold=False): \"\"\"Return the fields defined in field_list", "%s failed SQL DELETE. ' 'SQL=%s exception %s: %s', targetid,", "in result: # duplicate row handling print('ERROR. Duplicate Id in", "try: # pylint: disable=unused-variable mydata = cursor.execute(sql, (targetid,)) # noqa", "the userids. This list stored in db as string of", "by changes where each item is an entry in the", "in unique_keys] return unique_creds class SQLTargetsTable(TargetsTable): \"\"\" Subclass of Targets", "we should not be doing this in this manner but", "of all the column headers from the record_list.\"\"\" hdr =", "`host_data` exists return that record, otherwise return None. There may", "(id = key) with dictionary for # each set of", "' 'ScanEnabled. SQL=%s ' 'Change to %s exception %s: %s',", "inst = CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format) elif db_type == ('mysql'):", "`dictionary') Dictionary containing all of the parameters to open the", "= Column(String(30), nullable=False) SMIVersion = Column(String(15), nullable=False) Product = Column(String(30),", "Unless required by applicable law or agreed to in writing,", "TargetsTable object since that creates the correct object for the", "in changes.items(): if comma: set_names = set_names + \", \"", "= ['TargetsTable'] class TargetsTable(DBTableBase): \"\"\" Class representing the targets db", "support specialized sql databases. \"\"\" def __init__(self, db_dict, dbtype, verbose,", "the Target base.\"\"\" def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read", "the specific language governing permissions and # limitations under the", "to select subclass based on database type (db_type). Currently the", "# All fields in each record. fields = [key_field] +", "exception %s: %s', targetid, sql, ex.__class__.__name__, ex) self.connection.rollback() raise ex", "version\", 'Product': \"Product name\", 'Principal': \"User Name to access target\",", "return the list of integers representing the userids. This list", "types sql and csv are supported. Returns instance object of", "the url for targetid. Gets the Protocol, IPaddress and port", "= Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30), nullable=False) SMIVersion = Column(String(15),", "IPaddress and port and uses the common get_url_str to create", "textwrap import wrap import six from mysql.connector import Error as", "line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s' % field_value) else: line.append('%s' % field_value)", "Get the target data for the parameter target_id. This is", "additonal check for correct type for target_id Returns: target as", "Exceptions: \"\"\" cursor = self.connection.cursor() placeholders = ', '.join(['%s'] *", "f: writer = csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader() for key, value in", "processing of the TargetData class output_format (:term:`string`) String defining one", "not exist ' % fn) else: self.filename = fn else:", "base to the named file.\"\"\" with open(file_name, 'wb') as f:", "of targets (i.e. systems to be tested) TargetID = Column(Integer(11),", "('IPAddress', ('IPAddress', 12, str)), ('InteropNamespace', ('Interop', 8, str)), ('Notify', ('Notify',", "ids that are marked enabled.\"\"\" return [x for x in", "str)), ('Product', ('Product', 15, str)), ('Principal', ('Principal', 12, str)), ('Credential',", "the list \"\"\" total_width = 0 for name in col_list:", "cursor = self.connection.cursor() placeholders = ', '.join(['%s'] * len(fields)) columns", "get_output_width(self, col_list): \"\"\" Get the width of a table from", "= result def write_updated_record(self, record_id): \"\"\"Backup the existing file and", ": port from __future__ import print_function, absolute_import import os import", "base. Returns list of IP addresses:port entries. TODO: Does not", "be multiple ipaddress, port entries for a single ipaddress, port", "= self.get_format_dict(name) total_width += value[1] return total_width def get_unique_creds(self): \"\"\"", "import OrderedDict from textwrap import wrap import six from mysql.connector", "defining one of the allowed database types for the target", "of this class support specialized sql databases. \"\"\" def __init__(self,", "each record. fields = [key_field] + required_fields join_fields = ['CompanyName']", "verbose: print('targetdata factory datafile %s dbtype %s verbose %s' %", "return_list = [] for key, value in self.data_dict.items(): port =", "Targets data for all SQL databases. Subclasses of this class", "print_function, absolute_import import os import csv import re from collections", "be inserted into the table. There is one entry in", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s added. %s', new_targetid, fields) except", "or the same directory as the # config file defined", "verbose) self._load_table() self._load_joins() def _load_joins(self): \"\"\" Load the tables that", "dictionary of items defined by changes where each item is", "audit_logger.error('TargetTable userid %s failed SQL change ' 'ScanEnabled. SQL=%s '", "sete Active or Inactive strings into the field \"\"\" cursor", "fields, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close()", "# The Name is the database name for the property", "self._load_joins() def delete(self, targetid): \"\"\" Delete the target in the", "not include port right now. \"\"\" output_list = [] #", "from ._companiestable import CompaniesTable __all__ = ['TargetsTable'] class TargetsTable(DBTableBase): \"\"\"", "for possible exceptions. if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename) def", "__all__ = ['TargetsTable'] class TargetsTable(DBTableBase): \"\"\" Class representing the targets", "Error as mysqlerror from ._dbtablebase import DBTableBase from ._mysqldbmixin import", "%s: %s', sql, fields, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally:", "the WBEM CIM-XML standard definitions. \"\"\" target = self[targetid] return", "else: comma = True set_names = set_names + \"{0} =", "record_id): \"\"\"Backup the existing file and write the new one.", "Reserved # # Licensed under the Apache License, Version 2.0", "names, and common methods. Parameters: db_dict (:term: `dictionary') Dictionary containing", "x in self.data_dict if not self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get list", "__init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Pass through to SQL\"\"\" if", "from collections import OrderedDict from textwrap import wrap import six", "ex finally: self._load_table() self._load_joins() self.connection.close() def insert(self, fields): \"\"\" Write", "clean up for PY 3 return_list = [] for key,", "by the db_dict entry directory if os.path.isabs(fn): if not os.path.isfile(fn):", "original_data = {} target_record = self.get_target(targetid) for change in changes:", "'NotifyUsers': \"List of UserIDs to notify\", 'ScanEnabled': \"Enabled if this", "# # # (self.db_type, len(self.data_dict))) def test_fieldnames(self, fields): \"\"\"Test a", "table_name = 'Targets' key_field = 'TargetID' # Fields that are", "target_id marked disabled. Otherwise return True Parameters: target_id(:term:`integer`) Valid target", "return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list): \"\"\" Get the width of a", "changes.items(): if comma: set_names = set_names + \", \" else:", "{ 'IPAddress': \"Host name or ip address\", 'CompanyID': \"DB id", "else: self.filename = full_fn with open(self.filename) as input_file: reader =", "Column(String(30), nullable=False) Principal = Column(String(30), nullable=False) Credential = Column(String(30), nullable=False)", "value %s' % (value,)) output_list.append(value['IPAddress']) return output_list def tbl_hdr(self, record_list):", "\"User namespace\", 'SMIVersion': \"SMI version\", 'Product': \"Product name\", 'Principal': \"User", "file into a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) fn", "cursor.execute(sql, (enabled_kw, targetid)) # noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME)", "unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k in unique_keys] return unique_creds", "dbtype, verbose, output_format): \"\"\"Read the input file into a dictionary.\"\"\"", "self.get_target(targetid) for change in changes: original_data[change] = target_record[change] try: cursor.execute(sql,", "the table \"\"\" for field in fields: self.table_format_dict[field] # pylint:", "def get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\" Get all WBEM Server ipaddresses", "It does an additonal check for correct type for target_id", "os import csv import re from collections import OrderedDict from", "Active or Inactive strings into the field \"\"\" cursor =", "except Exception as ex: self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID:", "str)), ]) # noqa: E123 def __init__(self, db_dict, db_type, verbose,", "verbose, output_format): \"\"\"Initialize the abstract Targets instance. This controls all", "name in record_list: value = self.get_format_dict(name) hdr.append(value[0]) return hdr def", "0 for name in col_list: value = self.get_format_dict(name) total_width +=", "noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s Deleted',", "return list of any targets that match. The filters are", "VALUES ( %s )\" % (self.table_name, columns, placeholders) try: cursor.execute(sql,", "and int(port) == host_data[1]: return_list.append(key) return return_list def get_target(self, targetid):", "open(self.filename) as input_file: reader = csv.DictReader(input_file) # create dictionary (id", "disabled Exceptions: KeyError if target_id not in database \"\"\" return(self.disabled_target(self.data_dict[targetid]))", "as the original value. \"\"\" cursor = self.connection.cursor() # dynamically", "field_value) else: line.append('%s' % field_value) return line def disabled_target(self, target_record):", "db_dict\"\"\" return '%s' % self.db_dict @classmethod def factory(cls, db_dict, db_type,", "\"\"\" Delete the target in the targets table defined by", "targets factory inst %r' % inst) return inst def get_field_list(self):", "if it is not the WBEM CIM-XML standard definitions. \"\"\"", "new_targetid, fields) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable", "output_format=output_format) else: ValueError('Invalid targets factory db_type %s' % db_type) if", "super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connectdb(db_dict, verbose) self._load_table() self._load_joins() def", "'Targets' key_field = 'TargetID' # Fields that are required to", "self._load_joins() cursor.close() def activate(self, targetid, activate_flag): \"\"\" Activate or deactivate", "names. This test generates an exception, KeyError if a field", "._mysqldbmixin import MySQLDBMixin from ._common import get_url_str from ._logging import", "required_fields = [ 'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion', 'Product', 'Principal', 'Credential',", "'UPDATE Targets SET ScanEnabled = %s WHERE TargetID = %s'", "DELETE. ' 'SQL=%s exception %s: %s', targetid, sql, ex.__class__.__name__, ex)", "'.join(['%s'] * len(fields)) columns = ', '.join(fields.keys()) sql = \"INSERT", "' 'SQL: %s Changes: %s Exception: %s', targetid, sql, changes,", "'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port'] # All fields in each record.", "WBEM Server ipaddresses in the targets base. Returns list of", "ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s failed SQL change", "Protocol, IPaddress and port and uses the common get_url_str to", "a full directory, the data file must be # either", "Company Name in table %r error %s' % (self.db_dict, ex))", "the original data for the audit log. original_data = {}", "# TODO filename is config file name, not actual file", "%s', sql, fields, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table()", "environment. The factory method should be used to construct a", "if this target id disabled Exceptions: KeyError if target_id not", "db_dict['directory'])) else: self.filename = full_fn with open(self.filename) as input_file: reader", "the database record defined by targetid with the dictionary of", "If the filename is not a full directory, the data", "You may obtain a copy of the License at #", "the same directory as the # config file defined by", "must be # either in the local directory or the", "ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s failed SQL DELETE.", "representing the targets db table. This base contains information on", "TODO clean up for PY 3 return_list = [] for", "is the database name for the property # # The", "in creds.items()]) unique_keys = dict([[v, k] for k, v in", "can we make this a std cvt function. target =", "Namespace name\", 'Notify': \"'Enabled' if users to be notified of", "disable=pointless-statement def get_dbdict(self): \"\"\"Get string for the db_dict\"\"\" return '%s'", "directory or the same directory as the # config file", "os.rename(self.filename, backfile) self.write_file(self.filename) def write_file(self, file_name): \"\"\"Write the current Target", "provider type. \"\"\" inst = None if verbose: print('targetdata factory", "into a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) fn =", "= %s\".format(key) values.append(value) values.append(targetid) sql = \"Update Targets \" +", "db_type, verbose) self.output_format = output_format # def __str__(self): # #", "file must be # either in the local directory or", "get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set scanEnabled to %s', targetid, enabled_kw) except", "the table. There is one entry in the dictionary for", "field and split into python list and return the list", "Next state that will be set into the database for", "write_file(self, file_name): \"\"\"Write the current Target base to the named", "list of field names. This test generates an exception, KeyError", "# Defines each record for the data base and outputs.", "return line def disabled_target(self, target_record): # pylint: disable=no-self-use \"\"\" If", "= \"Update Targets \" + set_names # append targetid component", "+ join_fields hints = { 'IPAddress': \"Host name or ip", "update fields: %s, ' 'original fields: %s', targetid, changes, original_data)", "append targetid component sql = sql + \" WHERE TargetID=%s\"", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "test with all Principals/Credentials knows in the db. Return list", "\"\"\" output_list = [] # TODO clean up for python", "fmt_value[1] field_type = fmt_value[2] if isinstance(field_type, six.string_types) and field_value: if", "= %s' try: cursor.execute(sql, (enabled_kw, targetid)) # noqa F841 self.connection.commit()", "int(row['TargetID']) if key in result: # duplicate row handling print('ERROR.", "table, by mapping the data to the dictionary defined for", "= 'Enabled' if activate_flag else 'Disabled' sql = 'UPDATE Targets", "This is alternate to using [id] directly. It does an", "field names. This test generates an exception, KeyError if a", "All fields in each record. fields = [key_field] + required_fields", "cursor = self.connection.cursor() enabled_kw = 'Enabled' if activate_flag else 'Disabled'", "unique_creds class SQLTargetsTable(TargetsTable): \"\"\" Subclass of Targets data for all", "hostname or ipaddress and port) Returns list of targetdata keys", "in NotifyUsers. \"\"\" notify_users = self[targetid]['NotifyUsers'] if notify_users: notify_users_list =", "noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set scanEnabled", "\"{0} = %s\".format(key) values.append(value) values.append(targetid) sql = \"Update Targets \"", "info is displayed on the processing of the TargetData class", "for correct type for target_id Returns: target as dictionary Exceptions:", "mysqlerror from ._dbtablebase import DBTableBase from ._mysqldbmixin import MySQLDBMixin from", "or \"https\"', 'Port': \"Integer defining WBEM server port.\"} # #", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "for the audit log. original_data = {} target_record = self.get_target(targetid)", "'original fields: %s', targetid, changes, original_data) except Exception as ex:", "License. # You may obtain a copy of the License", "mysql.connector import Error as mysqlerror from ._dbtablebase import DBTableBase from", "Parameters: targetid (:term:`py:integer`): The database key property for this table", "target in the targets table defined by the targetid \"\"\"", "record for the data base and outputs. # # The", "ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30), nullable=False) SMIVersion = Column(String(15), nullable=False) Product", "companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName'] else: target['CompanyName'] = \"TableError CompanyID %s\"", "name, not actual file name. def __init__(self, db_dict, dbtype, verbose,", "to create new records required_fields = [ 'IPAddress', 'CompanyID', 'Namespace',", "table defined by the targetid \"\"\" cursor = self.connection.cursor() sql", "current Target base to the named file.\"\"\" with open(file_name, 'wb')", "( %s )\" % (self.table_name, columns, placeholders) try: cursor.execute(sql, fields.values())", "not provided, the default is a simple report format. \"\"\"", "= CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try: # set the companyname into", "open(file_name, 'wb') as f: writer = csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader() for", "unique_keys = dict([[v, k] for k, v in ucreds.items()]) unique_creds", "create new records required_fields = [ 'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion',", "# \"\"\"Rep of target data\"\"\" # # return ('Targetdata db_type", "database types for the target database. verbose (:class:`py:bool`) Boolean. If", "Subclass of Targets data for all SQL databases. Subclasses of", "for key, value in self.data_dict.items(): port = value[\"Port\"] # TODO", "the target record. Update does NOT test if the new", "TODO change ip_address to hostname where host name is name", "if isinstance(field_type, six.string_types) and field_value: if max_width < len(field_value): line.append('\\n'.join(wrap(field_value,", "disabled_target(self, target_record): # pylint: disable=no-self-use \"\"\" If target_record disabled, return", "it is the companies table. Move the companyName into the", "table for target_key in self.data_dict: target = self.data_dict[target_key] if target['CompanyID']", "set_names + \", \" else: comma = True set_names =", "This list stored in db as string of integers separated", "hints = { 'IPAddress': \"Host name or ip address\", 'CompanyID':", "the format_dictionary and fold=True \"\"\" # TODO can we make", "verbose, output_format): \"\"\"Read the input file into a dictionary.\"\"\" super(MySQLTargetsTable,", "writer = csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader() for key, value in sorted(self.data_dict.items()):", "If an record for `host_data` exists return that record, otherwise", "'Disabled' sql = 'UPDATE Targets SET ScanEnabled = %s WHERE", "record. fields = [key_field] + required_fields join_fields = ['CompanyName'] all_fields", "TODO clean up for python 3 for _id, value in", "fn # If the filename is not a full directory,", "the base of targets (i.e. systems to be tested) TargetID", "the db. Return list of targetIDs that represent unique sets", "defining WBEM server port.\"} # # Defines each record for", "for target_key in self.data_dict: target = self.data_dict[target_key] if target['CompanyID'] in", "may be multiple ipaddress, port entries for a single ipaddress,", "pylint: disable=unused-variable mydata = cursor.execute(sql, (targetid,)) # noqa F841 self.connection.commit()", "for this target_id marked disabled. Otherwise return True Parameters: target_id(:term:`integer`)", "in ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k in unique_keys]", "\"Update Targets \" + set_names # append targetid component sql", "supported. Returns instance object of the defined provider type. \"\"\"", "int(targetid) return self.data_dict[targetid] def filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\" Filter for", "in reader: key = int(row['TargetID']) if key in result: #", "== 'enabled': return False if val == 'disabled': return True", "field in fields: self.table_format_dict[field] # pylint: disable=pointless-statement def get_dbdict(self): \"\"\"Get", "x in self.data_dict if self.disabled_target_id(x)] # TODO we have multiple", "a list of the base table field names in the", "# noqa: E123 def __init__(self, db_dict, db_type, verbose, output_format): \"\"\"Initialize", "db_dict, dbtype, verbose, output_format): \"\"\"Read the input file into a", "this target to be scanned\", 'Protocol': '\"http\" or \"https\"', 'Port':", "verbose: print('SQL Database type %s verbose=%s' % (db_dict, verbose)) super(SQLTargetsTable,", "or deactivate the table entry defined by the targetid parameter", "TargetId %s Deleted', targetid) except mysqlerror as ex: audit_logger =", "csv import re from collections import OrderedDict from textwrap import", "host_id(tuple of hostname or ipaddress and port) Returns list of", "enabled_kw, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() def", "deactivate the table entry defined by the targetid parameter to", "format. String fields will be folded if their width is", "db_type, verbose, output_format='simple'): \"\"\"Factory method to select subclass based on", "host_data[1]: return_list.append(key) return return_list def get_target(self, targetid): \"\"\" Get the", "exist and return list of any targets that match. The", "db_dict attribute. db_type (:term: `string`) String defining one of the", "database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list): \"\"\" Get the width", "join. \"\"\" # Get companies table and insert into targets", "and # limitations under the License. \"\"\" Define the base", "TargetID=%s\" try: # pylint: disable=unused-variable mydata = cursor.execute(sql, (targetid,)) #", "str)), ('Port', ('Port', 4, int)), ('ScanEnabled', ('Enabled', 6, str)), ])", "return [x for x in self.data_dict if self.disabled_target_id(x)] # TODO", "into the database for this target. Since the db field", "or Inactive strings into the field \"\"\" cursor = self.connection.cursor()", "def delete(self, targetid): \"\"\" Delete the target in the targets", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "output_list def tbl_hdr(self, record_list): \"\"\"Return a list of all the", "'Change to %s exception %s: %s', targetid, sql, enabled_kw, ex.__class__.__name__,", "len(self.data_dict))) # def __repr__(self): # # \"\"\"Rep of target data\"\"\"", "for key, value in changes.items(): if comma: set_names = set_names", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "# # \"\"\"Rep of target data\"\"\" # # return ('Targetdata", "by the targetid parameter to the value defined by the", "def insert(self, fields): \"\"\" Write a new record to the", "(:class:`py:bool`) True if this target id disabled Exceptions: KeyError if", "Get list of entries in the notify users field and", "same directory as the # config file defined by the", "is alternate to using [id] directly. It does an additonal", "required by applicable law or agreed to in writing, software", "all SQL databases. Subclasses of this class support specialized sql", "verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connection = None class", "with cvs it writes the whole file back \"\"\" backfile", "file %s does not exist ' % fn) else: self.filename", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "get_logger from ._companiestable import CompaniesTable __all__ = ['TargetsTable'] class TargetsTable(DBTableBase):", "\"\"\"Pass through to SQL\"\"\" if verbose: print('SQL Database type %s", "to SQL\"\"\" if verbose: print('SQL Database type %s verbose=%s' %", "into the field \"\"\" cursor = self.connection.cursor() enabled_kw = 'Enabled'", "limitations under the License. \"\"\" Define the base of targets", "list stored in db as string of integers separated by", "dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) fn = db_dict['targetsfilename'] self.filename", "self).__init__(db_dict, dbtype, verbose, output_format) fn = db_dict['targetsfilename'] self.filename = fn", "field names in the order defined.\"\"\" return list(self.table_format_dict) def get_format_dict(self,", "notify users field and split into python list and return", "the db field is an enum it actually sete Active", "Fields that are required to create new records required_fields =", "not in the table \"\"\" for field in fields: self.table_format_dict[field]", "WBEM server port.\"} # # Defines each record for the", "if target not in targets dictionary \"\"\" if not isinstance(targetid,", "agreed to in writing, software # distributed under the License", "attribute. db_type (:term: `string`) String defining one of the allowed", "fields defined in field_list for the record_id in display format.", "('SMIVersion', ('SMIVersion', 12, str)), ('Product', ('Product', 15, str)), ('Principal', ('Principal',", "for the property # # The value tuple is display", "%s', targetid, sql, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table()", "KeyError if target not in targets dictionary \"\"\" if not", "('ID', 2, int)), ('CompanyName', ('CompanyName', 12, str)), ('Namespace', ('Namespace', 12,", "distributed under the License is distributed on an \"AS IS\"", "* len(fields)) columns = ', '.join(fields.keys()) sql = \"INSERT INTO", "%s Changes: %s Exception: %s', targetid, sql, changes, ex) raise", "a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connectdb(db_dict, verbose) self._load_table()", "return_list def get_target(self, targetid): \"\"\" Get the target data for", "inst %r' % inst) return inst def get_field_list(self): \"\"\"Return a", "only if it is not the WBEM CIM-XML standard definitions.", "%s ) VALUES ( %s )\" % (self.table_name, columns, placeholders)", "name): \"\"\"Return tuple of display name and length for name.\"\"\"", "Namespace = Column(String(30), nullable=False) SMIVersion = Column(String(15), nullable=False) Product =", "\"\"\"String info on targetdata. TODO. Put more info here\"\"\" #", "ids that are marked disabled\"\"\" return [x for x in", "os.path.join(db_dict['directory'], fn) if not os.path.isfile(full_fn): ValueError('CSV file %s does not", "normally be joins. In this case it is the companies", "return true, else return false. \"\"\" val = target_record['ScanEnabled'].lower() if", "else \" \"'Disabled'\", 'NotifyUsers': \"List of UserIDs to notify\", 'ScanEnabled':", "on targetdata. TODO. Put more info here\"\"\" # # return", "Column(String(30), nullable=False) CimomVersion = Column(String(30), nullable=False) InteropNamespace = Column(String(30), nullable=False)", "targetid) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid", "CompanyID %s\" % \\ target['CompanyID'] except Exception as ex: raise", "def test_fieldnames(self, fields): \"\"\"Test a list of field names. This", "output_format=output_format) elif db_type == ('mysql'): inst = MySQLTargetsTable(db_dict, db_type, verbose,", "OrderedDict() for key, value in self.data_dict.items(): if ip_filter and re.match(ip_filter,", "raise ValueError('Input Error. duplicate Id') else: result[key] = row self.data_dict", "set_names + \"{0} = %s\".format(key) values.append(value) values.append(targetid) sql = \"Update", "= {} target_record = self.get_target(targetid) for change in changes: original_data[change]", "(self.db_type, len(self.data_dict))) def test_fieldnames(self, fields): \"\"\"Test a list of field", "Id in table: %s\\nrow=%s' % (key, row)) raise ValueError('Input Error.", "output_list = [] # TODO clean up for python 3", "= { 'IPAddress': \"Host name or ip address\", 'CompanyID': \"DB", "into the targets table TODO we should not be doing", "Deleted', targetid) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable", "True ValueError('ScanEnabled field must contain \"Enabled\" or \"Disabled' ' string.", "in fields: field_value = target[field_name] fmt_value = self.get_format_dict(field_name) max_width =", "if self.disabled_target_id(x)] # TODO we have multiple of these. See", "enabled_kw = 'Enabled' if activate_flag else 'Disabled' sql = 'UPDATE", "companies table, by mapping the data to the dictionary defined", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed SQL update. SQL=%s. '", "data to the dictionary defined for targets \"\"\" # TODO", "= CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format) elif db_type == ('mysql'): inst", "IP addresses:port entries. TODO: Does not include port right now.", "record to the database containing the fields defined in the", "is display name and max width for the record table_format_dict", "= Column(String(15), nullable=False) CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30),", "case it is the companies table. Move the companyName into", "F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s Deleted', targetid)", "db_type == ('mysql'): inst = MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format) else:", "users field and split into python list and return the", "License. \"\"\" Define the base of targets (i.e. systems to", "# # The value tuple is display name and max", "targetid): \"\"\" Delete the target in the targets table defined", "sql = \"DELETE FROM Targets WHERE TargetID=%s\" try: # pylint:", "(:term: `string`) String defining one of the allowed database types", "that are required to create new records required_fields = [", "abstract Targets instance. This controls all other target bases. This", "\"\"\" table_name = 'Targets' key_field = 'TargetID' # Fields that", "list \"\"\" total_width = 0 for name in col_list: value", "tables that would normally be joins. In this case it", "cursor = self.connection.cursor() sql = \"DELETE FROM Targets WHERE TargetID=%s\"", "entries result = {} for row in reader: key =", "self.db_type, self.verbose) try: # set the companyname into the targets", "full_fn = os.path.join(db_dict['directory'], fn) if not os.path.isfile(full_fn): ValueError('CSV file %s", "dbtype %s verbose %s' % (db_dict, db_type, verbose)) if db_type", "regex strings. \"\"\" rtn = OrderedDict() for key, value in", "Error. duplicate Id') else: result[key] = row self.data_dict = result", "inst) return inst def get_field_list(self): \"\"\"Return a list of the", "output_format): \"\"\"Read the input file into a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict,", "and Principal that represents the unique combination of both. The", "target recorded for this target_id marked disabled. Otherwise return True", "else: result[key] = row self.data_dict = result def write_updated_record(self, record_id):", "self).__init__(db_dict, db_type, verbose) self.output_format = output_format # def __str__(self): #", "OR CONDITIONS OF ANY KIND, either express or implied. #", "sql database. Generate the targetstable from the sql database targets", "representing the userids. This list stored in db as string", "string. Port info is included only if it is not", "]) # noqa: E123 def __init__(self, db_dict, db_type, verbose, output_format):", "the License is distributed on an \"AS IS\" BASIS, #", "self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get list of target ids that are", "\"\"\"Read the input file into a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype,", "table. Move the companyName into the targets table TODO we", "('Interop', 8, str)), ('Notify', ('Notify', 12, str)), ('NotifyUsers', ('NotifyUsers', 12,", "SET ScanEnabled = %s WHERE TargetID = %s' try: cursor.execute(sql,", "for the record table_format_dict = OrderedDict([ ('TargetID', ('ID', 2, int)),", "'SMIVersion': \"SMI version\", 'Product': \"Product name\", 'Principal': \"User Name to", "audit_logger.info('TargetsTable TargetID: %s, update fields: %s, ' 'original fields: %s',", "get_unique_creds(self): \"\"\" Get the set of Credentials and Principal that", "\"\"\" Load the tables that would normally be joins. In", "single ipaddress, port in the database Parameters: host_id(tuple of hostname", "This test generates an exception, KeyError if a field in", "instance object of the defined provider type. \"\"\" inst =", "self.disabled_target_id(x)] # TODO we have multiple of these. See get", "target_id not in database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list): \"\"\"", "for PY 3 return_list = [] for key, value in", "ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() def delete(self,", "audit_logger.error('TargetTable targetid %s failed SQL DELETE. ' 'SQL=%s exception %s:", "E123 def __init__(self, db_dict, db_type, verbose, output_format): \"\"\"Initialize the abstract", "os.path.isfile(fn): ValueError('CSV file %s does not exist ' % fn)", "as f: writer = csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader() for key, value", "since that creates the correct object for the defined database", "law or agreed to in writing, software # distributed under", "required to create new records required_fields = [ 'IPAddress', 'CompanyID',", "Column(Integer(11), primary_key=True) IPAddress = Column(String(15), nullable=False) CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\"))", "# pylint: disable=unused-variable mydata = cursor.execute(sql, (targetid,)) # noqa F841", "%s\".format(key) values.append(value) values.append(targetid) sql = \"Update Targets \" + set_names", "\"List of UserIDs to notify\", 'ScanEnabled': \"Enabled if this target", "exception %s: %s', targetid, sql, enabled_kw, ex.__class__.__name__, ex) self.connection.rollback() raise", "the dictionary for each field to be inserted. Exceptions: \"\"\"", "finally: self._load_table() self._load_joins() cursor.close() def activate(self, targetid, activate_flag): \"\"\" Activate", "access target\", 'Credential': \"User password to access target\", 'CimomVersion': \"Version", "as the # config file defined by the db_dict entry", "4, int)), ('ScanEnabled', ('Enabled', 6, str)), ]) # noqa: E123", "may obtain a copy of the License at # #", "entries. TODO: Does not include port right now. \"\"\" output_list", "(self.db_type, self.get_dbdict(), # # # len(self.data_dict))) # def __repr__(self): #", "\"\"\"Read the input file into a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype,", "database key property for this table activate_flag (:class:`py:bool`): Next state", "Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers = Column(String(12), nullable=False) ScanEnabled = Column(Enum('Enabled',", "a string. Should be int internal. if value[\"IPAddress\"] == host_data[0]", "if their width is greater than the specification in the", "if target_id not in database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list):", "%s failed SQL change ' 'ScanEnabled. SQL=%s ' 'Change to", "update. SQL=%s. ' 'data=%s. Exception %s: %s', sql, fields, ex.__class__.__name__,", "the order defined.\"\"\" return list(self.table_format_dict) def get_format_dict(self, name): \"\"\"Return tuple", "ValueError('CSV file %s does not exist ' 'in local directory", "2, int)), ('CompanyName', ('CompanyName', 12, str)), ('Namespace', ('Namespace', 12, str)),", "'data=%s. Exception %s: %s', sql, fields, ex.__class__.__name__, ex) self.connection.rollback() raise", "six.integer_types): targetid = int(targetid) return self.data_dict[targetid] def filter_targets(self, ip_filter=None, company_name_filter=None):", "except Exception as ex: raise ValueError('Error: putting Company Name in", "%s', targetid, enabled_kw) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME)", "verbose, output_format) fn = db_dict['targetsfilename'] self.filename = fn # If", "with a join. \"\"\" # Get companies table and insert", "does this cover directories/clean up for possible exceptions. if os.path.isfile(backfile):", "may not use this file except in compliance with the", "database is a string. Should be int internal. if value[\"IPAddress\"]", "database type (db_type). Currently the types sql and csv are", "self.data_dict[targetid] def filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\" Filter for match of", "with the dictionary of items defined by changes where each", "db field is an enum it actually sete Active or", "in changes: original_data[change] = target_record[change] try: cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger", "not isinstance(targetid, six.integer_types): targetid = int(targetid) return self.data_dict[targetid] def filter_targets(self,", "MySQLDBMixin from ._common import get_url_str from ._logging import AUDIT_LOGGER_NAME, get_logger", "databases. Subclasses of this class support specialized sql databases. \"\"\"", "this file except in compliance with the License. # You", "12, str)), ('Credential', ('Credential', 12, str)), ('CimomVersion', ('CimomVersion', 15, str)),", "info is included only if it is not the WBEM", "keys \"\"\" # TODO clean up for PY 3 return_list", "'%s%s' % (v['Principal'], v['Credential']) for k, v in self.data_dict.items()} ucreds", "list of target ids that are marked enabled.\"\"\" return [x", "update_fields(self, targetid, changes): \"\"\" Update the database record defined by", "not exist ' 'in local directory or config directory %s'", "governing permissions and # limitations under the License. \"\"\" Define", "output formats. If not provided, the default is a simple", "%s' % (db_dict, db_type, verbose)) if db_type == ('csv'): inst", "verbose (:class:`py:bool`) Boolean. If true detailed info is displayed on", "verbose, output_format) self.connectdb(db_dict, verbose) self._load_table() self._load_joins() def _load_joins(self): \"\"\" Load", "this in this manner but with a join. \"\"\" #", "a join. \"\"\" # Get companies table and insert into", "cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s, update", "(self.db_dict, ex)) def update_fields(self, targetid, changes): \"\"\" Update the database", "# # Licensed under the Apache License, Version 2.0 (the", "the database containing the fields defined in the input. Parameters:", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Notify = Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers = Column(String(12), nullable=False) ScanEnabled", "= sql + \" WHERE TargetID=%s\" # Record the original", "WHERE TargetID=%s\" # Record the original data for the audit", "len(self.data_dict))) def test_fieldnames(self, fields): \"\"\"Test a list of field names.", "= [] for field_name in fields: field_value = target[field_name] fmt_value", "value in self.data_dict.items(): if ip_filter and re.match(ip_filter, value['IPAddress']): rtn[key] =", "this and __repr__ do not really match. # # \"\"\"String", "the activate_flag Parameters: targetid (:term:`py:integer`): The database key property for", "verbose)) if db_type == ('csv'): inst = CsvTargetsTable(db_dict, db_type, verbose,", "= output_format # def __str__(self): # # # TODO this", "record. Update does NOT test if the new value is", "return self.data_dict[targetid] def filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\" Filter for match", "class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This subclass of TargetsTable process targets", "controls all other target bases. This defines the common definition", "os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename) def write_file(self, file_name): \"\"\"Write the current", "Credentials and Principal that represents the unique combination of both.", "row)) raise ValueError('Input Error. duplicate Id') else: result[key] = row", "(C) Copyright 2017 Inova Development Inc. # All Rights Reserved", "12, str)), ('NotifyUsers', ('NotifyUsers', 12, str)), ('Protocol', ('Prot', 5, str)),", "\"\"\" Subclass of Targets data for all SQL databases. Subclasses", "a new TargetsTable object since that creates the correct object", "class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values form of the Target base.\"\"\"", "\"\"\" Get all WBEM Server ipaddresses in the targets base.", "for python 3 for _id, value in self.data_dict.items(): if self.verbose:", "value[1] return total_width def get_unique_creds(self): \"\"\" Get the set of", "k, v in creds.items()]) unique_keys = dict([[v, k] for k,", "targetstable from the sql database targets table and the companies", "dbtype, verbose, output_format) self.connectdb(db_dict, verbose) self._load_table() self._load_joins() def _load_joins(self): \"\"\"", "are supported. Returns instance object of the defined provider type.", "def get_dbdict(self): \"\"\"Get string for the db_dict\"\"\" return '%s' %", "the database Parameters: host_id(tuple of hostname or ipaddress and port)", "of UserIDs to notify\", 'ScanEnabled': \"Enabled if this target to", "an additonal check for correct type for target_id Returns: target", "as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed SQL update.", "data for the parameter target_id. This is alternate to using", "= self.get_format_dict(field_name) max_width = fmt_value[1] field_type = fmt_value[2] if isinstance(field_type,", "get_url_str from ._logging import AUDIT_LOGGER_NAME, get_logger from ._companiestable import CompaniesTable", "fields to be inserted into the table. There is one", "if comma: set_names = set_names + \", \" else: comma", "for k in unique_keys] return unique_creds class SQLTargetsTable(TargetsTable): \"\"\" Subclass", "%s' try: cursor.execute(sql, (enabled_kw, targetid)) # noqa F841 self.connection.commit() audit_logger", "Exception: %s', targetid, sql, changes, ex) raise ex finally: self._load_table()", "used to construct a new TargetsTable object since that creates", "in the input. Parameters: field_data () Dictionary of fields to", "%s,set scanEnabled to %s', targetid, enabled_kw) except mysqlerror as ex:", "col_list: value = self.get_format_dict(name) total_width += value[1] return total_width def", "or implied. # See the License for the specific language", "port from database is a string. Should be int internal.", "fmt_value[2] if isinstance(field_type, six.string_types) and field_value: if max_width < len(field_value):", "integers separated by commas. Returns None if there is no", "parameter to the value defined by the activate_flag Parameters: targetid", "userid in notify_users_list] return notify_users_list return None def format_record(self, record_id,", "error %s' % (self.db_dict, ex)) def update_fields(self, targetid, changes): \"\"\"", "and insert into targets table: # TODO in smipyping name", "== ('mysql'): inst = MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format) else: ValueError('Invalid", "actually sete Active or Inactive strings into the field \"\"\"", "for # each set of entries result = {} for", "could be used to test with all Principals/Credentials knows in", "= False for key, value in changes.items(): if comma: set_names", "\"https\"', 'Port': \"Integer defining WBEM server port.\"} # # Defines", "will be set into the database for this target. Since", "in display format. String fields will be folded if their", "'Product', 'Principal', 'Credential', 'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port']", "port in the database Parameters: host_id(tuple of hostname or ipaddress", "# TODO clean up for python 3 for _id, value", "# TODO port from database is a string. Should be", "process targets infromation from an sql database. Generate the targetstable", "self.filename # TODO does this cover directories/clean up for possible", "class output_format (:term:`string`) String defining one of the legal report", "'SQL: %s Changes: %s Exception: %s', targetid, sql, changes, ex)", "exceptions. if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename) def write_file(self, file_name):", "TODO: Does not include port right now. \"\"\" output_list =", "field_value: if max_width < len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s' %", "'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion', 'Product', 'Principal', 'Credential', 'CimomVersion', 'InteropNamespace', 'Notify',", "table \"\"\" for field in fields: self.table_format_dict[field] # pylint: disable=pointless-statement", "name is db_dict. Elsewhere it is db_info companies_tbl = CompaniesTable.factory(self.db_dict,", "for row in reader: key = int(row['TargetID']) if key in", "try: cursor.execute(sql, fields.values()) self.connection.commit() new_targetid = cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME)", "If true detailed info is displayed on the processing of", "CIMOM\", 'InteropNamespace': \"Interop Namespace name\", 'Notify': \"'Enabled' if users to", "write the new one. with cvs it writes the whole", "invalid.' % val) def disabled_target_id(self, targetid): \"\"\" Return True if", "{k: '%s%s' % (v['Principal'], v['Credential']) for k, v in self.data_dict.items()}", "input file into a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format)", "v['Credential']) for k, v in self.data_dict.items()} ucreds = dict([[v, k]", "by the activate_flag Parameters: targetid (:term:`py:integer`): The database key property", "test_fieldnames(self, fields): \"\"\"Test a list of field names. This test", "companyname filter if they exist and return list of any", "host systems, etc. in the environment. The factory method should", "ipaddress, port in the database Parameters: host_id(tuple of hostname or", "db_type, verbose)) if db_type == ('csv'): inst = CsvTargetsTable(db_dict, db_type,", "ipaddress, port entries for a single ipaddress, port in the", "Principals/Credentials knows in the db. Return list of targetIDs that", "output_format): \"\"\"Read the input file into a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict,", "'disabled': return True ValueError('ScanEnabled field must contain \"Enabled\" or \"Disabled'", "target_record): # pylint: disable=no-self-use \"\"\" If target_record disabled, return true,", "+ \" WHERE TargetID=%s\" # Record the original data for", "for the record_id in display format. String fields will be", "in table %r error %s' % (self.db_dict, ex)) def update_fields(self,", "dict([[v, k] for k, v in creds.items()]) unique_keys = dict([[v,", "get_target(self, targetid): \"\"\" Get the target data for the parameter", "targetid, sql, enabled_kw, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table()", "targets factory db_type %s' % db_type) if verbose: print('Resulting targets", "target['CompanyName'] = \"TableError CompanyID %s\" % \\ target['CompanyID'] except Exception", "\"Host name or ip address\", 'CompanyID': \"DB id of company\",", "the dictionary defined for targets \"\"\" # TODO filename is", "line.append('%s' % field_value) else: line.append('%s' % field_value) return line def", "% field_value) return line def disabled_target(self, target_record): # pylint: disable=no-self-use", "targetid): \"\"\"Get the string representing the url for targetid. Gets", "str)), ('Namespace', ('Namespace', 12, str)), ('SMIVersion', ('SMIVersion', 12, str)), ('Product',", "changes): \"\"\" Update the database record defined by targetid with", "other target bases. This defines the common definition of all", "= Column(String(30), nullable=False) Principal = Column(String(30), nullable=False) Credential = Column(String(30),", "the new one. with cvs it writes the whole file", "all of the parameters to open the database defined by", "def get_notifyusers(self, targetid): \"\"\" Get list of entries in the", "key_field = 'TargetID' # Fields that are required to create", "self.connection.commit() new_targetid = cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s", "for name in col_list: value = self.get_format_dict(name) total_width += value[1]", "common definition of all targets bases including field names, and", "('mysql'): inst = MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format) else: ValueError('Invalid targets", "TODO we should not be doing this in this manner", "value in changes.items(): if comma: set_names = set_names + \",", "key in result: # duplicate row handling print('ERROR. Duplicate Id", "company_name_filter and \\ re.match(value['CompanyName'], company_name_filter): rtn[key] = value return rtn", "in the target record. Update does NOT test if the", "filter if they exist and return list of any targets", "ip_filter and companyname filter if they exist and return list", "Should be int internal. if value[\"IPAddress\"] == host_data[0] and int(port)", "MySQLDBMixin): \"\"\" This subclass of TargetsTable process targets infromation from", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s Deleted', targetid) except mysqlerror as", "list of all the column headers from the record_list.\"\"\" hdr", "ucreds = dict([[v, k] for k, v in creds.items()]) unique_keys", "than the specification in the format_dictionary and fold=True \"\"\" #", "wrap import six from mysql.connector import Error as mysqlerror from", "targetid %s failed SQL DELETE. ' 'SQL=%s exception %s: %s',", "def __repr__(self): # # \"\"\"Rep of target data\"\"\" # #", "company\", 'Namespace': \"User namespace\", 'SMIVersion': \"SMI version\", 'Product': \"Product name\",", "defining one of the legal report output formats. If not", "to %s exception %s: %s', targetid, sql, enabled_kw, ex.__class__.__name__, ex)", "entries in the notify users field and split into python", "defined for targets \"\"\" # TODO filename is config file", "self.connection = None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This subclass of", "right now. \"\"\" output_list = [] # TODO clean up", "key, value in changes.items(): if comma: set_names = set_names +", "is an enum it actually sete Active or Inactive strings", "'Disabled'), default='Enabled') Protocol = Column(String(10), default='http') Port = Column(String(10), nullable=False)", "enum it actually sete Active or Inactive strings into the", "get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s failed SQL change ' 'ScanEnabled. SQL=%s", "Delete the target in the targets table defined by the", "the parameter target_id. This is alternate to using [id] directly.", "Id for the Target_Tableue . Returns: (:class:`py:bool`) True if this", "notify_users = self[targetid]['NotifyUsers'] if notify_users: notify_users_list = notify_users.split(',') notify_users_list =", "Rights Reserved # # Licensed under the Apache License, Version", "\"Version of CIMOM\", 'InteropNamespace': \"Interop Namespace name\", 'Notify': \"'Enabled' if", "value return rtn def build_url(self, targetid): \"\"\"Get the string representing", "targetid \"\"\" cursor = self.connection.cursor() sql = \"DELETE FROM Targets", "in the targets base. Returns list of IP addresses:port entries.", "\"TableError CompanyID %s\" % \\ target['CompanyID'] except Exception as ex:", "%s dbtype %s verbose %s' % (db_dict, db_type, verbose)) if", "defined provider type. \"\"\" inst = None if verbose: print('targetdata", "the companyname into the targets table for target_key in self.data_dict:", "not the WBEM CIM-XML standard definitions. \"\"\" target = self[targetid]", "placeholders = ', '.join(['%s'] * len(fields)) columns = ', '.join(fields.keys())", "used to test with all Principals/Credentials knows in the db.", "Parameters: host_id(tuple of hostname or ipaddress and port) Returns list", "TODO port from database is a string. Should be int", "= ', '.join(['%s'] * len(fields)) columns = ', '.join(fields.keys()) sql", "targets db table. This base contains information on the targets,", "a table from the column names in the list \"\"\"", "import Error as mysqlerror from ._dbtablebase import DBTableBase from ._mysqldbmixin", "return get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\" Get", "str)), ('Notify', ('Notify', 12, str)), ('NotifyUsers', ('NotifyUsers', 12, str)), ('Protocol',", "up for python 3 for _id, value in self.data_dict.items(): if", "\"Disabled' ' string. %s is invalid.' % val) def disabled_target_id(self,", "that represent unique sets of Principal and Credential \"\"\" creds", "else: line.append('%s' % field_value) else: line.append('%s' % field_value) return line", "def disabled_target(self, target_record): # pylint: disable=no-self-use \"\"\" If target_record disabled,", "sql and csv are supported. Returns instance object of the", "enabled.\"\"\" return [x for x in self.data_dict if not self.disabled_target_id(x)]", "based on database type (db_type). Currently the types sql and", "in writing, software # distributed under the License is distributed", "\"User password to access target\", 'CimomVersion': \"Version of CIMOM\", 'InteropNamespace':", "return_list.append(key) return return_list def get_target(self, targetid): \"\"\" Get the target", "ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k in unique_keys] return", "%s Exception: %s', targetid, sql, changes, ex) raise ex finally:", "on database type (db_type). Currently the types sql and csv", "CompaniesTable __all__ = ['TargetsTable'] class TargetsTable(DBTableBase): \"\"\" Class representing the", "= 0 for name in col_list: value = self.get_format_dict(name) total_width", "targetid, sql, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins()", "of target ids that are marked disabled\"\"\" return [x for", "parameter target_id. This is alternate to using [id] directly. It", "to be tested) TargetID = Column(Integer(11), primary_key=True) IPAddress = Column(String(15),", "# TODO in smipyping name is db_dict. Elsewhere it is", "result def write_updated_record(self, record_id): \"\"\"Backup the existing file and write", "the targets table TODO we should not be doing this", "Target_Tableue . Returns: (:class:`py:bool`) True if this target id disabled", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "value in self.data_dict.items(): if self.verbose: print('get_hostid_list value %s' % (value,))", "License, Version 2.0 (the \"License\"); # you may not use", "def update_fields(self, targetid, changes): \"\"\" Update the database record defined", "target as dictionary Exceptions: KeyError if target not in targets", "('type=%s db=%s, len=%s' % (self.db_type, self.get_dbdict(), # # # len(self.data_dict)))", "targets (i.e. systems to be tested) TargetID = Column(Integer(11), primary_key=True)", "# limitations under the License. \"\"\" Define the base of", "True if target recorded for this target_id marked disabled. Otherwise", "userids. This list stored in db as string of integers", "= int(row['TargetID']) if key in result: # duplicate row handling", "if they exist and return list of any targets that", "Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30), nullable=False) SMIVersion = Column(String(15), nullable=False)", "self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s failed SQL update.", "new TargetsTable object since that creates the correct object for", "def get_unique_creds(self): \"\"\" Get the set of Credentials and Principal", "int(port) == host_data[1]: return_list.append(key) return return_list def get_target(self, targetid): \"\"\"", "as ex: raise ValueError('Error: putting Company Name in table %r", "( %s ) VALUES ( %s )\" % (self.table_name, columns,", "the License for the specific language governing permissions and #", "mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s failed", "with dictionary for # each set of entries result =", "fold=False): \"\"\"Return the fields defined in field_list for the record_id", "the default is a simple report format. \"\"\" super(TargetsTable, self).__init__(db_dict,", "= '%s.bak' % self.filename # TODO does this cover directories/clean", "length for name.\"\"\" return self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get list of", "they exist and return list of any targets that match.", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Dictionary of fields to be inserted into the table. There", "set_names = set_names + \"{0} = %s\".format(key) values.append(value) values.append(targetid) sql", "existing file and write the new one. with cvs it", "('CimomVersion', 15, str)), ('IPAddress', ('IPAddress', 12, str)), ('InteropNamespace', ('Interop', 8,", "['CompanyName'] all_fields = fields + join_fields hints = { 'IPAddress':", "'wb') as f: writer = csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader() for key,", "sql, fields, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins()", "fn else: if os.path.isfile(fn): self.filename = fn else: full_fn =", "in fields: self.table_format_dict[field] # pylint: disable=pointless-statement def get_dbdict(self): \"\"\"Get string", "(:term:`py:integer`): The database key property for this table activate_flag (:class:`py:bool`):", "os.path.isabs(fn): if not os.path.isfile(fn): ValueError('CSV file %s does not exist", "Development Inc. # All Rights Reserved # # Licensed under", "sql = sql + \" WHERE TargetID=%s\" # Record the", "as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s failed SQL", "class SQLTargetsTable(TargetsTable): \"\"\" Subclass of Targets data for all SQL", "# TODO change ip_address to hostname where host name is", "file into a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connectdb(db_dict,", "\"\"\" This subclass of TargetsTable process targets infromation from an", "\" else: comma = True set_names = set_names + \"{0}", "fields defined in the input. Parameters: field_data () Dictionary of", "\"\"\" Write a new record to the database containing the", "create dictionary (id = key) with dictionary for # each", "in self.data_dict.items()} ucreds = dict([[v, k] for k, v in", "disabled\"\"\" return [x for x in self.data_dict if self.disabled_target_id(x)] #", "%s' % (value,)) output_list.append(value['IPAddress']) return output_list def tbl_hdr(self, record_list): \"\"\"Return", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "in this manner but with a join. \"\"\" # Get", "fn = db_dict['targetsfilename'] self.filename = fn # If the filename", "each record for the data base and outputs. # #", "else: line.append('%s' % field_value) return line def disabled_target(self, target_record): #", "= [] comma = False for key, value in changes.items():", "12, str)), ('Namespace', ('Namespace', 12, str)), ('SMIVersion', ('SMIVersion', 12, str)),", "strings into the field \"\"\" cursor = self.connection.cursor() enabled_kw =", "pylint: disable=no-self-use \"\"\" If target_record disabled, return true, else return", "%s, update fields: %s, ' 'original fields: %s', targetid, changes,", "marked disabled. Otherwise return True Parameters: target_id(:term:`integer`) Valid target Id", "changes where each item is an entry in the target", "and write the new one. with cvs it writes the", "columns, placeholders) try: cursor.execute(sql, fields.values()) self.connection.commit() new_targetid = cursor.lastrowid audit_logger", "comma = True set_names = set_names + \"{0} = %s\".format(key)", "def factory(cls, db_dict, db_type, verbose, output_format='simple'): \"\"\"Factory method to select", "noqa: E123 def __init__(self, db_dict, db_type, verbose, output_format): \"\"\"Initialize the", "\"\"\"Comma Separated Values form of the Target base.\"\"\" def __init__(self,", "fields in each record. fields = [key_field] + required_fields join_fields", "target Id for the Target_Tableue . Returns: (:class:`py:bool`) True if", "self.data_dict: target = self.data_dict[target_key] if target['CompanyID'] in companies_tbl: company =", "# # return ('Targetdata db_type %s, rep count=%s' % #", "a new record to the database containing the fields defined", "the types sql and csv are supported. Returns instance object", "correct object for the defined database type. \"\"\" table_name =", "entries for a single ipaddress, port in the database Parameters:", "('CompanyName', ('CompanyName', 12, str)), ('Namespace', ('Namespace', 12, str)), ('SMIVersion', ('SMIVersion',", "the License. \"\"\" Define the base of targets (i.e. systems", "== ('csv'): inst = CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format) elif db_type", "# distributed under the License is distributed on an \"AS", "Separated Values form of the Target base.\"\"\" def __init__(self, db_dict,", "__repr__(self): # # \"\"\"Rep of target data\"\"\" # # return", "% (fn, db_dict['directory'])) else: self.filename = full_fn with open(self.filename) as", "# Unless required by applicable law or agreed to in", "targetid): \"\"\" Get the target data for the parameter target_id.", "table %r error %s' % (self.db_dict, ex)) def update_fields(self, targetid,", "it is not the WBEM CIM-XML standard definitions. \"\"\" target", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "FROM Targets WHERE TargetID=%s\" try: # pylint: disable=unused-variable mydata =", "no data in NotifyUsers. \"\"\" notify_users = self[targetid]['NotifyUsers'] if notify_users:", "values = [] comma = False for key, value in", "Load the tables that would normally be joins. In this", "print('Resulting targets factory inst %r' % inst) return inst def", "verbose, output_format) self.connection = None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This", "url for targetid. Gets the Protocol, IPaddress and port and", "mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed SQL", "for k, v in ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for", "the value defined by the activate_flag Parameters: targetid (:term:`py:integer`): The", "nullable=False) ScanEnabled = Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol = Column(String(10), default='http')", "info here\"\"\" # # return ('type=%s db=%s, len=%s' % (self.db_type,", "server port.\"} # # Defines each record for the data", "included only if it is not the WBEM CIM-XML standard", "targets base. Returns list of IP addresses:port entries. TODO: Does", "ipaddress and port) Returns list of targetdata keys \"\"\" #", "cursor = self.connection.cursor() # dynamically build the update sql based", "self.connection.cursor() enabled_kw = 'Enabled' if activate_flag else 'Disabled' sql =", "\"\"\" # Get companies table and insert into targets table:", "val = target_record['ScanEnabled'].lower() if val == 'enabled': return False if", "to construct a new TargetsTable object since that creates the", "dict_for_host,get_hostid_list def get_targets_host(self, host_data): \"\"\" If an record for `host_data`", "the Apache License, Version 2.0 (the \"License\"); # you may", "field \"\"\" cursor = self.connection.cursor() enabled_kw = 'Enabled' if activate_flag", "self.connection.cursor() sql = \"DELETE FROM Targets WHERE TargetID=%s\" try: #", "the database for this target. Since the db field is", "# TODO clean up for PY 3 return_list = []", "%s', new_targetid, fields) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME)", "csv.DictReader(input_file) # create dictionary (id = key) with dictionary for", "file %s does not exist ' 'in local directory or", "' 'Change to %s exception %s: %s', targetid, sql, enabled_kw,", "('Prot', 5, str)), ('Port', ('Port', 4, int)), ('ScanEnabled', ('Enabled', 6,", "ex)) def update_fields(self, targetid, changes): \"\"\" Update the database record", "of the defined provider type. \"\"\" inst = None if", "Targets SET ScanEnabled = %s WHERE TargetID = %s' try:", "if val == 'disabled': return True ValueError('ScanEnabled field must contain", "def __init__(self, db_dict, db_type, verbose, output_format): \"\"\"Initialize the abstract Targets", "for the data base and outputs. # # The Name", "\"User Name to access target\", 'Credential': \"User password to access", "verbose) self.output_format = output_format # def __str__(self): # # #", "join_fields = ['CompanyName'] all_fields = fields + join_fields hints =", "where host name is name : port from __future__ import", "unique sets of Principal and Credential \"\"\" creds = {k:", "= os.path.join(db_dict['directory'], fn) if not os.path.isfile(full_fn): ValueError('CSV file %s does", "\"'Disabled'\", 'NotifyUsers': \"List of UserIDs to notify\", 'ScanEnabled': \"Enabled if", "('CimomVersion', ('CimomVersion', 15, str)), ('IPAddress', ('IPAddress', 12, str)), ('InteropNamespace', ('Interop',", "Database type %s verbose=%s' % (db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype,", "for _id, value in self.data_dict.items(): if self.verbose: print('get_hostid_list value %s'", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s failed SQL update. ' 'SQL:", "db_type (:term: `string`) String defining one of the allowed database", "\"\"\" creds = {k: '%s%s' % (v['Principal'], v['Credential']) for k,", "the abstract Targets instance. This controls all other target bases.", "'ScanEnabled': \"Enabled if this target to be scanned\", 'Protocol': '\"http\"", "databases. \"\"\" def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Pass through", "ScanEnabled = %s WHERE TargetID = %s' try: cursor.execute(sql, (enabled_kw,", "else: self.filename = fn else: if os.path.isfile(fn): self.filename = fn", "target\", 'Credential': \"User password to access target\", 'CimomVersion': \"Version of", "return return_list def get_target(self, targetid): \"\"\" Get the target data", "TODO this and __repr__ do not really match. # #", "with all Principals/Credentials knows in the db. Return list of", "%s is invalid.' % val) def disabled_target_id(self, targetid): \"\"\" Return", "defined by changes where each item is an entry in", "join_fields hints = { 'IPAddress': \"Host name or ip address\",", "Targets instance. This controls all other target bases. This defines", "\"\"\" Get list of entries in the notify users field", "otherwise return None. There may be multiple ipaddress, port entries", "all_fields = fields + join_fields hints = { 'IPAddress': \"Host", "Record the original data for the audit log. original_data =", "python list and return the list of integers representing the", "test if the new value is the same as the", "cvs it writes the whole file back \"\"\" backfile =", "from mysql.connector import Error as mysqlerror from ._dbtablebase import DBTableBase", "to access target\", 'CimomVersion': \"Version of CIMOM\", 'InteropNamespace': \"Interop Namespace", "factory method should be used to construct a new TargetsTable", "or ipaddress and port) Returns list of targetdata keys \"\"\"", "to notify\", 'ScanEnabled': \"Enabled if this target to be scanned\",", "output_list.append(value['IPAddress']) return output_list def tbl_hdr(self, record_list): \"\"\"Return a list of", "# noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set", "fold=True \"\"\" # TODO can we make this a std", "= [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k in unique_keys] return unique_creds class", "targets dictionary \"\"\" if not isinstance(targetid, six.integer_types): targetid = int(targetid)", "directory, the data file must be # either in the", "is the companies table. Move the companyName into the targets", "bases including field names, and common methods. Parameters: db_dict (:term:", "in the order defined.\"\"\" return list(self.table_format_dict) def get_format_dict(self, name): \"\"\"Return", "using [id] directly. It does an additonal check for correct", "Copyright 2017 Inova Development Inc. # All Rights Reserved #", "import get_url_str from ._logging import AUDIT_LOGGER_NAME, get_logger from ._companiestable import", "if activate_flag else 'Disabled' sql = 'UPDATE Targets SET ScanEnabled", "String fields will be folded if their width is greater", "self._load_table() self._load_joins() self.connection.close() def insert(self, fields): \"\"\" Write a new", "in the targets table defined by the targetid \"\"\" cursor", "get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\" Get all", "of issues, else \" \"'Disabled'\", 'NotifyUsers': \"List of UserIDs to", "under the License is distributed on an \"AS IS\" BASIS,", "# \"\"\"String info on targetdata. TODO. Put more info here\"\"\"", "for `host_data` exists return that record, otherwise return None. There", "isinstance(field_type, six.string_types) and field_value: if max_width < len(field_value): line.append('\\n'.join(wrap(field_value, max_width)))", "self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s, update fields: %s,", "\"\"\" backfile = '%s.bak' % self.filename # TODO does this", "# Fields that are required to create new records required_fields", "('Notify', ('Notify', 12, str)), ('NotifyUsers', ('NotifyUsers', 12, str)), ('Protocol', ('Prot',", "directories/clean up for possible exceptions. if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile)", "= 'Targets' key_field = 'TargetID' # Fields that are required", "changes, ex) raise ex finally: self._load_table() self._load_joins() cursor.close() def activate(self,", "and split into python list and return the list of", "max width for the record table_format_dict = OrderedDict([ ('TargetID', ('ID',", "comma = False for key, value in changes.items(): if comma:", "self[targetid] return get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\"", "for field_name in fields: field_value = target[field_name] fmt_value = self.get_format_dict(field_name)", "Target base.\"\"\" def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read the", "to be notified of issues, else \" \"'Disabled'\", 'NotifyUsers': \"List", "target_record['ScanEnabled'].lower() if val == 'enabled': return False if val ==", "activate_flag): \"\"\" Activate or deactivate the table entry defined by", "on the changes dictionary set_names = \"SET \" values =", "= dict([[v, k] for k, v in ucreds.items()]) unique_creds =", "the list of integers representing the userids. This list stored", "def tbl_hdr(self, record_list): \"\"\"Return a list of all the column", "self.data_dict = result def write_updated_record(self, record_id): \"\"\"Backup the existing file", "is not in the table \"\"\" for field in fields:", "nullable=False) Principal = Column(String(30), nullable=False) Credential = Column(String(30), nullable=False) CimomVersion", "in targets dictionary \"\"\" if not isinstance(targetid, six.integer_types): targetid =", "\"\"\"Return the fields defined in field_list for the record_id in", "of integers separated by commas. Returns None if there is", "through to SQL\"\"\" if verbose: print('SQL Database type %s verbose=%s'", "try: cursor.execute(sql, (enabled_kw, targetid)) # noqa F841 self.connection.commit() audit_logger =", "defined in the input. Parameters: field_data () Dictionary of fields", "Returns: target as dictionary Exceptions: KeyError if target not in", "inserted into the table. There is one entry in the", "= fn else: full_fn = os.path.join(db_dict['directory'], fn) if not os.path.isfile(full_fn):", "is not the WBEM CIM-XML standard definitions. \"\"\" target =", "return rtn def build_url(self, targetid): \"\"\"Get the string representing the", "table: # TODO in smipyping name is db_dict. Elsewhere it", "The filters are regex strings. \"\"\" rtn = OrderedDict() for", "= companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName'] else: target['CompanyName'] = \"TableError CompanyID", "that represents the unique combination of both. The result could", "(db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connection = None", "the companyName into the targets table TODO we should not", "'CimomVersion': \"Version of CIMOM\", 'InteropNamespace': \"Interop Namespace name\", 'Notify': \"'Enabled'", "here\"\"\" # # return ('type=%s db=%s, len=%s' % (self.db_type, self.get_dbdict(),", "self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set scanEnabled to %s',", "id disabled Exceptions: KeyError if target_id not in database \"\"\"", "from ._mysqldbmixin import MySQLDBMixin from ._common import get_url_str from ._logging", "is name : port from __future__ import print_function, absolute_import import", "ip_filter=None, company_name_filter=None): \"\"\" Get all WBEM Server ipaddresses in the", "scanEnabled to %s', targetid, enabled_kw) except mysqlerror as ex: audit_logger", "= \"DELETE FROM Targets WHERE TargetID=%s\" try: # pylint: disable=unused-variable", "these. See get dict_for_host,get_hostid_list def get_targets_host(self, host_data): \"\"\" If an", "target not in targets dictionary \"\"\" if not isinstance(targetid, six.integer_types):", "fields = [key_field] + required_fields join_fields = ['CompanyName'] all_fields =", "new value is the same as the original value. \"\"\"", "self.filename = full_fn with open(self.filename) as input_file: reader = csv.DictReader(input_file)", "import CompaniesTable __all__ = ['TargetsTable'] class TargetsTable(DBTableBase): \"\"\" Class representing", "else: ValueError('Invalid targets factory db_type %s' % db_type) if verbose:", "'Protocol', 'Port'] # All fields in each record. fields =", "target = self[targetid] return get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def get_hostid_list(self, ip_filter=None,", "output_format (:term:`string`) String defining one of the legal report output", "of all targets bases including field names, and common methods.", "if the new value is the same as the original", "= set_names + \"{0} = %s\".format(key) values.append(value) values.append(targetid) sql =", "database for this target. Since the db field is an", "(value,)) output_list.append(value['IPAddress']) return output_list def tbl_hdr(self, record_list): \"\"\"Return a list", "Id') else: result[key] = row self.data_dict = result def write_updated_record(self,", "companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try: # set the companyname", "width for the record table_format_dict = OrderedDict([ ('TargetID', ('ID', 2,", "\"\"\" # TODO can we make this a std cvt", "target = self.get_target(record_id) line = [] for field_name in fields:", "= value if company_name_filter and \\ re.match(value['CompanyName'], company_name_filter): rtn[key] =", "new_targetid = cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s added.", "\" + set_names # append targetid component sql = sql", "this manner but with a join. \"\"\" # Get companies", "for k, v in self.data_dict.items()} ucreds = dict([[v, k] for", "# # # len(self.data_dict))) # def __repr__(self): # # \"\"\"Rep", "= [ 'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion', 'Product', 'Principal', 'Credential', 'CimomVersion',", "six from mysql.connector import Error as mysqlerror from ._dbtablebase import", "Filter for match of ip_filter and companyname filter if they", "name. def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read the input", "database containing the fields defined in the input. Parameters: field_data", "ANY KIND, either express or implied. # See the License", "string. Should be int internal. if value[\"IPAddress\"] == host_data[0] and", "for this target. Since the db field is an enum", "If target_record disabled, return true, else return false. \"\"\" val", "self.data_dict.items(): port = value[\"Port\"] # TODO port from database is", "the License. # You may obtain a copy of the", "\"SET \" values = [] comma = False for key,", "the base table field names in the order defined.\"\"\" return", "# See the License for the specific language governing permissions", "= Column(Integer(11), primary_key=True) IPAddress = Column(String(15), nullable=False) CompanyID = Column(Integer(11),", "nullable=False) Product = Column(String(30), nullable=False) Principal = Column(String(30), nullable=False) Credential", "Parameters: db_dict (:term: `dictionary') Dictionary containing all of the parameters", "and port and uses the common get_url_str to create a", "to hostname where host name is name : port from", "scanned\", 'Protocol': '\"http\" or \"https\"', 'Port': \"Integer defining WBEM server", "_id, value in self.data_dict.items(): if self.verbose: print('get_hostid_list value %s' %", "targetid. Gets the Protocol, IPaddress and port and uses the", "required_fields join_fields = ['CompanyName'] all_fields = fields + join_fields hints", "return '%s' % self.db_dict @classmethod def factory(cls, db_dict, db_type, verbose,", "= \"TableError CompanyID %s\" % \\ target['CompanyID'] except Exception as", "be notified of issues, else \" \"'Disabled'\", 'NotifyUsers': \"List of", "'Product': \"Product name\", 'Principal': \"User Name to access target\", 'Credential':", "Parameters: target_id(:term:`integer`) Valid target Id for the Target_Tableue . Returns:", "that will be set into the database for this target.", "into the targets table for target_key in self.data_dict: target =", "of fields to be inserted into the table. There is", "\\ target['CompanyID'] except Exception as ex: raise ValueError('Error: putting Company", "% (db_dict, db_type, verbose)) if db_type == ('csv'): inst =", "file name, not actual file name. def __init__(self, db_dict, dbtype,", "in the database Parameters: host_id(tuple of hostname or ipaddress and", "port and uses the common get_url_str to create a string.", "targets table for target_key in self.data_dict: target = self.data_dict[target_key] if", "will be folded if their width is greater than the", "not a full directory, the data file must be #", "5, str)), ('Port', ('Port', 4, int)), ('ScanEnabled', ('Enabled', 6, str)),", "sql, changes, ex) raise ex finally: self._load_table() self._load_joins() cursor.close() def", "# # The Name is the database name for the", "audit log. original_data = {} target_record = self.get_target(targetid) for change", "field is an enum it actually sete Active or Inactive", "alternate to using [id] directly. It does an additonal check", "that creates the correct object for the defined database type.", "'Credential', 'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port'] # All", "TODO can we make this a std cvt function. target", "%s: %s', targetid, sql, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally:", "property for this table activate_flag (:class:`py:bool`): Next state that will", "on the processing of the TargetData class output_format (:term:`string`) String", "3 return_list = [] for key, value in self.data_dict.items(): port", "log. original_data = {} target_record = self.get_target(targetid) for change in", "'Port'] # All fields in each record. fields = [key_field]", "records required_fields = [ 'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion', 'Product', 'Principal',", "%s failed SQL update. ' 'SQL: %s Changes: %s Exception:", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "fields): \"\"\"Test a list of field names. This test generates", "str)), ('SMIVersion', ('SMIVersion', 12, str)), ('Product', ('Product', 15, str)), ('Principal',", "activate(self, targetid, activate_flag): \"\"\" Activate or deactivate the table entry", "values.append(targetid) sql = \"Update Targets \" + set_names # append", "# # Defines each record for the data base and", "import AUDIT_LOGGER_NAME, get_logger from ._companiestable import CompaniesTable __all__ = ['TargetsTable']", "and length for name.\"\"\" return self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get list", "== host_data[0] and int(port) == host_data[1]: return_list.append(key) return return_list def", "notify\", 'ScanEnabled': \"Enabled if this target to be scanned\", 'Protocol':", "writing, software # distributed under the License is distributed on", "dictionary for # each set of entries result = {}", "targetid with the dictionary of items defined by changes where", "\"\"\" Define the base of targets (i.e. systems to be", "= \"SET \" values = [] comma = False for", "TODO. Put more info here\"\"\" # # return ('type=%s db=%s,", "\"\"\" cursor = self.connection.cursor() # dynamically build the update sql", "tuple is display name and max width for the record", "actual file name. def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read", "('Product', ('Product', 15, str)), ('Principal', ('Principal', 12, str)), ('Credential', ('Credential',", "the record_list.\"\"\" hdr = [] for name in record_list: value", "match. # # \"\"\"String info on targetdata. TODO. Put more", "Activate or deactivate the table entry defined by the targetid", "change in changes: original_data[change] = target_record[change] try: cursor.execute(sql, tuple(values)) self.connection.commit()", "# # return ('type=%s db=%s, len=%s' % (self.db_type, self.get_dbdict(), #", "._companiestable import CompaniesTable __all__ = ['TargetsTable'] class TargetsTable(DBTableBase): \"\"\" Class", "and field_value: if max_width < len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s'", "mydata = cursor.execute(sql, (targetid,)) # noqa F841 self.connection.commit() audit_logger =", "fn else: full_fn = os.path.join(db_dict['directory'], fn) if not os.path.isfile(full_fn): ValueError('CSV", "the named file.\"\"\" with open(file_name, 'wb') as f: writer =", "table and the companies table, by mapping the data to", "len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s' % field_value) else: line.append('%s' %", "'SQL=%s exception %s: %s', targetid, sql, ex.__class__.__name__, ex) self.connection.rollback() raise", "\"SMI version\", 'Product': \"Product name\", 'Principal': \"User Name to access", "duplicate row handling print('ERROR. Duplicate Id in table: %s\\nrow=%s' %", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s Deleted', targetid) except mysqlerror", "value = self.get_format_dict(name) total_width += value[1] return total_width def get_unique_creds(self):", "Since the db field is an enum it actually sete", "in self.data_dict if self.disabled_target_id(x)] # TODO we have multiple of", "represents the unique combination of both. The result could be", "('ScanEnabled', ('Enabled', 6, str)), ]) # noqa: E123 def __init__(self,", "= fmt_value[2] if isinstance(field_type, six.string_types) and field_value: if max_width <", "# TODO can we make this a std cvt function.", "factory(cls, db_dict, db_type, verbose, output_format='simple'): \"\"\"Factory method to select subclass", "db_dict['targetsfilename'] self.filename = fn # If the filename is not", "('Namespace', 12, str)), ('SMIVersion', ('SMIVersion', 12, str)), ('Product', ('Product', 15,", "containing the fields defined in the input. Parameters: field_data ()", "os.path.isfile(fn): self.filename = fn else: full_fn = os.path.join(db_dict['directory'], fn) if", "select subclass based on database type (db_type). Currently the types", "def _load_joins(self): \"\"\" Load the tables that would normally be", "\"\"\" # TODO clean up for PY 3 return_list =", "fields: field_value = target[field_name] fmt_value = self.get_format_dict(field_name) max_width = fmt_value[1]", "up for PY 3 return_list = [] for key, value", "{} target_record = self.get_target(targetid) for change in changes: original_data[change] =", "true detailed info is displayed on the processing of the", "it is db_info companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try: #", "the targetid \"\"\" cursor = self.connection.cursor() sql = \"DELETE FROM", "be # either in the local directory or the same", "to be inserted. Exceptions: \"\"\" cursor = self.connection.cursor() placeholders =", "type (db_type). Currently the types sql and csv are supported.", "try: cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s,", "defined by the db_dict attribute. db_type (:term: `string`) String defining", ")\" % (self.table_name, columns, placeholders) try: cursor.execute(sql, fields.values()) self.connection.commit() new_targetid", "the targetid parameter to the value defined by the activate_flag", "val) def disabled_target_id(self, targetid): \"\"\" Return True if target recorded", "k, v in self.data_dict.items()} ucreds = dict([[v, k] for k,", "get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s, update fields: %s, ' 'original fields:", "nullable=False) Notify = Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers = Column(String(12), nullable=False)", "audit_logger.info('TargetsTable TargetId %s added. %s', new_targetid, fields) except mysqlerror as", "field names, and common methods. Parameters: db_dict (:term: `dictionary') Dictionary", "companies_tbl: company = companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName'] else: target['CompanyName'] =", "greater than the specification in the format_dictionary and fold=True \"\"\"", "companies table and insert into targets table: # TODO in", "language governing permissions and # limitations under the License. \"\"\"", "all other target bases. This defines the common definition of", "% (self.db_type, self.get_dbdict(), # # # len(self.data_dict))) # def __repr__(self):", "db_dict, dbtype, verbose, output_format): \"\"\"Pass through to SQL\"\"\" if verbose:", "notify_users_list] return notify_users_list return None def format_record(self, record_id, fields, fold=False):", "The database key property for this table activate_flag (:class:`py:bool`): Next", "ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() def delete(self, targetid):", "if target recorded for this target_id marked disabled. Otherwise return", "name for the property # # The value tuple is", "target database. verbose (:class:`py:bool`) Boolean. If true detailed info is", "\"Enabled\" or \"Disabled' ' string. %s is invalid.' % val)", "width of a table from the column names in the", "data for all SQL databases. Subclasses of this class support", "this case it is the companies table. Move the companyName", "of IP addresses:port entries. TODO: Does not include port right", "If not provided, the default is a simple report format.", "methods. Parameters: db_dict (:term: `dictionary') Dictionary containing all of the", "print('ERROR. Duplicate Id in table: %s\\nrow=%s' % (key, row)) raise", "WBEM CIM-XML standard definitions. \"\"\" target = self[targetid] return get_url_str(target['Protocol'],", "fields: %s', targetid, changes, original_data) except Exception as ex: self.connection.rollback()", "ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close() def", "\"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list): \"\"\" Get the width of", "audit_logger.info('TargetTable TargetId %s,set scanEnabled to %s', targetid, enabled_kw) except mysqlerror", "record, otherwise return None. There may be multiple ipaddress, port", "import csv import re from collections import OrderedDict from textwrap", "of items defined by changes where each item is an", "CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30), nullable=False) SMIVersion =", "type. \"\"\" table_name = 'Targets' key_field = 'TargetID' # Fields", "defined by targetid with the dictionary of items defined by", "base contains information on the targets, host systems, etc. in", "(:term: `dictionary') Dictionary containing all of the parameters to open", "this class support specialized sql databases. \"\"\" def __init__(self, db_dict,", "issues, else \" \"'Disabled'\", 'NotifyUsers': \"List of UserIDs to notify\",", "__init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read the input file into", "targets bases including field names, and common methods. Parameters: db_dict", "not be doing this in this manner but with a", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s failed SQL update. '", "generates an exception, KeyError if a field in fields is", "data\"\"\" # # return ('Targetdata db_type %s, rep count=%s' %", "audit_logger.info('TargetTable TargetId %s Deleted', targetid) except mysqlerror as ex: audit_logger", "field_data () Dictionary of fields to be inserted into the", "ex finally: self._load_table() self._load_joins() cursor.close() def activate(self, targetid, activate_flag): \"\"\"", "local directory or the same directory as the # config", "v in creds.items()]) unique_keys = dict([[v, k] for k, v", "String defining one of the allowed database types for the", "the db_dict\"\"\" return '%s' % self.db_dict @classmethod def factory(cls, db_dict,", "target record. Update does NOT test if the new value", "info on targetdata. TODO. Put more info here\"\"\" # #", "CimomVersion = Column(String(30), nullable=False) InteropNamespace = Column(String(30), nullable=False) Notify =", "the targets db table. This base contains information on the", "# # len(self.data_dict))) # def __repr__(self): # # \"\"\"Rep of", "(self.table_name, columns, placeholders) try: cursor.execute(sql, fields.values()) self.connection.commit() new_targetid = cursor.lastrowid", "db_dict entry directory if os.path.isabs(fn): if not os.path.isfile(fn): ValueError('CSV file", "headers from the record_list.\"\"\" hdr = [] for name in", "represent unique sets of Principal and Credential \"\"\" creds =", "self[targetid]['NotifyUsers'] if notify_users: notify_users_list = notify_users.split(',') notify_users_list = [int(userid) for", "%s\" % \\ target['CompanyID'] except Exception as ex: raise ValueError('Error:", "defined by the db_dict entry directory if os.path.isabs(fn): if not", "of integers representing the userids. This list stored in db", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "import wrap import six from mysql.connector import Error as mysqlerror", "values.append(value) values.append(targetid) sql = \"Update Targets \" + set_names #", "self.write_file(self.filename) def write_file(self, file_name): \"\"\"Write the current Target base to", "database name for the property # # The value tuple", "in col_list: value = self.get_format_dict(name) total_width += value[1] return total_width", "defined database type. \"\"\" table_name = 'Targets' key_field = 'TargetID'", "'ScanEnabled. SQL=%s ' 'Change to %s exception %s: %s', targetid,", "SQL=%s ' 'Change to %s exception %s: %s', targetid, sql,", "of these. See get dict_for_host,get_hostid_list def get_targets_host(self, host_data): \"\"\" If", "default='Enabled') Protocol = Column(String(10), default='http') Port = Column(String(10), nullable=False) \"\"\"", "Valid target Id for the Target_Tableue . Returns: (:class:`py:bool`) True", "self.connection.cursor() # dynamically build the update sql based on the", "for key, value in self.data_dict.items(): if ip_filter and re.match(ip_filter, value['IPAddress']):", "The result could be used to test with all Principals/Credentials", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= Column(String(30), nullable=False) InteropNamespace = Column(String(30), nullable=False) Notify = Column(Enum('Enabled',", "MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format) else: ValueError('Invalid targets factory db_type %s'", "the input file into a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose,", "in self.data_dict.items(): if self.verbose: print('get_hostid_list value %s' % (value,)) output_list.append(value['IPAddress'])", "fields) except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT", "self._load_joins() def _load_joins(self): \"\"\" Load the tables that would normally", "output_format): \"\"\"Initialize the abstract Targets instance. This controls all other", "# each set of entries result = {} for row", "display name and length for name.\"\"\" return self.table_format_dict[name] def get_enabled_targetids(self):", "raise ValueError('Error: putting Company Name in table %r error %s'", "Get the set of Credentials and Principal that represents the", "This base contains information on the targets, host systems, etc.", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set scanEnabled to %s', targetid,", "not in targets dictionary \"\"\" if not isinstance(targetid, six.integer_types): targetid", "ValueError('Input Error. duplicate Id') else: result[key] = row self.data_dict =", "NotifyUsers. \"\"\" notify_users = self[targetid]['NotifyUsers'] if notify_users: notify_users_list = notify_users.split(',')", "__future__ import print_function, absolute_import import os import csv import re", "inst = None if verbose: print('targetdata factory datafile %s dbtype", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "the database defined by the db_dict attribute. db_type (:term: `string`)", "self.verbose) try: # set the companyname into the targets table", "TargetID = %s' try: cursor.execute(sql, (enabled_kw, targetid)) # noqa F841", "Define the base of targets (i.e. systems to be tested)", "TargetsTable process targets infromation from an sql database. Generate the", "= Column(String(30), nullable=False) CimomVersion = Column(String(30), nullable=False) InteropNamespace = Column(String(30),", "'\"http\" or \"https\"', 'Port': \"Integer defining WBEM server port.\"} #", "(:class:`py:bool`) Boolean. If true detailed info is displayed on the", "the new value is the same as the original value.", "file and write the new one. with cvs it writes", "match of ip_filter and companyname filter if they exist and", "self.filename = fn else: full_fn = os.path.join(db_dict['directory'], fn) if not", "super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connection = None class MySQLTargetsTable(SQLTargetsTable,", "SQL\"\"\" if verbose: print('SQL Database type %s verbose=%s' % (db_dict,", "in the notify users field and split into python list", "F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s,set scanEnabled to", "putting Company Name in table %r error %s' % (self.db_dict,", "exists return that record, otherwise return None. There may be", "def get_enabled_targetids(self): \"\"\"Get list of target ids that are marked", "list and return the list of integers representing the userids.", "targets infromation from an sql database. Generate the targetstable from", "MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This subclass of TargetsTable process targets infromation", "if db_type == ('csv'): inst = CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format)", "TODO in smipyping name is db_dict. Elsewhere it is db_info", "dictionary Exceptions: KeyError if target not in targets dictionary \"\"\"", "= [int(userid) for userid in notify_users_list] return notify_users_list return None", "' 'original fields: %s', targetid, changes, original_data) except Exception as", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "isinstance(targetid, six.integer_types): targetid = int(targetid) return self.data_dict[targetid] def filter_targets(self, ip_filter=None,", "the column headers from the record_list.\"\"\" hdr = [] for", "directory %s' % (fn, db_dict['directory'])) else: self.filename = full_fn with", "the tables that would normally be joins. In this case", "# duplicate row handling print('ERROR. Duplicate Id in table: %s\\nrow=%s'", "and \\ re.match(value['CompanyName'], company_name_filter): rtn[key] = value return rtn def", "from textwrap import wrap import six from mysql.connector import Error", "'InteropNamespace': \"Interop Namespace name\", 'Notify': \"'Enabled' if users to be", "the Protocol, IPaddress and port and uses the common get_url_str", "# (C) Copyright 2017 Inova Development Inc. # All Rights", "value. \"\"\" cursor = self.connection.cursor() # dynamically build the update", "object since that creates the correct object for the defined", "table. This base contains information on the targets, host systems,", "the dictionary of items defined by changes where each item", "new records required_fields = [ 'IPAddress', 'CompanyID', 'Namespace', 'SMIVersion', 'Product',", "changes: original_data[change] = target_record[change] try: cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger =", "'enabled': return False if val == 'disabled': return True ValueError('ScanEnabled", "specific language governing permissions and # limitations under the License.", "and return list of any targets that match. The filters", "cover directories/clean up for possible exceptions. if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename,", "password to access target\", 'CimomVersion': \"Version of CIMOM\", 'InteropNamespace': \"Interop", "Column(String(12), nullable=False) ScanEnabled = Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol = Column(String(10),", "__repr__ do not really match. # # \"\"\"String info on", "a single ipaddress, port in the database Parameters: host_id(tuple of", "must contain \"Enabled\" or \"Disabled' ' string. %s is invalid.'", "Generate the targetstable from the sql database targets table and", "\"\"\" # TODO filename is config file name, not actual", "nullable=False) CimomVersion = Column(String(30), nullable=False) InteropNamespace = Column(String(30), nullable=False) Notify", "the whole file back \"\"\" backfile = '%s.bak' % self.filename", "Principal and Credential \"\"\" creds = {k: '%s%s' % (v['Principal'],", "Defines each record for the data base and outputs. #", "Port info is included only if it is not the", "default is a simple report format. \"\"\" super(TargetsTable, self).__init__(db_dict, db_type,", "are required to create new records required_fields = [ 'IPAddress',", "the property # # The value tuple is display name", "return ('type=%s db=%s, len=%s' % (self.db_type, self.get_dbdict(), # # #", "of the parameters to open the database defined by the", "('Protocol', ('Prot', 5, str)), ('Port', ('Port', 4, int)), ('ScanEnabled', ('Enabled',", "\"DB id of company\", 'Namespace': \"User namespace\", 'SMIVersion': \"SMI version\",", "self.data_dict if self.disabled_target_id(x)] # TODO we have multiple of these.", "match. The filters are regex strings. \"\"\" rtn = OrderedDict()", "one of the legal report output formats. If not provided,", "target. Since the db field is an enum it actually", "' 'SQL=%s exception %s: %s', targetid, sql, ex.__class__.__name__, ex) self.connection.rollback()", "set_names = \"SET \" values = [] comma = False", "ip_filter and re.match(ip_filter, value['IPAddress']): rtn[key] = value if company_name_filter and", "# you may not use this file except in compliance", "each field to be inserted. Exceptions: \"\"\" cursor = self.connection.cursor()", "SQL change ' 'ScanEnabled. SQL=%s ' 'Change to %s exception", "database targets table and the companies table, by mapping the", "'CompanyID', 'Namespace', 'SMIVersion', 'Product', 'Principal', 'Credential', 'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers',", "None if verbose: print('targetdata factory datafile %s dbtype %s verbose", "def get_field_list(self): \"\"\"Return a list of the base table field", "fields is not in the table \"\"\" for field in", "= None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\" This subclass of TargetsTable", "# def __str__(self): # # # TODO this and __repr__", "v in ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'], self.data_dict[k]['Credential']) for k in", "for the defined database type. \"\"\" table_name = 'Targets' key_field", "KeyError if a field in fields is not in the", "%s )\" % (self.table_name, columns, placeholders) try: cursor.execute(sql, fields.values()) self.connection.commit()", "def filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\" Filter for match of ip_filter", "for the target database. verbose (:class:`py:bool`) Boolean. If true detailed", "name and max width for the record table_format_dict = OrderedDict([", "= ', '.join(fields.keys()) sql = \"INSERT INTO %s ( %s", "clean up for python 3 for _id, value in self.data_dict.items():", "# # \"\"\"String info on targetdata. TODO. Put more info", "field_value) return line def disabled_target(self, target_record): # pylint: disable=no-self-use \"\"\"", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "disabled. Otherwise return True Parameters: target_id(:term:`integer`) Valid target Id for", "Gets the Protocol, IPaddress and port and uses the common", "an record for `host_data` exists return that record, otherwise return", "set the companyname into the targets table for target_key in", "creates the correct object for the defined database type. \"\"\"", "return None def format_record(self, record_id, fields, fold=False): \"\"\"Return the fields", "back \"\"\" backfile = '%s.bak' % self.filename # TODO does", "directly. It does an additonal check for correct type for", "for target_id Returns: target as dictionary Exceptions: KeyError if target", "\"\"\" inst = None if verbose: print('targetdata factory datafile %s", "failed SQL change ' 'ScanEnabled. SQL=%s ' 'Change to %s", "under the Apache License, Version 2.0 (the \"License\"); # you", "does not exist ' 'in local directory or config directory", "record defined by targetid with the dictionary of items defined", "that match. The filters are regex strings. \"\"\" rtn =", "db. Return list of targetIDs that represent unique sets of", "writes the whole file back \"\"\" backfile = '%s.bak' %", "table entry defined by the targetid parameter to the value", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s added. %s', new_targetid, fields)", "target data\"\"\" # # return ('Targetdata db_type %s, rep count=%s'", "except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed", "notify_users_list return None def format_record(self, record_id, fields, fold=False): \"\"\"Return the", "ValueError('CSV file %s does not exist ' % fn) else:", "Subclasses of this class support specialized sql databases. \"\"\" def", "config file defined by the db_dict entry directory if os.path.isabs(fn):", "Column(String(30), nullable=False) Notify = Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers = Column(String(12),", "into targets table: # TODO in smipyping name is db_dict.", "% (db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connection =", "ip_filter=None, company_name_filter=None): \"\"\" Filter for match of ip_filter and companyname", "backfile) self.write_file(self.filename) def write_file(self, file_name): \"\"\"Write the current Target base", "else 'Disabled' sql = 'UPDATE Targets SET ScanEnabled = %s", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s failed SQL change '", "return total_width def get_unique_creds(self): \"\"\" Get the set of Credentials", "\"\"\"Return a list of the base table field names in", "\"\"\" target = self[targetid] return get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def get_hostid_list(self,", "print('targetdata factory datafile %s dbtype %s verbose %s' % (db_dict,", "key, value in self.data_dict.items(): port = value[\"Port\"] # TODO port", "object for the defined database type. \"\"\" table_name = 'Targets'", "'Protocol': '\"http\" or \"https\"', 'Port': \"Integer defining WBEM server port.\"}", "str)), ('CimomVersion', ('CimomVersion', 15, str)), ('IPAddress', ('IPAddress', 12, str)), ('InteropNamespace',", "There may be multiple ipaddress, port entries for a single", "create a string. Port info is included only if it", "# def __repr__(self): # # \"\"\"Rep of target data\"\"\" #", "from the column names in the list \"\"\" total_width =", "target_record[change] try: cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID:", "\"\"\" Filter for match of ip_filter and companyname filter if", "a simple report format. \"\"\" super(TargetsTable, self).__init__(db_dict, db_type, verbose) self.output_format", "value[\"Port\"] # TODO port from database is a string. Should", "else return false. \"\"\" val = target_record['ScanEnabled'].lower() if val ==", "filename is not a full directory, the data file must", "each set of entries result = {} for row in", "SQL update. ' 'SQL: %s Changes: %s Exception: %s', targetid,", "= OrderedDict([ ('TargetID', ('ID', 2, int)), ('CompanyName', ('CompanyName', 12, str)),", "delete(self, targetid): \"\"\" Delete the target in the targets table", "== host_data[1]: return_list.append(key) return return_list def get_target(self, targetid): \"\"\" Get", "# config file defined by the db_dict entry directory if", "is included only if it is not the WBEM CIM-XML", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "of ip_filter and companyname filter if they exist and return", "self.data_dict[k]['Credential']) for k in unique_keys] return unique_creds class SQLTargetsTable(TargetsTable): \"\"\"", "def activate(self, targetid, activate_flag): \"\"\" Activate or deactivate the table", "for the Target_Tableue . Returns: (:class:`py:bool`) True if this target", "TODO filename is config file name, not actual file name.", "std cvt function. target = self.get_target(record_id) line = [] for", "the fields defined in the input. Parameters: field_data () Dictionary", "line.append('%s' % field_value) return line def disabled_target(self, target_record): # pylint:", "containing all of the parameters to open the database defined", "nullable=False) Credential = Column(String(30), nullable=False) CimomVersion = Column(String(30), nullable=False) InteropNamespace", "the TargetData class output_format (:term:`string`) String defining one of the", "SQL DELETE. ' 'SQL=%s exception %s: %s', targetid, sql, ex.__class__.__name__,", "database type. \"\"\" table_name = 'Targets' key_field = 'TargetID' #", "from __future__ import print_function, absolute_import import os import csv import", "str)), ('Credential', ('Credential', 12, str)), ('CimomVersion', ('CimomVersion', 15, str)), ('IPAddress',", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s failed SQL change ' 'ScanEnabled.", "AUDIT_LOGGER_NAME, get_logger from ._companiestable import CompaniesTable __all__ = ['TargetsTable'] class", "get_field_list(self): \"\"\"Return a list of the base table field names", "sql, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close()", "is not a full directory, the data file must be", "target = self.data_dict[target_key] if target['CompanyID'] in companies_tbl: company = companies_tbl[target['CompanyID']]", "get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable INSERT failed SQL update. SQL=%s. ' 'data=%s. Exception", "if not os.path.isfile(full_fn): ValueError('CSV file %s does not exist '", "tuple(values)) self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetID: %s, update fields:", "ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable):", "= Column(String(30), nullable=False) Notify = Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers =", "\"\"\"Get the string representing the url for targetid. Gets the", "[] comma = False for key, value in changes.items(): if", "to access target\", 'Credential': \"User password to access target\", 'CimomVersion':", "each item is an entry in the target record. Update", "dbtype, verbose, output_format) self.connection = None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin): \"\"\"", "rtn def build_url(self, targetid): \"\"\"Get the string representing the url", "Target base to the named file.\"\"\" with open(file_name, 'wb') as", "verbose, output_format): \"\"\"Pass through to SQL\"\"\" if verbose: print('SQL Database", "tbl_hdr(self, record_list): \"\"\"Return a list of all the column headers", "change ip_address to hostname where host name is name :", "are marked disabled\"\"\" return [x for x in self.data_dict if", "15, str)), ('IPAddress', ('IPAddress', 12, str)), ('InteropNamespace', ('Interop', 8, str)),", "same as the original value. \"\"\" cursor = self.connection.cursor() #", "targetid, activate_flag): \"\"\" Activate or deactivate the table entry defined", "print('SQL Database type %s verbose=%s' % (db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict,", "= self.get_target(record_id) line = [] for field_name in fields: field_value", "is the same as the original value. \"\"\" cursor =", "re.match(value['CompanyName'], company_name_filter): rtn[key] = value return rtn def build_url(self, targetid):", "%r' % inst) return inst def get_field_list(self): \"\"\"Return a list", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "\"\"\"Return tuple of display name and length for name.\"\"\" return", "of TargetsTable process targets infromation from an sql database. Generate", "a list of all the column headers from the record_list.\"\"\"", "in field_list for the record_id in display format. String fields", "= fn else: if os.path.isfile(fn): self.filename = fn else: full_fn", "= Column(Enum('Enabled', 'Disabled'), default='Disabled') NotifyUsers = Column(String(12), nullable=False) ScanEnabled =", "8, str)), ('Notify', ('Notify', 12, str)), ('NotifyUsers', ('NotifyUsers', 12, str)),", "return self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get list of target ids that", "TargetId %s added. %s', new_targetid, fields) except mysqlerror as ex:", "method to select subclass based on database type (db_type). Currently", "that are marked disabled\"\"\" return [x for x in self.data_dict", "it writes the whole file back \"\"\" backfile = '%s.bak'", "database. verbose (:class:`py:bool`) Boolean. If true detailed info is displayed", ") VALUES ( %s )\" % (self.table_name, columns, placeholders) try:", "Apache License, Version 2.0 (the \"License\"); # you may not", "the sql database targets table and the companies table, by", "either express or implied. # See the License for the", "WHERE TargetID=%s\" try: # pylint: disable=unused-variable mydata = cursor.execute(sql, (targetid,))", "item is an entry in the target record. Update does", "construct a new TargetsTable object since that creates the correct", "sql = \"INSERT INTO %s ( %s ) VALUES (", "Product = Column(String(30), nullable=False) Principal = Column(String(30), nullable=False) Credential =", "name in col_list: value = self.get_format_dict(name) total_width += value[1] return", "This subclass of TargetsTable process targets infromation from an sql", "('Principal', ('Principal', 12, str)), ('Credential', ('Credential', 12, str)), ('CimomVersion', ('CimomVersion',", "python 3 for _id, value in self.data_dict.items(): if self.verbose: print('get_hostid_list", "= MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format) else: ValueError('Invalid targets factory db_type", "= csv.DictReader(input_file) # create dictionary (id = key) with dictionary", "the audit log. original_data = {} target_record = self.get_target(targetid) for", "the existing file and write the new one. with cvs", "(enabled_kw, targetid)) # noqa F841 self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable", "._common import get_url_str from ._logging import AUDIT_LOGGER_NAME, get_logger from ._companiestable", "self.data_dict.items(): if ip_filter and re.match(ip_filter, value['IPAddress']): rtn[key] = value if", "company_name_filter=None): \"\"\" Get all WBEM Server ipaddresses in the targets", "to using [id] directly. It does an additonal check for", "in self.data_dict if not self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get list of", "db_type %s, rep count=%s' % # # # (self.db_type, len(self.data_dict)))", "raise ex finally: self._load_table() self._load_joins() cursor.close() def activate(self, targetid, activate_flag):", "output_format='simple'): \"\"\"Factory method to select subclass based on database type", "csv are supported. Returns instance object of the defined provider", "target_id(:term:`integer`) Valid target Id for the Target_Tableue . Returns: (:class:`py:bool`)", "write_updated_record(self, record_id): \"\"\"Backup the existing file and write the new", "Port = Column(String(10), nullable=False) \"\"\" # TODO change ip_address to", "set of Credentials and Principal that represents the unique combination", "targetdata keys \"\"\" # TODO clean up for PY 3", "the common get_url_str to create a string. Port info is", "the specification in the format_dictionary and fold=True \"\"\" # TODO", "be int internal. if value[\"IPAddress\"] == host_data[0] and int(port) ==", "systems to be tested) TargetID = Column(Integer(11), primary_key=True) IPAddress =", "dict([[v, k] for k, v in ucreds.items()]) unique_creds = [(self.data_dict[k]['Principal'],", "dictionary defined for targets \"\"\" # TODO filename is config", "fields: self.table_format_dict[field] # pylint: disable=pointless-statement def get_dbdict(self): \"\"\"Get string for", "as dictionary Exceptions: KeyError if target not in targets dictionary", "of the base table field names in the order defined.\"\"\"", "base and outputs. # # The Name is the database", "def get_format_dict(self, name): \"\"\"Return tuple of display name and length", "' 'data=%s. Exception %s: %s', sql, fields, ex.__class__.__name__, ex) self.connection.rollback()", "and max width for the record table_format_dict = OrderedDict([ ('TargetID',", "db_type, verbose, output_format=output_format) else: ValueError('Invalid targets factory db_type %s' %", "in self.data_dict.items(): if ip_filter and re.match(ip_filter, value['IPAddress']): rtn[key] = value", "total_width += value[1] return total_width def get_unique_creds(self): \"\"\" Get the", "do not really match. # # \"\"\"String info on targetdata.", "companyname into the targets table for target_key in self.data_dict: target", "KeyError if target_id not in database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self,", "% self.db_dict @classmethod def factory(cls, db_dict, db_type, verbose, output_format='simple'): \"\"\"Factory", "raise ex finally: self._load_table() self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated", "dictionary set_names = \"SET \" values = [] comma =", "All Rights Reserved # # Licensed under the Apache License,", "component sql = sql + \" WHERE TargetID=%s\" # Record", "(:class:`py:bool`): Next state that will be set into the database", "defined.\"\"\" return list(self.table_format_dict) def get_format_dict(self, name): \"\"\"Return tuple of display", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "specification in the format_dictionary and fold=True \"\"\" # TODO can", "Returns None if there is no data in NotifyUsers. \"\"\"", "of entries in the notify users field and split into", "= None if verbose: print('targetdata factory datafile %s dbtype %s", "\"\"\" super(TargetsTable, self).__init__(db_dict, db_type, verbose) self.output_format = output_format # def", "\"\"\"Get list of target ids that are marked disabled\"\"\" return", "Column(String(30), nullable=False) SMIVersion = Column(String(15), nullable=False) Product = Column(String(30), nullable=False)", "by the targetid \"\"\" cursor = self.connection.cursor() sql = \"DELETE", "value['IPAddress']): rtn[key] = value if company_name_filter and \\ re.match(value['CompanyName'], company_name_filter):", "to the named file.\"\"\" with open(file_name, 'wb') as f: writer", "return ('Targetdata db_type %s, rep count=%s' % # # #", "file defined by the db_dict entry directory if os.path.isabs(fn): if", "val == 'enabled': return False if val == 'disabled': return", "the filename is not a full directory, the data file", "the unique combination of both. The result could be used", "return hdr def get_notifyusers(self, targetid): \"\"\" Get list of entries", "in fields is not in the table \"\"\" for field", "\"\"\" def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Pass through to", "Get companies table and insert into targets table: # TODO", "have multiple of these. See get dict_for_host,get_hostid_list def get_targets_host(self, host_data):", "% inst) return inst def get_field_list(self): \"\"\"Return a list of", "based on the changes dictionary set_names = \"SET \" values", "def get_targets_host(self, host_data): \"\"\" If an record for `host_data` exists", "False if val == 'disabled': return True ValueError('ScanEnabled field must", "targetid = int(targetid) return self.data_dict[targetid] def filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\"", "column headers from the record_list.\"\"\" hdr = [] for name", "this a std cvt function. target = self.get_target(record_id) line =", "the record table_format_dict = OrderedDict([ ('TargetID', ('ID', 2, int)), ('CompanyName',", "fields, fold=False): \"\"\"Return the fields defined in field_list for the", "format. \"\"\" super(TargetsTable, self).__init__(db_dict, db_type, verbose) self.output_format = output_format #", "(db_dict, db_type, verbose)) if db_type == ('csv'): inst = CsvTargetsTable(db_dict,", "row handling print('ERROR. Duplicate Id in table: %s\\nrow=%s' % (key,", "be doing this in this manner but with a join.", "self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close() def insert(self, fields):", "sql based on the changes dictionary set_names = \"SET \"", "return false. \"\"\" val = target_record['ScanEnabled'].lower() if val == 'enabled':", "finally: self._load_table() self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values form", "reader = csv.DictReader(input_file) # create dictionary (id = key) with", "('Port', 4, int)), ('ScanEnabled', ('Enabled', 6, str)), ]) # noqa:", "separated by commas. Returns None if there is no data", "new one. with cvs it writes the whole file back", "port) Returns list of targetdata keys \"\"\" # TODO clean", "method should be used to construct a new TargetsTable object", "set of entries result = {} for row in reader:", "self).__init__(db_dict, dbtype, verbose, output_format) self.connection = None class MySQLTargetsTable(SQLTargetsTable, MySQLDBMixin):", "if val == 'enabled': return False if val == 'disabled':", "IPAddress = Column(String(15), nullable=False) CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace =", "self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get list of target ids that are", "str)), ('NotifyUsers', ('NotifyUsers', 12, str)), ('Protocol', ('Prot', 5, str)), ('Port',", "record table_format_dict = OrderedDict([ ('TargetID', ('ID', 2, int)), ('CompanyName', ('CompanyName',", "os.path.isfile(full_fn): ValueError('CSV file %s does not exist ' 'in local", "%s WHERE TargetID = %s' try: cursor.execute(sql, (enabled_kw, targetid)) #", "set_names = set_names + \", \" else: comma = True", "id of company\", 'Namespace': \"User namespace\", 'SMIVersion': \"SMI version\", 'Product':", "change ' 'ScanEnabled. SQL=%s ' 'Change to %s exception %s:", "verbose: print('Resulting targets factory inst %r' % inst) return inst", "TargetID=%s\" # Record the original data for the audit log.", "marked disabled\"\"\" return [x for x in self.data_dict if self.disabled_target_id(x)]", "and port) Returns list of targetdata keys \"\"\" # TODO", "is displayed on the processing of the TargetData class output_format", "self.get_dbdict(), # # # len(self.data_dict))) # def __repr__(self): # #", "strings. \"\"\" rtn = OrderedDict() for key, value in self.data_dict.items():", "= value return rtn def build_url(self, targetid): \"\"\"Get the string", "SQL databases. Subclasses of this class support specialized sql databases.", "\"DELETE FROM Targets WHERE TargetID=%s\" try: # pylint: disable=unused-variable mydata", "the database name for the property # # The value", "field in fields is not in the table \"\"\" for", "hostname where host name is name : port from __future__", "except mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s", "use this file except in compliance with the License. #", "the set of Credentials and Principal that represents the unique", "a dictionary.\"\"\" super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) fn = db_dict['targetsfilename']", "if verbose: print('Resulting targets factory inst %r' % inst) return", "targetdata. TODO. Put more info here\"\"\" # # return ('type=%s", "specialized sql databases. \"\"\" def __init__(self, db_dict, dbtype, verbose, output_format):", "name is name : port from __future__ import print_function, absolute_import", "order defined.\"\"\" return list(self.table_format_dict) def get_format_dict(self, name): \"\"\"Return tuple of", "target['CompanyID'] in companies_tbl: company = companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName'] else:", "if not self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get list of target ids", "field_list for the record_id in display format. String fields will", "local directory or config directory %s' % (fn, db_dict['directory'])) else:", "inst def get_field_list(self): \"\"\"Return a list of the base table", "\"\"\" Class representing the targets db table. This base contains", "for k, v in creds.items()]) unique_keys = dict([[v, k] for", "INSERT failed SQL update. SQL=%s. ' 'data=%s. Exception %s: %s',", "inserted. Exceptions: \"\"\" cursor = self.connection.cursor() placeholders = ', '.join(['%s']", "targetid component sql = sql + \" WHERE TargetID=%s\" #", "port from __future__ import print_function, absolute_import import os import csv", "__str__(self): # # # TODO this and __repr__ do not", "\"\"\"Return a list of all the column headers from the", "form of the Target base.\"\"\" def __init__(self, db_dict, dbtype, verbose,", "return unique_creds class SQLTargetsTable(TargetsTable): \"\"\" Subclass of Targets data for", "this target_id marked disabled. Otherwise return True Parameters: target_id(:term:`integer`) Valid", "self.get_format_dict(name) hdr.append(value[0]) return hdr def get_notifyusers(self, targetid): \"\"\" Get list", "self.filename = fn # If the filename is not a", "is one entry in the dictionary for each field to", "systems, etc. in the environment. The factory method should be", "uses the common get_url_str to create a string. Port info", "if target['CompanyID'] in companies_tbl: company = companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName']", "stored in db as string of integers separated by commas.", "sql database targets table and the companies table, by mapping", "this table activate_flag (:class:`py:bool`): Next state that will be set", "outputs. # # The Name is the database name for", "definitions. \"\"\" target = self[targetid] return get_url_str(target['Protocol'], target['IPAddress'], target['Port']) def", "be folded if their width is greater than the specification", "finally: self._load_table() self._load_joins() self.connection.close() def insert(self, fields): \"\"\" Write a", "recorded for this target_id marked disabled. Otherwise return True Parameters:", "self.connection.close() def insert(self, fields): \"\"\" Write a new record to", "else: target['CompanyName'] = \"TableError CompanyID %s\" % \\ target['CompanyID'] except", "does not exist ' % fn) else: self.filename = fn", "\" \"'Disabled'\", 'NotifyUsers': \"List of UserIDs to notify\", 'ScanEnabled': \"Enabled", "state that will be set into the database for this", "fields): \"\"\" Write a new record to the database containing", "key property for this table activate_flag (:class:`py:bool`): Next state that", "() Dictionary of fields to be inserted into the table.", "creds.items()]) unique_keys = dict([[v, k] for k, v in ucreds.items()])", "port = value[\"Port\"] # TODO port from database is a", "table: %s\\nrow=%s' % (key, row)) raise ValueError('Input Error. duplicate Id')", "from database is a string. Should be int internal. if", "but with a join. \"\"\" # Get companies table and", "# pylint: disable=no-self-use \"\"\" If target_record disabled, return true, else", "value defined by the activate_flag Parameters: targetid (:term:`py:integer`): The database", "targets table and the companies table, by mapping the data", "an entry in the target record. Update does NOT test", "\"\"\" Get the set of Credentials and Principal that represents", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "the db_dict entry directory if os.path.isabs(fn): if not os.path.isfile(fn): ValueError('CSV", "of the legal report output formats. If not provided, the", "6, str)), ]) # noqa: E123 def __init__(self, db_dict, db_type,", "% (key, row)) raise ValueError('Input Error. duplicate Id') else: result[key]", "by the db_dict attribute. db_type (:term: `string`) String defining one", "list of entries in the notify users field and split", "update. ' 'SQL: %s Changes: %s Exception: %s', targetid, sql,", "= dict([[v, k] for k, v in creds.items()]) unique_keys =", "notify_users_list = [int(userid) for userid in notify_users_list] return notify_users_list return", "\"\"\" cursor = self.connection.cursor() placeholders = ', '.join(['%s'] * len(fields))", "%s, rep count=%s' % # # # (self.db_type, len(self.data_dict))) def", "return notify_users_list return None def format_record(self, record_id, fields, fold=False): \"\"\"Return", "max_width))) else: line.append('%s' % field_value) else: line.append('%s' % field_value) return", "\"Interop Namespace name\", 'Notify': \"'Enabled' if users to be notified", "'CompanyID': \"DB id of company\", 'Namespace': \"User namespace\", 'SMIVersion': \"SMI", "string representing the url for targetid. Gets the Protocol, IPaddress", "%s' % db_type) if verbose: print('Resulting targets factory inst %r'", "dictionary (id = key) with dictionary for # each set", "%s added. %s', new_targetid, fields) except mysqlerror as ex: audit_logger", "changes dictionary set_names = \"SET \" values = [] comma", "items defined by changes where each item is an entry", "ex finally: self._load_table() self._load_joins() def delete(self, targetid): \"\"\" Delete the", "self).__init__(db_dict, dbtype, verbose, output_format) self.connectdb(db_dict, verbose) self._load_table() self._load_joins() def _load_joins(self):", "possible exceptions. if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename) def write_file(self,", "base.\"\"\" def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read the input", "= {} for row in reader: key = int(row['TargetID']) if", "Inova Development Inc. # All Rights Reserved # # Licensed", "does an additonal check for correct type for target_id Returns:", "from an sql database. Generate the targetstable from the sql", "are regex strings. \"\"\" rtn = OrderedDict() for key, value", "subclass based on database type (db_type). Currently the types sql", "is a simple report format. \"\"\" super(TargetsTable, self).__init__(db_dict, db_type, verbose)", "re from collections import OrderedDict from textwrap import wrap import", "def write_file(self, file_name): \"\"\"Write the current Target base to the", "Return True if target recorded for this target_id marked disabled.", "rtn = OrderedDict() for key, value in self.data_dict.items(): if ip_filter", "target bases. This defines the common definition of all targets", "# # # TODO this and __repr__ do not really", "elif db_type == ('mysql'): inst = MySQLTargetsTable(db_dict, db_type, verbose, output_format=output_format)", "in self.data_dict: target = self.data_dict[target_key] if target['CompanyID'] in companies_tbl: company", "self._load_table() self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values form of", "target[field_name] fmt_value = self.get_format_dict(field_name) max_width = fmt_value[1] field_type = fmt_value[2]", "Exception %s: %s', sql, fields, ex.__class__.__name__, ex) self.connection.rollback() raise ex", "absolute_import import os import csv import re from collections import", "file_name): \"\"\"Write the current Target base to the named file.\"\"\"", "('Port', ('Port', 4, int)), ('ScanEnabled', ('Enabled', 6, str)), ]) #", "= [key_field] + required_fields join_fields = ['CompanyName'] all_fields = fields", "= %s WHERE TargetID = %s' try: cursor.execute(sql, (enabled_kw, targetid))", "%s does not exist ' % fn) else: self.filename =", "Write a new record to the database containing the fields", "\"\"\" Update the database record defined by targetid with the", "< len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s' % field_value) else: line.append('%s'", "targets table defined by the targetid \"\"\" cursor = self.connection.cursor()", "= Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol = Column(String(10), default='http') Port =", "table activate_flag (:class:`py:bool`): Next state that will be set into", "data base and outputs. # # The Name is the", "with the License. # You may obtain a copy of", "verbose, output_format='simple'): \"\"\"Factory method to select subclass based on database", "db_info companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try: # set the", "from the record_list.\"\"\" hdr = [] for name in record_list:", "output_format) fn = db_dict['targetsfilename'] self.filename = fn # If the", "factory inst %r' % inst) return inst def get_field_list(self): \"\"\"Return", "' % fn) else: self.filename = fn else: if os.path.isfile(fn):", "file name. def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read the", "[] for name in record_list: value = self.get_format_dict(name) hdr.append(value[0]) return", "any targets that match. The filters are regex strings. \"\"\"", "import os import csv import re from collections import OrderedDict", "in the environment. The factory method should be used to", "%s verbose %s' % (db_dict, db_type, verbose)) if db_type ==", "TargetID: %s, update fields: %s, ' 'original fields: %s', targetid,", "from ._dbtablebase import DBTableBase from ._mysqldbmixin import MySQLDBMixin from ._common", "\"\"\"Test a list of field names. This test generates an", "as ex: self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s failed", "db=%s, len=%s' % (self.db_type, self.get_dbdict(), # # # len(self.data_dict))) #", "host_data[0] and int(port) == host_data[1]: return_list.append(key) return return_list def get_target(self,", "of target ids that are marked enabled.\"\"\" return [x for", "\"\"\"Factory method to select subclass based on database type (db_type).", "common methods. Parameters: db_dict (:term: `dictionary') Dictionary containing all of", "the data file must be # either in the local", "nullable=False) InteropNamespace = Column(String(30), nullable=False) Notify = Column(Enum('Enabled', 'Disabled'), default='Disabled')", "else: full_fn = os.path.join(db_dict['directory'], fn) if not os.path.isfile(full_fn): ValueError('CSV file", "In this case it is the companies table. Move the", "insert(self, fields): \"\"\" Write a new record to the database", "in record_list: value = self.get_format_dict(name) hdr.append(value[0]) return hdr def get_notifyusers(self,", "' string. %s is invalid.' % val) def disabled_target_id(self, targetid):", "targetIDs that represent unique sets of Principal and Credential \"\"\"", "a field in fields is not in the table \"\"\"", "= self.get_format_dict(name) hdr.append(value[0]) return hdr def get_notifyusers(self, targetid): \"\"\" Get", "('Namespace', ('Namespace', 12, str)), ('SMIVersion', ('SMIVersion', 12, str)), ('Product', ('Product',", "\"\"\" rtn = OrderedDict() for key, value in self.data_dict.items(): if", "%s' % (self.db_dict, ex)) def update_fields(self, targetid, changes): \"\"\" Update", "class support specialized sql databases. \"\"\" def __init__(self, db_dict, dbtype,", "+ \"{0} = %s\".format(key) values.append(value) values.append(targetid) sql = \"Update Targets", "for targets \"\"\" # TODO filename is config file name,", "result: # duplicate row handling print('ERROR. Duplicate Id in table:", "%s\\nrow=%s' % (key, row)) raise ValueError('Input Error. duplicate Id') else:", "express or implied. # See the License for the specific", "get_notifyusers(self, targetid): \"\"\" Get list of entries in the notify", "except in compliance with the License. # You may obtain", "of the allowed database types for the target database. verbose", "return True Parameters: target_id(:term:`integer`) Valid target Id for the Target_Tableue", "this target. Since the db field is an enum it", "self.connectdb(db_dict, verbose) self._load_table() self._load_joins() def _load_joins(self): \"\"\" Load the tables", "ValueError('ScanEnabled field must contain \"Enabled\" or \"Disabled' ' string. %s", "('Product', 15, str)), ('Principal', ('Principal', 12, str)), ('Credential', ('Credential', 12,", "provided, the default is a simple report format. \"\"\" super(TargetsTable,", "by targetid with the dictionary of items defined by changes", "of the Target base.\"\"\" def __init__(self, db_dict, dbtype, verbose, output_format):", "\"\"\"Backup the existing file and write the new one. with", "= key) with dictionary for # each set of entries", "'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port'] # All fields in", "a list of field names. This test generates an exception,", "Get all WBEM Server ipaddresses in the targets base. Returns", "list of target ids that are marked disabled\"\"\" return [x", "be used to construct a new TargetsTable object since that", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "is db_info companies_tbl = CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try: # set", "datafile %s dbtype %s verbose %s' % (db_dict, db_type, verbose))", "be used to test with all Principals/Credentials knows in the", "with open(file_name, 'wb') as f: writer = csv.DictWriter(f, fieldnames=self.get_field_list()) writer.writeheader()", "contain \"Enabled\" or \"Disabled' ' string. %s is invalid.' %", "in database \"\"\" return(self.disabled_target(self.data_dict[targetid])) def get_output_width(self, col_list): \"\"\" Get the", "for all SQL databases. Subclasses of this class support specialized", "field_type = fmt_value[2] if isinstance(field_type, six.string_types) and field_value: if max_width", "= company['CompanyName'] else: target['CompanyName'] = \"TableError CompanyID %s\" % \\", "= Column(String(10), nullable=False) \"\"\" # TODO change ip_address to hostname", "TODO we have multiple of these. See get dict_for_host,get_hostid_list def", "Boolean. If true detailed info is displayed on the processing", "target data for the parameter target_id. This is alternate to", "address\", 'CompanyID': \"DB id of company\", 'Namespace': \"User namespace\", 'SMIVersion':", "CONDITIONS OF ANY KIND, either express or implied. # See", "targets table TODO we should not be doing this in", "dynamically build the update sql based on the changes dictionary", "of CIMOM\", 'InteropNamespace': \"Interop Namespace name\", 'Notify': \"'Enabled' if users", "audit_logger.error('TargetsTable TargetID: %s failed SQL update. ' 'SQL: %s Changes:", "in the dictionary for each field to be inserted. Exceptions:", "self._load_table() self._load_joins() cursor.close() def activate(self, targetid, activate_flag): \"\"\" Activate or", "Name to access target\", 'Credential': \"User password to access target\",", "@classmethod def factory(cls, db_dict, db_type, verbose, output_format='simple'): \"\"\"Factory method to", "is a string. Should be int internal. if value[\"IPAddress\"] ==", "notify_users: notify_users_list = notify_users.split(',') notify_users_list = [int(userid) for userid in", "% (self.db_dict, ex)) def update_fields(self, targetid, changes): \"\"\" Update the", "if os.path.isabs(fn): if not os.path.isfile(fn): ValueError('CSV file %s does not", "directory if os.path.isabs(fn): if not os.path.isfile(fn): ValueError('CSV file %s does", "[x for x in self.data_dict if not self.disabled_target_id(x)] def get_disabled_targetids(self):", "Returns list of IP addresses:port entries. TODO: Does not include", "Returns list of targetdata keys \"\"\" # TODO clean up", "if a field in fields is not in the table", "Put more info here\"\"\" # # return ('type=%s db=%s, len=%s'", "print('get_hostid_list value %s' % (value,)) output_list.append(value['IPAddress']) return output_list def tbl_hdr(self,", "= self.connection.cursor() sql = \"DELETE FROM Targets WHERE TargetID=%s\" try:", "return output_list def tbl_hdr(self, record_list): \"\"\"Return a list of all", "\"\"\" Get the width of a table from the column", "not os.path.isfile(full_fn): ValueError('CSV file %s does not exist ' 'in", "output_format) self.connectdb(db_dict, verbose) self._load_table() self._load_joins() def _load_joins(self): \"\"\" Load the", "disable=no-self-use \"\"\" If target_record disabled, return true, else return false.", "that would normally be joins. In this case it is", "in each record. fields = [key_field] + required_fields join_fields =", "return False if val == 'disabled': return True ValueError('ScanEnabled field", "table. There is one entry in the dictionary for each", "['TargetsTable'] class TargetsTable(DBTableBase): \"\"\" Class representing the targets db table.", "# pylint: disable=pointless-statement def get_dbdict(self): \"\"\"Get string for the db_dict\"\"\"", "SQLTargetsTable(TargetsTable): \"\"\" Subclass of Targets data for all SQL databases.", "12, str)), ('Protocol', ('Prot', 5, str)), ('Port', ('Port', 4, int)),", "# dynamically build the update sql based on the changes", "if users to be notified of issues, else \" \"'Disabled'\",", "def write_updated_record(self, record_id): \"\"\"Backup the existing file and write the", "tuple of display name and length for name.\"\"\" return self.table_format_dict[name]", "# append targetid component sql = sql + \" WHERE", "users to be notified of issues, else \" \"'Disabled'\", 'NotifyUsers':", "false. \"\"\" val = target_record['ScanEnabled'].lower() if val == 'enabled': return", "the processing of the TargetData class output_format (:term:`string`) String defining", "('Credential', 12, str)), ('CimomVersion', ('CimomVersion', 15, str)), ('IPAddress', ('IPAddress', 12,", "self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values form of the", "targets \"\"\" # TODO filename is config file name, not", "of hostname or ipaddress and port) Returns list of targetdata", "for name in record_list: value = self.get_format_dict(name) hdr.append(value[0]) return hdr", "%s, ' 'original fields: %s', targetid, changes, original_data) except Exception", "common get_url_str to create a string. Port info is included", "name\", 'Notify': \"'Enabled' if users to be notified of issues,", "('csv'): inst = CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format) elif db_type ==", "[id] directly. It does an additonal check for correct type", "update sql based on the changes dictionary set_names = \"SET", "up for possible exceptions. if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename)", "fields: %s, ' 'original fields: %s', targetid, changes, original_data) except", "[key_field] + required_fields join_fields = ['CompanyName'] all_fields = fields +", "in the list \"\"\" total_width = 0 for name in", "key = int(row['TargetID']) if key in result: # duplicate row", "get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\" Get all WBEM Server ipaddresses in", "are marked enabled.\"\"\" return [x for x in self.data_dict if", "original_data[change] = target_record[change] try: cursor.execute(sql, tuple(values)) self.connection.commit() audit_logger = get_logger(AUDIT_LOGGER_NAME)", "get_format_dict(self, name): \"\"\"Return tuple of display name and length for", "if company_name_filter and \\ re.match(value['CompanyName'], company_name_filter): rtn[key] = value return", "of target data\"\"\" # # return ('Targetdata db_type %s, rep", "name : port from __future__ import print_function, absolute_import import os", "output_format # def __str__(self): # # # TODO this and", "output_format): \"\"\"Pass through to SQL\"\"\" if verbose: print('SQL Database type", "database defined by the db_dict attribute. db_type (:term: `string`) String", "cursor.close() def activate(self, targetid, activate_flag): \"\"\" Activate or deactivate the", "get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId %s added. %s', new_targetid, fields) except mysqlerror", "fmt_value = self.get_format_dict(field_name) max_width = fmt_value[1] field_type = fmt_value[2] if", "Update the database record defined by targetid with the dictionary", "the data base and outputs. # # The Name is", "self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close() class CsvTargetsTable(TargetsTable): \"\"\"Comma", "the targets, host systems, etc. in the environment. The factory", "super(CsvTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) fn = db_dict['targetsfilename'] self.filename =", "= 'TargetID' # Fields that are required to create new", "INTO %s ( %s ) VALUES ( %s )\" %", "an sql database. Generate the targetstable from the sql database", "\"\"\" Get the target data for the parameter target_id. This", "of Targets data for all SQL databases. Subclasses of this", "not actual file name. def __init__(self, db_dict, dbtype, verbose, output_format):", "= self.data_dict[target_key] if target['CompanyID'] in companies_tbl: company = companies_tbl[target['CompanyID']] target['CompanyName']", "= target[field_name] fmt_value = self.get_format_dict(field_name) max_width = fmt_value[1] field_type =", "and common methods. Parameters: db_dict (:term: `dictionary') Dictionary containing all", "NOT test if the new value is the same as", "it actually sete Active or Inactive strings into the field", "namespace\", 'SMIVersion': \"SMI version\", 'Product': \"Product name\", 'Principal': \"User Name", "= [] # TODO clean up for python 3 for", "port entries for a single ipaddress, port in the database", "and uses the common get_url_str to create a string. Port", "for x in self.data_dict if self.disabled_target_id(x)] # TODO we have", "Column(String(30), nullable=False) InteropNamespace = Column(String(30), nullable=False) Notify = Column(Enum('Enabled', 'Disabled'),", "True Parameters: target_id(:term:`integer`) Valid target Id for the Target_Tableue .", "= row self.data_dict = result def write_updated_record(self, record_id): \"\"\"Backup the", "config file name, not actual file name. def __init__(self, db_dict,", "+ set_names # append targetid component sql = sql +", "str)), ('Protocol', ('Prot', 5, str)), ('Port', ('Port', 4, int)), ('ScanEnabled',", "list of the base table field names in the order", "simple report format. \"\"\" super(TargetsTable, self).__init__(db_dict, db_type, verbose) self.output_format =", "# TODO we have multiple of these. See get dict_for_host,get_hostid_list", "access target\", 'CimomVersion': \"Version of CIMOM\", 'InteropNamespace': \"Interop Namespace name\",", "not really match. # # \"\"\"String info on targetdata. TODO.", "name and length for name.\"\"\" return self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get", "= self.connection.cursor() enabled_kw = 'Enabled' if activate_flag else 'Disabled' sql", "verbose %s' % (db_dict, db_type, verbose)) if db_type == ('csv'):", "Get the width of a table from the column names", "targets, host systems, etc. in the environment. The factory method", "the environment. The factory method should be used to construct", "not self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get list of target ids that", "Update does NOT test if the new value is the", "'IPAddress': \"Host name or ip address\", 'CompanyID': \"DB id of", "get dict_for_host,get_hostid_list def get_targets_host(self, host_data): \"\"\" If an record for", "really match. # # \"\"\"String info on targetdata. TODO. Put", "col_list): \"\"\" Get the width of a table from the", "allowed database types for the target database. verbose (:class:`py:bool`) Boolean.", "field_value = target[field_name] fmt_value = self.get_format_dict(field_name) max_width = fmt_value[1] field_type", "# Get companies table and insert into targets table: #", "%s verbose=%s' % (db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format)", "CsvTargetsTable(TargetsTable): \"\"\"Comma Separated Values form of the Target base.\"\"\" def", "object of the defined provider type. \"\"\" inst = None", "'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port'] # All fields in each", "('CompanyName', 12, str)), ('Namespace', ('Namespace', 12, str)), ('SMIVersion', ('SMIVersion', 12,", "for a single ipaddress, port in the database Parameters: host_id(tuple", "as input_file: reader = csv.DictReader(input_file) # create dictionary (id =", "\"\"\" Return True if target recorded for this target_id marked", "in table: %s\\nrow=%s' % (key, row)) raise ValueError('Input Error. duplicate", "host name is name : port from __future__ import print_function,", "for the parameter target_id. This is alternate to using [id]", "filters are regex strings. \"\"\" rtn = OrderedDict() for key,", "target['Port']) def get_hostid_list(self, ip_filter=None, company_name_filter=None): \"\"\" Get all WBEM Server", "self.connection.rollback() raise ex finally: self._load_table() self._load_joins() def delete(self, targetid): \"\"\"", "for the db_dict\"\"\" return '%s' % self.db_dict @classmethod def factory(cls,", "the correct object for the defined database type. \"\"\" table_name", "activate_flag else 'Disabled' sql = 'UPDATE Targets SET ScanEnabled =", "into python list and return the list of integers representing", "Class representing the targets db table. This base contains information", "more info here\"\"\" # # return ('type=%s db=%s, len=%s' %", "folded if their width is greater than the specification in", "# TODO this and __repr__ do not really match. #", "type for target_id Returns: target as dictionary Exceptions: KeyError if", "self._load_table() self._load_joins() def _load_joins(self): \"\"\" Load the tables that would", "__init__(self, db_dict, db_type, verbose, output_format): \"\"\"Initialize the abstract Targets instance.", "permissions and # limitations under the License. \"\"\" Define the", "notify_users.split(',') notify_users_list = [int(userid) for userid in notify_users_list] return notify_users_list", "max_width < len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s' % field_value) else:", "backfile = '%s.bak' % self.filename # TODO does this cover", "standard definitions. \"\"\" target = self[targetid] return get_url_str(target['Protocol'], target['IPAddress'], target['Port'])", "handling print('ERROR. Duplicate Id in table: %s\\nrow=%s' % (key, row))", "should not be doing this in this manner but with", "set_names # append targetid component sql = sql + \"", "ValueError('Error: putting Company Name in table %r error %s' %", "% # # # (self.db_type, len(self.data_dict))) def test_fieldnames(self, fields): \"\"\"Test", "% db_type) if verbose: print('Resulting targets factory inst %r' %", "'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port'] # All fields", "database Parameters: host_id(tuple of hostname or ipaddress and port) Returns", "value in self.data_dict.items(): port = value[\"Port\"] # TODO port from", "= fields + join_fields hints = { 'IPAddress': \"Host name", "target to be scanned\", 'Protocol': '\"http\" or \"https\"', 'Port': \"Integer", "include port right now. \"\"\" output_list = [] # TODO", "list of any targets that match. The filters are regex", "Column(String(30), nullable=False) Credential = Column(String(30), nullable=False) CimomVersion = Column(String(30), nullable=False)", "return [x for x in self.data_dict if not self.disabled_target_id(x)] def", "notify_users_list = notify_users.split(',') notify_users_list = [int(userid) for userid in notify_users_list]", "'Port': \"Integer defining WBEM server port.\"} # # Defines each", "should be used to construct a new TargetsTable object since", "if there is no data in NotifyUsers. \"\"\" notify_users =", "\" WHERE TargetID=%s\" # Record the original data for the", "%s', targetid, sql, enabled_kw, ex.__class__.__name__, ex) self.connection.rollback() raise ex finally:", "# (self.db_type, len(self.data_dict))) def test_fieldnames(self, fields): \"\"\"Test a list of", "db_type, verbose, output_format=output_format) elif db_type == ('mysql'): inst = MySQLTargetsTable(db_dict,", "for x in self.data_dict if not self.disabled_target_id(x)] def get_disabled_targetids(self): \"\"\"Get", "Return list of targetIDs that represent unique sets of Principal", "targetid): \"\"\" Return True if target recorded for this target_id", "._dbtablebase import DBTableBase from ._mysqldbmixin import MySQLDBMixin from ._common import", "is config file name, not actual file name. def __init__(self,", "failed SQL update. SQL=%s. ' 'data=%s. Exception %s: %s', sql,", "class TargetsTable(DBTableBase): \"\"\" Class representing the targets db table. This", "name\", 'Principal': \"User Name to access target\", 'Credential': \"User password", "key) with dictionary for # each set of entries result", "the targets table defined by the targetid \"\"\" cursor =", "config directory %s' % (fn, db_dict['directory'])) else: self.filename = full_fn", "sets of Principal and Credential \"\"\" creds = {k: '%s%s'", "return True ValueError('ScanEnabled field must contain \"Enabled\" or \"Disabled' '", "int internal. if value[\"IPAddress\"] == host_data[0] and int(port) == host_data[1]:", "NotifyUsers = Column(String(12), nullable=False) ScanEnabled = Column(Enum('Enabled', 'Disabled'), default='Enabled') Protocol", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "internal. if value[\"IPAddress\"] == host_data[0] and int(port) == host_data[1]: return_list.append(key)", "\\ re.match(value['CompanyName'], company_name_filter): rtn[key] = value return rtn def build_url(self,", "result could be used to test with all Principals/Credentials knows", "of field names. This test generates an exception, KeyError if", "of any targets that match. The filters are regex strings.", "Currently the types sql and csv are supported. Returns instance", "the db_dict attribute. db_type (:term: `string`) String defining one of", "False for key, value in changes.items(): if comma: set_names =", "an enum it actually sete Active or Inactive strings into", "would normally be joins. In this case it is the", "of targetdata keys \"\"\" # TODO clean up for PY", "# # (self.db_type, len(self.data_dict))) def test_fieldnames(self, fields): \"\"\"Test a list", "# either in the local directory or the same directory", "as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s failed SQL", "target['CompanyID'] except Exception as ex: raise ValueError('Error: putting Company Name", "and outputs. # # The Name is the database name", "function. target = self.get_target(record_id) line = [] for field_name in", "of the TargetData class output_format (:term:`string`) String defining one of", "of targetIDs that represent unique sets of Principal and Credential", "import re from collections import OrderedDict from textwrap import wrap", "to the database containing the fields defined in the input.", "or ip address\", 'CompanyID': \"DB id of company\", 'Namespace': \"User", "('InteropNamespace', ('Interop', 8, str)), ('Notify', ('Notify', 12, str)), ('NotifyUsers', ('NotifyUsers',", "the data to the dictionary defined for targets \"\"\" #", "failed SQL DELETE. ' 'SQL=%s exception %s: %s', targetid, sql,", "= Column(String(15), nullable=False) Product = Column(String(30), nullable=False) Principal = Column(String(30),", "exist ' % fn) else: self.filename = fn else: if", "('NotifyUsers', 12, str)), ('Protocol', ('Prot', 5, str)), ('Port', ('Port', 4,", "12, str)), ('CimomVersion', ('CimomVersion', 15, str)), ('IPAddress', ('IPAddress', 12, str)),", "changes, original_data) except Exception as ex: self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME)", "reader: key = int(row['TargetID']) if key in result: # duplicate", "company_name_filter=None): \"\"\" Filter for match of ip_filter and companyname filter", "\"\"\" # TODO change ip_address to hostname where host name", "Version 2.0 (the \"License\"); # you may not use this", "len(fields)) columns = ', '.join(fields.keys()) sql = \"INSERT INTO %s", "get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable TargetID: %s failed SQL update. ' 'SQL: %s", "total_width = 0 for name in col_list: value = self.get_format_dict(name)", "display format. String fields will be folded if their width", "companyName into the targets table TODO we should not be", "target['CompanyName'] = company['CompanyName'] else: target['CompanyName'] = \"TableError CompanyID %s\" %", "company = companies_tbl[target['CompanyID']] target['CompanyName'] = company['CompanyName'] else: target['CompanyName'] = \"TableError", "OrderedDict([ ('TargetID', ('ID', 2, int)), ('CompanyName', ('CompanyName', 12, str)), ('Namespace',", "the legal report output formats. If not provided, the default", "default='http') Port = Column(String(10), nullable=False) \"\"\" # TODO change ip_address", "The value tuple is display name and max width for", "is invalid.' % val) def disabled_target_id(self, targetid): \"\"\" Return True", "get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetTable TargetId %s Deleted', targetid) except mysqlerror as ex:", "self.get_format_dict(field_name) max_width = fmt_value[1] field_type = fmt_value[2] if isinstance(field_type, six.string_types)", "doing this in this manner but with a join. \"\"\"", "list(self.table_format_dict) def get_format_dict(self, name): \"\"\"Return tuple of display name and", "def disabled_target_id(self, targetid): \"\"\" Return True if target recorded for", "def __init__(self, db_dict, dbtype, verbose, output_format): \"\"\"Read the input file", "mysqlerror as ex: audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable userid %s failed", "= target_record['ScanEnabled'].lower() if val == 'enabled': return False if val", "by applicable law or agreed to in writing, software #", "etc. in the environment. The factory method should be used", "for targetid. Gets the Protocol, IPaddress and port and uses", "verbose, output_format=output_format) else: ValueError('Invalid targets factory db_type %s' % db_type)", "'.join(fields.keys()) sql = \"INSERT INTO %s ( %s ) VALUES", "directory as the # config file defined by the db_dict", "= {k: '%s%s' % (v['Principal'], v['Credential']) for k, v in", "= get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s failed SQL DELETE. ' 'SQL=%s", "get_enabled_targetids(self): \"\"\"Get list of target ids that are marked enabled.\"\"\"", "entry in the target record. Update does NOT test if", "to be scanned\", 'Protocol': '\"http\" or \"https\"', 'Port': \"Integer defining", "self.table_format_dict[field] # pylint: disable=pointless-statement def get_dbdict(self): \"\"\"Get string for the", "12, str)), ('Product', ('Product', 15, str)), ('Principal', ('Principal', 12, str)),", "type %s verbose=%s' % (db_dict, verbose)) super(SQLTargetsTable, self).__init__(db_dict, dbtype, verbose,", "the field \"\"\" cursor = self.connection.cursor() enabled_kw = 'Enabled' if", "a string. Port info is included only if it is", "('NotifyUsers', ('NotifyUsers', 12, str)), ('Protocol', ('Prot', 5, str)), ('Port', ('Port',", "data file must be # either in the local directory", "if self.verbose: print('get_hostid_list value %s' % (value,)) output_list.append(value['IPAddress']) return output_list", "string. %s is invalid.' % val) def disabled_target_id(self, targetid): \"\"\"", "file.\"\"\" with open(file_name, 'wb') as f: writer = csv.DictWriter(f, fieldnames=self.get_field_list())", "cursor.execute(sql, fields.values()) self.connection.commit() new_targetid = cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable", "the target data for the parameter target_id. This is alternate", "3 for _id, value in self.data_dict.items(): if self.verbose: print('get_hostid_list value", "= fmt_value[1] field_type = fmt_value[2] if isinstance(field_type, six.string_types) and field_value:", "original_data) except Exception as ex: self.connection.rollback() audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetsTable", "'Principal', 'Credential', 'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled', 'Protocol', 'Port'] #", "WHERE TargetID = %s' try: cursor.execute(sql, (enabled_kw, targetid)) # noqa", "import DBTableBase from ._mysqldbmixin import MySQLDBMixin from ._common import get_url_str", "factory datafile %s dbtype %s verbose %s' % (db_dict, db_type,", "all targets bases including field names, and common methods. Parameters:", "for each field to be inserted. Exceptions: \"\"\" cursor =", "= self[targetid]['NotifyUsers'] if notify_users: notify_users_list = notify_users.split(',') notify_users_list = [int(userid)", "of entries result = {} for row in reader: key", "if max_width < len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else: line.append('%s' % field_value)", "', '.join(['%s'] * len(fields)) columns = ', '.join(fields.keys()) sql =", "Column(String(15), nullable=False) CompanyID = Column(Integer(11), ForeignKey(\"Companies.CompanyID\")) Namespace = Column(String(30), nullable=False)", "mapping the data to the dictionary defined for targets \"\"\"", "('Credential', ('Credential', 12, str)), ('CimomVersion', ('CimomVersion', 15, str)), ('IPAddress', ('IPAddress',", "k in unique_keys] return unique_creds class SQLTargetsTable(TargetsTable): \"\"\" Subclass of", "userid %s failed SQL change ' 'ScanEnabled. SQL=%s ' 'Change", "defined by the targetid \"\"\" cursor = self.connection.cursor() sql =", "fields.values()) self.connection.commit() new_targetid = cursor.lastrowid audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.info('TargetsTable TargetId", "for name.\"\"\" return self.table_format_dict[name] def get_enabled_targetids(self): \"\"\"Get list of target", "ipaddresses in the targets base. Returns list of IP addresses:port", "import print_function, absolute_import import os import csv import re from", "verbose, output_format=output_format) elif db_type == ('mysql'): inst = MySQLTargetsTable(db_dict, db_type,", "See get dict_for_host,get_hostid_list def get_targets_host(self, host_data): \"\"\" If an record", "addresses:port entries. TODO: Does not include port right now. \"\"\"", "the targetstable from the sql database targets table and the", "the current Target base to the named file.\"\"\" with open(file_name,", "int)), ('ScanEnabled', ('Enabled', 6, str)), ]) # noqa: E123 def", "get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s failed SQL DELETE. ' 'SQL=%s exception", "entry directory if os.path.isabs(fn): if not os.path.isfile(fn): ValueError('CSV file %s", "for userid in notify_users_list] return notify_users_list return None def format_record(self,", "targetid): \"\"\" Get list of entries in the notify users", "applicable law or agreed to in writing, software # distributed", "into a dictionary.\"\"\" super(MySQLTargetsTable, self).__init__(db_dict, dbtype, verbose, output_format) self.connectdb(db_dict, verbose)", "finally: self._load_table() self._load_joins() def delete(self, targetid): \"\"\" Delete the target", "verbose, output_format): \"\"\"Read the input file into a dictionary.\"\"\" super(CsvTargetsTable,", "cvt function. target = self.get_target(record_id) line = [] for field_name", "ValueError('Invalid targets factory db_type %s' % db_type) if verbose: print('Resulting", "value[\"IPAddress\"] == host_data[0] and int(port) == host_data[1]: return_list.append(key) return return_list", "displayed on the processing of the TargetData class output_format (:term:`string`)", "in self.data_dict.items(): port = value[\"Port\"] # TODO port from database", "get_targets_host(self, host_data): \"\"\" If an record for `host_data` exists return", "db table. This base contains information on the targets, host", "the # config file defined by the db_dict entry directory", "# len(self.data_dict))) # def __repr__(self): # # \"\"\"Rep of target", "get_disabled_targetids(self): \"\"\"Get list of target ids that are marked disabled\"\"\"", "target_key in self.data_dict: target = self.data_dict[target_key] if target['CompanyID'] in companies_tbl:", "' 'in local directory or config directory %s' % (fn,", "we make this a std cvt function. target = self.get_target(record_id)", "the parameters to open the database defined by the db_dict", "six.string_types) and field_value: if max_width < len(field_value): line.append('\\n'.join(wrap(field_value, max_width))) else:", "type. \"\"\" inst = None if verbose: print('targetdata factory datafile", "either in the local directory or the same directory as", "% fn) else: self.filename = fn else: if os.path.isfile(fn): self.filename", "ip_address to hostname where host name is name : port", "directory or config directory %s' % (fn, db_dict['directory'])) else: self.filename", "# You may obtain a copy of the License at", "self.verbose: print('get_hostid_list value %s' % (value,)) output_list.append(value['IPAddress']) return output_list def", "[x for x in self.data_dict if self.disabled_target_id(x)] # TODO we", "pylint: disable=pointless-statement def get_dbdict(self): \"\"\"Get string for the db_dict\"\"\" return", "db_type, verbose, output_format): \"\"\"Initialize the abstract Targets instance. This controls", "return that record, otherwise return None. There may be multiple", "= notify_users.split(',') notify_users_list = [int(userid) for userid in notify_users_list] return", "target ids that are marked enabled.\"\"\" return [x for x", "\"Integer defining WBEM server port.\"} # # Defines each record", "host_data): \"\"\" If an record for `host_data` exists return that", "('IPAddress', 12, str)), ('InteropNamespace', ('Interop', 8, str)), ('Notify', ('Notify', 12,", "string of integers separated by commas. Returns None if there", "to the dictionary defined for targets \"\"\" # TODO filename", "None def format_record(self, record_id, fields, fold=False): \"\"\"Return the fields defined", "from ._common import get_url_str from ._logging import AUDIT_LOGGER_NAME, get_logger from", "TargetData class output_format (:term:`string`) String defining one of the legal", "\"\"\" If an record for `host_data` exists return that record,", "# All Rights Reserved # # Licensed under the Apache", "target_id Returns: target as dictionary Exceptions: KeyError if target not", "and Credential \"\"\" creds = {k: '%s%s' % (v['Principal'], v['Credential'])", "', '.join(fields.keys()) sql = \"INSERT INTO %s ( %s )", "\", \" else: comma = True set_names = set_names +", "ex.__class__.__name__, ex) self.connection.rollback() raise ex finally: self._load_table() self._load_joins() self.connection.close() class", "under the License. \"\"\" Define the base of targets (i.e.", "audit_logger = get_logger(AUDIT_LOGGER_NAME) audit_logger.error('TargetTable targetid %s failed SQL DELETE. '", "contains information on the targets, host systems, etc. in the", "[] for key, value in self.data_dict.items(): port = value[\"Port\"] #", "targets table: # TODO in smipyping name is db_dict. Elsewhere", "\"\"\" notify_users = self[targetid]['NotifyUsers'] if notify_users: notify_users_list = notify_users.split(',') notify_users_list", "table and insert into targets table: # TODO in smipyping", "make this a std cvt function. target = self.get_target(record_id) line", "formats. If not provided, the default is a simple report", "the target in the targets table defined by the targetid", "placeholders) try: cursor.execute(sql, fields.values()) self.connection.commit() new_targetid = cursor.lastrowid audit_logger =", "all WBEM Server ipaddresses in the targets base. Returns list", "('TargetID', ('ID', 2, int)), ('CompanyName', ('CompanyName', 12, str)), ('Namespace', ('Namespace',", "%s: %s', targetid, sql, enabled_kw, ex.__class__.__name__, ex) self.connection.rollback() raise ex", "% val) def disabled_target_id(self, targetid): \"\"\" Return True if target", "Parameters: field_data () Dictionary of fields to be inserted into", "if os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename) def write_file(self, file_name): \"\"\"Write", "os.path.isfile(backfile): os.remove(backfile) os.rename(self.filename, backfile) self.write_file(self.filename) def write_file(self, file_name): \"\"\"Write the", "dictionary for each field to be inserted. Exceptions: \"\"\" cursor", "15, str)), ('Principal', ('Principal', 12, str)), ('Credential', ('Credential', 12, str)),", "correct type for target_id Returns: target as dictionary Exceptions: KeyError", "targetid (:term:`py:integer`): The database key property for this table activate_flag", "input. Parameters: field_data () Dictionary of fields to be inserted", "build_url(self, targetid): \"\"\"Get the string representing the url for targetid.", "is greater than the specification in the format_dictionary and fold=True", "db_dict, db_type, verbose, output_format): \"\"\"Initialize the abstract Targets instance. This", "\"\"\" cursor = self.connection.cursor() enabled_kw = 'Enabled' if activate_flag else", "Principal = Column(String(30), nullable=False) Credential = Column(String(30), nullable=False) CimomVersion =", "and csv are supported. Returns instance object of the defined", "db_type == ('csv'): inst = CsvTargetsTable(db_dict, db_type, verbose, output_format=output_format) elif", "2017 Inova Development Inc. # All Rights Reserved # #", "get_url_str to create a string. Port info is included only", "None if there is no data in NotifyUsers. \"\"\" notify_users", "the targets table for target_key in self.data_dict: target = self.data_dict[target_key]", "self.get_format_dict(name) total_width += value[1] return total_width def get_unique_creds(self): \"\"\" Get", "\"\"\"Get list of target ids that are marked enabled.\"\"\" return", "True if this target id disabled Exceptions: KeyError if target_id", "value tuple is display name and max width for the", "\"License\"); # you may not use this file except in", "self.output_format = output_format # def __str__(self): # # # TODO", "= int(targetid) return self.data_dict[targetid] def filter_targets(self, ip_filter=None, company_name_filter=None): \"\"\" Filter", "width is greater than the specification in the format_dictionary and", "from the sql database targets table and the companies table,", "raise ex finally: self._load_table() self._load_joins() self.connection.close() def insert(self, fields): \"\"\"", "joins. In this case it is the companies table. Move", "'Principal': \"User Name to access target\", 'Credential': \"User password to", "None. There may be multiple ipaddress, port entries for a", "self.filename = fn else: if os.path.isfile(fn): self.filename = fn else:", "# return ('type=%s db=%s, len=%s' % (self.db_type, self.get_dbdict(), # #", "SMIVersion = Column(String(15), nullable=False) Product = Column(String(30), nullable=False) Principal =", "the original value. \"\"\" cursor = self.connection.cursor() # dynamically build", "def get_target(self, targetid): \"\"\" Get the target data for the", "base table field names in the order defined.\"\"\" return list(self.table_format_dict)", "base of targets (i.e. systems to be tested) TargetID =", "company['CompanyName'] else: target['CompanyName'] = \"TableError CompanyID %s\" % \\ target['CompanyID']", "'Namespace', 'SMIVersion', 'Product', 'Principal', 'Credential', 'CimomVersion', 'InteropNamespace', 'Notify', 'NotifyUsers', 'ScanEnabled',", "if this target to be scanned\", 'Protocol': '\"http\" or \"https\"',", "%s', targetid, sql, changes, ex) raise ex finally: self._load_table() self._load_joins()", "str)), ('IPAddress', ('IPAddress', 12, str)), ('InteropNamespace', ('Interop', 8, str)), ('Notify',", "one. with cvs it writes the whole file back \"\"\"", "super(TargetsTable, self).__init__(db_dict, db_type, verbose) self.output_format = output_format # def __str__(self):", "= value[\"Port\"] # TODO port from database is a string.", "if verbose: print('SQL Database type %s verbose=%s' % (db_dict, verbose))", "def build_url(self, targetid): \"\"\"Get the string representing the url for", "CompaniesTable.factory(self.db_dict, self.db_type, self.verbose) try: # set the companyname into the", "table from the column names in the list \"\"\" total_width", "SQL=%s. ' 'data=%s. Exception %s: %s', sql, fields, ex.__class__.__name__, ex)", "= ['CompanyName'] all_fields = fields + join_fields hints = {", "'Enabled' if activate_flag else 'Disabled' sql = 'UPDATE Targets SET", "to be inserted into the table. There is one entry", "CIM-XML standard definitions. \"\"\" target = self[targetid] return get_url_str(target['Protocol'], target['IPAddress'],", "+ \", \" else: comma = True set_names = set_names", "v in self.data_dict.items()} ucreds = dict([[v, k] for k, v", "set into the database for this target. Since the db" ]
[ "# # All or portions of this file Copyright (c)", "the root of this # distribution (the \"License\"). All use", "format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object): format_cpp_annotations(json_object) def render_templates(self, input_file,", "root of this # distribution (the \"License\"). All use of", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "by the license below or the license accompanying this file.", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "import * from AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self,", "input_file, **template_kwargs): input_file_name, input_file_ext = os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name))", "This file is distributed on an \"AS IS\" BASIS, #", "AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object): format_cpp_annotations(json_object) def", "Copyright (c) Amazon.com, Inc. or its affiliates or # its", "# remove or modify any license notices. This file is", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "# or, if provided, by the license below or the", "the License, # or, if provided, by the license below", "licensors. # # For complete copyright and license terms please", "* from AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object):", "Do not # remove or modify any license notices. This", "class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object): format_cpp_annotations(json_object) def render_templates(self, input_file, **template_kwargs):", "# distribution (the \"License\"). All use of this software is", "this # distribution (the \"License\"). All use of this software", "az_code_gen.base import * from AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def", "# For complete copyright and license terms please see the", "its affiliates or # its licensors. # # For complete", "License, # or, if provided, by the license below or", "either express or implied. # import os from az_code_gen.base import", "remove or modify any license notices. This file is distributed", "json_object): format_cpp_annotations(json_object) def render_templates(self, input_file, **template_kwargs): input_file_name, input_file_ext = os.path.splitext(input_file)", "the license below or the license accompanying this file. Do", "(the \"License\"). All use of this software is governed by", "portions of this file Copyright (c) Amazon.com, Inc. or its", "# Factory function - called from launcher def create_drivers(env): return", "All or portions of this file Copyright (c) Amazon.com, Inc.", "# # For complete copyright and license terms please see", "modify any license notices. This file is distributed on an", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "affiliates or # its licensors. # # For complete copyright", "distribution (the \"License\"). All use of this software is governed", "the license accompanying this file. Do not # remove or", "input_file_ext = os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory function", "import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object): format_cpp_annotations(json_object) def render_templates(self,", "'{}.generated.inline'.format(input_file_name)) # Factory function - called from launcher def create_drivers(env):", "copyright and license terms please see the LICENSE at the", "KIND, either express or implied. # import os from az_code_gen.base", "notices. This file is distributed on an \"AS IS\" BASIS,", "this file. Do not # remove or modify any license", "os from az_code_gen.base import * from AzReflectionCpp import format_cpp_annotations class", "please see the LICENSE at the root of this #", "this file Copyright (c) Amazon.com, Inc. or its affiliates or", "license terms please see the LICENSE at the root of", "by the License, # or, if provided, by the license", "from AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object): format_cpp_annotations(json_object)", "# import os from az_code_gen.base import * from AzReflectionCpp import", "or modify any license notices. This file is distributed on", "CONDITIONS OF ANY KIND, either express or implied. # import", "# its licensors. # # For complete copyright and license", "license notices. This file is distributed on an \"AS IS\"", "template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory function - called from launcher def", "LICENSE at the root of this # distribution (the \"License\").", "from az_code_gen.base import * from AzReflectionCpp import format_cpp_annotations class AZEBusInline_Driver(TemplateDriver):", "OR CONDITIONS OF ANY KIND, either express or implied. #", "input_file_name, input_file_ext = os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory", "\"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory function - called from launcher", "ANY KIND, either express or implied. # import os from", "file Copyright (c) Amazon.com, Inc. or its affiliates or #", "or its affiliates or # its licensors. # # For", "the LICENSE at the root of this # distribution (the", "governed by the License, # or, if provided, by the", "(c) Amazon.com, Inc. or its affiliates or # its licensors.", "accompanying this file. Do not # remove or modify any", "license accompanying this file. Do not # remove or modify", "or implied. # import os from az_code_gen.base import * from", "use of this software is governed by the License, #", "os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory function - called", "and license terms please see the LICENSE at the root", "Inc. or its affiliates or # its licensors. # #", "its licensors. # # For complete copyright and license terms", "= os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory function -", "of this file Copyright (c) Amazon.com, Inc. or its affiliates", "Factory function - called from launcher def create_drivers(env): return [AZEBusInline_Driver(env)]", "def render_templates(self, input_file, **template_kwargs): input_file_name, input_file_ext = os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\",", "For complete copyright and license terms please see the LICENSE", "\"License\"). All use of this software is governed by the", "provided, by the license below or the license accompanying this", "or # its licensors. # # For complete copyright and", "import os from az_code_gen.base import * from AzReflectionCpp import format_cpp_annotations", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "terms please see the LICENSE at the root of this", "or, if provided, by the license below or the license", "not # remove or modify any license notices. This file", "license below or the license accompanying this file. Do not", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "of this # distribution (the \"License\"). All use of this", "complete copyright and license terms please see the LICENSE at", "see the LICENSE at the root of this # distribution", "self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) # Factory function - called from", "file is distributed on an \"AS IS\" BASIS, # WITHOUT", "format_cpp_annotations(json_object) def render_templates(self, input_file, **template_kwargs): input_file_name, input_file_ext = os.path.splitext(input_file) self.render_template_to_file(", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "of this software is governed by the License, # or,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "AZEBusInline_Driver(TemplateDriver): def apply_transformations(self, json_object): format_cpp_annotations(json_object) def render_templates(self, input_file, **template_kwargs): input_file_name,", "below or the license accompanying this file. Do not #", "render_templates(self, input_file, **template_kwargs): input_file_name, input_file_ext = os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs,", "**template_kwargs): input_file_name, input_file_ext = os.path.splitext(input_file) self.render_template_to_file( \"AzEBusInline.tpl\", template_kwargs, '{}.generated.inline'.format(input_file_name)) #", "# All or portions of this file Copyright (c) Amazon.com,", "is governed by the License, # or, if provided, by", "OF ANY KIND, either express or implied. # import os", "at the root of this # distribution (the \"License\"). All", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "apply_transformations(self, json_object): format_cpp_annotations(json_object) def render_templates(self, input_file, **template_kwargs): input_file_name, input_file_ext =", "software is governed by the License, # or, if provided,", "or portions of this file Copyright (c) Amazon.com, Inc. or", "Amazon.com, Inc. or its affiliates or # its licensors. #", "or the license accompanying this file. Do not # remove", "def apply_transformations(self, json_object): format_cpp_annotations(json_object) def render_templates(self, input_file, **template_kwargs): input_file_name, input_file_ext", "if provided, by the license below or the license accompanying", "file. Do not # remove or modify any license notices.", "express or implied. # import os from az_code_gen.base import *", "any license notices. This file is distributed on an \"AS", "this software is governed by the License, # or, if", "implied. # import os from az_code_gen.base import * from AzReflectionCpp", "All use of this software is governed by the License," ]
[ "'):] # _stockName = _stockName.strip(\"\\\"\\\"\\,\") # if '_market' in aline:", "requestStr + iItem # print(requestStr) # 延时 time.sleep(1.456) response =", "iItem # print(requestStr) # 延时 time.sleep(1.456) response = urllib.request.urlopen(requestStr) content2", "当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec) if ret == None: coll_stock_zjlx.insert_one(aRec) print(\"🤑", "\", aRec) else: print(\"😵 记录已经存在 \", ret) ''' 作为测试用例来获取, 对比", "= data07.strip('\"') # print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] = data07 # 中单净流入", "dict_row['ddjll_je_jzb'] = data07 # 中单净流入 净额 data08 = dataArrays[aItemIndex +", "if 'var strUrl = ' in aline: aline = aline[len('var", "def QA_request_eastmoney_zjlx( param_stock_code_list ): # 改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) #", "{} dict_row['stock_code'] = param_stock_code_list[iStockCode] # 日期 # print(aItemIndex) data01 =", "== False: # os.mkdir(path_for_save_data) # isExists = os.path.exists(path_for_save_data) # if", "content = response.read() # 🛠todo 改用 re 正则表达式做匹配 strings =", "response.read() # 🛠todo 改用 re 正则表达式做匹配 strings = content.decode(\"utf-8\", \"ignore\")", "\"\" strCode = param_stock_code_list[iStockCode] if strCode[0:2] == '60': _stockMarke =", "= dataArrays[aItemIndex + 4] data05 = data05.strip('\"') # print('超大单净流入 净占比',data05)", "ret == None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \", aRec) else: print(\"😵", "# if isExists == False: # os.mkdir(path_for_save_data) # isExists =", "aline: # _market = aline[len('_market = '):] # _market =", "净额',data02) dict_row['zljll_je_wy'] = data02 # 主力净流入 净占比 data03 = dataArrays[aItemIndex", "2 # 30XXXX , # _stockMarke = 2 # if", "= DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in", "= aline[len('_stockMarke = '):] # _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") # #", "leftChars.split(',') # print(dataArrays) for aItemIndex in range(0, len(dataArrays), 13): '''", "aline in string_lines: aline = aline.strip() if 'EM_CapitalFlowInterface' in aline:", "\"/eastmoney_stock_zjlx\" # isExists = os.path.exists(path_for_save_data) # if isExists == False:", "data13 = data13.strip('\"') data13 = data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price'] =", "in aline: # _stockMarke = aline[len('_stockMarke = '):] # _stockMarke", "'var strUrl = ' in aline: aline = aline[len('var strUrl", "print(df) client = DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for", "iItem = iItem.strip(' \"') iItem = iItem.rstrip(' \"') requestStr =", "if ret == None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \", aRec) else:", "\"ignore\") string_lines = strings.split(\"\\r\\n\") #for aline in string_lines: # aline", "data06.strip('\"') # print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] = data06 # 大单净流入 净占比", "from QUANTAXIS_CRAWLY.run_selenium_alone import * import urllib import pandas as pd", "range(0, len(dataArrays), 13): ''' 日期 收盘价 涨跌幅 主力净流入 净额 净占比", "'hsa' # print(_stockCode) # print(_stockMarke) # print(_stockName) # print(_market) values", "DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in range(len(list_data_zjlx)):", "urllib.request.urlopen(strUrl) content = response.read() # 🛠todo 改用 re 正则表达式做匹配 strings", "ret) ''' 作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList =", "data10 = dataArrays[aItemIndex + 9] data10 = data10.strip('\"') # print('小单净流入", "return for iItem in values: if '_stockCode' in iItem: requestStr", "data07.strip('\"') # print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] = data07 # 中单净流入 净额", "# print(strings) list_data_zjlx = [] if 'var aff_data=({data:[[\"' in strings:", "净额 data08 = dataArrays[aItemIndex + 7] data08 = data08.strip('\"') #", "收盘价 涨跌幅 主力净流入 净额 净占比 超大单净流入 净额 净占比 大单净流入 净额", "print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] = data06 # 大单净流入 净占比 data07 =", "for iItem in values: if '_stockCode' in iItem: requestStr =", "requestStr = 'http://ff.eastmoney.com/' else: iItem = iItem.strip(' \"') iItem =", "对比 reqeust 方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): # todo", "= _stockName.strip(\"\\\"\\\"\\,\") # if '_market' in aline: # _market =", "= '):] # _stockCode = _stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke' in", "# print(aItemIndex) data01 = dataArrays[aItemIndex] data01 = data01.strip('\"') # print('日期',data01)", "as pd import time from QUANTAXIS.QAUtil import (DATABASE) def QA_request_eastmoney_zjlx(", "): # 改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223) response", "# return # else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser = open_chrome_driver()", "+ 12] data13 = data13.strip('\"') data13 = data13.strip('\"]]})') # print('涨跌幅',data13)", "超大单净流入 净额 净占比 大单净流入 净额 净占比 中单净流入 净额 净占比 小单净流入", "# 读取一条记录成功 # print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx) df", "# print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] = data10 # 小单净流入 净占比 data11", "\"') requestStr = requestStr + iItem # print(requestStr) # 延时", "= dataArrays[aItemIndex + 7] data08 = data08.strip('\"') # print('中单净流入 净额',data08)", "dataArrays[aItemIndex] data01 = data01.strip('\"') # print('日期',data01) dict_row['date'] = data01 #", "净占比 data09 = dataArrays[aItemIndex + 8] data09 = data09.strip('\"') #", "# print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx) # print(df) client = DATABASE", "else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\") # path_for_save_data = QALocalize.download_path +", "else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser = open_chrome_driver() for indexCode in", "strings.split(\"\\r\\n\") #for aline in string_lines: # aline = aline.strip() #", "values = aline.split('+') # print(values) break # print('------------------') print(values) for", "else: # print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限 🈲\") # return #", "小单净流入 净额 净占比 ''' dict_row = {} dict_row['stock_code'] = param_stock_code_list[iStockCode]", "dict_row['xdjll_je_jzb'] = data11 # 收盘价 data12 = dataArrays[aItemIndex + 11]", "\",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) == False: print(\"😵 确认当前路径是否包含selenium_driver目录", "print(strings) list_data_zjlx = [] if 'var aff_data=({data:[[\"' in strings: leftChars", "00, 30 开头的股票代码\") return for iItem in values: if '_stockCode'", "_stockCode = _stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke' in aline: # _stockMarke", "🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec) if ret == None: coll_stock_zjlx.insert_one(aRec)", "import (DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list ): # 改用 strUrl =", "in range(len(param_stock_code_list)): requestStr = \"\" strCode = param_stock_code_list[iStockCode] if strCode[0:2]", "8] data09 = data09.strip('\"') # print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] = data09", "= data12.strip('\"') # print('收盘价',data12) dict_row['close_price'] = data12 # 涨跌幅 data13", "for aItemIndex in range(0, len(dataArrays), 13): ''' 日期 收盘价 涨跌幅", "= strings[len('var aff_data=({data:[[\"'):] # print(leftChars) dataArrays = leftChars.split(',') # print(dataArrays)", "in values: if '_stockCode' in iItem: requestStr = requestStr +", "60XXXX , #_stockMarke = 1 # 00XXXX , # _stockMarke", "os.path.exists(path_check) == False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\"", "dataArrays = leftChars.split(',') # print(dataArrays) for aItemIndex in range(0, len(dataArrays),", "(read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import * import urllib import", "净占比',data11) dict_row['xdjll_je_jzb'] = data11 # 收盘价 data12 = dataArrays[aItemIndex +", "from QUANTAXIS.QASetting import QALocalize #from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver)", "_market.strip(\"\\\"\\\"\\,\") # break #_market= 'hsa' # print(_stockCode) # print(_stockMarke) #", "import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import * import urllib", "'):] # _market = _market.strip(\"\\\"\\\"\\,\") # break #_market= 'hsa' #", "= dataArrays[aItemIndex] data01 = data01.strip('\"') # print('日期',data01) dict_row['date'] = data01", "净额 净占比 小单净流入 净额 净占比 ''' dict_row = {} dict_row['stock_code']", "# _stockCode = aline[len('var _stockCode = '):] # _stockCode =", "os from QUANTAXIS.QASetting import QALocalize #from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver,", "# 涨跌幅 data13 = dataArrays[aItemIndex + 12] data13 = data13.strip('\"')", "+ \"/eastmoney_stock_zjlx\" # isExists = os.path.exists(path_for_save_data) # if isExists ==", "in aline: # _market = aline[len('_market = '):] # _market", "aline: # _stockName = aline[len('_stockName = '):] # _stockName =", "= strings.split(\"\\r\\n\") #for aline in string_lines: # aline = aline.strip()", "or strCode[0:2] == '30': _stockMarke = '2' else: print(strCode +", "string_lines: aline = aline.strip() if 'EM_CapitalFlowInterface' in aline: # print(aline)", "30XXXX , # _stockMarke = 2 # if '_stockName' in", "aline = aline.strip() if 'EM_CapitalFlowInterface' in aline: # print(aline) #", "for indexCode in range(len(stockCodeList)): #full_path_name = path_for_save_data + \"/\" +", "reqeust 方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): # todo 🛠", "todo 🛠 check stockCode 是否存在有效合法 # todo 🛠 QALocalize 从QALocalize", "print(_stockName) # print(_market) values = [] for aline in string_lines:", "= data12 # 涨跌幅 data13 = dataArrays[aItemIndex + 12] data13", "else: print(\"😵 记录已经存在 \", ret) ''' 作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致", "净占比 data05 = dataArrays[aItemIndex + 4] data05 = data05.strip('\"') #", "aline.startswith('var strUrl = '): if 'var strUrl = ' in", "\", ret) ''' 作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList", "_market = _market.strip(\"\\\"\\\"\\,\") # break #_market= 'hsa' # print(_stockCode) #", "# aline = aline.strip() # if '_stockCode' in aline: #", "if os.path.exists(path_check) == False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \") return else:", "strCode[0:2] == '00' or strCode[0:2] == '30': _stockMarke = '2'", "= ' in aline: aline = aline[len('var strUrl = '):]", "print(_market) values = [] for aline in string_lines: aline =", "data13 # 读取一条记录成功 # print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx)", "print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx) #", "7] data08 = data08.strip('\"') # print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] = data08", "print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] = data08 # 中单净流入 净占比 data09 =", "= data13 # 读取一条记录成功 # print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row) #", "_stockName = _stockName.strip(\"\\\"\\\"\\,\") # if '_market' in aline: # _market", "大单净流入 净占比 data07 = dataArrays[aItemIndex + 6] data07 = data07.strip('\"')", "= requestStr + param_stock_code_list[iStockCode] elif '_stockMarke' in iItem: requestStr =", "涨跌幅 主力净流入 净额 净占比 超大单净流入 净额 净占比 大单净流入 净额 净占比", "print(_stockMarke) # print(_stockName) # print(_market) values = [] for aline", "print(leftChars) dataArrays = leftChars.split(',') # print(dataArrays) for aItemIndex in range(0,", "# _stockName = aline[len('_stockName = '):] # _stockName = _stockName.strip(\"\\\"\\\"\\,\")", "13): ''' 日期 收盘价 涨跌幅 主力净流入 净额 净占比 超大单净流入 净额", "import QALocalize #from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone", "aline = aline[len('var strUrl = '):] values = aline.split('+') #", "data06 = dataArrays[aItemIndex + 5] data06 = data06.strip('\"') # print('大单净流入", "# print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] = data09 # 小单净流入 净额 data10", "#_stockMarke = 1 # 00XXXX , # _stockMarke = 2", "response = urllib.request.urlopen(requestStr) content2 = response.read() # print(content2) strings =", "# 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec) if ret == None:", "净占比',data07) dict_row['ddjll_je_jzb'] = data07 # 中单净流入 净额 data08 = dataArrays[aItemIndex", ", # _stockMarke = 2 # 30XXXX , # _stockMarke", "'):] values = aline.split('+') # print(values) break # print('------------------') print(values)", "QALocalize.download_path + \"/eastmoney_stock_zjlx\" # isExists = os.path.exists(path_for_save_data) # if isExists", "# 日期 # print(aItemIndex) data01 = dataArrays[aItemIndex] data01 = data01.strip('\"')", "00XXXX , # _stockMarke = 2 # 30XXXX , #", "data10.strip('\"') # print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] = data10 # 小单净流入 净占比", "🤮, 可能没有权限 🈲\") # return # else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\")", "== True: # print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") # else: # print(path_for_save_data,\"目录不存在!", "目录存在 😁\") print(\"\") # path_for_save_data = QALocalize.download_path + \"/eastmoney_stock_zjlx\" #", "= response.read() # print(content2) strings = content2.decode(\"utf-8\", \"ignore\") # print(strings)", "print('------------------') aline = aline.strip() if aline.startswith('var strUrl = '): if", "60, 00, 30 开头的股票代码\") return for iItem in values: if", "净额 净占比 中单净流入 净额 净占比 小单净流入 净额 净占比 ''' dict_row", "urllib import pandas as pd import time from QUANTAXIS.QAUtil import", "+ 3] data04 = data04.strip('\"') # print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] =", "+ 2] data03 = data03.strip('\"') # print('主力净流入 净占比',data03) # date01", "净额',data10) dict_row['xdjll_je_wy'] = data10 # 小单净流入 净占比 data11 = dataArrays[aItemIndex", "_stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX , #_stockMarke = 1", "= aline.strip() if aline.startswith('var strUrl = '): if 'var strUrl", "# 大单净流入 净占比 data07 = dataArrays[aItemIndex + 6] data07 =", "净额 净占比 超大单净流入 净额 净占比 大单净流入 净额 净占比 中单净流入 净额", "aline.strip() if 'EM_CapitalFlowInterface' in aline: # print(aline) # print('------------------') aline", "print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx) # print(df) client = DATABASE coll_stock_zjlx", "dict_row['cddjll_je_wy'] = data04 # 超大单净流入 净占比 data05 = dataArrays[aItemIndex +", "in aline: aline = aline[len('var strUrl = '):] values =", "= data10 # 小单净流入 净占比 data11 = dataArrays[aItemIndex + 10]", "= aline[len('var strUrl = '):] values = aline.split('+') # print(values)", "if '_stockName' in aline: # _stockName = aline[len('_stockName = '):]", "'00' or strCode[0:2] == '30': _stockMarke = '2' else: print(strCode", "= content.decode(\"utf-8\", \"ignore\") string_lines = strings.split(\"\\r\\n\") #for aline in string_lines:", "dataArrays[aItemIndex + 3] data04 = data04.strip('\"') # print('超大单净流入 净额',data04) dict_row['cddjll_je_wy']", "# 小单净流入 净占比 data11 = dataArrays[aItemIndex + 10] data11 =", "range(len(list_data_zjlx)): aRec = list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec)", "# isExists = os.path.exists(path_for_save_data) # if isExists == True: #", "dict_row = {} dict_row['stock_code'] = param_stock_code_list[iStockCode] # 日期 # print(aItemIndex)", "os.mkdir(path_for_save_data) # isExists = os.path.exists(path_for_save_data) # if isExists == True:", "失败建立目录 🤮, 可能没有权限 🈲\") # return # else: # print(path_for_save_data,\"目录存在!准备读取数据", "if '_stockMarke' in aline: # _stockMarke = aline[len('_stockMarke = '):]", "param_stock_code_list[iStockCode] if strCode[0:2] == '60': _stockMarke = '1' elif strCode[0:2]", "净额',data04) dict_row['cddjll_je_wy'] = data04 # 超大单净流入 净占比 data05 = dataArrays[aItemIndex", "9] data10 = data10.strip('\"') # print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] = data10", "作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): #", "None): # todo 🛠 check stockCode 是否存在有效合法 # todo 🛠", "True: # print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") # else: # print(path_for_save_data,\"目录不存在! 失败建立目录", "\"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223) response = urllib.request.urlopen(strUrl) content = response.read()", "净额 data06 = dataArrays[aItemIndex + 5] data06 = data06.strip('\"') #", "净占比 中单净流入 净额 净占比 小单净流入 净额 净占比 ''' dict_row =", "data03.strip('\"') # print('主力净流入 净占比',data03) # date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] =", "strUrl = '):] values = aline.split('+') # print(values) break #", "+ 7] data08 = data08.strip('\"') # print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] =", "#full_path_name = path_for_save_data + \"/\" + stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode],", "= dataArrays[aItemIndex + 1] data02 = data02.strip('\"') # print('主力净流入 净额',data02)", "print(_stockCode) # print(_stockMarke) # print(_stockName) # print(_market) values = []", "os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) == False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \") return", ", #_stockMarke = 1 # 00XXXX , # _stockMarke =", "data13 = dataArrays[aItemIndex + 12] data13 = data13.strip('\"') data13 =", "aline[len('var _stockCode = '):] # _stockCode = _stockCode.strip(\"\\\"\\\"\\,\") # if", "= None): # todo 🛠 check stockCode 是否存在有效合法 # todo", "+ 1] data02 = data02.strip('\"') # print('主力净流入 净额',data02) dict_row['zljll_je_wy'] =", "strings = content2.decode(\"utf-8\", \"ignore\") # print(strings) list_data_zjlx = [] if", "= data08.strip('\"') # print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] = data08 # 中单净流入", "# print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] = data05 # 大单净流入 净额 data06", "data09 = dataArrays[aItemIndex + 8] data09 = data09.strip('\"') # print('中单净流入", "# 主力净流入 净额 data02 = dataArrays[aItemIndex + 1] data02 =", "aRec = list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec) if", "print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx) # print(df) client", "= urllib.request.urlopen(requestStr) content2 = response.read() # print(content2) strings = content2.decode(\"utf-8\",", "# 60XXXX , #_stockMarke = 1 # 00XXXX , #", "dataArrays[aItemIndex + 7] data08 = data08.strip('\"') # print('中单净流入 净额',data08) dict_row['zdjll_je_wy']", "data08.strip('\"') # print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] = data08 # 中单净流入 净占比", "# # 60XXXX , #_stockMarke = 1 # 00XXXX ,", "= '2' else: print(strCode + \" 暂不支持, 60, 00, 30", "dataArrays[aItemIndex + 11] data12 = data12.strip('\"') # print('收盘价',data12) dict_row['close_price'] =", "大单净流入 净额 data06 = dataArrays[aItemIndex + 5] data06 = data06.strip('\"')", "12] data13 = data13.strip('\"') data13 = data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price']", "content.decode(\"utf-8\", \"ignore\") string_lines = strings.split(\"\\r\\n\") #for aline in string_lines: #", "data11.strip('\"') # print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] = data11 # 收盘价 data12", "time.sleep(1.223) response = urllib.request.urlopen(strUrl) content = response.read() # 🛠todo 改用", "延时 time.sleep(1.456) response = urllib.request.urlopen(requestStr) content2 = response.read() # print(content2)", "# os.mkdir(path_for_save_data) # isExists = os.path.exists(path_for_save_data) # if isExists ==", "data05 = dataArrays[aItemIndex + 4] data05 = data05.strip('\"') # print('超大单净流入", "import urllib import pandas as pd import time from QUANTAXIS.QAUtil", "iItem in values: if '_stockCode' in iItem: requestStr = requestStr", "print(dataArrays) for aItemIndex in range(0, len(dataArrays), 13): ''' 日期 收盘价", "# 超大单净流入 净占比 data05 = dataArrays[aItemIndex + 4] data05 =", "4] data05 = data05.strip('\"') # print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] = data05", "content2 = response.read() # print(content2) strings = content2.decode(\"utf-8\", \"ignore\") #", "in range(len(stockCodeList)): #full_path_name = path_for_save_data + \"/\" + stockCodeList[indexCode] +", "# print(_stockMarke) # print(_stockName) # print(_market) values = [] for", "browser = open_chrome_driver() for indexCode in range(len(stockCodeList)): #full_path_name = path_for_save_data", "return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\") # path_for_save_data = QALocalize.download_path", "# isExists = os.path.exists(path_for_save_data) # if isExists == False: #", "# print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] = data04 # 超大单净流入 净占比 data05", "print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\") # path_for_save_data = QALocalize.download_path + \"/eastmoney_stock_zjlx\"", "# print('涨跌幅',data13) dict_row['change_price'] = data13 # 读取一条记录成功 # print(\"成功读取一条记录\") #", "+ 9] data10 = data10.strip('\"') # print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] =", "= QALocalize.download_path + \"/eastmoney_stock_zjlx\" # isExists = os.path.exists(path_for_save_data) # if", "aline: # print(aline) # print('------------------') aline = aline.strip() if aline.startswith('var", "aline: aline = aline[len('var strUrl = '):] values = aline.split('+')", "# print('收盘价',data12) dict_row['close_price'] = data12 # 涨跌幅 data13 = dataArrays[aItemIndex", "string_lines: # aline = aline.strip() # if '_stockCode' in aline:", "import time from QUANTAXIS.QAUtil import (DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list ):", "' in aline: aline = aline[len('var strUrl = '):] values", "5] data06 = data06.strip('\"') # print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] = data06", "string_lines = strings.split(\"\\r\\n\") #for aline in string_lines: # aline =", "6] data07 = data07.strip('\"') # print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] = data07", "'EM_CapitalFlowInterface' in aline: # print(aline) # print('------------------') aline = aline.strip()", "10] data11 = data11.strip('\"') # print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] = data11", "中单净流入 净额 data08 = dataArrays[aItemIndex + 7] data08 = data08.strip('\"')", "净占比',data09) dict_row['zdjll_je_jzb'] = data09 # 小单净流入 净额 data10 = dataArrays[aItemIndex", "# print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限 🈲\") # return # else:", "requestStr = requestStr + _stockMarke else: if 'http://ff.eastmoney.com/' in iItem:", "_stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke' in aline: # _stockMarke = aline[len('_stockMarke", "= {} dict_row['stock_code'] = param_stock_code_list[iStockCode] # 日期 # print(aItemIndex) data01", "+ 8] data09 = data09.strip('\"') # print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] =", "= data09 # 小单净流入 净额 data10 = dataArrays[aItemIndex + 9]", "in iItem: requestStr = requestStr + param_stock_code_list[iStockCode] elif '_stockMarke' in", "print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser = open_chrome_driver() for indexCode in range(len(stockCodeList)): #full_path_name", "for iStockCode in range(len(param_stock_code_list)): requestStr = \"\" strCode = param_stock_code_list[iStockCode]", "= data02 # 主力净流入 净占比 data03 = dataArrays[aItemIndex + 2]", "# 延时 time.sleep(1.223) response = urllib.request.urlopen(strUrl) content = response.read() #", "date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03 # 超大单净流入 净额 data04", "= list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec) if ret", "= 2 # if '_stockName' in aline: # _stockName =", "# _stockMarke = 2 # if '_stockName' in aline: #", "+ 6] data07 = data07.strip('\"') # print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] =", "= data13.strip('\"') data13 = data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price'] = data13", "data02 # 主力净流入 净占比 data03 = dataArrays[aItemIndex + 2] data03", "dict_row['stock_code'] = param_stock_code_list[iStockCode] # 日期 # print(aItemIndex) data01 = dataArrays[aItemIndex]", "in strings: leftChars = strings[len('var aff_data=({data:[[\"'):] # print(leftChars) dataArrays =", "list_data_zjlx.append(dict_row) # print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx) # print(df) client =", "print(aline) # print('------------------') aline = aline.strip() if aline.startswith('var strUrl =", "aline.split('+') # print(values) break # print('------------------') print(values) for iStockCode in", "return # else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser = open_chrome_driver() for", "+ 5] data06 = data06.strip('\"') # print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] =", "print('主力净流入 净占比',data03) # date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03 #", "aline: # _stockCode = aline[len('var _stockCode = '):] # _stockCode", "if 'http://ff.eastmoney.com/' in iItem: requestStr = 'http://ff.eastmoney.com/' else: iItem =", "# print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] = data07 # 中单净流入 净额 data08", "print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] = data07 # 中单净流入 净额 data08 =", "= data01.strip('\"') # print('日期',data01) dict_row['date'] = data01 # 主力净流入 净额", "# print(requestStr) # 延时 time.sleep(1.456) response = urllib.request.urlopen(requestStr) content2 =", "elif '_stockMarke' in iItem: requestStr = requestStr + _stockMarke else:", "dict_row['zdjll_je_jzb'] = data09 # 小单净流入 净额 data10 = dataArrays[aItemIndex +", "strings = content.decode(\"utf-8\", \"ignore\") string_lines = strings.split(\"\\r\\n\") #for aline in", "requestStr + _stockMarke else: if 'http://ff.eastmoney.com/' in iItem: requestStr =", "''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): # todo 🛠 check stockCode", "# print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] = data11 # 收盘价 data12 =", "= path_for_save_data + \"/\" + stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode], browser)", "data10 # 小单净流入 净占比 data11 = dataArrays[aItemIndex + 10] data11", "+ iItem # print(requestStr) # 延时 time.sleep(1.456) response = urllib.request.urlopen(requestStr)", "= '):] # _market = _market.strip(\"\\\"\\\"\\,\") # break #_market= 'hsa'", "# todo 🛠 QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd())", "dataArrays[aItemIndex + 6] data07 = data07.strip('\"') # print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb']", "in iItem: requestStr = 'http://ff.eastmoney.com/' else: iItem = iItem.strip(' \"')", "list_data_zjlx = [] if 'var aff_data=({data:[[\"' in strings: leftChars =", "+ param_stock_code_list[iStockCode] elif '_stockMarke' in iItem: requestStr = requestStr +", "isExists = os.path.exists(path_for_save_data) # if isExists == True: # print(path_for_save_data,\"目录不存在!", "+ \" 暂不支持, 60, 00, 30 开头的股票代码\") return for iItem", "dataArrays[aItemIndex + 1] data02 = data02.strip('\"') # print('主力净流入 净额',data02) dict_row['zljll_je_wy']", "stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode], browser) pass close_chrome_dirver(browser) #创建目录 #启动线程读取网页,写入数据库 #等待完成", "🛠todo 改用 re 正则表达式做匹配 strings = content.decode(\"utf-8\", \"ignore\") string_lines =", "print(\"🤑 插入新的记录 \", aRec) else: print(\"😵 记录已经存在 \", ret) '''", "= data03.strip('\"') # print('主力净流入 净占比',data03) # date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb']", "= dataArrays[aItemIndex + 9] data10 = data10.strip('\"') # print('小单净流入 净额',data10)", "print('日期',data01) dict_row['date'] = data01 # 主力净流入 净额 data02 = dataArrays[aItemIndex", "净额 data04 = dataArrays[aItemIndex + 3] data04 = data04.strip('\"') #", "= dataArrays[aItemIndex + 10] data11 = data11.strip('\"') # print('小单净流入 净占比',data11)", "dict_row['zljll_jzb_bfb'] = data03 # 超大单净流入 净额 data04 = dataArrays[aItemIndex +", "# _stockName = _stockName.strip(\"\\\"\\\"\\,\") # if '_market' in aline: #", "print(aItemIndex) data01 = dataArrays[aItemIndex] data01 = data01.strip('\"') # print('日期',data01) dict_row['date']", "# 主力净流入 净占比 data03 = dataArrays[aItemIndex + 2] data03 =", "data07 # 中单净流入 净额 data08 = dataArrays[aItemIndex + 7] data08", "#for aline in string_lines: # aline = aline.strip() # if", "import pandas as pd import time from QUANTAXIS.QAUtil import (DATABASE)", "# print('------------------') print(values) for iStockCode in range(len(param_stock_code_list)): requestStr = \"\"", "dataArrays[aItemIndex + 4] data05 = data05.strip('\"') # print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb']", "if 'EM_CapitalFlowInterface' in aline: # print(aline) # print('------------------') aline =", "可能没有权限 🈲\") # return # else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser", "data02.strip('\"') # print('主力净流入 净额',data02) dict_row['zljll_je_wy'] = data02 # 主力净流入 净占比", "print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) == False:", "print(\"\") # path_for_save_data = QALocalize.download_path + \"/eastmoney_stock_zjlx\" # isExists =", "'_stockCode' in iItem: requestStr = requestStr + param_stock_code_list[iStockCode] elif '_stockMarke'", "_stockMarke = '2' else: print(strCode + \" 暂不支持, 60, 00,", "strUrl = ' in aline: aline = aline[len('var strUrl =", "''' dict_row = {} dict_row['stock_code'] = param_stock_code_list[iStockCode] # 日期 #", "False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\")", "isExists == True: # print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") # else: #", "data08 = data08.strip('\"') # print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] = data08 #", "净额 净占比 ''' dict_row = {} dict_row['stock_code'] = param_stock_code_list[iStockCode] #", "# 🛠todo 改用 re 正则表达式做匹配 strings = content.decode(\"utf-8\", \"ignore\") string_lines", "print(requestStr) # 延时 time.sleep(1.456) response = urllib.request.urlopen(requestStr) content2 = response.read()", "= os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) == False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \")", "False: # os.mkdir(path_for_save_data) # isExists = os.path.exists(path_for_save_data) # if isExists", "response.read() # print(content2) strings = content2.decode(\"utf-8\", \"ignore\") # print(strings) list_data_zjlx", "data12 # 涨跌幅 data13 = dataArrays[aItemIndex + 12] data13 =", "[] if 'var aff_data=({data:[[\"' in strings: leftChars = strings[len('var aff_data=({data:[[\"'):]", "# 大单净流入 净额 data06 = dataArrays[aItemIndex + 5] data06 =", "aline = aline.strip() # if '_stockCode' in aline: # _stockCode", "1] data02 = data02.strip('\"') # print('主力净流入 净额',data02) dict_row['zljll_je_wy'] = data02", "dataArrays[aItemIndex + 2] data03 = data03.strip('\"') # print('主力净流入 净占比',data03) #", "30 开头的股票代码\") return for iItem in values: if '_stockCode' in", "超大单净流入 净占比 data05 = dataArrays[aItemIndex + 4] data05 = data05.strip('\"')", "= data04.strip('\"') # print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] = data04 # 超大单净流入", "固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) ==", "data12.strip('\"') # print('收盘价',data12) dict_row['close_price'] = data12 # 涨跌幅 data13 =", "# _stockMarke = aline[len('_stockMarke = '):] # _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\")", "data06 = data06.strip('\"') # print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] = data06 #", "close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import * import urllib import pandas as", "aItemIndex in range(0, len(dataArrays), 13): ''' 日期 收盘价 涨跌幅 主力净流入", "= _stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke' in aline: # _stockMarke =", "in range(len(list_data_zjlx)): aRec = list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret =", "\") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\") # path_for_save_data =", "if '_stockCode' in aline: # _stockCode = aline[len('var _stockCode =", "pandas as pd import time from QUANTAXIS.QAUtil import (DATABASE) def", "= data06 # 大单净流入 净占比 data07 = dataArrays[aItemIndex + 6]", "os.path.exists(path_for_save_data) # if isExists == False: # os.mkdir(path_for_save_data) # isExists", "# if '_stockMarke' in aline: # _stockMarke = aline[len('_stockMarke =", "print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限 🈲\") # return # else: #", "改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223) response = urllib.request.urlopen(strUrl)", "# _market = aline[len('_market = '):] # _market = _market.strip(\"\\\"\\\"\\,\")", "收盘价 data12 = dataArrays[aItemIndex + 11] data12 = data12.strip('\"') #", "None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \", aRec) else: print(\"😵 记录已经存在 \",", "# print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] = data06 # 大单净流入 净占比 data07", "client = DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i", "print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") # else: # print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限", "df = pd.DataFrame(list_data_zjlx) # print(df) client = DATABASE coll_stock_zjlx =", "in string_lines: aline = aline.strip() if 'EM_CapitalFlowInterface' in aline: #", "data09 # 小单净流入 净额 data10 = dataArrays[aItemIndex + 9] data10", "目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check)", "= \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223) response = urllib.request.urlopen(strUrl) content =", "in range(0, len(dataArrays), 13): ''' 日期 收盘价 涨跌幅 主力净流入 净额", "# 超大单净流入 净额 data04 = dataArrays[aItemIndex + 3] data04 =", "print('涨跌幅',data13) dict_row['change_price'] = data13 # 读取一条记录成功 # print(\"成功读取一条记录\") # print(dict_row)", "😢\") # else: # print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限 🈲\") #", "aline[len('_market = '):] # _market = _market.strip(\"\\\"\\\"\\,\") # break #_market=", "'2' else: print(strCode + \" 暂不支持, 60, 00, 30 开头的股票代码\")", "= [] if 'var aff_data=({data:[[\"' in strings: leftChars = strings[len('var", "requestStr = requestStr + param_stock_code_list[iStockCode] elif '_stockMarke' in iItem: requestStr", "dict_row['zljll_je_wy'] = data02 # 主力净流入 净占比 data03 = dataArrays[aItemIndex +", "break # print('------------------') print(values) for iStockCode in range(len(param_stock_code_list)): requestStr =", "QUANTAXIS.QAUtil import (DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list ): # 改用 strUrl", "data05.strip('\"') # print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] = data05 # 大单净流入 净额", "aline[len('_stockMarke = '):] # _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX", "= data10.strip('\"') # print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] = data10 # 小单净流入", "+ _stockMarke else: if 'http://ff.eastmoney.com/' in iItem: requestStr = 'http://ff.eastmoney.com/'", "isExists = os.path.exists(path_for_save_data) # if isExists == False: # os.mkdir(path_for_save_data)", "\"') iItem = iItem.rstrip(' \"') requestStr = requestStr + iItem", "else: iItem = iItem.strip(' \"') iItem = iItem.rstrip(' \"') requestStr", "# print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser = open_chrome_driver() for indexCode in range(len(stockCodeList)):", "= aline.split('+') # print(values) break # print('------------------') print(values) for iStockCode", "😰 \") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\") # path_for_save_data", "in aline: # _stockCode = aline[len('var _stockCode = '):] #", "range(len(param_stock_code_list)): requestStr = \"\" strCode = param_stock_code_list[iStockCode] if strCode[0:2] ==", "_market = aline[len('_market = '):] # _market = _market.strip(\"\\\"\\\"\\,\") #", "读取一条记录成功 # print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx) df =", "pd import time from QUANTAXIS.QAUtil import (DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list", "# print('中单净流入 净额',data08) dict_row['zdjll_je_wy'] = data08 # 中单净流入 净占比 data09", "ret = coll_stock_zjlx.find_one(aRec) if ret == None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录", "\"/\" + stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode], browser) pass close_chrome_dirver(browser) #创建目录", "🛠 check stockCode 是否存在有效合法 # todo 🛠 QALocalize 从QALocalize 目录中读取", "# 延时 time.sleep(1.456) response = urllib.request.urlopen(requestStr) content2 = response.read() #", "print(values) for iStockCode in range(len(param_stock_code_list)): requestStr = \"\" strCode =", "2] data03 = data03.strip('\"') # print('主力净流入 净占比',data03) # date01 =", "iItem: requestStr = requestStr + _stockMarke else: if 'http://ff.eastmoney.com/' in", "data12 = data12.strip('\"') # print('收盘价',data12) dict_row['close_price'] = data12 # 涨跌幅", "data11 = data11.strip('\"') # print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] = data11 #", "data12 = dataArrays[aItemIndex + 11] data12 = data12.strip('\"') # print('收盘价',data12)", "+ 11] data12 = data12.strip('\"') # print('收盘价',data12) dict_row['close_price'] = data12", "QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\"", "os.path.exists(path_for_save_data) # if isExists == True: # print(path_for_save_data,\"目录不存在! 成功建立目录 😢\")", "11] data12 = data12.strip('\"') # print('收盘价',data12) dict_row['close_price'] = data12 #", "# path_for_save_data = QALocalize.download_path + \"/eastmoney_stock_zjlx\" # isExists = os.path.exists(path_for_save_data)", "# print(_market) values = [] for aline in string_lines: aline", "= aline.strip() if 'EM_CapitalFlowInterface' in aline: # print(aline) # print('------------------')", "'var aff_data=({data:[[\"' in strings: leftChars = strings[len('var aff_data=({data:[[\"'):] # print(leftChars)", "''' 作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None):", "iStockCode in range(len(param_stock_code_list)): requestStr = \"\" strCode = param_stock_code_list[iStockCode] if", "= aline[len('_stockName = '):] # _stockName = _stockName.strip(\"\\\"\\\"\\,\") # if", "= data05 # 大单净流入 净额 data06 = dataArrays[aItemIndex + 5]", "净占比 超大单净流入 净额 净占比 大单净流入 净额 净占比 中单净流入 净额 净占比", "data09.strip('\"') # print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] = data09 # 小单净流入 净额", "= data04 # 超大单净流入 净占比 data05 = dataArrays[aItemIndex + 4]", "= 'http://ff.eastmoney.com/' else: iItem = iItem.strip(' \"') iItem = iItem.rstrip('", "= data03 # 超大单净流入 净额 data04 = dataArrays[aItemIndex + 3]", "# print(_stockName) # print(_market) values = [] for aline in", "#from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import *", "'_stockCode' in aline: # _stockCode = aline[len('var _stockCode = '):]", "= dataArrays[aItemIndex + 5] data06 = data06.strip('\"') # print('大单净流入 净额',data06)", "from QUANTAXIS.QAUtil import (DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list ): # 改用", "print('------------------') print(values) for iStockCode in range(len(param_stock_code_list)): requestStr = \"\" strCode", "# if '_stockCode' in aline: # _stockCode = aline[len('var _stockCode", "data06 # 大单净流入 净占比 data07 = dataArrays[aItemIndex + 6] data07", "是否存在有效合法 # todo 🛠 QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 :", "_stockName.strip(\"\\\"\\\"\\,\") # if '_market' in aline: # _market = aline[len('_market", "= _stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX , #_stockMarke = 1 #", "# print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") # else: # print(path_for_save_data,\"目录不存在! 失败建立目录 🤮,", "aline.strip() # if '_stockCode' in aline: # _stockCode = aline[len('var", "data05 # 大单净流入 净额 data06 = dataArrays[aItemIndex + 5] data06", "'):] # _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX , #_stockMarke", "净额',data08) dict_row['zdjll_je_wy'] = data08 # 中单净流入 净占比 data09 = dataArrays[aItemIndex", "print('收盘价',data12) dict_row['close_price'] = data12 # 涨跌幅 data13 = dataArrays[aItemIndex +", "2 # if '_stockName' in aline: # _stockName = aline[len('_stockName", "= data07 # 中单净流入 净额 data08 = dataArrays[aItemIndex + 7]", "# _stockMarke = 2 # 30XXXX , # _stockMarke =", "# 中单净流入 净占比 data09 = dataArrays[aItemIndex + 8] data09 =", "if 'var aff_data=({data:[[\"' in strings: leftChars = strings[len('var aff_data=({data:[[\"'):] #", "data02 = dataArrays[aItemIndex + 1] data02 = data02.strip('\"') # print('主力净流入", "== False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在", "if '_stockCode' in iItem: requestStr = requestStr + param_stock_code_list[iStockCode] elif", "= '1' elif strCode[0:2] == '00' or strCode[0:2] == '30':", "indexCode in range(len(stockCodeList)): #full_path_name = path_for_save_data + \"/\" + stockCodeList[indexCode]", "# print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx)", "print('主力净流入 净额',data02) dict_row['zljll_je_wy'] = data02 # 主力净流入 净占比 data03 =", "= data06.strip('\"') # print('大单净流入 净额',data06) dict_row['ddjll_je_wy'] = data06 # 大单净流入", "QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): # todo 🛠 check stockCode 是否存在有效合法 #", "= data09.strip('\"') # print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] = data09 # 小单净流入", "else: if 'http://ff.eastmoney.com/' in iItem: requestStr = 'http://ff.eastmoney.com/' else: iItem", "😁\") print(\"\") # path_for_save_data = QALocalize.download_path + \"/eastmoney_stock_zjlx\" # isExists", "print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] = data05 # 大单净流入 净额 data06 =", "time.sleep(1.456) response = urllib.request.urlopen(requestStr) content2 = response.read() # print(content2) strings", "requestStr = \"\" strCode = param_stock_code_list[iStockCode] if strCode[0:2] == '60':", "iItem: requestStr = 'http://ff.eastmoney.com/' else: iItem = iItem.strip(' \"') iItem", "= leftChars.split(',') # print(dataArrays) for aItemIndex in range(0, len(dataArrays), 13):", "= data11 # 收盘价 data12 = dataArrays[aItemIndex + 11] data12", "== '60': _stockMarke = '1' elif strCode[0:2] == '00' or", "response = urllib.request.urlopen(strUrl) content = response.read() # 🛠todo 改用 re", "aline[len('_stockName = '):] # _stockName = _stockName.strip(\"\\\"\\\"\\,\") # if '_market'", "dataArrays[aItemIndex + 12] data13 = data13.strip('\"') data13 = data13.strip('\"]]})') #", "= content2.decode(\"utf-8\", \"ignore\") # print(strings) list_data_zjlx = [] if 'var", "aline in string_lines: # aline = aline.strip() # if '_stockCode'", "dataArrays[aItemIndex + 9] data10 = data10.strip('\"') # print('小单净流入 净额',data10) dict_row['xdjll_je_wy']", "# 改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223) response =", "# else: # print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限 🈲\") # return", "= [] for aline in string_lines: aline = aline.strip() if", "+ 10] data11 = data11.strip('\"') # print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] =", "_stockCode = aline[len('var _stockCode = '):] # _stockCode = _stockCode.strip(\"\\\"\\\"\\,\")", "# print('------------------') aline = aline.strip() if aline.startswith('var strUrl = '):", "'):] # _stockCode = _stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke' in aline:", "content2.decode(\"utf-8\", \"ignore\") # print(strings) list_data_zjlx = [] if 'var aff_data=({data:[[\"'", "= aline.strip() # if '_stockCode' in aline: # _stockCode =", "# print(df) client = DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df))", "# print(aline) # print('------------------') aline = aline.strip() if aline.startswith('var strUrl", "净占比 data11 = dataArrays[aItemIndex + 10] data11 = data11.strip('\"') #", "# print(dict_row) list_data_zjlx.append(dict_row) # print(list_data_zjlx) df = pd.DataFrame(list_data_zjlx) # print(df)", "开头的股票代码\") return for iItem in values: if '_stockCode' in iItem:", "净占比 data07 = dataArrays[aItemIndex + 6] data07 = data07.strip('\"') #", "净额',data06) dict_row['ddjll_je_wy'] = data06 # 大单净流入 净占比 data07 = dataArrays[aItemIndex", "if '_market' in aline: # _market = aline[len('_market = '):]", "data10 = data10.strip('\"') # print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] = data10 #", "\" 暂不支持, 60, 00, 30 开头的股票代码\") return for iItem in", "aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03 # 超大单净流入 净额 data04 = dataArrays[aItemIndex", "涨跌幅 data13 = dataArrays[aItemIndex + 12] data13 = data13.strip('\"') data13", "🛠 QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check =", "in aline: # _stockName = aline[len('_stockName = '):] # _stockName", "😋\") browser = open_chrome_driver() for indexCode in range(len(stockCodeList)): #full_path_name =", "# print(_stockCode) # print(_stockMarke) # print(_stockName) # print(_market) values =", "print('小单净流入 净额',data10) dict_row['xdjll_je_wy'] = data10 # 小单净流入 净占比 data11 =", "* import urllib import pandas as pd import time from", "日期 # print(aItemIndex) data01 = dataArrays[aItemIndex] data01 = data01.strip('\"') #", "print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] = data09 # 小单净流入 净额 data10 =", "_stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX , #_stockMarke = 1 # 00XXXX", "= requestStr + _stockMarke else: if 'http://ff.eastmoney.com/' in iItem: requestStr", "= pd.DataFrame(list_data_zjlx) # print(df) client = DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx", "if isExists == False: # os.mkdir(path_for_save_data) # isExists = os.path.exists(path_for_save_data)", "print(content2) strings = content2.decode(\"utf-8\", \"ignore\") # print(strings) list_data_zjlx = []", "# 00XXXX , # _stockMarke = 2 # 30XXXX ,", "1 # 00XXXX , # _stockMarke = 2 # 30XXXX", "requestStr = requestStr + iItem # print(requestStr) # 延时 time.sleep(1.456)", "= data08 # 中单净流入 净占比 data09 = dataArrays[aItemIndex + 8]", "# print('主力净流入 净额',data02) dict_row['zljll_je_wy'] = data02 # 主力净流入 净占比 data03", "== '00' or strCode[0:2] == '30': _stockMarke = '2' else:", "# print('日期',data01) dict_row['date'] = data01 # 主力净流入 净额 data02 =", "else: print(strCode + \" 暂不支持, 60, 00, 30 开头的股票代码\") return", "data07 = dataArrays[aItemIndex + 6] data07 = data07.strip('\"') # print('大单净流入", "= 1 # 00XXXX , # _stockMarke = 2 #", "= dataArrays[aItemIndex + 11] data12 = data12.strip('\"') # print('收盘价',data12) dict_row['close_price']", "= iItem.rstrip(' \"') requestStr = requestStr + iItem # print(requestStr)", "data11 = dataArrays[aItemIndex + 10] data11 = data11.strip('\"') # print('小单净流入", "in iItem: requestStr = requestStr + _stockMarke else: if 'http://ff.eastmoney.com/'", "= client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in range(len(list_data_zjlx)): aRec =", "param_stock_code_list[iStockCode] elif '_stockMarke' in iItem: requestStr = requestStr + _stockMarke", "pd.DataFrame(list_data_zjlx) # print(df) client = DATABASE coll_stock_zjlx = client.eastmoney_stock_zjlx #", "= dataArrays[aItemIndex + 2] data03 = data03.strip('\"') # print('主力净流入 净占比',data03)", "''' 日期 收盘价 涨跌幅 主力净流入 净额 净占比 超大单净流入 净额 净占比", "插入新的记录 \", aRec) else: print(\"😵 记录已经存在 \", ret) ''' 作为测试用例来获取,", "_stockCode = '):] # _stockCode = _stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke'", "# if '_stockName' in aline: # _stockName = aline[len('_stockName =", "#_market= 'hsa' # print(_stockCode) # print(_stockMarke) # print(_stockName) # print(_market)", "# print(dataArrays) for aItemIndex in range(0, len(dataArrays), 13): ''' 日期", "= dataArrays[aItemIndex + 3] data04 = data04.strip('\"') # print('超大单净流入 净额',data04)", "open_chrome_driver() for indexCode in range(len(stockCodeList)): #full_path_name = path_for_save_data + \"/\"", "记录已经存在 \", ret) ''' 作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致 ''' def", "check stockCode 是否存在有效合法 # todo 🛠 QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件", "# _market = _market.strip(\"\\\"\\\"\\,\") # break #_market= 'hsa' # print(_stockCode)", "_stockMarke = aline[len('_stockMarke = '):] # _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") #", "strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223) response = urllib.request.urlopen(strUrl) content", "data07 = data07.strip('\"') # print('大单净流入 净占比',data07) dict_row['ddjll_je_jzb'] = data07 #", "iItem.strip(' \"') iItem = iItem.rstrip(' \"') requestStr = requestStr +", "leftChars = strings[len('var aff_data=({data:[[\"'):] # print(leftChars) dataArrays = leftChars.split(',') #", "print(\"😵 记录已经存在 \", ret) ''' 作为测试用例来获取, 对比 reqeust 方式的获取数据是否一致 '''", "# break #_market= 'hsa' # print(_stockCode) # print(_stockMarke) # print(_stockName)", "= dataArrays[aItemIndex + 8] data09 = data09.strip('\"') # print('中单净流入 净占比',data09)", "= data05.strip('\"') # print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] = data05 # 大单净流入", "= param_stock_code_list[iStockCode] if strCode[0:2] == '60': _stockMarke = '1' elif", "coll_stock_zjlx.find_one(aRec) if ret == None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \", aRec)", "= '):] values = aline.split('+') # print(values) break # print('------------------')", "data09 = data09.strip('\"') # print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb'] = data09 #", "aline[len('var strUrl = '):] values = aline.split('+') # print(values) break", "+ \"/\" + stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode], browser) pass close_chrome_dirver(browser)", "dataArrays[aItemIndex + 5] data06 = data06.strip('\"') # print('大单净流入 净额',data06) dict_row['ddjll_je_wy']", "'_market' in aline: # _market = aline[len('_market = '):] #", "aline.strip() if aline.startswith('var strUrl = '): if 'var strUrl =", "成功建立目录 😢\") # else: # print(path_for_save_data,\"目录不存在! 失败建立目录 🤮, 可能没有权限 🈲\")", "data03 # 超大单净流入 净额 data04 = dataArrays[aItemIndex + 3] data04", "= os.path.exists(path_for_save_data) # if isExists == False: # os.mkdir(path_for_save_data) #", "print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] = data04 # 超大单净流入 净占比 data05 =", "# 收盘价 data12 = dataArrays[aItemIndex + 11] data12 = data12.strip('\"')", "# print(values) break # print('------------------') print(values) for iStockCode in range(len(param_stock_code_list)):", "= coll_stock_zjlx.find_one(aRec) if ret == None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \",", "'http://ff.eastmoney.com/' in iItem: requestStr = 'http://ff.eastmoney.com/' else: iItem = iItem.strip('", "== None: coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \", aRec) else: print(\"😵 记录已经存在", "主力净流入 净额 净占比 超大单净流入 净额 净占比 大单净流入 净额 净占比 中单净流入", ", # _stockMarke = 2 # if '_stockName' in aline:", "values = [] for aline in string_lines: aline = aline.strip()", "= requestStr + iItem # print(requestStr) # 延时 time.sleep(1.456) response", "QUANTAXIS_CRAWLY.run_selenium_alone import * import urllib import pandas as pd import", "iItem = iItem.rstrip(' \"') requestStr = requestStr + iItem #", "小单净流入 净额 data10 = dataArrays[aItemIndex + 9] data10 = data10.strip('\"')", "+ 4] data05 = data05.strip('\"') # print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] =", "确认当前路径是否包含selenium_driver目录 😰 \") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\") #", "净占比 小单净流入 净额 净占比 ''' dict_row = {} dict_row['stock_code'] =", "strCode = param_stock_code_list[iStockCode] if strCode[0:2] == '60': _stockMarke = '1'", "# date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03 # 超大单净流入 净额", "主力净流入 净额 data02 = dataArrays[aItemIndex + 1] data02 = data02.strip('\"')", "todo 🛠 QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check", "data08 = dataArrays[aItemIndex + 7] data08 = data08.strip('\"') # print('中单净流入", "data04 # 超大单净流入 净占比 data05 = dataArrays[aItemIndex + 4] data05", "dataArrays[aItemIndex + 10] data11 = data11.strip('\"') # print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb']", "coll_stock_zjlx.insert_one(aRec) print(\"🤑 插入新的记录 \", aRec) else: print(\"😵 记录已经存在 \", ret)", "list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret = coll_stock_zjlx.find_one(aRec) if ret ==", "dict_row['cddjll_je_jzb'] = data05 # 大单净流入 净额 data06 = dataArrays[aItemIndex +", "_stockMarke = 2 # if '_stockName' in aline: # _stockName", "日期 收盘价 涨跌幅 主力净流入 净额 净占比 超大单净流入 净额 净占比 大单净流入", "= param_stock_code_list[iStockCode] # 日期 # print(aItemIndex) data01 = dataArrays[aItemIndex] data01", "data04 = dataArrays[aItemIndex + 3] data04 = data04.strip('\"') # print('超大单净流入", "for aline in string_lines: aline = aline.strip() if 'EM_CapitalFlowInterface' in", "'30': _stockMarke = '2' else: print(strCode + \" 暂不支持, 60,", "data13.strip('\"') data13 = data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price'] = data13 #", "dict_row['date'] = data01 # 主力净流入 净额 data02 = dataArrays[aItemIndex +", "# print(leftChars) dataArrays = leftChars.split(',') # print(dataArrays) for aItemIndex in", "_stockName = aline[len('_stockName = '):] # _stockName = _stockName.strip(\"\\\"\\\"\\,\") #", "'_stockName' in aline: # _stockName = aline[len('_stockName = '):] #", "'_stockMarke' in aline: # _stockMarke = aline[len('_stockMarke = '):] #", "= data11.strip('\"') # print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] = data11 # 收盘价", "QA_request_eastmoney_zjlx( param_stock_code_list ): # 改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时", "# if '_market' in aline: # _market = aline[len('_market =", "= '):] # _stockName = _stockName.strip(\"\\\"\\\"\\,\") # if '_market' in", "iItem: requestStr = requestStr + param_stock_code_list[iStockCode] elif '_stockMarke' in iItem:", "dict_row['change_price'] = data13 # 读取一条记录成功 # print(\"成功读取一条记录\") # print(dict_row) list_data_zjlx.append(dict_row)", "大单净流入 净额 净占比 中单净流入 净额 净占比 小单净流入 净额 净占比 '''", "'60': _stockMarke = '1' elif strCode[0:2] == '00' or strCode[0:2]", "strCode[0:2] == '30': _stockMarke = '2' else: print(strCode + \"", "净占比',data05) dict_row['cddjll_je_jzb'] = data05 # 大单净流入 净额 data06 = dataArrays[aItemIndex", "aRec) else: print(\"😵 记录已经存在 \", ret) ''' 作为测试用例来获取, 对比 reqeust", "净占比',data03) # date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03 # 超大单净流入", "净占比 ''' dict_row = {} dict_row['stock_code'] = param_stock_code_list[iStockCode] # 日期", "path_for_save_data = QALocalize.download_path + \"/eastmoney_stock_zjlx\" # isExists = os.path.exists(path_for_save_data) #", "'1' elif strCode[0:2] == '00' or strCode[0:2] == '30': _stockMarke", "data13 = data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price'] = data13 # 读取一条记录成功", "净额 data10 = dataArrays[aItemIndex + 9] data10 = data10.strip('\"') #", "+ stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode], browser) pass close_chrome_dirver(browser) #创建目录 #启动线程读取网页,写入数据库", "# _stockCode = _stockCode.strip(\"\\\"\\\"\\,\") # if '_stockMarke' in aline: #", "净额 data02 = dataArrays[aItemIndex + 1] data02 = data02.strip('\"') #", "print('小单净流入 净占比',data11) dict_row['xdjll_je_jzb'] = data11 # 收盘价 data12 = dataArrays[aItemIndex", "import os from QUANTAXIS.QASetting import QALocalize #from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite,", "正则表达式做匹配 strings = content.decode(\"utf-8\", \"ignore\") string_lines = strings.split(\"\\r\\n\") #for aline", "= data01 # 主力净流入 净额 data02 = dataArrays[aItemIndex + 1]", "data05 = data05.strip('\"') # print('超大单净流入 净占比',data05) dict_row['cddjll_je_jzb'] = data05 #", "strings[len('var aff_data=({data:[[\"'):] # print(leftChars) dataArrays = leftChars.split(',') # print(dataArrays) for", "净占比 data03 = dataArrays[aItemIndex + 2] data03 = data03.strip('\"') #", "aline: # _stockMarke = aline[len('_stockMarke = '):] # _stockMarke =", "# print('主力净流入 净占比',data03) # date01 = aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03", "_stockMarke = 2 # 30XXXX , # _stockMarke = 2", "dict_row['ddjll_je_wy'] = data06 # 大单净流入 净占比 data07 = dataArrays[aItemIndex +", "in string_lines: # aline = aline.strip() # if '_stockCode' in", "方式的获取数据是否一致 ''' def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): # todo 🛠 check", "requestStr + param_stock_code_list[iStockCode] elif '_stockMarke' in iItem: requestStr = requestStr", "data01 = data01.strip('\"') # print('日期',data01) dict_row['date'] = data01 # 主力净流入", "isExists == False: # os.mkdir(path_for_save_data) # isExists = os.path.exists(path_for_save_data) #", "'http://ff.eastmoney.com/' else: iItem = iItem.strip(' \"') iItem = iItem.rstrip(' \"')", "import * import urllib import pandas as pd import time", "QALocalize #from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import", "re 正则表达式做匹配 strings = content.decode(\"utf-8\", \"ignore\") string_lines = strings.split(\"\\r\\n\") #for", "print(strCode + \" 暂不支持, 60, 00, 30 开头的股票代码\") return for", "'_stockMarke' in iItem: requestStr = requestStr + _stockMarke else: if", "[] for aline in string_lines: aline = aline.strip() if 'EM_CapitalFlowInterface'", "# todo 🛠 check stockCode 是否存在有效合法 # todo 🛠 QALocalize", "# _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX , #_stockMarke =", "# print(content2) strings = content2.decode(\"utf-8\", \"ignore\") # print(strings) list_data_zjlx =", "data08 # 中单净流入 净占比 data09 = dataArrays[aItemIndex + 8] data09", "# else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser = open_chrome_driver() for indexCode", "client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in range(len(list_data_zjlx)): aRec = list_data_zjlx[i]", "= aline[len('var _stockCode = '):] # _stockCode = _stockCode.strip(\"\\\"\\\"\\,\") #", "= '):] # _stockMarke = _stockMarke.strip(\"\\\"\\\"\\,\") # # 60XXXX ,", "iItem.rstrip(' \"') requestStr = requestStr + iItem # print(requestStr) #", "data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price'] = data13 # 读取一条记录成功 # print(\"成功读取一条记录\")", "stockCode 是否存在有效合法 # todo 🛠 QALocalize 从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置", "= aline[len('_market = '):] # _market = _market.strip(\"\\\"\\\"\\,\") # break", "path_for_save_data + \"/\" + stockCodeList[indexCode] + \"_zjlx.sqlite.db\" read_east_money_page_zjlx_to_sqllite(stockCodeList[indexCode], browser) pass", "小单净流入 净占比 data11 = dataArrays[aItemIndex + 10] data11 = data11.strip('\"')", "aff_data=({data:[[\"' in strings: leftChars = strings[len('var aff_data=({data:[[\"'):] # print(leftChars) dataArrays", "= response.read() # 🛠todo 改用 re 正则表达式做匹配 strings = content.decode(\"utf-8\",", "for i in range(len(list_data_zjlx)): aRec = list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的", "中单净流入 净额 净占比 小单净流入 净额 净占比 ''' dict_row = {}", "= '): if 'var strUrl = ' in aline: aline", "QUANTAXIS.QASetting import QALocalize #from QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from", "QUANTAXIS_CRAWLY.run_selenium_alone import (read_east_money_page_zjlx_to_sqllite, open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import * import", "# if isExists == True: # print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") #", "data01 = dataArrays[aItemIndex] data01 = data01.strip('\"') # print('日期',data01) dict_row['date'] =", "_stockMarke = '1' elif strCode[0:2] == '00' or strCode[0:2] ==", "净额 净占比 大单净流入 净额 净占比 中单净流入 净额 净占比 小单净流入 净额", "改用 re 正则表达式做匹配 strings = content.decode(\"utf-8\", \"ignore\") string_lines = strings.split(\"\\r\\n\")", "3] data04 = data04.strip('\"') # print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] = data04", "if strCode[0:2] == '60': _stockMarke = '1' elif strCode[0:2] ==", "# 小单净流入 净额 data10 = dataArrays[aItemIndex + 9] data10 =", "if isExists == True: # print(path_for_save_data,\"目录不存在! 成功建立目录 😢\") # else:", "== '30': _stockMarke = '2' else: print(strCode + \" 暂不支持,", "dict_row['xdjll_je_wy'] = data10 # 小单净流入 净占比 data11 = dataArrays[aItemIndex +", "print(values) break # print('------------------') print(values) for iStockCode in range(len(param_stock_code_list)): requestStr", "strUrl = '): if 'var strUrl = ' in aline:", "= _market.strip(\"\\\"\\\"\\,\") # break #_market= 'hsa' # print(_stockCode) # print(_stockMarke)", "print(\"😵 确认当前路径是否包含selenium_driver目录 😰 \") return else: print(os.getcwd()+\"/QUANTAXIS_WEBDRIVER\",\" 目录存在 😁\") print(\"\")", "range(len(stockCodeList)): #full_path_name = path_for_save_data + \"/\" + stockCodeList[indexCode] + \"_zjlx.sqlite.db\"", "aline = aline.strip() if aline.startswith('var strUrl = '): if 'var", "= 2 # 30XXXX , # _stockMarke = 2 #", "= data13.strip('\"]]})') # print('涨跌幅',data13) dict_row['change_price'] = data13 # 读取一条记录成功 #", "# 30XXXX , # _stockMarke = 2 # if '_stockName'", "= dataArrays[aItemIndex + 12] data13 = data13.strip('\"') data13 = data13.strip('\"]]})')", "= iItem.strip(' \"') iItem = iItem.rstrip(' \"') requestStr = requestStr", "data11 # 收盘价 data12 = dataArrays[aItemIndex + 11] data12 =", "主力净流入 净占比 data03 = dataArrays[aItemIndex + 2] data03 = data03.strip('\"')", "= urllib.request.urlopen(strUrl) content = response.read() # 🛠todo 改用 re 正则表达式做匹配", "data04.strip('\"') # print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] = data04 # 超大单净流入 净占比", "data01 # 主力净流入 净额 data02 = dataArrays[aItemIndex + 1] data02", "urllib.request.urlopen(requestStr) content2 = response.read() # print(content2) strings = content2.decode(\"utf-8\", \"ignore\")", "净占比 大单净流入 净额 净占比 中单净流入 净额 净占比 小单净流入 净额 净占比", "dict_row['zdjll_je_wy'] = data08 # 中单净流入 净占比 data09 = dataArrays[aItemIndex +", "= os.path.exists(path_for_save_data) # if isExists == True: # print(path_for_save_data,\"目录不存在! 成功建立目录", "# 中单净流入 净额 data08 = dataArrays[aItemIndex + 7] data08 =", "len(dataArrays), 13): ''' 日期 收盘价 涨跌幅 主力净流入 净额 净占比 超大单净流入", "# coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in range(len(list_data_zjlx)): aRec = list_data_zjlx[i] #", "path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) == False: print(\"😵 确认当前路径是否包含selenium_driver目录 😰", "time from QUANTAXIS.QAUtil import (DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list ): #", "def QA_read_eastmoney_zjlx_web_page_to_sqllite(stockCodeList = None): # todo 🛠 check stockCode 是否存在有效合法", "if aline.startswith('var strUrl = '): if 'var strUrl = '", "超大单净流入 净额 data04 = dataArrays[aItemIndex + 3] data04 = data04.strip('\"')", "中单净流入 净占比 data09 = dataArrays[aItemIndex + 8] data09 = data09.strip('\"')", "param_stock_code_list[iStockCode] # 日期 # print(aItemIndex) data01 = dataArrays[aItemIndex] data01 =", "i in range(len(list_data_zjlx)): aRec = list_data_zjlx[i] # 🛠todo 当天结束后,获取当天的资金流相,当天的资金流向是瞬时间点的 ret", "elif strCode[0:2] == '00' or strCode[0:2] == '30': _stockMarke =", "data01.strip('\"') # print('日期',data01) dict_row['date'] = data01 # 主力净流入 净额 data02", "(DATABASE) def QA_request_eastmoney_zjlx( param_stock_code_list ): # 改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0])", "in aline: # print(aline) # print('------------------') aline = aline.strip() if", "param_stock_code_list ): # 改用 strUrl = \"http://data.eastmoney.com/zjlx/{}.html\".format(param_stock_code_list[0]) # 延时 time.sleep(1.223)", "strings: leftChars = strings[len('var aff_data=({data:[[\"'):] # print(leftChars) dataArrays = leftChars.split(',')", "🈲\") # return # else: # print(path_for_save_data,\"目录存在!准备读取数据 😋\") browser =", "coll_stock_zjlx = client.eastmoney_stock_zjlx # coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in range(len(list_data_zjlx)): aRec", "data03 = data03.strip('\"') # print('主力净流入 净占比',data03) # date01 = aItemData.strip('[\\'\\'')", "open_chrome_driver, close_chrome_dirver) from QUANTAXIS_CRAWLY.run_selenium_alone import * import urllib import pandas", "aff_data=({data:[[\"'):] # print(leftChars) dataArrays = leftChars.split(',') # print(dataArrays) for aItemIndex", "暂不支持, 60, 00, 30 开头的股票代码\") return for iItem in values:", "values: if '_stockCode' in iItem: requestStr = requestStr + param_stock_code_list[iStockCode]", "从QALocalize 目录中读取 固定位置存放驱动文件 print(\"📨当前工作路径文件位置 : \",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if", "'): if 'var strUrl = ' in aline: aline =", "data04 = data04.strip('\"') # print('超大单净流入 净额',data04) dict_row['cddjll_je_wy'] = data04 #", "= open_chrome_driver() for indexCode in range(len(stockCodeList)): #full_path_name = path_for_save_data +", "= dataArrays[aItemIndex + 6] data07 = data07.strip('\"') # print('大单净流入 净占比',data07)", "data02 = data02.strip('\"') # print('主力净流入 净额',data02) dict_row['zljll_je_wy'] = data02 #", "= \"\" strCode = param_stock_code_list[iStockCode] if strCode[0:2] == '60': _stockMarke", "dict_row['close_price'] = data12 # 涨跌幅 data13 = dataArrays[aItemIndex + 12]", ": \",os.getcwd()) path_check = os.getcwd()+\"/QUANTAXIS_WEBDRIVER\" if os.path.exists(path_check) == False: print(\"😵", "data03 = dataArrays[aItemIndex + 2] data03 = data03.strip('\"') # print('主力净流入", "= data02.strip('\"') # print('主力净流入 净额',data02) dict_row['zljll_je_wy'] = data02 # 主力净流入", "= aItemData.strip('[\\'\\'') dict_row['zljll_jzb_bfb'] = data03 # 超大单净流入 净额 data04 =", "break #_market= 'hsa' # print(_stockCode) # print(_stockMarke) # print(_stockName) #", "coll_stock_zjlx.insert_many(QA_util_to_json_from_pandas(df)) for i in range(len(list_data_zjlx)): aRec = list_data_zjlx[i] # 🛠todo", "_stockMarke else: if 'http://ff.eastmoney.com/' in iItem: requestStr = 'http://ff.eastmoney.com/' else:", "dataArrays[aItemIndex + 8] data09 = data09.strip('\"') # print('中单净流入 净占比',data09) dict_row['zdjll_je_jzb']", "\"ignore\") # print(strings) list_data_zjlx = [] if 'var aff_data=({data:[[\"' in", "strCode[0:2] == '60': _stockMarke = '1' elif strCode[0:2] == '00'", "延时 time.sleep(1.223) response = urllib.request.urlopen(strUrl) content = response.read() # 🛠todo" ]
[ "level for the general logger # each handler can then", "can then restrict the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging() if __name__", "logging.StreamHandler(sys.stdout) # Log to a file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO)", "import app as application def setup_flask_logging(): # Log to stdout", "# Set default log level for the general logger #", "sys from app import app as application def setup_flask_logging(): #", "handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s ' )) application.logger.addHandler(handler) # Set", "#!/usr/bin/env python import logging import sys from app import app", "Set default log level for the general logger # each", "log level for the general logger # each handler can", "to a file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s]", "import logging import sys from app import app as application", "logging import sys from app import app as application def", "# Log to a file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter(", "'%(asctime)s [%(funcName)s] %(levelname)s: %(message)s ' )) application.logger.addHandler(handler) # Set default", "[%(funcName)s] %(levelname)s: %(message)s ' )) application.logger.addHandler(handler) # Set default log", "application def setup_flask_logging(): # Log to stdout handler = logging.StreamHandler(sys.stdout)", "' )) application.logger.addHandler(handler) # Set default log level for the", "def setup_flask_logging(): # Log to stdout handler = logging.StreamHandler(sys.stdout) #", "Log to stdout handler = logging.StreamHandler(sys.stdout) # Log to a", "default log level for the general logger # each handler", "%(message)s ' )) application.logger.addHandler(handler) # Set default log level for", "handler = logging.StreamHandler(sys.stdout) # Log to a file #handler =", "app as application def setup_flask_logging(): # Log to stdout handler", "as application def setup_flask_logging(): # Log to stdout handler =", "to stdout handler = logging.StreamHandler(sys.stdout) # Log to a file", "the general logger # each handler can then restrict the", "the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging() if __name__ == '__main__': application.run()", "= logging.StreamHandler(sys.stdout) # Log to a file #handler = logging.FileHandler('./application.log')", "logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s ' )) application.logger.addHandler(handler)", "# Log to stdout handler = logging.StreamHandler(sys.stdout) # Log to", "for the general logger # each handler can then restrict", "handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s ' )) application.logger.addHandler(handler) #", "= logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s ' ))", "logger # each handler can then restrict the messages logged", "restrict the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging() if __name__ == '__main__':", "a file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s:", "setup_flask_logging(): # Log to stdout handler = logging.StreamHandler(sys.stdout) # Log", "then restrict the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging() if __name__ ==", "from app import app as application def setup_flask_logging(): # Log", "app import app as application def setup_flask_logging(): # Log to", "# each handler can then restrict the messages logged application.logger.setLevel(logging.INFO)", "%(levelname)s: %(message)s ' )) application.logger.addHandler(handler) # Set default log level", "each handler can then restrict the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging()", ")) application.logger.addHandler(handler) # Set default log level for the general", "#handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s '", "Log to a file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s", "application.logger.addHandler(handler) # Set default log level for the general logger", "general logger # each handler can then restrict the messages", "import sys from app import app as application def setup_flask_logging():", "file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s", "python import logging import sys from app import app as", "handler can then restrict the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging() if", "stdout handler = logging.StreamHandler(sys.stdout) # Log to a file #handler" ]
[ "__init__(self, app, scene, **kwargs): super().__init__(app, scene, **kwargs) self.friendly = False", "Being class Enemy(Being): def __init__(self, app, scene, **kwargs): super().__init__(app, scene,", "python from game.base.being import Being class Enemy(Being): def __init__(self, app,", "Enemy(Being): def __init__(self, app, scene, **kwargs): super().__init__(app, scene, **kwargs) self.friendly", "def __init__(self, app, scene, **kwargs): super().__init__(app, scene, **kwargs) self.friendly =", "game.base.being import Being class Enemy(Being): def __init__(self, app, scene, **kwargs):", "#!/usr/bin/env python from game.base.being import Being class Enemy(Being): def __init__(self,", "from game.base.being import Being class Enemy(Being): def __init__(self, app, scene,", "class Enemy(Being): def __init__(self, app, scene, **kwargs): super().__init__(app, scene, **kwargs)", "<gh_stars>1-10 #!/usr/bin/env python from game.base.being import Being class Enemy(Being): def", "import Being class Enemy(Being): def __init__(self, app, scene, **kwargs): super().__init__(app," ]
[ "# -*- coding: utf-8 -*- # Generated by Django 1.11.1", "model_name='rate', old_name='euro_rate', new_name='eur_rate', ), migrations.RenameField( model_name='rate', old_name='pound_rates', new_name='gbp_rate', ), ]", "from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):", "Migration(migrations.Migration): dependencies = [ ('rates', '0001_initial'), ] operations = [", "Generated by Django 1.11.1 on 2017-06-25 15:10 from __future__ import", "15:10 from __future__ import unicode_literals from django.db import migrations class", "dependencies = [ ('rates', '0001_initial'), ] operations = [ migrations.RenameField(", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rates', '0001_initial'),", "unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [", "= [ ('rates', '0001_initial'), ] operations = [ migrations.RenameField( model_name='rate',", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rates',", "on 2017-06-25 15:10 from __future__ import unicode_literals from django.db import", "Django 1.11.1 on 2017-06-25 15:10 from __future__ import unicode_literals from", "migrations class Migration(migrations.Migration): dependencies = [ ('rates', '0001_initial'), ] operations", "-*- # Generated by Django 1.11.1 on 2017-06-25 15:10 from", "[ migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate', ), migrations.RenameField( model_name='rate', old_name='pound_rates', new_name='gbp_rate',", "migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate', ), migrations.RenameField( model_name='rate', old_name='pound_rates', new_name='gbp_rate', ),", "-*- coding: utf-8 -*- # Generated by Django 1.11.1 on", "utf-8 -*- # Generated by Django 1.11.1 on 2017-06-25 15:10", "1.11.1 on 2017-06-25 15:10 from __future__ import unicode_literals from django.db", "import migrations class Migration(migrations.Migration): dependencies = [ ('rates', '0001_initial'), ]", "import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies =", "] operations = [ migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate', ), migrations.RenameField(", "by Django 1.11.1 on 2017-06-25 15:10 from __future__ import unicode_literals", "2017-06-25 15:10 from __future__ import unicode_literals from django.db import migrations", "# Generated by Django 1.11.1 on 2017-06-25 15:10 from __future__", "coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-25", "__future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies", "operations = [ migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate', ), migrations.RenameField( model_name='rate',", "= [ migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate', ), migrations.RenameField( model_name='rate', old_name='pound_rates',", "'0001_initial'), ] operations = [ migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate', ),", "[ ('rates', '0001_initial'), ] operations = [ migrations.RenameField( model_name='rate', old_name='euro_rate',", "class Migration(migrations.Migration): dependencies = [ ('rates', '0001_initial'), ] operations =", "('rates', '0001_initial'), ] operations = [ migrations.RenameField( model_name='rate', old_name='euro_rate', new_name='eur_rate'," ]
[ "and their associated metadata. OpenAPI spec version: 0.5.0 Contact: <EMAIL>", "# http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3 >= 1.15\", \"six >= 1.10\",", "Internet :: WWW/HTTP', 'Topic :: System :: Archiving', ], )", "metadata. See more at [quetz.al](https://quetz.al) and its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\",", "setuptools import setup, find_packages # noqa: H301 NAME = \"quetzal-openapi-client\"", "import setup, find_packages # noqa: H301 NAME = \"quetzal-openapi-client\" VERSION", ":: Python :: 3.6', 'Programming Language :: Python :: 3.7',", "quetzal-client package. Quetzal is an API to manage data files", "\"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development Status :: 4 - Beta', 'Intended", "[quetz.al](https://quetz.al) and its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development Status", "\"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ======================", "an OpenAPI specification of the Quetzal API. An improvement layer", "an API to manage data files and their associated metadata.", "specification of the Quetzal API. An improvement layer on this", "[openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI specification of the Quetzal API. An", ":: Internet :: WWW/HTTP', 'Topic :: System :: Archiving', ],", "exists in the quetzal-client package. Quetzal is an API to", "the quetzal-client package. Quetzal is an API to manage data", "setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3 >= 1.15\", \"six >=", "OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language", "# To install the library, run the following # #", "using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI specification of the Quetzal API.", "version=VERSION, description=\"Quetzal API auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\":", "from an OpenAPI specification of the Quetzal API. An improvement", "}, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'],", "====================== This is an auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an", "BSD License', 'Operating System :: OS Independent', 'Programming Language ::", "more at [quetz.al](https://quetz.al) and its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[", "documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development Status :: 4 - Beta',", "\"\"\" from setuptools import setup, find_packages # noqa: H301 NAME", "NAME = \"quetzal-openapi-client\" VERSION = \"0.5.0\" # To install the", "1.10\", \"certifi\", \"python-dateutil\"] setup( name=NAME, version=VERSION, description=\"Quetzal API auto-generated client\",", "API auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\":", "manage data files and their associated metadata. See more at", "# # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3 >=", ":: Database :: Front-Ends', 'Topic :: Internet :: WWW/HTTP', 'Topic", "by: https://openapi-generator.tech \"\"\" from setuptools import setup, find_packages # noqa:", "setup, find_packages # noqa: H301 NAME = \"quetzal-openapi-client\" VERSION =", "# coding: utf-8 \"\"\" Quetzal API Quetzal: an API to", "# prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3 >= 1.15\",", "improvement layer on this client exists in the quetzal-client package.", "https://openapi-generator.tech \"\"\" from setuptools import setup, find_packages # noqa: H301", "manage data files and their associated metadata. OpenAPI spec version:", "\"0.5.0\" # To install the library, run the following #", "'Intended Audience :: Developers', 'License :: OSI Approved :: BSD", "\"certifi\", \"python-dateutil\"] setup( name=NAME, version=VERSION, description=\"Quetzal API auto-generated client\", author='<NAME>',", "author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\":", "= \"quetzal-openapi-client\" VERSION = \"0.5.0\" # To install the library,", "include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ====================== This is an auto-generated package using", "H301 NAME = \"quetzal-openapi-client\" VERSION = \"0.5.0\" # To install", "'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ====================== This is an auto-generated", "install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ====================== This is", "the library, run the following # # python setup.py install", "author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\",", "packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ====================== This is an", "REQUIRES = [\"urllib3 >= 1.15\", \"six >= 1.10\", \"certifi\", \"python-dateutil\"]", "Language :: Python :: 3.6', 'Programming Language :: Python ::", "the following # # python setup.py install # # prerequisite:", ">= 1.15\", \"six >= 1.10\", \"certifi\", \"python-dateutil\"] setup( name=NAME, version=VERSION,", "\"python-dateutil\"] setup( name=NAME, version=VERSION, description=\"Quetzal API auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\",", "utf-8 \"\"\" Quetzal API Quetzal: an API to manage data", "= [\"urllib3 >= 1.15\", \"six >= 1.10\", \"certifi\", \"python-dateutil\"] setup(", "OSI Approved :: BSD License', 'Operating System :: OS Independent',", "quetzal-openapi-client ====================== This is an auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from", "library, run the following # # python setup.py install #", "= \"0.5.0\" # To install the library, run the following", "package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI specification of the Quetzal", "keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\", "<EMAIL> Generated by: https://openapi-generator.tech \"\"\" from setuptools import setup, find_packages", "- Beta', 'Intended Audience :: Developers', 'License :: OSI Approved", ":: 2.7', 'Programming Language :: Python :: 3.6', 'Programming Language", "setup( name=NAME, version=VERSION, description=\"Quetzal API auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\",", "long_description_content_type='text/markdown', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience", "Language :: Python :: 2.7', 'Programming Language :: Python ::", "Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from setuptools import setup,", ":: 3.8', 'Topic :: Database :: Front-Ends', 'Topic :: Internet", ":: Python :: 3.7', 'Programming Language :: Python :: 3.8',", "install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3", "their associated metadata. OpenAPI spec version: 0.5.0 Contact: <EMAIL> Generated", ":: Python :: 2.7', 'Programming Language :: Python :: 3.6',", "auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI specification of the", "'Development Status :: 4 - Beta', 'Intended Audience :: Developers',", "name=NAME, version=VERSION, description=\"Quetzal API auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={", ":: BSD License', 'Operating System :: OS Independent', 'Programming Language", "Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Programming", "'Programming Language :: Python :: 3.6', 'Programming Language :: Python", ":: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language", "'Operating System :: OS Independent', 'Programming Language :: Python ::", "package. Quetzal is an API to manage data files and", "Database :: Front-Ends', 'Topic :: Internet :: WWW/HTTP', 'Topic ::", "# python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools", "API to manage data files and their associated metadata. OpenAPI", "client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue", "data files and their associated metadata. OpenAPI spec version: 0.5.0", "'Programming Language :: Python :: 2.7', 'Programming Language :: Python", "Beta', 'Intended Audience :: Developers', 'License :: OSI Approved ::", "license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True,", "\"\"\" Quetzal API Quetzal: an API to manage data files", "tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test',", "3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Database", "OpenAPI specification of the Quetzal API. An improvement layer on", "in the quetzal-client package. Quetzal is an API to manage", "and their associated metadata. See more at [quetz.al](https://quetz.al) and its", "to manage data files and their associated metadata. OpenAPI spec", "files and their associated metadata. OpenAPI spec version: 0.5.0 Contact:", "python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES", ":: Python :: 3.8', 'Topic :: Database :: Front-Ends', 'Topic", "client exists in the quetzal-client package. Quetzal is an API", "noqa: H301 NAME = \"quetzal-openapi-client\" VERSION = \"0.5.0\" # To", "License', 'Operating System :: OS Independent', 'Programming Language :: Python", "on this client exists in the quetzal-client package. Quetzal is", ":: Developers', 'License :: OSI Approved :: BSD License', 'Operating", "Quetzal API Quetzal: an API to manage data files and", "\"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']),", "is an API to manage data files and their associated", "their associated metadata. See more at [quetz.al](https://quetz.al) and its [readthedocs", "Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic", "Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming", "3.8', 'Topic :: Database :: Front-Ends', 'Topic :: Internet ::", "Front-Ends', 'Topic :: Internet :: WWW/HTTP', 'Topic :: System ::", "Quetzal: an API to manage data files and their associated", "associated metadata. See more at [quetz.al](https://quetz.al) and its [readthedocs documentation](https://quetzal-api.readthedocs.io).", "description=\"Quetzal API auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\",", "OpenAPI spec version: 0.5.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\"", ":: Front-Ends', 'Topic :: Internet :: WWW/HTTP', 'Topic :: System", "\"quetzal-openapi-client\" VERSION = \"0.5.0\" # To install the library, run", "\"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\",", "of the Quetzal API. An improvement layer on this client", "System :: OS Independent', 'Programming Language :: Python :: 2.7',", "Language :: Python :: 3.8', 'Topic :: Database :: Front-Ends',", "prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3 >= 1.15\", \"six", "Approved :: BSD License', 'Operating System :: OS Independent', 'Programming", "3.6', 'Programming Language :: Python :: 3.7', 'Programming Language ::", "setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES =", "data files and their associated metadata. See more at [quetz.al](https://quetz.al)", "VERSION = \"0.5.0\" # To install the library, run the", "4 - Beta', 'Intended Audience :: Developers', 'License :: OSI", "Python :: 3.8', 'Topic :: Database :: Front-Ends', 'Topic ::", "its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development Status :: 4", "API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ====================== This", "'Topic :: Database :: Front-Ends', 'Topic :: Internet :: WWW/HTTP',", "API Quetzal: an API to manage data files and their", "http://pypi.python.org/pypi/setuptools REQUIRES = [\"urllib3 >= 1.15\", \"six >= 1.10\", \"certifi\",", "[readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development Status :: 4 -", "\"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"],", "\"six >= 1.10\", \"certifi\", \"python-dateutil\"] setup( name=NAME, version=VERSION, description=\"Quetzal API", "associated metadata. OpenAPI spec version: 0.5.0 Contact: <EMAIL> Generated by:", "find_packages # noqa: H301 NAME = \"quetzal-openapi-client\" VERSION = \"0.5.0\"", "this client exists in the quetzal-client package. Quetzal is an", "Generated by: https://openapi-generator.tech \"\"\" from setuptools import setup, find_packages #", ":: 3.7', 'Programming Language :: Python :: 3.8', 'Topic ::", "Quetzal API. An improvement layer on this client exists in", "project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\",", "is an auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI specification", "# noqa: H301 NAME = \"quetzal-openapi-client\" VERSION = \"0.5.0\" #", "'Programming Language :: Python :: 3.7', 'Programming Language :: Python", "Language :: Python :: 3.7', 'Programming Language :: Python ::", "files and their associated metadata. See more at [quetz.al](https://quetz.al) and", "[\"urllib3 >= 1.15\", \"six >= 1.10\", \"certifi\", \"python-dateutil\"] setup( name=NAME,", "To install the library, run the following # # python", ":: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming", "following # # python setup.py install # # prerequisite: setuptools", "coding: utf-8 \"\"\" Quetzal API Quetzal: an API to manage", "This is an auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI", "\"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES,", "2.7', 'Programming Language :: Python :: 3.6', 'Programming Language ::", "'License :: OSI Approved :: BSD License', 'Operating System ::", "API to manage data files and their associated metadata. See", "Quetzal is an API to manage data files and their", "spec version: 0.5.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from", "metadata. OpenAPI spec version: 0.5.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech", "run the following # # python setup.py install # #", "\"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\", \"Quetzal", "Independent', 'Programming Language :: Python :: 2.7', 'Programming Language ::", "Audience :: Developers', 'License :: OSI Approved :: BSD License',", "classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience ::", ">= 1.10\", \"certifi\", \"python-dateutil\"] setup( name=NAME, version=VERSION, description=\"Quetzal API auto-generated", "'Programming Language :: Python :: 3.8', 'Topic :: Database ::", "at [quetz.al](https://quetz.al) and its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development", "\"OpenAPI-Generator\", \"Quetzal API\"], install_requires=REQUIRES, packages=find_packages(exclude=['test', 'docs']), namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client", "layer on this client exists in the quetzal-client package. Quetzal", "Status :: 4 - Beta', 'Intended Audience :: Developers', 'License", "API. An improvement layer on this client exists in the", "install the library, run the following # # python setup.py", "# # python setup.py install # # prerequisite: setuptools #", "auto-generated client\", author='<NAME>', author_email=\"<EMAIL>\", url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\",", "the Quetzal API. An improvement layer on this client exists", "long_description=\"\"\"\\ quetzal-openapi-client ====================== This is an auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator)", ":: 4 - Beta', 'Intended Audience :: Developers', 'License ::", "Developers', 'License :: OSI Approved :: BSD License', 'Operating System", "\"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", }, license=\"BSD-3-Clause\", keywords=[\"OpenAPI\", \"OpenAPI-Generator\",", "from setuptools import setup, find_packages # noqa: H301 NAME =", ":: OSI Approved :: BSD License', 'Operating System :: OS", "1.15\", \"six >= 1.10\", \"certifi\", \"python-dateutil\"] setup( name=NAME, version=VERSION, description=\"Quetzal", "namespace_packages=['quetzal'], include_package_data=True, long_description=\"\"\"\\ quetzal-openapi-client ====================== This is an auto-generated package", "an auto-generated package using [openapi-generator](https://github.com/OpenAPITools/openapi-generator) from an OpenAPI specification of", "to manage data files and their associated metadata. See more", "0.5.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from setuptools import", "'Topic :: Internet :: WWW/HTTP', 'Topic :: System :: Archiving',", "An improvement layer on this client exists in the quetzal-client", "url=\"https://github.com/quet.zal/quetzal-openapi-client\", project_urls={ \"Documentation\": \"https://quetzal-openapi-client.readthedocs.io\", \"Code\": \"https://github.com/quetz-al/quetzal-openapi-client\", \"Issue tracker\": \"https://github.com/quetz-al/quetzal-openapi-client/issues\", },", "version: 0.5.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" from setuptools", "See more at [quetz.al](https://quetz.al) and its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown',", "and its [readthedocs documentation](https://quetzal-api.readthedocs.io). \"\"\", long_description_content_type='text/markdown', classifiers=[ 'Development Status ::" ]
[ "video_data = self._download_xml( data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if", "video_id = video_data.attrib['id'] title = xpath_text(video_data, 'headline', fatal=True) content_id =", "= url_or_none(video_file.text.strip()) if not video_url: continue ext = determine_ext(video_url) if", "r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path') # auth = self._download_webpage( # protected_path_data['tokenizer_src'],", "float_or_none(stream_data.get('totalRuntime')) if not chapters: for chapter in stream_data.get('contentSegments', []): start_time", "== 'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or", "'vcodec': 'none', 'ext': 'm4a', }) else: f['tbr'] = int(mobj.group(1)) formats.append(f)", "'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live':", "nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http':", "urls = [] formats = [] thumbnails = [] subtitles", "('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl') or", "aifp = xpath_text(video_data, 'akamai/aifp', default='') urls = [] formats =", "xpath_text(auth, 'error/msg') if error_msg: raise ExtractorError(error_msg, expected=True) token = xpath_text(auth,", "error_msg = xpath_text(auth, 'error/msg') if error_msg: raise ExtractorError(error_msg, expected=True) token", "fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data: return {} video_id = video_data.attrib['id']", "elif ext == 'png': thumbnails.append({ 'id': format_id, 'url': video_url, })", "fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none,", "video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds':", "video_url, 'secure path') + '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not", "maybe others for video_file in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if", "'/secure/' in video_url and '?hdnea=' in video_url: for f in", "token: query = { 'path': secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query)", "start_time = float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if start_time is None", "is None: continue chapters.append({ 'start_time': start_time, 'end_time': start_time + chapter_duration,", "{}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)) duration =", "fatal=False)) else: f = { 'format_id': format_id, 'url': video_url, 'ext':", "content_id if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth", "'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data,", "chapters: for chapter in stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start')) chapter_duration", "chapter_duration, }) self._sort_formats(formats) return { 'formats': formats, 'chapters': chapters, 'duration':", "'url': video_url, }) elif ext == 'smil': formats.extend(self._extract_smil_formats( video_url, video_id,", "+ token elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if not secure_path_data:", "from ..compat import compat_str from ..utils import ( fix_xml_ampersands, xpath_text,", "_extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url,", "'akamai/aifp', default='') urls = [] formats = [] thumbnails =", "'true' return { 'id': video_id, 'title': self._live_title(title) if is_live else", "= self._download_xml( data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if not", "'akamai/src') # if rtmp_src: # split_rtmp_src = rtmp_src.split(',') # if", "# protected_path_data = path_data.get('protected') # if not protected_path_data or not", "import compat_str from ..utils import ( fix_xml_ampersands, xpath_text, int_or_none, determine_ext,", "secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*' token =", "'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or", "for chapter in stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start')) chapter_duration =", "aifp, # }) # token = xpath_text(auth, 'token') # if", "chapter_duration is None: continue chapters.append({ 'start_time': start_time, 'end_time': start_time +", "path_data.get('default', {})) media_src = base_path_data.get('media_src') if not media_src: continue video_url", "if not media_src: continue video_url = media_src + video_url if", "self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path') # auth = self._download_webpage(", "for track in source.findall('track'): track_url = url_or_none(track.get('url')) if not track_url", "content_id, ap_data) elif not re.match('https?://', video_url): base_path_data = path_data.get(ext, path_data.get('default',", "self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url,", "chapters = [] formats = [] for supported_type in ('unprotected',", "{ 'format_id': format_id, 'url': video_url, 'ext': ext, } mobj =", "self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if", "+ video_url if video_url in urls: continue urls.append(video_url) format_id =", "} mobj = rex.search(video_url) if mobj: f.update({ 'width': int(mobj.group('width')), 'height':", "error_msg: raise ExtractorError(error_msg, expected=True) token = xpath_text(auth, 'token') if not", "'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id or 'hds', fatal=False))", "media_id, media_id)['media']['tv'] duration = None chapters = [] formats =", "content_id, ap_data['site_name'], ap_data['site_name']) auth = self._download_xml( tokenizer_src, content_id, query=query) error_msg", "secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] = content_id if", "stream_data.get('playlistProtection') == 'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data", "fatal=False): video_data = self._download_xml( data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal)", "video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, {", "mobj: f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif", "}) # token = xpath_text(auth, 'token') # if not token:", "not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url +", "= [] for supported_type in ('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type,", "'mp4', m3u8_id=format_id or 'hls', fatal=False) if '/secure/' in video_url and", "video_url in urls: continue urls.append(video_url) format_id = video_file.get('bitrate') if ext", "'3.7.0'}), video_id, f4m_id=format_id or 'hds', fatal=False)) else: f = {", "= float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if start_time is None or", "{ 'id': video_id, 'title': self._live_title(title) if is_live else title, 'formats':", "if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] = content_id if ap_data.get('auth_required'): query['accessToken']", "compat_str from ..utils import ( fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none,", "ExtractorError(error_msg, expected=True) token = xpath_text(auth, 'token') if not token: return", "None chapters = [] formats = [] for supported_type in", "auth = self._download_xml( tokenizer_src, content_id, query=query) error_msg = xpath_text(auth, 'error/msg')", "{}) m3u8_url = stream_data.get('secureUrl') or stream_data.get('url') if not m3u8_url: continue", "'en' subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext': { 'scc': 'scc', 'webvtt':", "m3u8_url = stream_data.get('secureUrl') or stream_data.get('url') if not m3u8_url: continue if", "'url': video_url, 'ext': ext, } mobj = rex.search(video_url) if mobj:", "in source.findall('track'): track_url = url_or_none(track.get('url')) if not track_url or track_url.endswith('/big'):", "media_id, tokenizer_query, ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv']", "if not video_url: continue ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue", "'hls', fatal=False) if '/secure/' in video_url and '?hdnea=' in video_url:", "xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data,", "ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth = self._download_xml(", "__future__ import unicode_literals import re from .adobepass import AdobePassIE from", "= self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query = { 'path': secure_path,", "= re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations: files/file, files/groupFiles/files #", "video_url, }) elif ext == 'png': thumbnails.append({ 'id': format_id, 'url':", "video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id,", "= [] subtitles = {} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') #", "'path': protected_path, # 'videoId': content_id, # 'aifp': aifp, # })", "video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False) if '/secure/' in video_url", ") class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self, video_data): return", "+ '?hdnea=' + token def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={},", "for image in video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive') == 'true'", "rtmp_src: # split_rtmp_src = rtmp_src.split(',') # if len(split_rtmp_src) == 2:", "video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url + '?hdnea=' + token", "video_url: for f in m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats) elif", "'path': secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] = content_id", "int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'): for track in", "if not secure_path_data: continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] +", "image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for image in video_data.findall('images/image'))", "video_url and '?hdnea=' in video_url: for f in m3u8_formats: f['_seekable']", "subtitles = {} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats", "not video_url: continue ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue #", "re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds': path_data.get('f4m', {}).get('host'), #", "fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if not chapters: for chapter in", "in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if not video_url: continue ext", "= xpath_text(video_data, 'contentId') or video_id # rtmp_src = xpath_text(video_data, 'akamai/src')", "= video_file.get('bitrate') if ext in ('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({", "token elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if not secure_path_data: continue", "for these files # protected_path_data = path_data.get('protected') # if not", "format_id) if mobj: if mobj.group(1) == 'audio': f.update({ 'vcodec': 'none',", "ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False))", "url_or_none(video_file.text.strip()) if not video_url: continue ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'):", "# TODO Correct extraction for these files # protected_path_data =", "# aifp = xpath_text(video_data, 'akamai/aifp', default='') urls = [] formats", "[] formats = [] for supported_type in ('unprotected', 'bulkaes'): stream_data", "= self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path)", "compat_str): if format_id.isdigit(): f['tbr'] = int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$',", "# if rtmp_src: # split_rtmp_src = rtmp_src.split(',') # if len(split_rtmp_src)", "path_data.get('protected') # if not protected_path_data or not rtmp_src: # continue", "content_id, # 'aifp': aifp, # }) # token = xpath_text(auth,", "isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr'] = int(format_id) else: mobj =", "ExtractorError, strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def", "== 'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats(", "thumbnails = [] subtitles = {} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?')", "ext == 'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url):", "query.update(custom_tokenizer_query) else: query['videoId'] = content_id if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'],", "'vtt', 'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut') or image.get('name'),", "'length') or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'),", "if not m3u8_url: continue if stream_data.get('playlistProtection') == 'spe': m3u8_url =", "continue if stream_data.get('playlistProtection') == 'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url,", "streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl') or stream_data.get('url') if not m3u8_url:", "'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or {},", "track_url or track_url.endswith('/big'): continue lang = track.get('lang') or track.get('label') or", "strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self,", "in video_url and '?hdnea=' in video_url: for f in m3u8_formats:", "video_id, f4m_id=format_id or 'hds', fatal=False)) else: f = { 'format_id':", "xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data,", "# Possible formats locations: files/file, files/groupFiles/files # and maybe others", "continue chapters.append({ 'start_time': start_time, 'end_time': start_time + chapter_duration, }) self._sort_formats(formats)", "elif ext == 'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/',", "mobj = rex.search(video_url) if mobj: f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')),", "url_or_none(track.get('url')) if not track_url or track_url.endswith('/big'): continue lang = track.get('lang')", "= video_data.attrib['id'] title = xpath_text(video_data, 'headline', fatal=True) content_id = xpath_text(video_data,", "self._live_title(title) if is_live else title, 'formats': formats, 'subtitles': subtitles, 'thumbnails':", "elif ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id", "}) self._sort_formats(formats) return { 'formats': formats, 'chapters': chapters, 'duration': duration,", "chapter in stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration'))", "'token') if not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return", "= self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats(", "not chapters: for chapter in stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start'))", "video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data: return {}", "format_id = video_file.get('bitrate') if ext in ('scc', 'srt', 'vtt'): subtitles.setdefault('en',", "= xpath_text(video_data, 'headline', fatal=True) content_id = xpath_text(video_data, 'contentId') or video_id", "protected_path_data = path_data.get('protected') # if not protected_path_data or not rtmp_src:", "content_id, ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') +", "'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext, 'url': video_url, }) elif", "% media_id, media_id)['media']['tv'] duration = None chapters = [] formats", "= [] thumbnails = [] subtitles = {} rex =", "= track.get('lang') or track.get('label') or 'en' subtitles.setdefault(lang, []).append({ 'url': track_url,", "or chapter_duration is None: continue chapters.append({ 'start_time': start_time, 'end_time': start_time", "not video_data: return {} video_id = video_data.attrib['id'] title = xpath_text(video_data,", "def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False): video_data = self._download_xml(", "these files # protected_path_data = path_data.get('protected') # if not protected_path_data", "{ 'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com,", "elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if not secure_path_data: continue video_url", "start_time is None or chapter_duration is None: continue chapters.append({ 'start_time':", "video_data.attrib['id'] title = xpath_text(video_data, 'headline', fatal=True) content_id = xpath_text(video_data, 'contentId')", "video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id, ap_data) elif", "# if len(split_rtmp_src) == 2: # rtmp_src = split_rtmp_src[1] #", "= stream_data.get('secureUrl') or stream_data.get('url') if not m3u8_url: continue if stream_data.get('playlistProtection')", "ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue # TODO Correct extraction", "continue # TODO Correct extraction for these files # protected_path_data", "re.match('https?://', video_url): base_path_data = path_data.get(ext, path_data.get('default', {})) media_src = base_path_data.get('media_src')", "'?' + token elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if not", "token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url + '?hdnea='", "video_url = url_or_none(video_file.text.strip()) if not video_url: continue ext = determine_ext(video_url)", "base_path_data = path_data.get(ext, path_data.get('default', {})) media_src = base_path_data.get('media_src') if not", "thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length')", "# split_rtmp_src = rtmp_src.split(',') # if len(split_rtmp_src) == 2: #", "f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'): for", "token = xpath_text(auth, 'token') if not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path]", "track_url, 'ext': { 'scc': 'scc', 'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format'))", "if '/secure/' in video_url and '?hdnea=' in video_url: for f", "mobj: if mobj.group(1) == 'audio': f.update({ 'vcodec': 'none', 'ext': 'm4a',", "self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id, ap_data) elif not re.match('https?://',", "video_data.findall('closedCaptions/source'): for track in source.findall('track'): track_url = url_or_none(track.get('url')) if not", "'ext': ext, 'url': video_url, }) elif ext == 'png': thumbnails.append({", "tokenizer_src, content_id, query=query) error_msg = xpath_text(auth, 'error/msg') if error_msg: raise", "self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth = self._download_xml( tokenizer_src, content_id, query=query)", "if start_time is None or chapter_duration is None: continue chapters.append({", "'*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query = {", "return { 'id': video_id, 'title': self._live_title(title) if is_live else title,", "# ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif", "ap_data['site_name']) auth = self._download_xml( tokenizer_src, content_id, query=query) error_msg = xpath_text(auth,", "'audio': f.update({ 'vcodec': 'none', 'ext': 'm4a', }) else: f['tbr'] =", "{} video_id = video_data.attrib['id'] title = xpath_text(video_data, 'headline', fatal=True) content_id", "} def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv'", "xpath_text(video_data, 'akamai/aifp', default='') urls = [] formats = [] thumbnails", "or not rtmp_src: # continue # protected_path = self._search_regex( #", "def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' %", "# video_url = rtmp_src + video_url + '?' + token", "coding: utf-8 from __future__ import unicode_literals import re from .adobepass", "..utils import ( fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr,", "source.findall('track'): track_url = url_or_none(track.get('url')) if not track_url or track_url.endswith('/big'): continue", "or track.get('label') or 'en' subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext': {", "'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'),", "xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live,", "int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none, )", "'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path", "+ token def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False): video_data", "'mp4', m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if not chapters: for", "import unicode_literals import re from .adobepass import AdobePassIE from ..compat", "xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number':", "import ( fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query,", "format_id, 'url': video_url, }) elif ext == 'smil': formats.extend(self._extract_smil_formats( video_url,", "formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id or 'hds', fatal=False)) else:", "= float_or_none(chapter.get('duration')) if start_time is None or chapter_duration is None:", "default='') urls = [] formats = [] thumbnails = []", "query={ # 'path': protected_path, # 'videoId': content_id, # 'aifp': aifp,", "}) elif ext == 'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif", "duration = None chapters = [] formats = [] for", "self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query = { 'path': secure_path, }", "stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if start_time", "parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas',", "= path_data.get('protected') # if not protected_path_data or not rtmp_src: #", "video_url = media_src + video_url if video_url in urls: continue", "self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url + '?hdnea=' + token def", "token def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False): video_data =", "# continue # video_url = rtmp_src + video_url + '?'", "'secure path') + '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token:", "'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')),", "token return video_url + '?hdnea=' + token def _extract_cvp_info(self, data_src,", "== 'true' return { 'id': video_id, 'title': self._live_title(title) if is_live", "auth = self._download_webpage( # protected_path_data['tokenizer_src'], query={ # 'path': protected_path, #", "media_id)['media']['tv'] duration = None chapters = [] formats = []", "files/file, files/groupFiles/files # and maybe others for video_file in video_data.findall('.//file'):", "else title, 'formats': formats, 'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data,", "path') + '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query", "'id': format_id, 'url': video_url, }) elif ext == 'smil': formats.extend(self._extract_smil_formats(", "urls.append(video_url) format_id = video_file.get('bitrate') if ext in ('scc', 'srt', 'vtt'):", "start_time, 'end_time': start_time + chapter_duration, }) self._sort_formats(formats) return { 'formats':", "supported_type in ('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type, {}) m3u8_url =", "return {} video_id = video_data.attrib['id'] title = xpath_text(video_data, 'headline', fatal=True)", "is None or chapter_duration is None: continue chapters.append({ 'start_time': start_time,", "video_url.startswith('/mp4:protected/'): continue # TODO Correct extraction for these files #", "rex.search(video_url) if mobj: f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')),", "'episodeNumber')), 'is_live': is_live, } def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data", "video_id, path_data={}, ap_data={}, fatal=False): video_data = self._download_xml( data_src, video_id, transform_source=lambda", "= xpath_text(auth, 'error/msg') if error_msg: raise ExtractorError(error_msg, expected=True) token =", "for source in video_data.findall('closedCaptions/source'): for track in source.findall('track'): track_url =", "video_url, 'ext': ext, } mobj = rex.search(video_url) if mobj: f.update({", "('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext, 'url': video_url, })", "continue # protected_path = self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path')", "= self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False) if", "class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data,", "from __future__ import unicode_literals import re from .adobepass import AdobePassIE", "strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data),", "_extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id,", "token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query = { 'path':", "stream_data = streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl') or stream_data.get('url') if", "( fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError,", "else: f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'):", "not re.match('https?://', video_url): base_path_data = path_data.get(ext, path_data.get('default', {})) media_src =", "ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration =", "determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none, ) class", "float_or_none(chapter.get('duration')) if start_time is None or chapter_duration is None: continue", "'none', 'ext': 'm4a', }) else: f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats)", "secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id, ap_data) elif not re.match('https?://', video_url):", "in video_data.findall('closedCaptions/source'): for track in source.findall('track'): track_url = url_or_none(track.get('url')) if", "'is_live': is_live, } def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data =", "= re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if mobj.group(1) == 'audio': f.update({", "in video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive') == 'true' return {", "for supported_type in ('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type, {}) m3u8_url", "ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif ext", "if rtmp_src: # split_rtmp_src = rtmp_src.split(',') # if len(split_rtmp_src) ==", "expected=True) token = xpath_text(auth, 'token') if not token: return video_url", "= rtmp_src + video_url + '?' + token elif video_url.startswith('/secure/'):", "Possible formats locations: files/file, files/groupFiles/files # and maybe others for", "'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url,", "formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if", "ap_data) elif not re.match('https?://', video_url): base_path_data = path_data.get(ext, path_data.get('default', {}))", "elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds': path_data.get('f4m', {}).get('host'),", "'url': image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for image in", "'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')),", "in ('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl')", "'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, } def _extract_ngtv_info(self, media_id,", "not token: query = { 'path': secure_path, } if custom_tokenizer_query:", "+ '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query =", "len(split_rtmp_src) == 2: # rtmp_src = split_rtmp_src[1] # aifp =", "rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations: files/file, files/groupFiles/files", "= determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue # TODO Correct extraction for", "if not video_data: return {} video_id = video_data.attrib['id'] title =", "video_url: continue ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue # TODO", "is_live = xpath_text(video_data, 'isLive') == 'true' return { 'id': video_id,", "continue # video_url = rtmp_src + video_url + '?' +", "'png': thumbnails.append({ 'id': format_id, 'url': video_url, }) elif ext ==", "not protected_path_data or not rtmp_src: # continue # protected_path =", "'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext, 'url': video_url, }) elif ext", "image.get('cut') or image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), }", "'title': self._live_title(title) if is_live else title, 'formats': formats, 'subtitles': subtitles,", "= [] formats = [] for supported_type in ('unprotected', 'bulkaes'):", "chapter_duration = float_or_none(chapter.get('duration')) if start_time is None or chapter_duration is", "# continue # protected_path = self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure", "[] formats = [] thumbnails = [] subtitles = {}", "fatal=True) content_id = xpath_text(video_data, 'contentId') or video_id # rtmp_src =", "rtmp_src.split(',') # if len(split_rtmp_src) == 2: # rtmp_src = split_rtmp_src[1]", "= xpath_text(video_data, 'akamai/aifp', default='') urls = [] formats = []", "duration = float_or_none(stream_data.get('totalRuntime')) if not chapters: for chapter in stream_data.get('contentSegments',", "video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if not secure_path_data: continue video_url =", "chapters.append({ 'start_time': start_time, 'end_time': start_time + chapter_duration, }) self._sort_formats(formats) return", "query['videoId'] = content_id if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'],", "= path_data.get('secure') if not secure_path_data: continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'],", "'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut') or image.get('name'), 'url': image.text,", "or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)) duration", "formats = [] for supported_type in ('unprotected', 'bulkaes'): stream_data =", "continue video_url = media_src + video_url if video_url in urls:", "re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if mobj.group(1) == 'audio': f.update({ 'vcodec':", "}) else: f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source in", "if not protected_path_data or not rtmp_src: # continue # protected_path", "'isLive') == 'true' return { 'id': video_id, 'title': self._live_title(title) if", "video_url + '?hdnea=' + token def _extract_cvp_info(self, data_src, video_id, path_data={},", "if not chapters: for chapter in stream_data.get('contentSegments', []): start_time =", "= base_path_data.get('media_src') if not media_src: continue video_url = media_src +", "# token = xpath_text(auth, 'token') # if not token: #", "track.get('label') or 'en' subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext': { 'scc':", "image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for image", "'token') # if not token: # continue # video_url =", "# nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com", "thumbnails.append({ 'id': format_id, 'url': video_url, }) elif ext == 'smil':", "ext == 'm3u8': m3u8_formats = self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id", "'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut') or image.get('name'), 'url':", "if mobj.group(1) == 'audio': f.update({ 'vcodec': 'none', 'ext': 'm4a', })", "f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id,", "fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds': path_data.get('f4m',", "return video_url + '?hdnea=' + token def _extract_cvp_info(self, data_src, video_id,", "media_src: continue video_url = media_src + video_url if video_url in", "'m4a', }) else: f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source", "if len(split_rtmp_src) == 2: # rtmp_src = split_rtmp_src[1] # aifp", "or 'hls', fatal=False) if '/secure/' in video_url and '?hdnea=' in", "self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration = None chapters =", "or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series':", "ext, 'url': video_url, }) elif ext == 'png': thumbnails.append({ 'id':", "int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None):", "{ 'scc': 'scc', 'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({", "_AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts'))", "int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, } def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None):", "..compat import compat_str from ..utils import ( fix_xml_ampersands, xpath_text, int_or_none,", "xpath_text(video_data, 'headline', fatal=True) content_id = xpath_text(video_data, 'contentId') or video_id #", "extraction for these files # protected_path_data = path_data.get('protected') # if", "not rtmp_src: # continue # protected_path = self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]',", "split_rtmp_src[1] # aifp = xpath_text(video_data, 'akamai/aifp', default='') urls = []", "video_file.get('bitrate') if ext in ('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext':", "= xpath_text(video_data, 'isLive') == 'true' return { 'id': video_id, 'title':", "and maybe others for video_file in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip())", "return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url + '?hdnea=' +", "query=query) error_msg = xpath_text(auth, 'error/msg') if error_msg: raise ExtractorError(error_msg, expected=True)", "token: # continue # video_url = rtmp_src + video_url +", "data_src, video_id, path_data={}, ap_data={}, fatal=False): video_data = self._download_xml( data_src, video_id,", "'start_time': start_time, 'end_time': start_time + chapter_duration, }) self._sort_formats(formats) return {", "int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if mobj.group(1)", "tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure", "format_id, 'url': video_url, 'ext': ext, } mobj = rex.search(video_url) if", "format_id.isdigit(): f['tbr'] = int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if", "video_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False) if '/secure/' in", "'scc': 'scc', 'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id':", "protected_path = self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path') # auth", "s: fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data: return {} video_id =", "re from .adobepass import AdobePassIE from ..compat import compat_str from", "TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated',", "split_rtmp_src = rtmp_src.split(',') # if len(split_rtmp_src) == 2: # rtmp_src", "r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations: files/file, files/groupFiles/files # and maybe", "'ext': ext, } mobj = rex.search(video_url) if mobj: f.update({ 'width':", "self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data,", "[]).append({ 'ext': ext, 'url': video_url, }) elif ext == 'png':", "update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id or 'hds', fatal=False)) else: f", "'http': 'pmd.cdn.turner.com', })) elif ext == 'm3u8': m3u8_formats = self._extract_m3u8_formats(", "query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth = self._download_xml( tokenizer_src,", "TODO Correct extraction for these files # protected_path_data = path_data.get('protected')", "_add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url,", "utf-8 from __future__ import unicode_literals import re from .adobepass import", "else: query['videoId'] = content_id if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id,", "streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration = None", "tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime'))", "# protected_path = self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path') #", "i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif ext ==", "ap_data['site_name'], ap_data['site_name']) auth = self._download_xml( tokenizer_src, content_id, query=query) error_msg =", "{}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com #", "'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for image in video_data.findall('images/image')) is_live", "determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue # TODO Correct extraction for these", "files # protected_path_data = path_data.get('protected') # if not protected_path_data or", "or 'en' subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext': { 'scc': 'scc',", "in m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats) elif ext == 'f4m':", "ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif ext == 'm3u8': m3u8_formats =", "m3u8_formats = self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False)", "'url': video_url, }) elif ext == 'png': thumbnails.append({ 'id': format_id,", "title, 'formats': formats, 'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'),", "= rtmp_src.split(',') # if len(split_rtmp_src) == 2: # rtmp_src =", "from .adobepass import AdobePassIE from ..compat import compat_str from ..utils", "f.update({ 'vcodec': 'none', 'ext': 'm4a', }) else: f['tbr'] = int(mobj.group(1))", "'?hdnea=' in video_url: for f in m3u8_formats: f['_seekable'] = False", "data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data: return", "if is_live else title, 'formats': formats, 'subtitles': subtitles, 'thumbnails': thumbnails,", "re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations: files/file, files/groupFiles/files # and", "rtmp_src: # continue # protected_path = self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url,", "= None chapters = [] formats = [] for supported_type", "# 'videoId': content_id, # 'aifp': aifp, # }) # token", "'pmd.cdn.turner.com', })) elif ext == 'm3u8': m3u8_formats = self._extract_m3u8_formats( video_url,", "= self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth = self._download_xml( tokenizer_src, content_id,", "[]).append({ 'url': track_url, 'ext': { 'scc': 'scc', 'webvtt': 'vtt', 'smptett':", "Correct extraction for these files # protected_path_data = path_data.get('protected') #", "+ chapter_duration, }) self._sort_formats(formats) return { 'formats': formats, 'chapters': chapters,", "video_id # rtmp_src = xpath_text(video_data, 'akamai/src') # if rtmp_src: #", "secure_path_data = path_data.get('secure') if not secure_path_data: continue video_url = self._add_akamai_spe_token(", "not token: # continue # video_url = rtmp_src + video_url", "return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data,", "path_data.get(ext, path_data.get('default', {})) media_src = base_path_data.get('media_src') if not media_src: continue", "{} def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self,", "formats, 'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data,", "'ext': 'm4a', }) else: f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for", "if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth =", "f4m_id=format_id or 'hds', fatal=False)) else: f = { 'format_id': format_id,", "'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, }", "= media_src + video_url if video_url in urls: continue urls.append(video_url)", "int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for image in video_data.findall('images/image')) is_live =", "mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if mobj.group(1) == 'audio':", "'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration = None chapters = []", "video_file in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if not video_url: continue", "f['tbr'] = int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj:", "[]): start_time = float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if start_time is", "tokenizer_query, ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration", "formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com,", "track_url = url_or_none(track.get('url')) if not track_url or track_url.endswith('/big'): continue lang", "= path_data.get(ext, path_data.get('default', {})) media_src = base_path_data.get('media_src') if not media_src:", "= int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'): for track", "formats = [] thumbnails = [] subtitles = {} rex", "m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or {}, tokenizer_query)", "'contentId') or video_id # rtmp_src = xpath_text(video_data, 'akamai/src') # if", "if ext in ('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext,", "formats.extend(m3u8_formats) elif ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id,", "video_url + '?' + token elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure')", "and '?hdnea=' in video_url: for f in m3u8_formats: f['_seekable'] =", "video_url, video_id, { 'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com", "self._download_xml( data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data:", "2: # rtmp_src = split_rtmp_src[1] # aifp = xpath_text(video_data, 'akamai/aifp',", "'id': image.get('cut') or image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')),", "= split_rtmp_src[1] # aifp = xpath_text(video_data, 'akamai/aifp', default='') urls =", "in ('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext, 'url': video_url,", "or 'hds', fatal=False)) else: f = { 'format_id': format_id, 'url':", "url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self, video_data):", "'m3u8': m3u8_formats = self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id or 'hls',", "int_or_none(image.get('height')), } for image in video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive')", "video_url = rtmp_src + video_url + '?' + token elif", "elif isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr'] = int(format_id) else: mobj", "= streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl') or stream_data.get('url') if not", "fatal=False) if '/secure/' in video_url and '?hdnea=' in video_url: for", "ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id or", "'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path =", "m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if not", "# r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path') # auth = self._download_webpage( #", "m3u8_url, media_id, ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4',", "= self._download_webpage( # protected_path_data['tokenizer_src'], query={ # 'path': protected_path, # 'videoId':", "int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, } def _extract_ngtv_info(self,", "{} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations: files/file,", "for video_file in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if not video_url:", "base_path_data.get('media_src') if not media_src: continue video_url = media_src + video_url", "float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE):", "'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, } def _extract_ngtv_info(self, media_id, tokenizer_query,", "int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str): if", "import re from .adobepass import AdobePassIE from ..compat import compat_str", "track.get('lang') or track.get('label') or 'en' subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext':", "or track_url.endswith('/big'): continue lang = track.get('lang') or track.get('label') or 'en'", "ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com',", "unicode_literals import re from .adobepass import AdobePassIE from ..compat import", "self._download_webpage( # protected_path_data['tokenizer_src'], query={ # 'path': protected_path, # 'videoId': content_id,", "AdobePassIE from ..compat import compat_str from ..utils import ( fix_xml_ampersands,", "content_id, query=query) error_msg = xpath_text(auth, 'error/msg') if error_msg: raise ExtractorError(error_msg,", "is_live, } def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data = self._download_json(", "continue lang = track.get('lang') or track.get('label') or 'en' subtitles.setdefault(lang, []).append({", "else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if mobj.group(1) ==", "'height': int_or_none(image.get('height')), } for image in video_data.findall('images/image')) is_live = xpath_text(video_data,", "== 'm3u8': m3u8_formats = self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id or", "xpath_text(auth, 'token') if not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token", "path_data={}, ap_data={}, fatal=False): video_data = self._download_xml( data_src, video_id, transform_source=lambda s:", "= xpath_text(video_data, 'akamai/src') # if rtmp_src: # split_rtmp_src = rtmp_src.split(',')", "'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date':", "'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, } def", "path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com", "if mobj: if mobj.group(1) == 'audio': f.update({ 'vcodec': 'none', 'ext':", "ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*'", "= token return video_url + '?hdnea=' + token def _extract_cvp_info(self,", "'scc', 'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut')", "xpath_text(auth, 'token') # if not token: # continue # video_url", "video_url): base_path_data = path_data.get(ext, path_data.get('default', {})) media_src = base_path_data.get('media_src') if", "update_url_query, ExtractorError, strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {}", "= False formats.extend(m3u8_formats) elif ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore':", "'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str):", "media_src + video_url if video_url in urls: continue urls.append(video_url) format_id", "secure_path_data['media_src'] + video_url, content_id, ap_data) elif not re.match('https?://', video_url): base_path_data", "= rex.search(video_url) if mobj: f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr':", "}) elif isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr'] = int(format_id) else:", "'id': video_id, 'title': self._live_title(title) if is_live else title, 'formats': formats,", "'error/msg') if error_msg: raise ExtractorError(error_msg, expected=True) token = xpath_text(auth, 'token')", "'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data,", "media_id, 'mp4', m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if not chapters:", "} for image in video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive') ==", "= self._search_regex( # r'/mp4:(.+)\\.[a-z0-9]', video_url, 'secure path') # auth =", "protected_path, # 'videoId': content_id, # 'aifp': aifp, # }) #", "if not track_url or track_url.endswith('/big'): continue lang = track.get('lang') or", "= self._download_xml( tokenizer_src, content_id, query=query) error_msg = xpath_text(auth, 'error/msg') if", "s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif ext == 'm3u8':", "in video_url: for f in m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats)", "f = { 'format_id': format_id, 'url': video_url, 'ext': ext, }", "}.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut') or image.get('name'), 'url': image.text, 'width':", "= self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration = None chapters", "video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com,", "locations: files/file, files/groupFiles/files # and maybe others for video_file in", "'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')),", "def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)',", "def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src,", "is_live else title, 'formats': formats, 'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail':", "stream_data.get('secureUrl') or stream_data.get('url') if not m3u8_url: continue if stream_data.get('playlistProtection') ==", "'ext': { 'scc': 'scc', 'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format')) })", "m3u8_id=format_id or 'hls', fatal=False) if '/secure/' in video_url and '?hdnea='", "= xpath_text(auth, 'token') if not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] =", ".adobepass import AdobePassIE from ..compat import compat_str from ..utils import", "f['_seekable'] = False formats.extend(m3u8_formats) elif ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url,", "= url_or_none(track.get('url')) if not track_url or track_url.endswith('/big'): continue lang =", "self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'): for track in source.findall('track'): track_url", "'bulkaes'): stream_data = streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl') or stream_data.get('url')", "self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False) if '/secure/'", "+ '?' + token elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if", "path') # auth = self._download_webpage( # protected_path_data['tokenizer_src'], query={ # 'path':", "'?hdnea=' + token def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False):", "start_time + chapter_duration, }) self._sort_formats(formats) return { 'formats': formats, 'chapters':", "_extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False): video_data = self._download_xml( data_src,", "{'hdcore': '3.7.0'}), video_id, f4m_id=format_id or 'hds', fatal=False)) else: f =", "in stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if", "# if not token: # continue # video_url = rtmp_src", "not m3u8_url: continue if stream_data.get('playlistProtection') == 'spe': m3u8_url = self._add_akamai_spe_token(", "video_data: return {} video_id = video_data.attrib['id'] title = xpath_text(video_data, 'headline',", "video_id, { 'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com #", "elif not re.match('https?://', video_url): base_path_data = path_data.get(ext, path_data.get('default', {})) media_src", "'end_time': start_time + chapter_duration, }) self._sort_formats(formats) return { 'formats': formats,", "video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path')", "track_url.endswith('/big'): continue lang = track.get('lang') or track.get('label') or 'en' subtitles.setdefault(lang,", "'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')), 'timestamp':", "})) elif ext == 'm3u8': m3u8_formats = self._extract_m3u8_formats( video_url, video_id,", "source in video_data.findall('closedCaptions/source'): for track in source.findall('track'): track_url = url_or_none(track.get('url'))", "continue urls.append(video_url) format_id = video_file.get('bitrate') if ext in ('scc', 'srt',", "# 'aifp': aifp, # }) # token = xpath_text(auth, 'token')", "formats.append(f) self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'): for track in source.findall('track'):", "xpath_text, int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none,", "# and maybe others for video_file in video_data.findall('.//file'): video_url =", "or image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for", "lang = track.get('lang') or track.get('label') or 'en' subtitles.setdefault(lang, []).append({ 'url':", "= { 'format_id': format_id, 'url': video_url, 'ext': ext, } mobj", "not media_src: continue video_url = media_src + video_url if video_url", "'formats': formats, 'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description':", "video_url, content_id, ap_data) elif not re.match('https?://', video_url): base_path_data = path_data.get(ext,", "content_id = xpath_text(video_data, 'contentId') or video_id # rtmp_src = xpath_text(video_data,", "+ video_url + '?' + token elif video_url.startswith('/secure/'): secure_path_data =", "= { 'path': secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId']", "= content_id if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name'])", "'videoId': content_id, # 'aifp': aifp, # }) # token =", "= [] formats = [] thumbnails = [] subtitles =", "continue ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue # TODO Correct", "video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive') == 'true' return { 'id':", "not track_url or track_url.endswith('/big'): continue lang = track.get('lang') or track.get('label')", "in urls: continue urls.append(video_url) format_id = video_file.get('bitrate') if ext in", "stream_data.get('url') if not m3u8_url: continue if stream_data.get('playlistProtection') == 'spe': m3u8_url", "[] for supported_type in ('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type, {})", "ext == 'png': thumbnails.append({ 'id': format_id, 'url': video_url, }) elif", "False formats.extend(m3u8_formats) elif ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}),", "subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration':", "xpath_text(video_data, 'contentId') or video_id # rtmp_src = xpath_text(video_data, 'akamai/src') #", "= {} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations:", "'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')),", "== 2: # rtmp_src = split_rtmp_src[1] # aifp = xpath_text(video_data,", "others for video_file in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if not", "# }) # token = xpath_text(auth, 'token') # if not", "transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data: return {} video_id", "[] thumbnails = [] subtitles = {} rex = re.compile(", "else: f = { 'format_id': format_id, 'url': video_url, 'ext': ext,", "token = xpath_text(auth, 'token') # if not token: # continue", "'aifp': aifp, # }) # token = xpath_text(auth, 'token') #", "'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id,", "raise ExtractorError(error_msg, expected=True) token = xpath_text(auth, 'token') if not token:", "formats locations: files/file, files/groupFiles/files # and maybe others for video_file", "title = xpath_text(video_data, 'headline', fatal=True) content_id = xpath_text(video_data, 'contentId') or", "'headline', fatal=True) content_id = xpath_text(video_data, 'contentId') or video_id # rtmp_src", "subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext': { 'scc': 'scc', 'webvtt': 'vtt',", "video_id, 'title': self._live_title(title) if is_live else title, 'formats': formats, 'subtitles':", "= self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id, ap_data) elif not", "formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\\.akamaihd\\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id,", "float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if start_time is None or chapter_duration", "track in source.findall('track'): track_url = url_or_none(track.get('url')) if not track_url or", "mobj.group(1) == 'audio': f.update({ 'vcodec': 'none', 'ext': 'm4a', }) else:", "'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data,", "if not token: query = { 'path': secure_path, } if", "parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE", "subtitles.setdefault('en', []).append({ 'ext': ext, 'url': video_url, }) elif ext ==", "'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut') or", "for f in m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats) elif ext", "protected_path_data['tokenizer_src'], query={ # 'path': protected_path, # 'videoId': content_id, # 'aifp':", "custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*' token", "not secure_path_data: continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url,", "int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr']", "or stream_data.get('url') if not m3u8_url: continue if stream_data.get('playlistProtection') == 'spe':", "# auth = self._download_webpage( # protected_path_data['tokenizer_src'], query={ # 'path': protected_path,", "if stream_data.get('playlistProtection') == 'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id,", "# coding: utf-8 from __future__ import unicode_literals import re from", "m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats) elif ext == 'f4m': formats.extend(self._extract_f4m_formats(", "video_url, 'secure path') # auth = self._download_webpage( # protected_path_data['tokenizer_src'], query={", "rtmp_src = xpath_text(video_data, 'akamai/src') # if rtmp_src: # split_rtmp_src =", "m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if not chapters: for chapter", "xpath_text(video_data, 'isLive') == 'true' return { 'id': video_id, 'title': self._live_title(title)", "} if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] = content_id if ap_data.get('auth_required'):", "'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str): if format_id.isdigit():", "if video_url in urls: continue urls.append(video_url) format_id = video_file.get('bitrate') if", "== 'audio': f.update({ 'vcodec': 'none', 'ext': 'm4a', }) else: f['tbr']", "None: continue chapters.append({ 'start_time': start_time, 'end_time': start_time + chapter_duration, })", "ap_data={}, fatal=False): video_data = self._download_xml( data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(),", "continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id, ap_data)", "# rtmp_src = split_rtmp_src[1] # aifp = xpath_text(video_data, 'akamai/aifp', default='')", "media_src = base_path_data.get('media_src') if not media_src: continue video_url = media_src", "or video_id # rtmp_src = xpath_text(video_data, 'akamai/src') # if rtmp_src:", "self._sort_formats(formats) return { 'formats': formats, 'chapters': chapters, 'duration': duration, }", "urls: continue urls.append(video_url) format_id = video_file.get('bitrate') if ext in ('scc',", "if not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url", "media_id, ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls',", "rtmp_src = split_rtmp_src[1] # aifp = xpath_text(video_data, 'akamai/aifp', default='') urls", "m3u8_url: continue if stream_data.get('playlistProtection') == 'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe',", "# rtmp_src = xpath_text(video_data, 'akamai/src') # if rtmp_src: # split_rtmp_src", "int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr'] = int(format_id)", "path_data.get('secure') if not secure_path_data: continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src']", "+ video_url, content_id, ap_data) elif not re.match('https?://', video_url): base_path_data =", "'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com,", "'format_id': format_id, 'url': video_url, 'ext': ext, } mobj = rex.search(video_url)", "self._download_xml( tokenizer_src, content_id, query=query) error_msg = xpath_text(auth, 'error/msg') if error_msg:", "# ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif ext == 'm3u8': m3u8_formats", "[] subtitles = {} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible", "}) thumbnails.extend({ 'id': image.get('cut') or image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')),", "if video_url.startswith('/mp4:protected/'): continue # TODO Correct extraction for these files", "video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if not video_url: continue ext =", "'url': track_url, 'ext': { 'scc': 'scc', 'webvtt': 'vtt', 'smptett': 'tt',", "= {} def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def", "None or chapter_duration is None: continue chapters.append({ 'start_time': start_time, 'end_time':", "if not token: # continue # video_url = rtmp_src +", "f in m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats) elif ext ==", "rtmp_src + video_url + '?' + token elif video_url.startswith('/secure/'): secure_path_data", "if format_id.isdigit(): f['tbr'] = int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id)", "= int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if", "from ..utils import ( fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none, parse_duration,", "custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] = content_id if ap_data.get('auth_required'): query['accessToken'] =", "files/groupFiles/files # and maybe others for video_file in video_data.findall('.//file'): video_url", "ext in ('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext, 'url':", "'hds', fatal=False)) else: f = { 'format_id': format_id, 'url': video_url,", "image in video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive') == 'true' return", "query = { 'path': secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query) else:", "{ 'path': secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] =", "'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr'] =", "import AdobePassIE from ..compat import compat_str from ..utils import (", "= xpath_text(auth, 'token') # if not token: # continue #", "protected_path_data or not rtmp_src: # continue # protected_path = self._search_regex(", "{})) media_src = base_path_data.get('media_src') if not media_src: continue video_url =", "thumbnails.extend({ 'id': image.get('cut') or image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')), 'height':", "= float_or_none(stream_data.get('totalRuntime')) if not chapters: for chapter in stream_data.get('contentSegments', []):", "if error_msg: raise ExtractorError(error_msg, expected=True) token = xpath_text(auth, 'token') if", "video_url if video_url in urls: continue urls.append(video_url) format_id = video_file.get('bitrate')", "'secure path') # auth = self._download_webpage( # protected_path_data['tokenizer_src'], query={ #", "ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', }))", "xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE =", "# if not protected_path_data or not rtmp_src: # continue #", "elif ext == 'm3u8': m3u8_formats = self._extract_m3u8_formats( video_url, video_id, 'mp4',", "== 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id or 'hds',", "ext, } mobj = rex.search(video_url) if mobj: f.update({ 'width': int(mobj.group('width')),", "# protected_path_data['tokenizer_src'], query={ # 'path': protected_path, # 'videoId': content_id, #", "if mobj: f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), })", "}) elif ext == 'png': thumbnails.append({ 'id': format_id, 'url': video_url,", "secure_path_data: continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id,", "# 'path': protected_path, # 'videoId': content_id, # 'aifp': aifp, #", "fatal=fatal) if not video_data: return {} video_id = video_data.attrib['id'] title", "== 'png': thumbnails.append({ 'id': format_id, 'url': video_url, }) elif ext", "'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number':", "xpath_text(video_data, 'akamai/src') # if rtmp_src: # split_rtmp_src = rtmp_src.split(',') #", "video_url, }) elif ext == 'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False))" ]
[ "alpha_vantage.timeseries import TimeSeries from pprint import pprint import json import", "TimeSeries from pprint import pprint import json import argparse def", "import json import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json',", "type=str, choices=[ 'intraday', 'daily', 'daily_adj'], help=\"the time period you want", "= credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window", "time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv')", "= ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif time_window == 'daily': data,", "parser.add_argument('symbol', type=str, help=\"the stock symbol you want to download\") parser.add_argument('time_window',", "download\") parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily', 'daily_adj'], help=\"the time period", "'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj':", "argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the stock symbol you want to download\")", "'r')) api_key = credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas')", "credentials = json.load(open('creds.json', 'r')) api_key = credentials['av_api_key'] print(symbol, time_window) ts", "from alpha_vantage.timeseries import TimeSeries from pprint import pprint import json", "__name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the stock", "ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data", "pprint import json import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials =", "pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('symbol',", "parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily', 'daily_adj'], help=\"the time period you", "= ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == \"__main__\": parser", "data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str,", "== 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window ==", "want to download\") parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily', 'daily_adj'], help=\"the", "= ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data =", "ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data", "'daily_adj'], help=\"the time period you want to download the stock", "print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday':", "elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif", "elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10))", "time period you want to download the stock history for\")", "argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json', 'r')) api_key =", "'intraday': data, meta_data = ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif time_window", "'intraday', 'daily', 'daily_adj'], help=\"the time period you want to download", "ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == \"__main__\": parser =", "stock symbol you want to download\") parser.add_argument('time_window', type=str, choices=[ 'intraday',", "symbol=symbol, interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data =", "save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json', 'r')) api_key = credentials['av_api_key'] print(symbol,", "data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data,", "outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full')", "import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json', 'r')) api_key", "outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full')", "choices=[ 'intraday', 'daily', 'daily_adj'], help=\"the time period you want to", "time_window='daily_adj'): credentials = json.load(open('creds.json', 'r')) api_key = credentials['av_api_key'] print(symbol, time_window)", "period you want to download the stock history for\") namespace", "from pprint import pprint import json import argparse def save_dataset(symbol='MSFT',", "data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ ==", "to download\") parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily', 'daily_adj'], help=\"the time", "data, meta_data = ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif time_window ==", "json import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json', 'r'))", "symbol you want to download\") parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily',", "= json.load(open('creds.json', 'r')) api_key = credentials['av_api_key'] print(symbol, time_window) ts =", "help=\"the time period you want to download the stock history", "== 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if", "time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window", "meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == \"__main__\":", "want to download the stock history for\") namespace = parser.parse_args()", "if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the", "\"__main__\": parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the stock symbol you", "meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data", "type=str, help=\"the stock symbol you want to download\") parser.add_argument('time_window', type=str,", "output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday( symbol=symbol,", "to download the stock history for\") namespace = parser.parse_args() save_dataset(**vars(namespace))", "api_key = credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if", "json.load(open('creds.json', 'r')) api_key = credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key,", "outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == \"__main__\": parser = argparse.ArgumentParser()", "import pprint import json import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials", "time_window == 'intraday': data, meta_data = ts.get_intraday( symbol=symbol, interval='1min', outputsize='full')", "pprint import pprint import json import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'):", "meta_data = ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif time_window == 'daily':", "'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__", "credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window ==", "import TimeSeries from pprint import pprint import json import argparse", "ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol,", "def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json', 'r')) api_key = credentials['av_api_key']", "interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol,", "'daily', 'daily_adj'], help=\"the time period you want to download the", "parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the stock symbol you want", "you want to download\") parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily', 'daily_adj'],", "you want to download the stock history for\") namespace =", "if time_window == 'intraday': data, meta_data = ts.get_intraday( symbol=symbol, interval='1min',", "TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday(", "== 'intraday': data, meta_data = ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif", "help=\"the stock symbol you want to download\") parser.add_argument('time_window', type=str, choices=[", "== \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the stock symbol", "= TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data =", "time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data,", "= argparse.ArgumentParser() parser.add_argument('symbol', type=str, help=\"the stock symbol you want to" ]
[ "objects into JSON structures.\"\"\" # Record class and module information", ") placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" ) output_dir =", "self.recording = True return lambda region=region, assume=None: boto3.Session(region_name=region) if not", "None placebo.pill.serialize = serialize placebo.pill.deserialize = deserialize # END PLACEBO", "%s\", base_name) next_file = None while next_file is None: index", "file ({0}) not found\".format(fn)) return fn def attach(session, data_path, prefix=None,", "not zdata new_pill = placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return", "`region` argument is to allow functional tests to override the", "stop(self): result = super(BluePill, self).stop() if self._avail: print(\"Unused json files", "test_case, zdata=False, region=None): \"\"\" The `region` argument is to allow", "strtobool import boto3 import placebo from botocore.response import StreamingBody from", "= {\"__class__\": obj.__class__.__name__} try: result[\"__module__\"] = obj.__module__ except AttributeError: pass", "= placebo.attach(session, test_dir) # pill = BluePill() # pill.attach(session, test_dir)", "if m: i = int(m.group(\"index\")) if i > index: index", "if fn in self._avail: self._avail.remove(fn) else: print(\"\\ndouble use %s\\n\" %", "# SPDX-License-Identifier: Apache-2.0 import fnmatch from io import StringIO import", "# Disabled by default. if 0 and (assume is not", "TypeError if the object isn't recognized raise TypeError(\"Type not serializable\")", "debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session return session return FakeFactory() def", "region=region, assume=None: boto3.Session(region_name=region) if not zdata: test_dir = os.path.join(self.placebo_dir, test_case)", "filepath) json_data = {\"status_code\": http_response, \"data\": response_data} self.archive.writestr( filepath, json.dumps(json_data,", "pill.record() self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake,", "drop this when this issue is resolved # # https://github.com/garnaat/placebo/issues/63", "import json import os import shutil import zipfile import re", "into JSON structures.\"\"\" # Record class and module information for", "1 self._files.add(fn) elif index != 1: self._index[base_name] = 1 else:", "using # cross account assumes, note this will record sts", "( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def get_new_file_path(self, service, operation): base_name =", "in self._files: next_file = fn self._index[base_name] += 1 self._files.add(fn) elif", "session.region_name if not zdata: pill = RedPill() pill.attach(session, test_dir) else:", "fn = fn.replace('\\\\', '/') if fn in self._files: next_file =", "# we are looking for the first index and it's", "self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file) response_data = json.loads( self.archive.read(response_file),", "timedelta(0) utc = UTC() def deserialize(obj): \"\"\"Convert JSON dicts back", "self._avail = self.get_available() def get_available(self): return { os.path.join(self.data_path, n) for", "if needed if class_name == \"datetime\": return datetime(tzinfo=utc, **target) if", "# END PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill): def playback(self): super(BluePill,", "if not zdata: pill = placebo.attach(session, test_dir) # pill =", "on type if isinstance(obj, datetime): result[\"year\"] = obj.year result[\"month\"] =", "= True return lambda region=region, assume=None: boto3.Session(region_name=region) if not zdata:", "test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) return lambda region=None, assume=None: session", "structures as-is return obj def serialize(obj): \"\"\"Convert objects into JSON", "obj.__class__.__name__} try: result[\"__module__\"] = obj.__module__ except AttributeError: pass # Convert", "# Copyright (c) 2015 <NAME> class UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self,", "deserialization result = {\"__class__\": obj.__class__.__name__} try: result[\"__module__\"] = obj.__module__ except", "if not (zdata or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session", "zdata: pill = placebo.attach(session, test_dir) # pill = BluePill() #", "placebo import pill from c7n.testing import CustodianTestCore from .constants import", "load_response(self, service, operation): response_file = self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\",", "session return FakeFactory() def replay_flight_data(self, test_case, zdata=False, region=None): \"\"\" The", "testing. # Access is available for community project maintainers. ###########################################################################", "json files \\n %s\" % (\"\\n\".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill):", "os.remove(\"%s.tmp\" % self.path) return super(ZippedPill, self).record() def stop(self): super(ZippedPill, self).stop()", "self.addCleanup(new_pill.stop) return new_session return session return FakeFactory() def replay_flight_data(self, test_case,", "It is unused when replaying stored data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL',", ") recording = False def cleanUp(self): self.pill = None def", "boto3.Session(region_name=region) if not zdata: pill = placebo.attach(session, test_dir) # pill", "response_data: response_data['ResponseMetadata'] = {} response_data = json.dumps(response_data, default=serialize) response_data =", "# BEGIN PLACEBO MONKEY PATCH # # Placebo is effectively", "this when this issue is resolved # # https://github.com/garnaat/placebo/issues/63 #", "<gh_stars>1000+ # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0", "\\n %s\" % (\"\\n\".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill): def __init__(self,", "def stop(self): result = super(BluePill, self).stop() if self._avail: print(\"Unused json", "if class_name == \"datetime\": return datetime(tzinfo=utc, **target) if class_name ==", "response metadata and account_ids \"\"\" # aws sso setups involve", "FakeFactory() def replay_flight_data(self, test_case, zdata=False, region=None): \"\"\" The `region` argument", "functional tests to override the default region. It is unused", "if \"__class__\" in target: class_name = target.pop(\"__class__\") if \"__module__\" in", "strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True return lambda region=region, assume=None: boto3.Session(region_name=region)", "BluePill() # pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case,", "= dict(obj) class_name = None if \"__class__\" in target: class_name", "datetime_converter(self, obj): if isinstance(obj, datetime): return obj.isoformat() def save_response(self, service,", "not found\".format(fn)) return fn def attach(session, data_path, prefix=None, debug=False): pill", "stale, but its best to modify before commiting. # Disabled", "# Be careful of shallow copy here target = dict(obj)", "os.path.join(self._data_path, base_name + \"*\") for file_path in fnmatch.filter(self._files, glob_pattern): file_name", "in response_data: response_data['ResponseMetadata'] = {} response_data = json.dumps(response_data, default=serialize) response_data", "\"data\", \"placebo\" ) output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" )", "override the default region. It is unused when replaying stored", "import re from datetime import datetime, timedelta, tzinfo from distutils.util", "data_path, prefix=None, debug=False): pill = ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix)", "import datetime, timedelta, tzinfo from distutils.util import strtobool import boto3", "session = boto3.Session(region_name=region) if not zdata: pill = placebo.attach(session, test_dir)", "files: return super(ZippedPill, self).record() # We can't update files in", "timedelta(0) def tzname(self, dt): return \"UTC\" def dst(self, dt): return", "= set() files = {n for n in self.archive.namelist() if", "return timedelta(0) def tzname(self, dt): return \"UTC\" def dst(self, dt):", "debug) self.path = path self._used = set() self.archive = None", "and module information for deserialization result = {\"__class__\": obj.__class__.__name__} try:", "base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name) index = 0 glob_pattern = os.path.join(self._data_path,", "Copyright (c) 2015 <NAME> class UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self, dt):", "augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region =", "operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name)", "base_name + \"*\") for file_path in fnmatch.filter(self._files, glob_pattern): file_name =", "1) fn = os.path.join(self._data_path, base_name + \"_{0}.json\".format(index)) fn = fn.replace('\\\\',", "it's not here raise IOError(\"response file ({0}) not found\".format(fn)) return", "test recording, using # cross account assumes, note this will", "test_dir) # pill = BluePill() # pill.attach(session, test_dir) else: pill", "objects to dictionary representation based on type if isinstance(obj, datetime):", "to sanitize response metadata and account_ids \"\"\" # aws sso", "issue is resolved # # https://github.com/garnaat/placebo/issues/63 # # License -", "= attach(session, self.archive_path, test_case, debug=True) pill.record() self.pill = pill self.addCleanup(pill.stop)", "setups involve a short lived credential transfer if service ==", "= obj.minute result[\"second\"] = obj.second result[\"microsecond\"] = obj.microsecond return result", "= True test_dir = os.path.join(self.placebo_dir, test_case) if not (zdata or", "{\"__class__\": obj.__class__.__name__} try: result[\"__module__\"] = obj.__module__ except AttributeError: pass #", "and region != default_region: new_session = boto3.Session(region_name=region) if new_session: assert", "import ACCOUNT_ID # Custodian Test Account. This is used only", "http_response=200): filepath = self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\", filepath) json_data =", "indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self, service, operation): response_file", "utc = UTC() def deserialize(obj): \"\"\"Convert JSON dicts back into", "self).stop() if self.archive: self.archive.close() def save_response(self, service, operation, response_data, http_response=200):", "mitch went back to work at AWS, irony... # These", "if isinstance(obj, datetime): return obj.isoformat() def save_response(self, service, operation, response_data,", "else: pill = attach(session, self.archive_path, test_case, debug=True) pill.record() self.pill =", "self.archive = zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for n in src.namelist(): if", "# These monkeypatch patches represent fixes on trunk of that", "so copy self.archive.close() os.rename(self.path, \"%s.tmp\" % self.path) src = zipfile.ZipFile(\"%s.tmp\"", "**target) if class_name == \"StreamingBody\": return StringIO(target[\"body\"]) # Return unrecognized", "from .constants import ACCOUNT_ID # Custodian Test Account. This is", "- Apache 2.0 # Copyright (c) 2015 <NAME> class UTC(tzinfo):", "from botocore.response import StreamingBody from placebo import pill from c7n.testing", "super(BluePill, self).get_next_file_path(service, operation) # couple of double use cases if", "project maintainers. ########################################################################### # BEGIN PLACEBO MONKEY PATCH # #", "index = i index += 1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index))", "careful of shallow copy here target = dict(obj) class_name =", "isinstance(obj, StreamingBody): result[\"body\"] = obj.read() obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read =", "0 and (assume is not False and fake.assume_role): client =", "experimental for test recording, using # cross account assumes, note", "they will # go stale, but its best to modify", "double use cases if fn in self._avail: self._avail.remove(fn) else: print(\"\\ndouble", "PLACEBO MONKEY PATCH # # Placebo is effectively abandoned upstream,", "def __call__(fake, region=None, assume=None): new_session = None # slightly experimental", "= super(BluePill, self).stop() if self._avail: print(\"Unused json files \\n %s\"", "def get_next_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation) if self.prefix:", "+= 1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self, service, operation):", "in a zip, so copy self.archive.close() os.rename(self.path, \"%s.tmp\" % self.path)", "= ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix) return pill class RedPill(pill.Pill):", "new_session = boto3.Session(region_name=region) if new_session: assert not zdata new_pill =", "needed if class_name == \"datetime\": return datetime(tzinfo=utc, **target) if class_name", "########################################################################## class BluePill(pill.Pill): def playback(self): super(BluePill, self).playback() self._avail = self.get_available()", "\"\"\" The `region` argument is to allow functional tests to", "at AWS, irony... # These monkeypatch patches represent fixes on", "class_name == \"StreamingBody\": return StringIO(target[\"body\"]) # Return unrecognized structures as-is", "if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name) index", "datetime): return obj.isoformat() def save_response(self, service, operation, response_data, http_response=200): \"\"\"", "placebo.pill.serialize = serialize placebo.pill.deserialize = deserialize # END PLACEBO MONKEY", "output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" ) recording = False", "self.path, \"r\") self.archive = zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for n in", "else: print(\"\\ndouble use %s\\n\" % fn) return (fn, format) def", "= \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name) index = 0 glob_pattern", "not zdata: pill = placebo.attach(session, test_dir) # pill = BluePill()", "shutil import zipfile import re from datetime import datetime, timedelta,", "if the object isn't recognized raise TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw", "test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session return session return FakeFactory()", "self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self,", "data %s\" % test_dir) session = boto3.Session(region_name=region) if not zdata:", "%s\\n\" % fn) return (fn, format) def stop(self): result =", "== \"StreamingBody\": return StringIO(target[\"body\"]) # Return unrecognized structures as-is return", "in files: continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" % self.path) return super(ZippedPill,", "= self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\", filepath) json_data = {\"status_code\": http_response,", "{\"status_code\": http_response, \"data\": response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED,", "index += 1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self, service,", "placebo.pill.deserialize = deserialize # END PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill):", "fn.replace('\\\\', '/') if fn in self._files: next_file = fn self._index[base_name]", "def playback(self): super(BluePill, self).playback() self._avail = self.get_available() def get_available(self): return", "patches represent fixes on trunk of that repo that have", "c7n.testing import CustodianTestCore from .constants import ACCOUNT_ID # Custodian Test", "import pill from c7n.testing import CustodianTestCore from .constants import ACCOUNT_ID", "of double use cases if fn in self._avail: self._avail.remove(fn) else:", "set(self.archive.namelist()) return super(ZippedPill, self).playback() def record(self): self.archive = zipfile.ZipFile(self.path, \"a\",", "next_file is None: index = self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path,", "calls creds into test data, they will # go stale,", "zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\") self.archive = zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for", "# https://github.com/garnaat/placebo/issues/63 # # License - Apache 2.0 # Copyright", "if not zdata: pill = RedPill() pill.attach(session, test_dir) else: pill", "structures.\"\"\" # Record class and module information for deserialization result", "maintainers. ########################################################################### # BEGIN PLACEBO MONKEY PATCH # # Placebo", "return datetime(tzinfo=utc, **target) if class_name == \"StreamingBody\": return StringIO(target[\"body\"]) #", "stored data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True return", "We can't update files in a zip, so copy self.archive.close()", "if self.archive: self.archive.close() def save_response(self, service, operation, response_data, http_response=200): filepath", "\"portal.sso\": return if 'ResponseMetadata' in response_data: response_data['ResponseMetadata'] = {} response_data", "community project maintainers. ########################################################################### # BEGIN PLACEBO MONKEY PATCH #", "index != 1: self._index[base_name] = 1 else: # we are", "will record sts # assume role api calls creds into", "= RedPill() pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case,", "save_response(self, service, operation, response_data, http_response=200): \"\"\" Override to sanitize response", "else: pill = attach(session, self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp)", "for test recording, using # cross account assumes, note this", "fn = os.path.join(self._data_path, base_name + \"_{0}.json\".format(index)) fn = fn.replace('\\\\', '/')", "= obj.second result[\"microsecond\"] = obj.microsecond return result if isinstance(obj, StreamingBody):", "glob_pattern = os.path.join(self._data_path, base_name + \"*\") for file_path in fnmatch.filter(self._files,", "None if \"__class__\" in target: class_name = target.pop(\"__class__\") if \"__module__\"", "index)) def get_next_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation) if", "transfer if service == \"portal.sso\": return if 'ResponseMetadata' in response_data:", "result[\"body\"] = obj.read() obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read = 0 return", "zdata=False, region=None): \"\"\" The `region` argument is to allow functional", "= os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir): raise RuntimeError(\"Invalid Test Dir", "super(ZippedPill, self).record() def stop(self): super(ZippedPill, self).stop() if self.archive: self.archive.close() def", "return pill class RedPill(pill.Pill): def datetime_converter(self, obj): if isinstance(obj, datetime):", "obj.decode('utf8') # Raise a TypeError if the object isn't recognized", "that have not been released # into an extant version,", "role api calls creds into test data, they will #", "to override the default region. It is unused when replaying", "\"StreamingBody\": return StringIO(target[\"body\"]) # Return unrecognized structures as-is return obj", "os.path.join(self._data_path, base_name + \"_{0}.json\".format(index)) fn = fn.replace('\\\\', '/') if fn", "from io import StringIO import json import os import shutil", "\"placebo\" ) output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" ) recording", "def cleanUp(self): self.pill = None def record_flight_data(self, test_case, zdata=False, augment=False,", "to dictionary representation based on type if isinstance(obj, datetime): result[\"year\"]", "def record_flight_data(self, test_case, zdata=False, augment=False, region=None): self.recording = True test_dir", "test_dir) session = boto3.Session(region_name=region) if not zdata: pill = placebo.attach(session,", "operation, response_data, http_response=200): filepath = self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\", filepath)", "obj.microsecond return result if isinstance(obj, StreamingBody): result[\"body\"] = obj.read() obj._raw_stream", "fn def attach(session, data_path, prefix=None, debug=False): pill = ZippedPill(data_path, prefix=prefix,", "obj def serialize(obj): \"\"\"Convert objects into JSON structures.\"\"\" # Record", "ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix) return pill class RedPill(pill.Pill): def", "short lived credential transfer if service == \"portal.sso\": return if", "ACCOUNT_ID, response_data) # noqa response_data = json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service,", "have not been released # into an extant version, we", "import fnmatch from io import StringIO import json import os", "self._files = set(self.archive.namelist()) return super(ZippedPill, self).playback() def record(self): self.archive =", "response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def", "api calls creds into test data, they will # go", "get_next_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation) if self.prefix: base_name", "self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake, region=None,", "self.archive.read(response_file), object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def get_new_file_path(self,", "= zipfile.ZipFile(self.path, \"r\") self._files = set(self.archive.namelist()) return super(ZippedPill, self).playback() def", "self._files.add(fn) elif index != 1: self._index[base_name] = 1 else: #", "or fake.region or default_region) elif region and region != default_region:", "__init__(self, path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path = path", "m: i = int(m.group(\"index\")) if i > index: index =", "used only for testing. # Access is available for community", "= 0 return result if isinstance(obj, bytes): return obj.decode('utf8') #", "base_name) index = 0 glob_pattern = os.path.join(self._data_path, base_name + \"*\")", "os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" ) output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\"", "BEGIN PLACEBO MONKEY PATCH # # Placebo is effectively abandoned", "import strtobool import boto3 import placebo from botocore.response import StreamingBody", "not (zdata or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session =", "zdata: pill = RedPill() pill.attach(session, test_dir) else: pill = attach(session,", "= serialize placebo.pill.deserialize = deserialize # END PLACEBO MONKEY ##########################################################################", "super(ZippedPill, self).stop() if self.archive: self.archive.close() def save_response(self, service, operation, response_data,", "an extant version, we carry them here. We can drop", "next_file = None while next_file is None: index = self._index.setdefault(base_name,", "operation, response_data, http_response=200): \"\"\" Override to sanitize response metadata and", "region=None): \"\"\" The `region` argument is to allow functional tests", ") return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def get_new_file_path(self, service, operation):", "self).save_response(service, operation, response_data, http_response) class PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)),", "not os.path.exists(test_dir): raise RuntimeError(\"Invalid Test Dir for flight data %s\"", "default_region) elif region and region != default_region: new_session = boto3.Session(region_name=region)", "\"*.json\") } def get_next_file_path(self, service, operation): fn, format = super(BluePill,", "debug=debug) pill.attach(session, prefix) return pill class RedPill(pill.Pill): def datetime_converter(self, obj):", "Convert objects to dictionary representation based on type if isinstance(obj,", "response_data = json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data, http_response) class", "class ZippedPill(pill.Pill): def __init__(self, path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug)", "return lambda region=region, assume=None: boto3.Session(region_name=region) if not zdata: test_dir =", "are looking for the first index and it's not here", "zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for n in src.namelist(): if n in", "into an extant version, we carry them here. We can", "new_pill.record() self.addCleanup(new_pill.stop) return new_session return session return FakeFactory() def replay_flight_data(self,", "dt): return timedelta(0) def tzname(self, dt): return \"UTC\" def dst(self,", "PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill): def playback(self): super(BluePill, self).playback() self._avail", "return fn def attach(session, data_path, prefix=None, debug=False): pill = ZippedPill(data_path,", "result if isinstance(obj, StreamingBody): result[\"body\"] = obj.read() obj._raw_stream = StringIO(result[\"body\"])", "return obj.decode('utf8') # Raise a TypeError if the object isn't", "\"\"\"Convert objects into JSON structures.\"\"\" # Record class and module", "\"{0}.{1}\".format(service, operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\",", "else: # we are looking for the first index and", "def datetime_converter(self, obj): if isinstance(obj, datetime): return obj.isoformat() def save_response(self,", "to allow functional tests to override the default region. It", "since mitch went back to work at AWS, irony... #", "unused when replaying stored data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording", "monkeypatch patches represent fixes on trunk of that repo that", "print(\"Unused json files \\n %s\" % (\"\\n\".join(sorted(self._avail)))) return result class", "response_data, http_response=200): filepath = self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\", filepath) json_data", "def load_response(self, service, operation): response_file = self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses:", "involve a short lived credential transfer if service == \"portal.sso\":", "This is used only for testing. # Access is available", "\"_{0}.json\".format(index)) fn = fn.replace('\\\\', '/') if fn in self._files: next_file", "StreamingBody): result[\"body\"] = obj.read() obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read = 0", "def get_available(self): return { os.path.join(self.data_path, n) for n in fnmatch.filter(os.listdir(self.data_path),", "json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self, service, operation):", "ZippedPill(pill.Pill): def __init__(self, path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path", "shallow copy here target = dict(obj) class_name = None if", "return result if isinstance(obj, StreamingBody): result[\"body\"] = obj.read() obj._raw_stream =", "copy self.archive.close() os.rename(self.path, \"%s.tmp\" % self.path) src = zipfile.ZipFile(\"%s.tmp\" %", "base_name + \"_{0}.json\".format(index)) fn = fn.replace('\\\\', '/') if fn in", "zdata=False, augment=False, region=None): self.recording = True test_dir = os.path.join(self.placebo_dir, test_case)", "work at AWS, irony... # These monkeypatch patches represent fixes", "pill.LOG.debug(\"load_responses: %s\", response_file) response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return", "isinstance(obj, datetime): result[\"year\"] = obj.year result[\"month\"] = obj.month result[\"day\"] =", ") self._files.add(filepath) def load_response(self, service, operation): response_file = self.get_next_file_path(service, operation)", "dict(obj) class_name = None if \"__class__\" in target: class_name =", "obj.year result[\"month\"] = obj.month result[\"day\"] = obj.day result[\"hour\"] = obj.hour", "\"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name) index = 0 glob_pattern =", "we are looking for the first index and it's not", "boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region or default_region) elif", "botocore.response import StreamingBody from placebo import pill from c7n.testing import", "class_name) for custom types if needed if class_name == \"datetime\":", "if isinstance(obj, bytes): return obj.decode('utf8') # Raise a TypeError if", "= StringIO(result[\"body\"]) obj._amount_read = 0 return result if isinstance(obj, bytes):", "is not False and fake.assume_role): client = session.client('sts') creds =", "type if isinstance(obj, datetime): result[\"year\"] = obj.year result[\"month\"] = obj.month", "service, operation): base_name = \"{0}.{1}\".format(service, operation) if self.prefix: base_name =", ".constants import ACCOUNT_ID # Custodian Test Account. This is used", "return if 'ResponseMetadata' in response_data: response_data['ResponseMetadata'] = {} response_data =", "= os.path.join(self._data_path, base_name + \"*\") for file_path in fnmatch.filter(self._files, glob_pattern):", "here target = dict(obj) class_name = None if \"__class__\" in", "pill.attach(session, prefix) return pill class RedPill(pill.Pill): def datetime_converter(self, obj): if", "zdata new_pill = placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session", "# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import", "if isinstance(obj, StreamingBody): result[\"body\"] = obj.read() obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read", "and account_ids \"\"\" # aws sso setups involve a short", "result if isinstance(obj, bytes): return obj.decode('utf8') # Raise a TypeError", "n in src.namelist(): if n in files: continue self.archive.writestr(n, src.read(n))", "% self.path) src = zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\") self.archive =", "os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" ) recording = False def cleanUp(self): self.pill", "target: class_name = target.pop(\"__class__\") if \"__module__\" in obj: obj.pop(\"__module__\") #", "aws_session_token=creds['SessionToken'], region_name=region or fake.region or default_region) elif region and region", "looking for the first index and it's not here raise", "self._index[base_name] += 1 self._files.add(fn) elif index != 1: self._index[base_name] =", "import CustodianTestCore from .constants import ACCOUNT_ID # Custodian Test Account.", "= json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] )", "__call__(fake, region=None, assume=None): new_session = None # slightly experimental for", "go stale, but its best to modify before commiting. #", "= self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path, base_name + \"_{0}.json\".format(index)) fn", "pill = attach(session, self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) return", "attach(session, self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) return lambda region=None,", "deserialize(obj): \"\"\"Convert JSON dicts back into objects.\"\"\" # Be careful", "if self._avail: print(\"Unused json files \\n %s\" % (\"\\n\".join(sorted(self._avail)))) return", "noqa response_data = json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data, http_response)", "fake.assume_role): client = session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session", "RuntimeError(\"Invalid Test Dir for flight data %s\" % test_dir) session", "= super(BluePill, self).get_next_file_path(service, operation) # couple of double use cases", "None def playback(self): self.archive = zipfile.ZipFile(self.path, \"r\") self._files = set(self.archive.namelist())", "found\".format(fn)) return fn def attach(session, data_path, prefix=None, debug=False): pill =", "debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path = path self._used = set()", "copy here target = dict(obj) class_name = None if \"__class__\"", "= target.pop(\"__class__\") if \"__module__\" in obj: obj.pop(\"__module__\") # Use getattr(module,", "test data, they will # go stale, but its best", "on trunk of that repo that have not been released", "dst(self, dt): return timedelta(0) utc = UTC() def deserialize(obj): \"\"\"Convert", "PATCH # # Placebo is effectively abandoned upstream, since mitch", "Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import fnmatch from io", "carry them here. We can drop this when this issue", "\"{0}.{1}\".format(service, operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\",", "for community project maintainers. ########################################################################### # BEGIN PLACEBO MONKEY PATCH", "# # https://github.com/garnaat/placebo/issues/63 # # License - Apache 2.0 #", "self).playback() self._avail = self.get_available() def get_available(self): return { os.path.join(self.data_path, n)", "= \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file = None while", "obj.day result[\"hour\"] = obj.hour result[\"minute\"] = obj.minute result[\"second\"] = obj.second", "return super(ZippedPill, self).playback() def record(self): self.archive = zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED)", "files = {n for n in self.archive.namelist() if n.startswith(self.prefix)} if", "########################################################################### # BEGIN PLACEBO MONKEY PATCH # # Placebo is", "pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake, region=None, assume=None): new_session", "prefix=prefix, debug=debug) pill.attach(session, prefix) return pill class RedPill(pill.Pill): def datetime_converter(self,", "= json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data, http_response) class PillTest(CustodianTestCore):", "= attach(session, self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) return lambda", "fn self._index[base_name] += 1 self._files.add(fn) elif index != 1: self._index[base_name]", "zip, so copy self.archive.close() os.rename(self.path, \"%s.tmp\" % self.path) src =", "prefix=None, debug=False): pill = ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix) return", "pill = placebo.attach(session, test_dir) # pill = BluePill() # pill.attach(session,", "(c) 2015 <NAME> class UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self, dt): return", "new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region or", "playback(self): super(BluePill, self).playback() self._avail = self.get_available() def get_available(self): return {", "this will record sts # assume role api calls creds", "operation) # couple of double use cases if fn in", "return super(ZippedPill, self).record() def stop(self): super(ZippedPill, self).stop() if self.archive: self.archive.close()", "return obj def serialize(obj): \"\"\"Convert objects into JSON structures.\"\"\" #", "\"data\": response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath)", "} def get_next_file_path(self, service, operation): fn, format = super(BluePill, self).get_next_file_path(service,", "import shutil import zipfile import re from datetime import datetime,", "self.archive.close() def save_response(self, service, operation, response_data, http_response=200): filepath = self.get_new_file_path(service,", "first index and it's not here raise IOError(\"response file ({0})", "operation): response_file = self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file) response_data", "assumes, note this will record sts # assume role api", "%s\", response_file) response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return (", "Test Account. This is used only for testing. # Access", "Custodian Test Account. This is used only for testing. #", "= os.path.join(self.placebo_dir, test_case) if not (zdata or augment): if os.path.exists(test_dir):", "record_flight_data(self, test_case, zdata=False, augment=False, region=None): self.recording = True test_dir =", "= obj.month result[\"day\"] = obj.day result[\"hour\"] = obj.hour result[\"minute\"] =", "files: continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" % self.path) return super(ZippedPill, self).record()", "int(m.group(\"index\")) if i > index: index = i index +=", "default region. It is unused when replaying stored data. \"\"\"", "True return lambda region=region, assume=None: boto3.Session(region_name=region) if not zdata: test_dir", "from distutils.util import strtobool import boto3 import placebo from botocore.response", "back into objects.\"\"\" # Be careful of shallow copy here", "super(BluePill, self).playback() self._avail = self.get_available() def get_available(self): return { os.path.join(self.data_path,", "test_case) if not (zdata or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir)", "boto3.Session(region_name=region) default_region = session.region_name if not zdata: pill = RedPill()", "'ResponseMetadata' in response_data: response_data['ResponseMetadata'] = {} response_data = json.dumps(response_data, default=serialize)", "obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read = 0 return result if isinstance(obj,", "record(self): self.archive = zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files = set() files", "index and it's not here raise IOError(\"response file ({0}) not", "fnmatch from io import StringIO import json import os import", "None: index = self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path, base_name +", "result[\"minute\"] = obj.minute result[\"second\"] = obj.second result[\"microsecond\"] = obj.microsecond return", "= session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session(", "response_data = json.dumps(response_data, default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) #", "is None: index = self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path, base_name", "them here. We can drop this when this issue is", "stop(self): super(ZippedPill, self).stop() if self.archive: self.archive.close() def save_response(self, service, operation,", "False and fake.assume_role): client = session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role,", "= set(self.archive.namelist()) return super(ZippedPill, self).playback() def record(self): self.archive = zipfile.ZipFile(self.path,", "session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'],", "replay_flight_data(self, test_case, zdata=False, region=None): \"\"\" The `region` argument is to", "back to work at AWS, irony... # These monkeypatch patches", "= None while next_file is None: index = self._index.setdefault(base_name, 1)", "+ \"*\") for file_path in fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path)", "sts # assume role api calls creds into test data,", "self._files.add(filepath) def load_response(self, service, operation): response_file = self.get_next_file_path(service, operation) self._used.add(response_file)", "Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import fnmatch from io import", "i index += 1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self,", "base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file = None", "datetime(tzinfo=utc, **target) if class_name == \"StreamingBody\": return StringIO(target[\"body\"]) # Return", "and fake.assume_role): client = session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials']", "= placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session return session", "self.pill = None def record_flight_data(self, test_case, zdata=False, augment=False, region=None): self.recording", "dt): return timedelta(0) utc = UTC() def deserialize(obj): \"\"\"Convert JSON", "target.pop(\"__class__\") if \"__module__\" in obj: obj.pop(\"__module__\") # Use getattr(module, class_name)", "can't update files in a zip, so copy self.archive.close() os.rename(self.path,", "tzinfo from distutils.util import strtobool import boto3 import placebo from", "operation): base_name = \"{0}.{1}\".format(service, operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix,", "if n.startswith(self.prefix)} if not files: return super(ZippedPill, self).record() # We", "src = zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\") self.archive = zipfile.ZipFile(self.path, \"w\",", "\"%s.tmp\" % self.path) src = zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\") self.archive", "def record(self): self.archive = zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files = set()", "self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name) index =", "import placebo from botocore.response import StreamingBody from placebo import pill", "StringIO import json import os import shutil import zipfile import", "self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" % self.path) return super(ZippedPill, self).record() def stop(self):", "flight data %s\" % test_dir) session = boto3.Session(region_name=region) if not", "MONKEY ########################################################################## class BluePill(pill.Pill): def playback(self): super(BluePill, self).playback() self._avail =", "new_session: assert not zdata new_pill = placebo.attach(new_session, test_dir, debug=True) new_pill.record()", "self.filename_re.match(file_name) if m: i = int(m.group(\"index\")) if i > index:", "\"output\" ) recording = False def cleanUp(self): self.pill = None", "if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region = session.region_name", "pill.FakeHttpResponse.raw = None placebo.pill.serialize = serialize placebo.pill.deserialize = deserialize #", "Placebo is effectively abandoned upstream, since mitch went back to", "assume=None): new_session = None # slightly experimental for test recording,", "+ \"_{0}.json\".format(index)) fn = fn.replace('\\\\', '/') if fn in self._files:", "to modify before commiting. # Disabled by default. if 0", "in obj: obj.pop(\"__module__\") # Use getattr(module, class_name) for custom types", "if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True return lambda region=region, assume=None:", "result[\"day\"] = obj.day result[\"hour\"] = obj.hour result[\"minute\"] = obj.minute result[\"second\"]", "self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake, region=None, assume=None): new_session =", "os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" ) output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\",", "obj: obj.pop(\"__module__\") # Use getattr(module, class_name) for custom types if", "isn't recognized raise TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw = None placebo.pill.serialize", "fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path) m = self.filename_re.match(file_name) if m:", "and (assume is not False and fake.assume_role): client = session.client('sts')", "is to allow functional tests to override the default region.", "fn in self._avail: self._avail.remove(fn) else: print(\"\\ndouble use %s\\n\" % fn)", "return FakeFactory() def replay_flight_data(self, test_case, zdata=False, region=None): \"\"\" The `region`", "return result if isinstance(obj, bytes): return obj.decode('utf8') # Raise a", "(\"\\n\".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill): def __init__(self, path, prefix=None, debug=False):", "Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import fnmatch", "is unused when replaying stored data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')):", "\"__class__\" in target: class_name = target.pop(\"__class__\") if \"__module__\" in obj:", "self.archive.close() os.rename(self.path, \"%s.tmp\" % self.path) src = zipfile.ZipFile(\"%s.tmp\" % self.path,", "import StringIO import json import os import shutil import zipfile", "\"datetime\": return datetime(tzinfo=utc, **target) if class_name == \"StreamingBody\": return StringIO(target[\"body\"])", "in fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path) m = self.filename_re.match(file_name) if", "obj.pop(\"__module__\") # Use getattr(module, class_name) for custom types if needed", "save_response(self, service, operation, response_data, http_response=200): filepath = self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response:", "def dst(self, dt): return timedelta(0) utc = UTC() def deserialize(obj):", "pill.LOG.debug(\"get_new_file_path: %s\", base_name) index = 0 glob_pattern = os.path.join(self._data_path, base_name", "of shallow copy here target = dict(obj) class_name = None", "class RedPill(pill.Pill): def datetime_converter(self, obj): if isinstance(obj, datetime): return obj.isoformat()", "here. We can drop this when this issue is resolved", "dictionary representation based on type if isinstance(obj, datetime): result[\"year\"] =", "i > index: index = i index += 1 return", "= boto3.Session(region_name=region) default_region = session.region_name if not zdata: pill =", "will # go stale, but its best to modify before", "default. if 0 and (assume is not False and fake.assume_role):", "== \"datetime\": return datetime(tzinfo=utc, **target) if class_name == \"StreamingBody\": return", "def get_new_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation) if self.prefix:", "if not os.path.exists(test_dir): raise RuntimeError(\"Invalid Test Dir for flight data", "not False and fake.assume_role): client = session.client('sts') creds = client.assume_role(", "service, operation, response_data, http_response=200): \"\"\" Override to sanitize response metadata", "test_case) if not os.path.exists(test_dir): raise RuntimeError(\"Invalid Test Dir for flight", "PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir = os.path.join(", "creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'],", "operation) pill.LOG.debug(\"save_response: path=%s\", filepath) json_data = {\"status_code\": http_response, \"data\": response_data}", "or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region", "response_file = self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file) response_data =", "data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True return lambda", "os import shutil import zipfile import re from datetime import", "%s\" % (\"\\n\".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill): def __init__(self, path,", "boto3 import placebo from botocore.response import StreamingBody from placebo import", "ACCOUNT_ID # Custodian Test Account. This is used only for", "2015 <NAME> class UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self, dt): return timedelta(0)", "% self.path) return super(ZippedPill, self).record() def stop(self): super(ZippedPill, self).stop() if", "= {} response_data = json.dumps(response_data, default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID,", "pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case, debug=True) pill.record()", "1: self._index[base_name] = 1 else: # we are looking for", "abandoned upstream, since mitch went back to work at AWS,", "def __init__(self, path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path =", "(fn, format) def stop(self): result = super(BluePill, self).stop() if self._avail:", "test_case, zdata=False, augment=False, region=None): self.recording = True test_dir = os.path.join(self.placebo_dir,", "but its best to modify before commiting. # Disabled by", "# aws sso setups involve a short lived credential transfer", "StreamingBody from placebo import pill from c7n.testing import CustodianTestCore from", "self.recording = True test_dir = os.path.join(self.placebo_dir, test_case) if not (zdata", "base_name) next_file = None while next_file is None: index =", "base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file = None while next_file is", "serializable\") pill.FakeHttpResponse.raw = None placebo.pill.serialize = serialize placebo.pill.deserialize = deserialize", "cases if fn in self._avail: self._avail.remove(fn) else: print(\"\\ndouble use %s\\n\"", "http_response, \"data\": response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, )", "result class ZippedPill(pill.Pill): def __init__(self, path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix,", "1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self, service, operation): base_name", "return session return FakeFactory() def replay_flight_data(self, test_case, zdata=False, region=None): \"\"\"", "released # into an extant version, we carry them here.", "from c7n.testing import CustodianTestCore from .constants import ACCOUNT_ID # Custodian", "pill = ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix) return pill class", "obj._amount_read = 0 return result if isinstance(obj, bytes): return obj.decode('utf8')", "client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region", "% test_dir) session = boto3.Session(region_name=region) if not zdata: pill =", "# We can't update files in a zip, so copy", "True test_dir = os.path.join(self.placebo_dir, test_case) if not (zdata or augment):", "self._avail.remove(fn) else: print(\"\\ndouble use %s\\n\" % fn) return (fn, format)", "when this issue is resolved # # https://github.com/garnaat/placebo/issues/63 # #", "AttributeError: pass # Convert objects to dictionary representation based on", "test_dir) else: pill = attach(session, self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop)", "!= 1: self._index[base_name] = 1 else: # we are looking", "self._files = set() files = {n for n in self.archive.namelist()", "= \"{0}.{1}\".format(service, operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path:", "\"*\") for file_path in fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path) m", "super(ZippedPill, self).record() # We can't update files in a zip,", "for file_path in fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path) m =", "os.path.basename(file_path) m = self.filename_re.match(file_name) if m: i = int(m.group(\"index\")) if", "before commiting. # Disabled by default. if 0 and (assume", "(assume is not False and fake.assume_role): client = session.client('sts') creds", "END PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill): def playback(self): super(BluePill, self).playback()", "get_next_file_path(self, service, operation): fn, format = super(BluePill, self).get_next_file_path(service, operation) #", "if \"__module__\" in obj: obj.pop(\"__module__\") # Use getattr(module, class_name) for", "raise IOError(\"response file ({0}) not found\".format(fn)) return fn def attach(session,", "The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import fnmatch from", "class and module information for deserialization result = {\"__class__\": obj.__class__.__name__}", "% (\"\\n\".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill): def __init__(self, path, prefix=None,", "default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self, service, operation): response_file =", "Override to sanitize response metadata and account_ids \"\"\" # aws", "self.archive_path, test_case, debug=True) pill.record() self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class", "\"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True return lambda region=region,", "default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) # noqa response_data =", "def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return \"UTC\"", "as-is return obj def serialize(obj): \"\"\"Convert objects into JSON structures.\"\"\"", "return result class ZippedPill(pill.Pill): def __init__(self, path, prefix=None, debug=False): super(ZippedPill,", "# Raise a TypeError if the object isn't recognized raise", "= boto3.Session(region_name=region) if new_session: assert not zdata new_pill = placebo.attach(new_session,", "from placebo import pill from c7n.testing import CustodianTestCore from .constants", "\"\"\" # aws sso setups involve a short lived credential", "def save_response(self, service, operation, response_data, http_response=200): filepath = self.get_new_file_path(service, operation)", "\"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file = None while next_file", "obj.month result[\"day\"] = obj.day result[\"hour\"] = obj.hour result[\"minute\"] = obj.minute", "# into an extant version, we carry them here. We", "# Placebo is effectively abandoned upstream, since mitch went back", "self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\", filepath) json_data = {\"status_code\": http_response, \"data\":", "None # slightly experimental for test recording, using # cross", "return obj.isoformat() def save_response(self, service, operation, response_data, http_response=200): \"\"\" Override", "for deserialization result = {\"__class__\": obj.__class__.__name__} try: result[\"__module__\"] = obj.__module__", "in fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def get_next_file_path(self, service, operation): fn, format", "continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" % self.path) return super(ZippedPill, self).record() def", "import zipfile import re from datetime import datetime, timedelta, tzinfo", "for flight data %s\" % test_dir) session = boto3.Session(region_name=region) if", "get_new_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation) if self.prefix: base_name", "JSON structures.\"\"\" # Record class and module information for deserialization", "result[\"microsecond\"] = obj.microsecond return result if isinstance(obj, StreamingBody): result[\"body\"] =", "record sts # assume role api calls creds into test", "None while next_file is None: index = self._index.setdefault(base_name, 1) fn", "replaying stored data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True", "return \"UTC\" def dst(self, dt): return timedelta(0) utc = UTC()", "'no')): self.recording = True return lambda region=region, assume=None: boto3.Session(region_name=region) if", "creds into test data, they will # go stale, but", "extant version, we carry them here. We can drop this", "SPDX-License-Identifier: Apache-2.0 import fnmatch from io import StringIO import json", "if i > index: index = i index += 1", "re from datetime import datetime, timedelta, tzinfo from distutils.util import", "pass # Convert objects to dictionary representation based on type", "= obj.year result[\"month\"] = obj.month result[\"day\"] = obj.day result[\"hour\"] =", "re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) # noqa response_data = json.loads(response_data, object_hook=deserialize) super(RedPill,", "or default_region) elif region and region != default_region: new_session =", "from datetime import datetime, timedelta, tzinfo from distutils.util import strtobool", "self.archive = zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files = set() files =", "os.path.join(self.data_path, n) for n in fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def get_next_file_path(self,", "class_name = None if \"__class__\" in target: class_name = target.pop(\"__class__\")", "def deserialize(obj): \"\"\"Convert JSON dicts back into objects.\"\"\" # Be", "Be careful of shallow copy here target = dict(obj) class_name", "n) for n in fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def get_next_file_path(self, service,", "for the first index and it's not here raise IOError(\"response", "cleanUp(self): self.pill = None def record_flight_data(self, test_case, zdata=False, augment=False, region=None):", "when replaying stored data. \"\"\" if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording =", "= fn.replace('\\\\', '/') if fn in self._files: next_file = fn", "self._avail: print(\"Unused json files \\n %s\" % (\"\\n\".join(sorted(self._avail)))) return result", "obj.isoformat() def save_response(self, service, operation, response_data, http_response=200): \"\"\" Override to", "raise RuntimeError(\"Invalid Test Dir for flight data %s\" % test_dir)", "path=%s\", filepath) json_data = {\"status_code\": http_response, \"data\": response_data} self.archive.writestr( filepath,", "n in files: continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" % self.path) return", "dicts back into objects.\"\"\" # Be careful of shallow copy", "index: index = i index += 1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name,", "pill class RedPill(pill.Pill): def datetime_converter(self, obj): if isinstance(obj, datetime): return", "json import os import shutil import zipfile import re from", "json_data = {\"status_code\": http_response, \"data\": response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4,", "obj): if isinstance(obj, datetime): return obj.isoformat() def save_response(self, service, operation,", "None def record_flight_data(self, test_case, zdata=False, augment=False, region=None): self.recording = True", "super(RedPill, self).save_response(service, operation, response_data, http_response) class PillTest(CustodianTestCore): archive_path = os.path.join(", "import StreamingBody from placebo import pill from c7n.testing import CustodianTestCore", "use %s\\n\" % fn) return (fn, format) def stop(self): result", "License - Apache 2.0 # Copyright (c) 2015 <NAME> class", "= self.get_available() def get_available(self): return { os.path.join(self.data_path, n) for n", "os.rename(self.path, \"%s.tmp\" % self.path) src = zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\")", "print(\"\\ndouble use %s\\n\" % fn) return (fn, format) def stop(self):", "i = int(m.group(\"index\")) if i > index: index = i", "(zdata or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region)", "= {n for n in self.archive.namelist() if n.startswith(self.prefix)} if not", "= \"{0}.{1}\".format(service, operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path:", "# cross account assumes, note this will record sts #", "pill = RedPill() pill.attach(session, test_dir) else: pill = attach(session, self.archive_path,", "filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self, service,", "response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"]", "io import StringIO import json import os import shutil import", "serialize placebo.pill.deserialize = deserialize # END PLACEBO MONKEY ########################################################################## class", "# Use getattr(module, class_name) for custom types if needed if", "zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files = set() files = {n for", "information for deserialization result = {\"__class__\": obj.__class__.__name__} try: result[\"__module__\"] =", "in self._avail: self._avail.remove(fn) else: print(\"\\ndouble use %s\\n\" % fn) return", "operation): fn, format = super(BluePill, self).get_next_file_path(service, operation) # couple of", "for testing. # Access is available for community project maintainers.", "index = 0 glob_pattern = os.path.join(self._data_path, base_name + \"*\") for", "timedelta, tzinfo from distutils.util import strtobool import boto3 import placebo", "= os.path.basename(file_path) m = self.filename_re.match(file_name) if m: i = int(m.group(\"index\"))", "the first index and it's not here raise IOError(\"response file", "account_ids \"\"\" # aws sso setups involve a short lived", "a TypeError if the object isn't recognized raise TypeError(\"Type not", "{} response_data = json.dumps(response_data, default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data)", "fixes on trunk of that repo that have not been", "0 return result if isinstance(obj, bytes): return obj.decode('utf8') # Raise", "+= 1 self._files.add(fn) elif index != 1: self._index[base_name] = 1", "the default region. It is unused when replaying stored data.", "commiting. # Disabled by default. if 0 and (assume is", "prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path = path self._used =", "class PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir =", "self._index[base_name] = 1 else: # we are looking for the", "format = super(BluePill, self).get_next_file_path(service, operation) # couple of double use", "n.startswith(self.prefix)} if not files: return super(ZippedPill, self).record() # We can't", "session = boto3.Session(region_name=region) default_region = session.region_name if not zdata: pill", "Raise a TypeError if the object isn't recognized raise TypeError(\"Type", "into test data, they will # go stale, but its", "RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region", "base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name) index = 0", "n in fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def get_next_file_path(self, service, operation): fn,", "def playback(self): self.archive = zipfile.ZipFile(self.path, \"r\") self._files = set(self.archive.namelist()) return", "self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file =", "fake.region or default_region) elif region and region != default_region: new_session", "response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) # noqa response_data = json.loads(response_data,", "attach(session, data_path, prefix=None, debug=False): pill = ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session,", "lived credential transfer if service == \"portal.sso\": return if 'ResponseMetadata'", "operation, response_data, http_response) class PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\"", "its best to modify before commiting. # Disabled by default.", "<NAME> class UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self, dt): return timedelta(0) def", "# Return unrecognized structures as-is return obj def serialize(obj): \"\"\"Convert", "'/') if fn in self._files: next_file = fn self._index[base_name] +=", "update files in a zip, so copy self.archive.close() os.rename(self.path, \"%s.tmp\"", "for custom types if needed if class_name == \"datetime\": return", "= int(m.group(\"index\")) if i > index: index = i index", "return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self, service, operation): base_name =", "data, they will # go stale, but its best to", "by default. if 0 and (assume is not False and", "service, operation, response_data, http_response=200): filepath = self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\",", "only for testing. # Access is available for community project", "metadata and account_ids \"\"\" # aws sso setups involve a", "= None placebo.pill.serialize = serialize placebo.pill.deserialize = deserialize # END", "raise TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw = None placebo.pill.serialize = serialize", "placebo.attach(session, test_dir) # pill = BluePill() # pill.attach(session, test_dir) else:", "object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data, http_response) class PillTest(CustodianTestCore): archive_path =", "getattr(module, class_name) for custom types if needed if class_name ==", "object isn't recognized raise TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw = None", "= zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for n in src.namelist(): if n", "if isinstance(obj, datetime): result[\"year\"] = obj.year result[\"month\"] = obj.month result[\"day\"]", "datetime import datetime, timedelta, tzinfo from distutils.util import strtobool import", "= obj.read() obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read = 0 return result", "dt): return \"UTC\" def dst(self, dt): return timedelta(0) utc =", "# License - Apache 2.0 # Copyright (c) 2015 <NAME>", "os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region = session.region_name if not zdata:", "not serializable\") pill.FakeHttpResponse.raw = None placebo.pill.serialize = serialize placebo.pill.deserialize =", "client = session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session =", "boto3.Session(region_name=region) if new_session: assert not zdata new_pill = placebo.attach(new_session, test_dir,", "in self.archive.namelist() if n.startswith(self.prefix)} if not files: return super(ZippedPill, self).record()", "% self.path, \"r\") self.archive = zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for n", "= client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'],", "test_dir = os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir): raise RuntimeError(\"Invalid Test", "class FakeFactory: def __call__(fake, region=None, assume=None): new_session = None #", "def get_next_file_path(self, service, operation): fn, format = super(BluePill, self).get_next_file_path(service, operation)", "result[\"hour\"] = obj.hour result[\"minute\"] = obj.minute result[\"second\"] = obj.second result[\"microsecond\"]", "Access is available for community project maintainers. ########################################################################### # BEGIN", "next_file = fn self._index[base_name] += 1 self._files.add(fn) elif index !=", "= re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) # noqa response_data = json.loads(response_data, object_hook=deserialize)", "archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)),", "response_data) # noqa response_data = json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation,", "# pill = BluePill() # pill.attach(session, test_dir) else: pill =", "# pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case, False)", "object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def get_new_file_path(self, service,", "not been released # into an extant version, we carry", "Dir for flight data %s\" % test_dir) session = boto3.Session(region_name=region)", "if service == \"portal.sso\": return if 'ResponseMetadata' in response_data: response_data['ResponseMetadata']", "json.dumps(response_data, default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) # noqa response_data", "represent fixes on trunk of that repo that have not", "result[\"month\"] = obj.month result[\"day\"] = obj.day result[\"hour\"] = obj.hour result[\"minute\"]", "def tzname(self, dt): return \"UTC\" def dst(self, dt): return timedelta(0)", "result = {\"__class__\": obj.__class__.__name__} try: result[\"__module__\"] = obj.__module__ except AttributeError:", "the object isn't recognized raise TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw =", "base_name = \"{0}.{1}\".format(service, operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name)", "region. It is unused when replaying stored data. \"\"\" if", "if not files: return super(ZippedPill, self).record() # We can't update", "return (fn, format) def stop(self): result = super(BluePill, self).stop() if", "trunk of that repo that have not been released #", "self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path, base_name + \"_{0}.json\".format(index)) fn =", "playback(self): self.archive = zipfile.ZipFile(self.path, \"r\") self._files = set(self.archive.namelist()) return super(ZippedPill,", "n in self.archive.namelist() if n.startswith(self.prefix)} if not files: return super(ZippedPill,", "# Record class and module information for deserialization result =", "tests to override the default region. It is unused when", "\"data\", \"output\" ) recording = False def cleanUp(self): self.pill =", "# Custodian Test Account. This is used only for testing.", "= json.dumps(response_data, default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\", ACCOUNT_ID, response_data) # noqa", "\"r\") self._files = set(self.archive.namelist()) return super(ZippedPill, self).playback() def record(self): self.archive", "representation based on type if isinstance(obj, datetime): result[\"year\"] = obj.year", "= UTC() def deserialize(obj): \"\"\"Convert JSON dicts back into objects.\"\"\"", "return StringIO(target[\"body\"]) # Return unrecognized structures as-is return obj def", "prefix) return pill class RedPill(pill.Pill): def datetime_converter(self, obj): if isinstance(obj,", "def attach(session, data_path, prefix=None, debug=False): pill = ZippedPill(data_path, prefix=prefix, debug=debug)", "response_data[\"data\"] ) def get_new_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation)", "The `region` argument is to allow functional tests to override", "response_file) response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data[\"status_code\"]),", "self.archive = None def playback(self): self.archive = zipfile.ZipFile(self.path, \"r\") self._files", "= deserialize # END PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill): def", "use cases if fn in self._avail: self._avail.remove(fn) else: print(\"\\ndouble use", "self.get_available() def get_available(self): return { os.path.join(self.data_path, n) for n in", "src.read(n)) os.remove(\"%s.tmp\" % self.path) return super(ZippedPill, self).record() def stop(self): super(ZippedPill,", "is used only for testing. # Access is available for", "not zdata: test_dir = os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir): raise", "= zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\") self.archive = zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED)", "# go stale, but its best to modify before commiting.", "Use getattr(module, class_name) for custom types if needed if class_name", "fn, format = super(BluePill, self).get_next_file_path(service, operation) # couple of double", "= fn self._index[base_name] += 1 self._files.add(fn) elif index != 1:", "class_name = target.pop(\"__class__\") if \"__module__\" in obj: obj.pop(\"__module__\") # Use", "glob_pattern): file_name = os.path.basename(file_path) m = self.filename_re.match(file_name) if m: i", "deserialize # END PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill): def playback(self):", "available for community project maintainers. ########################################################################### # BEGIN PLACEBO MONKEY", "class UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self, dt): return timedelta(0) def tzname(self,", "StringIO(result[\"body\"]) obj._amount_read = 0 return result if isinstance(obj, bytes): return", "Record class and module information for deserialization result = {\"__class__\":", "Account. This is used only for testing. # Access is", "obj.second result[\"microsecond\"] = obj.microsecond return result if isinstance(obj, StreamingBody): result[\"body\"]", "in src.namelist(): if n in files: continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\"", "new_session = None # slightly experimental for test recording, using", "\"__module__\" in obj: obj.pop(\"__module__\") # Use getattr(module, class_name) for custom", "while next_file is None: index = self._index.setdefault(base_name, 1) fn =", "os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region = session.region_name if", "elif index != 1: self._index[base_name] = 1 else: # we", "allow functional tests to override the default region. It is", "= None if \"__class__\" in target: class_name = target.pop(\"__class__\") if", "types if needed if class_name == \"datetime\": return datetime(tzinfo=utc, **target)", "placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" ) output_dir = os.path.join(", "def stop(self): super(ZippedPill, self).stop() if self.archive: self.archive.close() def save_response(self, service,", "os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" )", "# # License - Apache 2.0 # Copyright (c) 2015", "# Access is available for community project maintainers. ########################################################################### #", "self).record() def stop(self): super(ZippedPill, self).stop() if self.archive: self.archive.close() def save_response(self,", "for n in fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def get_next_file_path(self, service, operation):", "if 'ResponseMetadata' in response_data: response_data['ResponseMetadata'] = {} response_data = json.dumps(response_data,", "= os.path.join(self._data_path, base_name + \"_{0}.json\".format(index)) fn = fn.replace('\\\\', '/') if", "except AttributeError: pass # Convert objects to dictionary representation based", "irony... # These monkeypatch patches represent fixes on trunk of", "== \"portal.sso\": return if 'ResponseMetadata' in response_data: response_data['ResponseMetadata'] = {}", "# assume role api calls creds into test data, they", "is resolved # # https://github.com/garnaat/placebo/issues/63 # # License - Apache", "recording = False def cleanUp(self): self.pill = None def record_flight_data(self,", "default_region = session.region_name if not zdata: pill = RedPill() pill.attach(session,", "import boto3 import placebo from botocore.response import StreamingBody from placebo", "FakeFactory: def __call__(fake, region=None, assume=None): new_session = None # slightly", "if 0 and (assume is not False and fake.assume_role): client", "assert not zdata new_pill = placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop)", "self._avail: self._avail.remove(fn) else: print(\"\\ndouble use %s\\n\" % fn) return (fn,", "fn in self._files: next_file = fn self._index[base_name] += 1 self._files.add(fn)", "super(ZippedPill, self).__init__(prefix, debug) self.path = path self._used = set() self.archive", "index = self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path, base_name + \"_{0}.json\".format(index))", "= pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake, region=None, assume=None):", "datetime, timedelta, tzinfo from distutils.util import strtobool import boto3 import", "self).record() # We can't update files in a zip, so", "src.namelist(): if n in files: continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" %", "test_case, debug=True) pill.record() self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory:", "files \\n %s\" % (\"\\n\".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill): def", "and it's not here raise IOError(\"response file ({0}) not found\".format(fn))", "= os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" ) output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)),", "# slightly experimental for test recording, using # cross account", "if n in files: continue self.archive.writestr(n, src.read(n)) os.remove(\"%s.tmp\" % self.path)", "upstream, since mitch went back to work at AWS, irony...", "\"r\") self.archive = zipfile.ZipFile(self.path, \"w\", zipfile.ZIP_DEFLATED) for n in src.namelist():", "self).get_next_file_path(service, operation) # couple of double use cases if fn", "= obj.day result[\"hour\"] = obj.hour result[\"minute\"] = obj.minute result[\"second\"] =", "AWS, irony... # These monkeypatch patches represent fixes on trunk", "repo that have not been released # into an extant", "= boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region or default_region)", "# Convert objects to dictionary representation based on type if", "if not zdata: test_dir = os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir):", "cross account assumes, note this will record sts # assume", "argument is to allow functional tests to override the default", "pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case, False) pill.playback()", "result[\"second\"] = obj.second result[\"microsecond\"] = obj.microsecond return result if isinstance(obj,", "return new_session return session return FakeFactory() def replay_flight_data(self, test_case, zdata=False,", "we carry them here. We can drop this when this", "response_data['ResponseMetadata'] = {} response_data = json.dumps(response_data, default=serialize) response_data = re.sub(r\"\\b\\d{12}\\b\",", "best to modify before commiting. # Disabled by default. if", "Return unrecognized structures as-is return obj def serialize(obj): \"\"\"Convert objects", "shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region = session.region_name if not", "1 else: # we are looking for the first index", "set() self.archive = None def playback(self): self.archive = zipfile.ZipFile(self.path, \"r\")", "obj.minute result[\"second\"] = obj.second result[\"microsecond\"] = obj.microsecond return result if", "\"\"\" Override to sanitize response metadata and account_ids \"\"\" #", "region=None): self.recording = True test_dir = os.path.join(self.placebo_dir, test_case) if not", "can drop this when this issue is resolved # #", "format) def stop(self): result = super(BluePill, self).stop() if self._avail: print(\"Unused", "{n for n in self.archive.namelist() if n.startswith(self.prefix)} if not files:", "self.archive = zipfile.ZipFile(self.path, \"r\") self._files = set(self.archive.namelist()) return super(ZippedPill, self).playback()", "version, we carry them here. We can drop this when", "file_path in fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path) m = self.filename_re.match(file_name)", "RedPill() pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case, debug=True)", "isinstance(obj, bytes): return obj.decode('utf8') # Raise a TypeError if the", "%s\", base_name) index = 0 glob_pattern = os.path.join(self._data_path, base_name +", "2.0 # Copyright (c) 2015 <NAME> class UTC(tzinfo): \"\"\"UTC\"\"\" def", "= i index += 1 return os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def", "objects.\"\"\" # Be careful of shallow copy here target =", "\"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation)", "isinstance(obj, datetime): return obj.isoformat() def save_response(self, service, operation, response_data, http_response=200):", "return { os.path.join(self.data_path, n) for n in fnmatch.filter(os.listdir(self.data_path), \"*.json\") }", "service, operation): response_file = self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file)", "placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session return session return", "try: result[\"__module__\"] = obj.__module__ except AttributeError: pass # Convert objects", "slightly experimental for test recording, using # cross account assumes,", "lambda region=region, assume=None: boto3.Session(region_name=region) if not zdata: test_dir = os.path.join(self.placebo_dir,", "distutils.util import strtobool import boto3 import placebo from botocore.response import", "for n in src.namelist(): if n in files: continue self.archive.writestr(n,", "unrecognized structures as-is return obj def serialize(obj): \"\"\"Convert objects into", "serialize(obj): \"\"\"Convert objects into JSON structures.\"\"\" # Record class and", "zipfile.ZIP_DEFLATED) for n in src.namelist(): if n in files: continue", "False def cleanUp(self): self.pill = None def record_flight_data(self, test_case, zdata=False,", "region_name=region or fake.region or default_region) elif region and region !=", "= os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" ) recording = False def", "= obj.microsecond return result if isinstance(obj, StreamingBody): result[\"body\"] = obj.read()", "couple of double use cases if fn in self._avail: self._avail.remove(fn)", "result = super(BluePill, self).stop() if self._avail: print(\"Unused json files \\n", "= BluePill() # pill.attach(session, test_dir) else: pill = attach(session, self.archive_path,", "= boto3.Session(region_name=region) if not zdata: pill = placebo.attach(session, test_dir) #", "UTC(tzinfo): \"\"\"UTC\"\"\" def utcoffset(self, dt): return timedelta(0) def tzname(self, dt):", "result[\"year\"] = obj.year result[\"month\"] = obj.month result[\"day\"] = obj.day result[\"hour\"]", "def save_response(self, service, operation, response_data, http_response=200): \"\"\" Override to sanitize", "We can drop this when this issue is resolved #", "# couple of double use cases if fn in self._avail:", "sanitize response metadata and account_ids \"\"\" # aws sso setups", "self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file) response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize )", "zipfile.ZIP_DEFLATED) self._files = set() files = {n for n in", "= None # slightly experimental for test recording, using #", "zipfile import re from datetime import datetime, timedelta, tzinfo from", "= self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file) response_data = json.loads(", "service, operation): fn, format = super(BluePill, self).get_next_file_path(service, operation) # couple", "super(BluePill, self).stop() if self._avail: print(\"Unused json files \\n %s\" %", "RedPill(pill.Pill): def datetime_converter(self, obj): if isinstance(obj, datetime): return obj.isoformat() def", "tzname(self, dt): return \"UTC\" def dst(self, dt): return timedelta(0) utc", "super(ZippedPill, self).playback() def record(self): self.archive = zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files", "not files: return super(ZippedPill, self).record() # We can't update files", "= False def cleanUp(self): self.pill = None def record_flight_data(self, test_case,", "\"UTC\" def dst(self, dt): return timedelta(0) utc = UTC() def", "datetime): result[\"year\"] = obj.year result[\"month\"] = obj.month result[\"day\"] = obj.day", "not here raise IOError(\"response file ({0}) not found\".format(fn)) return fn", "= session.region_name if not zdata: pill = RedPill() pill.attach(session, test_dir)", "% fn) return (fn, format) def stop(self): result = super(BluePill,", "recognized raise TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw = None placebo.pill.serialize =", "assume=None: boto3.Session(region_name=region) if not zdata: test_dir = os.path.join(self.placebo_dir, test_case) if", "aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region or default_region) elif region and", "\"a\", zipfile.ZIP_DEFLATED) self._files = set() files = {n for n", "set() files = {n for n in self.archive.namelist() if n.startswith(self.prefix)}", "assume role api calls creds into test data, they will", "credential transfer if service == \"portal.sso\": return if 'ResponseMetadata' in", "if class_name == \"StreamingBody\": return StringIO(target[\"body\"]) # Return unrecognized structures", "pill = attach(session, self.archive_path, test_case, debug=True) pill.record() self.pill = pill", "CustodianTestCore from .constants import ACCOUNT_ID # Custodian Test Account. This", "= path self._used = set() self.archive = None def playback(self):", "JSON dicts back into objects.\"\"\" # Be careful of shallow", "= None def record_flight_data(self, test_case, zdata=False, augment=False, region=None): self.recording =", "debug=True) pill.record() self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def", "zdata: test_dir = os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir): raise RuntimeError(\"Invalid", "BluePill(pill.Pill): def playback(self): super(BluePill, self).playback() self._avail = self.get_available() def get_available(self):", "\"placebo_data.zip\" ) placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\" ) output_dir", "= obj.__module__ except AttributeError: pass # Convert objects to dictionary", "os.path.join(self.placebo_dir, test_case) if not (zdata or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir)", "bytes): return obj.decode('utf8') # Raise a TypeError if the object", "to work at AWS, irony... # These monkeypatch patches represent", "self).playback() def record(self): self.archive = zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files =", "this issue is resolved # # https://github.com/garnaat/placebo/issues/63 # # License", "os.path.exists(test_dir): raise RuntimeError(\"Invalid Test Dir for flight data %s\" %", "operation) if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_new_file_path: %s\", base_name)", "recording, using # cross account assumes, note this will record", "\"\"\"UTC\"\"\" def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return", "placebo from botocore.response import StreamingBody from placebo import pill from", "that repo that have not been released # into an", "of that repo that have not been released # into", "if fn in self._files: next_file = fn self._index[base_name] += 1", "elif region and region != default_region: new_session = boto3.Session(region_name=region) if", "!= default_region: new_session = boto3.Session(region_name=region) if new_session: assert not zdata", "test_dir = os.path.join(self.placebo_dir, test_case) if not (zdata or augment): if", "zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self, service, operation): response_file = self.get_next_file_path(service,", "is effectively abandoned upstream, since mitch went back to work", "if new_session: assert not zdata new_pill = placebo.attach(new_session, test_dir, debug=True)", "module information for deserialization result = {\"__class__\": obj.__class__.__name__} try: result[\"__module__\"]", "went back to work at AWS, irony... # These monkeypatch", "aws sso setups involve a short lived credential transfer if", "pill = BluePill() # pill.attach(session, test_dir) else: pill = attach(session,", "0 glob_pattern = os.path.join(self._data_path, base_name + \"*\") for file_path in", "files in a zip, so copy self.archive.close() os.rename(self.path, \"%s.tmp\" %", "os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" ) recording = False def cleanUp(self):", "path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path = path self._used", "region != default_region: new_session = boto3.Session(region_name=region) if new_session: assert not", "not zdata: pill = RedPill() pill.attach(session, test_dir) else: pill =", "These monkeypatch patches represent fixes on trunk of that repo", "get_available(self): return { os.path.join(self.data_path, n) for n in fnmatch.filter(os.listdir(self.data_path), \"*.json\")", "return timedelta(0) utc = UTC() def deserialize(obj): \"\"\"Convert JSON dicts", "self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake, region=None, assume=None): new_session = None", "> index: index = i index += 1 return os.path.join(self._data_path,", "aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region or default_region) elif region", "self.path = path self._used = set() self.archive = None def", "UTC() def deserialize(obj): \"\"\"Convert JSON dicts back into objects.\"\"\" #", "based on type if isinstance(obj, datetime): result[\"year\"] = obj.year result[\"month\"]", "self._used = set() self.archive = None def playback(self): self.archive =", "effectively abandoned upstream, since mitch went back to work at", "is available for community project maintainers. ########################################################################### # BEGIN PLACEBO", "import os import shutil import zipfile import re from datetime", "path self._used = set() self.archive = None def playback(self): self.archive", "account assumes, note this will record sts # assume role", "service == \"portal.sso\": return if 'ResponseMetadata' in response_data: response_data['ResponseMetadata'] =", "obj.__module__ except AttributeError: pass # Convert objects to dictionary representation", "test_dir) else: pill = attach(session, self.archive_path, test_case, debug=True) pill.record() self.pill", "obj.read() obj._raw_stream = StringIO(result[\"body\"]) obj._amount_read = 0 return result if", "Test Dir for flight data %s\" % test_dir) session =", "class_name == \"datetime\": return datetime(tzinfo=utc, **target) if class_name == \"StreamingBody\":", "= zipfile.ZipFile(self.path, \"a\", zipfile.ZIP_DEFLATED) self._files = set() files = {n", "self.path) src = zipfile.ZipFile(\"%s.tmp\" % self.path, \"r\") self.archive = zipfile.ZipFile(self.path,", "json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def", "return ( pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def get_new_file_path(self, service, operation): base_name", ") output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"output\" ) recording =", "boto3.Session(region_name=region) if not zdata: test_dir = os.path.join(self.placebo_dir, test_case) if not", "self).stop() if self._avail: print(\"Unused json files \\n %s\" % (\"\\n\".join(sorted(self._avail))))", "file_name = os.path.basename(file_path) m = self.filename_re.match(file_name) if m: i =", "modify before commiting. # Disabled by default. if 0 and", "Apache 2.0 # Copyright (c) 2015 <NAME> class UTC(tzinfo): \"\"\"UTC\"\"\"", "return super(ZippedPill, self).record() # We can't update files in a", "target = dict(obj) class_name = None if \"__class__\" in target:", "%s\" % test_dir) session = boto3.Session(region_name=region) if not zdata: pill", "# noqa response_data = json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data,", "augment=False, region=None): self.recording = True test_dir = os.path.join(self.placebo_dir, test_case) if", "class BluePill(pill.Pill): def playback(self): super(BluePill, self).playback() self._avail = self.get_available() def", "self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) return lambda region=None, assume=None:", "response_data, http_response=200): \"\"\" Override to sanitize response metadata and account_ids", "os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\", \"placebo\"", "utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return \"UTC\" def", "note this will record sts # assume role api calls", "\"w\", zipfile.ZIP_DEFLATED) for n in src.namelist(): if n in files:", "a short lived credential transfer if service == \"portal.sso\": return", "sso setups involve a short lived credential transfer if service", "for n in self.archive.namelist() if n.startswith(self.prefix)} if not files: return", "def serialize(obj): \"\"\"Convert objects into JSON structures.\"\"\" # Record class", "IOError(\"response file ({0}) not found\".format(fn)) return fn def attach(session, data_path,", "zipfile.ZipFile(self.path, \"r\") self._files = set(self.archive.namelist()) return super(ZippedPill, self).playback() def record(self):", "a zip, so copy self.archive.close() os.rename(self.path, \"%s.tmp\" % self.path) src", "{ os.path.join(self.data_path, n) for n in fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def", "os.path.join(self._data_path, \"{0}_{1}.json\".format(base_name, index)) def get_next_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service,", "Disabled by default. if 0 and (assume is not False", "= 0 glob_pattern = os.path.join(self._data_path, base_name + \"*\") for file_path", "Apache-2.0 import fnmatch from io import StringIO import json import", "attach(session, self.archive_path, test_case, debug=True) pill.record() self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp)", "resolved # # https://github.com/garnaat/placebo/issues/63 # # License - Apache 2.0", "= self.filename_re.match(file_name) if m: i = int(m.group(\"index\")) if i >", "new_session return session return FakeFactory() def replay_flight_data(self, test_case, zdata=False, region=None):", "\"\"\"Convert JSON dicts back into objects.\"\"\" # Be careful of", "= 1 else: # we are looking for the first", "TypeError(\"Type not serializable\") pill.FakeHttpResponse.raw = None placebo.pill.serialize = serialize placebo.pill.deserialize", ") def get_new_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service, operation) if", "StringIO(target[\"body\"]) # Return unrecognized structures as-is return obj def serialize(obj):", "debug=False): pill = ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix) return pill", "region=None, assume=None): new_session = None # slightly experimental for test", "self._files: next_file = fn self._index[base_name] += 1 self._files.add(fn) elif index", "# # Placebo is effectively abandoned upstream, since mitch went", "self.archive: self.archive.close() def save_response(self, service, operation, response_data, http_response=200): filepath =", "def replay_flight_data(self, test_case, zdata=False, region=None): \"\"\" The `region` argument is", "pill from c7n.testing import CustodianTestCore from .constants import ACCOUNT_ID #", "http_response=200): \"\"\" Override to sanitize response metadata and account_ids \"\"\"", "http_response) class PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir", "fnmatch.filter(os.listdir(self.data_path), \"*.json\") } def get_next_file_path(self, service, operation): fn, format =", "self.archive.namelist() if n.startswith(self.prefix)} if not files: return super(ZippedPill, self).record() #", "https://github.com/garnaat/placebo/issues/63 # # License - Apache 2.0 # Copyright (c)", "in target: class_name = target.pop(\"__class__\") if \"__module__\" in obj: obj.pop(\"__module__\")", "= {\"status_code\": http_response, \"data\": response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize),", "RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or", "custom types if needed if class_name == \"datetime\": return datetime(tzinfo=utc,", "into objects.\"\"\" # Be careful of shallow copy here target", "pill.FakeHttpResponse(response_data[\"status_code\"]), response_data[\"data\"] ) def get_new_file_path(self, service, operation): base_name = \"{0}.{1}\".format(service,", "pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file = None while next_file is None:", "obj.hour result[\"minute\"] = obj.minute result[\"second\"] = obj.second result[\"microsecond\"] = obj.microsecond", "m = self.filename_re.match(file_name) if m: i = int(m.group(\"index\")) if i", "json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data, http_response) class PillTest(CustodianTestCore): archive_path", "result[\"__module__\"] = obj.__module__ except AttributeError: pass # Convert objects to", "os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir): raise RuntimeError(\"Invalid Test Dir for", "= obj.hour result[\"minute\"] = obj.minute result[\"second\"] = obj.second result[\"microsecond\"] =", "region and region != default_region: new_session = boto3.Session(region_name=region) if new_session:", "here raise IOError(\"response file ({0}) not found\".format(fn)) return fn def", "= set() self.archive = None def playback(self): self.archive = zipfile.ZipFile(self.path,", "MONKEY PATCH # # Placebo is effectively abandoned upstream, since", "default_region: new_session = boto3.Session(region_name=region) if new_session: assert not zdata new_pill", "self).__init__(prefix, debug) self.path = path self._used = set() self.archive =", "self.path) return super(ZippedPill, self).record() def stop(self): super(ZippedPill, self).stop() if self.archive:", "Authors. # SPDX-License-Identifier: Apache-2.0 import fnmatch from io import StringIO", "= os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" ) placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"data\",", "= None def playback(self): self.archive = zipfile.ZipFile(self.path, \"r\") self._files =", "new_pill = placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session return", "pill.LOG.debug(\"save_response: path=%s\", filepath) json_data = {\"status_code\": http_response, \"data\": response_data} self.archive.writestr(", "operation) self._used.add(response_file) pill.LOG.debug(\"load_responses: %s\", response_file) response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize", "been released # into an extant version, we carry them", "filepath = self.get_new_file_path(service, operation) pill.LOG.debug(\"save_response: path=%s\", filepath) json_data = {\"status_code\":", "({0}) not found\".format(fn)) return fn def attach(session, data_path, prefix=None, debug=False):", "if self.prefix: base_name = \"{0}.{1}\".format(self.prefix, base_name) pill.LOG.debug(\"get_next_file_path: %s\", base_name) next_file", "response_data, http_response) class PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), \"placebo_data.zip\" )", "fn) return (fn, format) def stop(self): result = super(BluePill, self).stop()" ]
[ "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 24:", "execute_task, release_name): execute_task( 'inject_series', options={'inject': [Entry(title=release_name, url='')], 'disable_tracking': True}, )", "tuple of lists: [task name, list of series ID(s) to", "9 S03E01'], ['Test Series 9 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test", "series: - Test Series 8: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin:", "series: - Test Series 100: <<: *series_ep_pack max_reruns: 0 \"\"\"", "in result_find: assert task.find_entry(title=result_title) assert len(task.all_entries) == len(result_find) # Tests", "tracking: backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by:", "9 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10 S02', 'Test", "( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12 S02', 'Test Series 12 S03E01'],", "season_packs: threshold: 1000 reject_eps: yes tasks: inject_series: series: settings: test_series:", "S02'], ['Test Series 4 S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series", "S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10 S02', 'Test Series", "Series 14 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15", "'Test Series 21 S07E01'], ['Test Series 21 S07', 'Test Series", "Test Series 17 - Test Series 18 - Test Series", "@pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test Series 1 S02'], ['Test Series", "of series ID(s) to inject, list of result(s) to find]", "*nss_backfill series: - Test Series 15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0", "Entry # TODO Add more standard tests class TestNextSeriesSeasonSeasonsPack(object): _config", "# noqa pylint: disable=unused-import, redefined-builtin import pytest from flexget.entry import", "run_parameters): for this_test in run_parameters: for entity_id in this_test[1]: self.inject_series(execute_task,", "S06'], ['Test Series 16 S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series", "release_name): execute_task( 'inject_series', options={'inject': [Entry(title=release_name, url='')], 'disable_tracking': True}, ) @pytest.mark.parametrize(", "next_series_seasons: backfill: yes _nss_from_start: &nss_from_start next_series_seasons: from_start: yes _nss_backfill_from_start: &nss_backfill_from_start", "<<: *nss_backfill series: - Test Series 3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns:", "Test Series 1 - Test Series 2 - Test Series", "( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22 S02', 'Test Series 22 S03E01',", "Series 4: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series:", "test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series 21: <<: *series_ep_tracking_pack_begin_s04e01", "( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3 S02'], ['Test Series 3 S03'],", "yes series: - Test Series 1: <<: *series_ep_pack max_reruns: 0", "import Entry # TODO Add more standard tests class TestNextSeriesSeasonSeasonsPack(object):", "test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series: - Test Series 16: <<: *series_ep_pack", "series: - Test Series 24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed:", "Series 23 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24", "( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9 S02', 'Test Series 9 S03E01'],", "1 - Test Series 2 - Test Series 3 -", "50 S02'], ['Test Series 50 S03'], ), ], ) def", "['Test Series 13 S02', 'Test Series 13 S06'], ['Test Series", "*nss_backfill_from_start series: - Test Series 5: <<: *series_ep_tracking_pack max_reruns: 0", "Series 20 S07E01'], [ 'Test Series 20 S07', 'Test Series", "'Test Series 20 S03', 'Test Series 20 S01', ], ),", "task = execute_task(task_name) for result_title in result_find: assert task.find_entry(title=result_title) assert", "7: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series: -", "series: - Test Series 10: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill:", "'Test Series 18 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19", "'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11 S02', 'Test Series 11 S03E01'], ['Test", "], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18 S02', 'Test Series", "test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 18: <<: *series_ep_tracking_pack_begin_s04e01", "Test Series 5 - Test Series 6 - Test Series", "16 - Test Series 17 - Test Series 18 -", "Series 8: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series:", "100: <<: *series_ep_pack max_reruns: 0 \"\"\" @pytest.fixture() def config(self): \"\"\"Season", "'test_next_series_seasons_season_pack_gap', ['Test Series 13 S02', 'Test Series 13 S06'], ['Test", "<<: *series_ep_pack max_reruns: 0 \"\"\" @pytest.fixture() def config(self): \"\"\"Season packs", "( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17 S02', 'Test Series 17 S06'],", "19 - Test Series 20 - Test Series 21 -", "[ 'Test Series 14 S07', 'Test Series 14 S05', 'Test", "Series 20 S02', 'Test Series 20 S06', 'Test Series 20", "for this_test in run_parameters: for entity_id in this_test[1]: self.inject_series(execute_task, entity_id)", "Series 14 - Test Series 15 - Test Series 16", "Test Series 23: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start", "&series_ep_tracking_pack identified_by: ep tracking: backfill season_packs: threshold: 1000 reject_eps: yes", "'Test Series 24 S05', 'Test Series 24 S04'], ), (", "test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series: - Test Series 4: <<: *series_ep_pack", "S04', 'Test Series 23 S03', 'Test Series 23 S01', ],", "test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series: - Test Series 8: <<: *series_ep_tracking_pack", "0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series 15: <<:", "<<: *nss_backfill_from_start series: - Test Series 24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns:", "by guessit yet.\"\"\" return self._config def inject_series(self, execute_task, release_name): execute_task(", "- Test Series 19 - Test Series 20 - Test", "from flexget.entry import Entry # TODO Add more standard tests", "Series 24 S06'], ['Test Series 24 S07', 'Test Series 24", "100 S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S02'],", "14 - Test Series 15 - Test Series 16 -", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series: - Test Series 7:", "Series 8 S02', 'Test Series 8 S03E01'], ['Test Series 8", "( 'test_next_series_seasons_season_pack_and_ep', ['Test Series 7 S02', 'Test Series 7 S03E01'],", "'Test Series 5 S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6", "Series 19 S07E01'], ['Test Series 19 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill',", "17 S06'], [ 'Test Series 17 S07', 'Test Series 17", "self._config def inject_series(self, execute_task, release_name): execute_task( 'inject_series', options={'inject': [Entry(title=release_name, url='')],", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series: - Test", "S07', 'Test Series 17 S05', 'Test Series 17 S04', 'Test", "S02', 'Test Series 18 S06'], ['Test Series 18 S07', 'Test", ") ], ) def test_next_series_seasons_multirun(self, execute_task, run_parameters): for this_test in", "9 - Test Series 10 - Test Series 11 -", "Series 21 S07E01'], ['Test Series 21 S07', 'Test Series 21", "tasks: inject_series: series: settings: test_series: season_packs: always test_series: - Test", "Test Series 20 - Test Series 21 - Test Series", "Series 13 S06'], ['Test Series 13 S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill',", "Series 17 S05', 'Test Series 17 S04', 'Test Series 17", "S03E01'], ['Test Series 11 S03', 'Test Series 11 S01'], ),", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series: - Test", "), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3 S02'], ['Test Series 3", "inject: self.inject_series(execute_task, entity_id) task = execute_task(task_name) for result_title in result_find:", "series: - Test Series 19: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill:", "yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes series: - Test", "execute_task, run_parameters): for this_test in run_parameters: for entity_id in this_test[1]:", "'Test Series 20 S05', 'Test Series 20 S04', 'Test Series", "next_series_seasons: yes series: - Test Series 7: <<: *series_ep_pack max_reruns:", "*nss_backfill_from_start series: - Test Series 24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0", "len(result_find) # Tests which require multiple tasks to be executed", "Add more standard tests class TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\" templates:", "test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series: - Test Series 3: <<: *series_ep_tracking_pack_begin_s02e01", "Test Series 4: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start", "'Test Series 17 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series", "backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep", "['Test Series 18 S07', 'Test Series 18 S05', 'Test Series", "Test Series 22 - Test Series 23 - Test Series", "- Test Series 20: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<:", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series: - Test Series", "ep tracking: backfill begin: s04e01 season_packs: threshold: 1000 reject_eps: yes", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series: - Test Series", "<<: *nss_from_start series: - Test Series 10: <<: *series_ep_pack max_reruns:", "'Test Series 19 S07E01'], ['Test Series 19 S07'], ), (", "Test Series 19: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill", "'Test Series 14 S04', 'Test Series 14 S03', 'Test Series", "test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 11: <<: *series_ep_tracking_pack", "test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series: - Test Series 2: <<: *series_ep_tracking_pack", "'Test Series 2 S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3", "13 S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14 S02', 'Test", "24 S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50 S02'], ['Test", "of lists: [task name, list of series ID(s) to inject,", "<<: *nss_backfill_from_start series: - Test Series 18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns:", "<<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series: - Test", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series: - Test", "yes series: - Test Series 100: <<: *series_ep_pack max_reruns: 0", "), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15 S02', 'Test Series 15", "*nss_backfill series: - Test Series 2: <<: *series_ep_tracking_pack max_reruns: 0", "test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series: - Test Series 9: <<: *series_ep_tracking_pack_begin_s02e01", "['Test Series 12 S03'], ), ( 'test_next_series_seasons_season_pack_gap', ['Test Series 13", "True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test Series 1 S02'],", "from_start: yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill: yes from_start: yes _series_ep_pack:", "- Test Series 3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<:", "0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 11: <<:", "*nss_backfill_from_start series: - Test Series 6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0", "['Test Series 13 S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14", "['Test Series 18 S02', 'Test Series 18 S06'], ['Test Series", "result(s) to find] @pytest.mark.parametrize( \"run_parameters\", [ ( [ 'test_next_series_seasons_season_pack_from_start_multirun', [],", "Series 2: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series:", "20 S03', 'Test Series 20 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin',", "['Test Series 21 S07', 'Test Series 21 S05', 'Test Series", "series: - Test Series 14: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin:", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series 21:", "13 S02', 'Test Series 13 S06'], ['Test Series 13 S07'],", "- Test Series 24 - Test Series 25 - Test", "['Test Series 16 S02', 'Test Series 16 S06'], ['Test Series", "<<: *nss_backfill series: - Test Series 21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns:", "series: - Test Series 17: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin:", "24 - Test Series 25 - Test Series 50 -", "), ( 'test_next_series_seasons_season_pack_gap', ['Test Series 13 S02', 'Test Series 13", "unicode_literals, division, absolute_import from builtins import * # noqa pylint:", "Series 19 S06', 'Test Series 19 S07E01'], ['Test Series 19", "Series 5 S03', 'Test Series 5 S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin',", "result_find): for entity_id in inject: self.inject_series(execute_task, entity_id) task = execute_task(task_name)", "'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10 S02', 'Test Series 10 S03E01'], ['Test", "S03'], ), ( 'test_next_series_seasons_season_pack_and_ep', ['Test Series 7 S02', 'Test Series", "@pytest.fixture() def config(self): \"\"\"Season packs aren't supported by guessit yet.\"\"\"", "- Test Series 21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<:", "Series 23 S03E01', 'Test Series 23 S06'], [ 'Test Series", "s02e01 season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test", "S03', 'Test Series 23 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test", "<gh_stars>0 from __future__ import unicode_literals, division, absolute_import from builtins import", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series: - Test", "Series 5 S02'], ['Test Series 5 S03', 'Test Series 5", "S03E01'], ['Test Series 7 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series", "'Test Series 23 S03E01', 'Test Series 23 S06'], [ 'Test", "for entity_id in this_test[1]: self.inject_series(execute_task, entity_id) task = execute_task(this_test[0]) for", "- Test Series 100 test_next_series_seasons_season_pack: next_series_seasons: yes series: - Test", "10 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11 S02', 'Test", "Test Series 7 - Test Series 8 - Test Series", "Series 25 - Test Series 50 - Test Series 100", "'Test Series 23 S05', 'Test Series 23 S04', 'Test Series", "a tuple of lists: [task name, list of series ID(s)", "0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 12: <<:", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series: - Test", "- Test Series 7: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<:", "series: - Test Series 21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start:", "Test Series 24 - Test Series 25 - Test Series", "test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series: - Test Series 50: identified_by: ep", "'Test Series 18 S05', 'Test Series 18 S04'], ), (", "settings: test_series: season_packs: always test_series: - Test Series 1 -", "<<: *nss_backfill series: - Test Series 15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns:", "1000 reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking: backfill begin:", "Series 24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series:", "<<: *nss_from_start series: - Test Series 16: <<: *series_ep_pack max_reruns:", "Series 8 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9 S02',", "S03'], ), ( 'test_next_series_seasons_season_pack_gap', ['Test Series 13 S02', 'Test Series", "max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series: - Test Series 4:", "- Test Series 19: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<:", "5 S02'], ['Test Series 5 S03', 'Test Series 5 S01'],", "from_start: yes _series_ep_pack: &series_ep_pack identified_by: ep tracking: backfill season_packs: threshold:", "Series 6 S02'], ['Test Series 6 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep',", "S05', 'Test Series 15 S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series", "series: - Test Series 13: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill:", "Series 50: identified_by: ep begin: S02E01 season_packs: threshold: 1000 reject_eps:", "next_series_seasons: yes series: - Test Series 13: <<: *series_ep_pack max_reruns:", "*series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series: - Test Series", "inject_series(self, execute_task, release_name): execute_task( 'inject_series', options={'inject': [Entry(title=release_name, url='')], 'disable_tracking': True},", "6 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep', ['Test Series 7 S02', 'Test", "), ( 'test_next_series_seasons_season_pack_and_ep', ['Test Series 7 S02', 'Test Series 7", "- Test Series 14 - Test Series 15 - Test", "'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14 S02', 'Test Series 14 S06'], [", "'Test Series 17 S03', 'Test Series 17 S01', ], ),", "- Test Series 6 - Test Series 7 - Test", "Test Series 50: identified_by: ep begin: S02E01 season_packs: threshold: 1000", "21 S06', 'Test Series 21 S07E01'], ['Test Series 21 S07',", "tracking: backfill begin: s04e01 season_packs: threshold: 1000 reject_eps: yes tasks:", "17 - Test Series 18 - Test Series 19 -", "'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19 S02', 'Test Series 19 S06', 'Test", "- Test Series 24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons:", "['Test Series 22 S02', 'Test Series 22 S03E01', 'Test Series", "S03E01', 'Test Series 22 S06'], ['Test Series 22 S07'], ),", "supported by guessit yet.\"\"\" return self._config def inject_series(self, execute_task, release_name):", "['Test Series 17 S02', 'Test Series 17 S06'], [ 'Test", "- Test Series 15 - Test Series 16 - Test", "Series 100 S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100", "<<: *nss_backfill series: - Test Series 14: <<: *series_ep_tracking_pack max_reruns:", "- Test Series 15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<:", "Series 20 S07', 'Test Series 20 S05', 'Test Series 20", "S03'], ), ( 'test_next_series_seasons_season_pack_from_start', ['Test Series 4 S02'], ['Test Series", "Series 7 S03E01'], ['Test Series 7 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill',", "['Test Series 8 S01', 'Test Series 8 S03'], ), (", "17: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: -", "S06', 'Test Series 20 S07E01'], [ 'Test Series 20 S07',", "test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series: - Test Series 22: <<: *series_ep_pack", "S03', 'Test Series 11 S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series", "*series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series: - Test Series", "['Test Series 4 S02'], ['Test Series 4 S03'], ), (", "S06', 'Test Series 19 S07E01'], ['Test Series 19 S07'], ),", "_nss_backfill: &nss_backfill next_series_seasons: backfill: yes _nss_from_start: &nss_from_start next_series_seasons: from_start: yes", "15 S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16 S02', 'Test", "Test Series 1: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill", "test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 6: <<: *series_ep_tracking_pack_begin_s02e01", "assert task.find_entry(title=result_title) assert len(task.all_entries) == len(result_find) # Tests which require", "Series 1 S02'], ['Test Series 1 S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test", "execute_task, task_name, inject, result_find): for entity_id in inject: self.inject_series(execute_task, entity_id)", "'Test Series 14 S07', 'Test Series 14 S05', 'Test Series", "), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10 S02', 'Test Series 10", "S07E01'], [ 'Test Series 20 S07', 'Test Series 20 S05',", "Series 19 S02', 'Test Series 19 S06', 'Test Series 19", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series", "Series 12 - Test Series 13 - Test Series 14", "Series 50 S02'], ['Test Series 50 S03'], ), ], )", "max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes series: - Test Series 13:", "'Test Series 24 S06'], ['Test Series 24 S07', 'Test Series", "'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16 S02', 'Test Series 16 S06'], ['Test", "( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19 S02', 'Test Series 19 S06',", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series: - Test Series 9:", "Series 9 S02', 'Test Series 9 S03E01'], ['Test Series 9", "S02', 'Test Series 9 S03E01'], ['Test Series 9 S03'], ),", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series: - Test Series", "assert len(task.all_entries) == len(result_find) # Tests which require multiple tasks", "S02', 'Test Series 10 S03E01'], ['Test Series 10 S03'], ),", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series: - Test", "22 - Test Series 23 - Test Series 24 -", "<<: *nss_backfill_from_start series: - Test Series 6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns:", "run_parameters: for entity_id in this_test[1]: self.inject_series(execute_task, entity_id) task = execute_task(this_test[0])", "&nss_backfill next_series_seasons: backfill: yes _nss_from_start: &nss_from_start next_series_seasons: from_start: yes _nss_backfill_from_start:", "Series 17 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18", "test_next_series_seasons_multirun(self, execute_task, run_parameters): for this_test in run_parameters: for entity_id in", "reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking: backfill begin: s04e01", "# TODO Add more standard tests class TestNextSeriesSeasonSeasonsPack(object): _config =", "s04e01 season_packs: threshold: 1000 reject_eps: yes tasks: inject_series: series: settings:", "import pytest from flexget.entry import Entry # TODO Add more", "*series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series: - Test Series", "21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series: -", "def inject_series(self, execute_task, release_name): execute_task( 'inject_series', options={'inject': [Entry(title=release_name, url='')], 'disable_tracking':", "50 S03'], ), ], ) def test_next_series_seasons(self, execute_task, task_name, inject,", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series", "test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series 15: <<: *series_ep_tracking_pack_begin_s04e01", "test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 23: <<: *series_ep_tracking_pack", "1 S02'], ['Test Series 1 S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test Series", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series", "Test Series 2: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill", "[ ('test_next_series_seasons_season_pack', ['Test Series 1 S02'], ['Test Series 1 S03']),", "11 S02', 'Test Series 11 S03E01'], ['Test Series 11 S03',", "), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14 S02', 'Test Series 14", "( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18 S02', 'Test Series 18 S06'],", "( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24 S02', 'Test Series 24 S03E01',", "Series 20 S05', 'Test Series 20 S04', 'Test Series 20", "begin: s04e01 season_packs: threshold: 1000 reject_eps: yes tasks: inject_series: series:", "), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23 S02', 'Test Series 23", "12 - Test Series 13 - Test Series 14 -", "- Test Series 2: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<:", "Series 15 S06'], ['Test Series 15 S07', 'Test Series 15", "S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16 S02', 'Test Series", "['Test Series 2 S01', 'Test Series 2 S03'], ), (", "9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series: -", "['Test Series 23 S02', 'Test Series 23 S03E01', 'Test Series", "Series 6 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep', ['Test Series 7 S02',", "24 S07', 'Test Series 24 S05', 'Test Series 24 S04'],", "test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 5: <<: *series_ep_tracking_pack", "require multiple tasks to be executed in order # Each", "5 S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6 S02'], ['Test", "Series 21 S07', 'Test Series 21 S05', 'Test Series 21", "- Test Series 18 - Test Series 19 - Test", "8 S02', 'Test Series 8 S03E01'], ['Test Series 8 S01',", "from_start: yes series: - Test Series 100: <<: *series_ep_pack max_reruns:", "Series 11 S03E01'], ['Test Series 11 S03', 'Test Series 11", "['Test Series 24 S07', 'Test Series 24 S05', 'Test Series", "S02', 'Test Series 24 S03E01', 'Test Series 24 S06'], ['Test", "'Test Series 11 S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12", "Series 8 S01', 'Test Series 8 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin',", "['Test Series 10 S02', 'Test Series 10 S03E01'], ['Test Series", "( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20 S02', 'Test Series 20 S06',", "Test Series 5: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start", "<<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes series: - Test", "S03'], ), ], ) def test_next_series_seasons(self, execute_task, task_name, inject, result_find):", "- Test Series 8 - Test Series 9 - Test", "6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series: -", "21 S02', 'Test Series 21 S06', 'Test Series 21 S07E01'],", "- Test Series 22: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<:", "test_next_series_seasons(self, execute_task, task_name, inject, result_find): for entity_id in inject: self.inject_series(execute_task,", "*nss_from_start series: - Test Series 22: <<: *series_ep_pack max_reruns: 0", "), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5 S02'], ['Test Series 5", ") def test_next_series_seasons(self, execute_task, task_name, inject, result_find): for entity_id in", "*nss_backfill_from_start series: - Test Series 23: <<: *series_ep_tracking_pack max_reruns: 0", "11 S03', 'Test Series 11 S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test", "S04', 'Test Series 14 S03', 'Test Series 14 S01', ],", "18 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19 S02', 'Test", "S06', 'Test Series 21 S07E01'], ['Test Series 21 S07', 'Test", "S03E01', 'Test Series 24 S06'], ['Test Series 24 S07', 'Test", "20 S07E01'], [ 'Test Series 20 S07', 'Test Series 20", "reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep tracking: backfill season_packs: threshold:", "Series 9 S03E01'], ['Test Series 9 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start',", "22 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23 S02', 'Test", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 12:", "0 \"\"\" @pytest.fixture() def config(self): \"\"\"Season packs aren't supported by", "backfill: yes from_start: yes _series_ep_pack: &series_ep_pack identified_by: ep tracking: backfill", "14 S05', 'Test Series 14 S04', 'Test Series 14 S03',", "'Test Series 15 S06'], ['Test Series 15 S07', 'Test Series", "Series 2 - Test Series 3 - Test Series 4", "- Test Series 3 - Test Series 4 - Test", "S01', ], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18 S02', 'Test", "S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5 S02'], ['Test Series", "series: - Test Series 1: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill:", "Series 3 - Test Series 4 - Test Series 5", "24 S02', 'Test Series 24 S03E01', 'Test Series 24 S06'],", "max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series 15:", "['Test Series 21 S02', 'Test Series 21 S06', 'Test Series", "S03E01'], ['Test Series 12 S03'], ), ( 'test_next_series_seasons_season_pack_gap', ['Test Series", "S05', 'Test Series 21 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series", "20 - Test Series 21 - Test Series 22 -", "Test Series 8: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill", "S05', 'Test Series 17 S04', 'Test Series 17 S03', 'Test", "['Test Series 100 S02'], ], ) ], ) def test_next_series_seasons_multirun(self,", "*nss_backfill series: - Test Series 3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0", "'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50 S02'], ['Test Series 50 S03'], ),", "[ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S02'], ], ) ],", "S02', 'Test Series 19 S06', 'Test Series 19 S07E01'], ['Test", "Series 14 S04', 'Test Series 14 S03', 'Test Series 14", "S02', 'Test Series 12 S03E01'], ['Test Series 12 S03'], ),", "S07', 'Test Series 21 S05', 'Test Series 21 S04'], ),", "4 - Test Series 5 - Test Series 6 -", "[ 'Test Series 20 S07', 'Test Series 20 S05', 'Test", "S01', 'Test Series 8 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series", "17 S07', 'Test Series 17 S05', 'Test Series 17 S04',", "*nss_backfill series: - Test Series 8: <<: *series_ep_tracking_pack max_reruns: 0", "11 - Test Series 12 - Test Series 13 -", "15 S07', 'Test Series 15 S05', 'Test Series 15 S04'],", "], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15 S02', 'Test Series", "<<: *nss_backfill series: - Test Series 9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns:", "13 - Test Series 14 - Test Series 15 -", "Series 11 S02', 'Test Series 11 S03E01'], ['Test Series 11", "'Test Series 22 S03E01', 'Test Series 22 S06'], ['Test Series", "S06'], ['Test Series 22 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series", "result_find: assert task.find_entry(title=result_title) assert len(task.all_entries) == len(result_find) # Tests which", "[ ( [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S01'], ],", "S06'], ['Test Series 24 S07', 'Test Series 24 S05', 'Test", "1000 reject_eps: yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes series:", "S07E01'], ['Test Series 19 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series", "for result_title in result_find: assert task.find_entry(title=result_title) assert len(task.all_entries) == len(result_find)", "18 - Test Series 19 - Test Series 20 -", "Test Series 10 - Test Series 11 - Test Series", "( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6 S02'], ['Test Series 6 S03'],", "'Test Series 9 S03E01'], ['Test Series 9 S03'], ), (", "S06'], ['Test Series 18 S07', 'Test Series 18 S05', 'Test", "'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6 S02'], ['Test Series 6 S03'], ),", "Series 23 S02', 'Test Series 23 S03E01', 'Test Series 23", "_series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking: backfill begin: s02e01 season_packs: threshold:", "<<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series: - Test", "Series 23 S07', 'Test Series 23 S05', 'Test Series 23", "'Test Series 21 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22", "Series 13: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series:", "for entity_id in inject: self.inject_series(execute_task, entity_id) task = execute_task(task_name) for", "'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8 S02', 'Test Series 8 S03E01'], ['Test", "- Test Series 16 - Test Series 17 - Test", "find] @pytest.mark.parametrize( \"run_parameters\", [ ( [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series", "Series 12 S03'], ), ( 'test_next_series_seasons_season_pack_gap', ['Test Series 13 S02',", "12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes series: -", "&series_ep_pack identified_by: ep tracking: backfill season_packs: threshold: 1000 reject_eps: yes", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series", "backfill: yes _nss_from_start: &nss_from_start next_series_seasons: from_start: yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons:", "test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series: - Test Series 7: <<: *series_ep_pack", "S03E01'], ['Test Series 9 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series", "18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series: -", "- Test Series 2 - Test Series 3 - Test", "execute_task( 'inject_series', options={'inject': [Entry(title=release_name, url='')], 'disable_tracking': True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\",", "always test_series: - Test Series 1 - Test Series 2", "Test Series 9 - Test Series 10 - Test Series", "18 S06'], ['Test Series 18 S07', 'Test Series 18 S05',", "season_packs: threshold: 1000 reject_eps: yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start:", "'Test Series 11 S03E01'], ['Test Series 11 S03', 'Test Series", "( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21 S02', 'Test Series 21 S06',", "Test Series 10: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start", "23 S03', 'Test Series 23 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin',", "'test_next_series_seasons_season_pack_and_ep', ['Test Series 7 S02', 'Test Series 7 S03E01'], ['Test", "S06'], ['Test Series 13 S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series", "'Test Series 21 S06', 'Test Series 21 S07E01'], ['Test Series", "Series 100 S02'], ], ) ], ) def test_next_series_seasons_multirun(self, execute_task,", "Test Series 7: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill", "S01', 'Test Series 2 S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series", "( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8 S02', 'Test Series 8 S03E01'],", "10 S02', 'Test Series 10 S03E01'], ['Test Series 10 S03'],", "Series 13 S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14 S02',", "- Test Series 11 - Test Series 12 - Test", "Series 14 S05', 'Test Series 14 S04', 'Test Series 14", "2 S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3 S02'], ['Test", "- Test Series 13: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<:", "Test Series 11 - Test Series 12 - Test Series", "test_next_series_seasons_season_pack_gap: next_series_seasons: yes series: - Test Series 13: <<: *series_ep_pack", "17 S03', 'Test Series 17 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin',", "*nss_backfill_from_start series: - Test Series 12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0", "10 - Test Series 11 - Test Series 12 -", "Series 22 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23 S02',", "series: - Test Series 4: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill:", "8: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series: -", "24 S06'], ['Test Series 24 S07', 'Test Series 24 S05',", "= execute_task(task_name) for result_title in result_find: assert task.find_entry(title=result_title) assert len(task.all_entries)", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test", "Series 7 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8 S02',", "_series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep tracking: backfill season_packs: threshold: 1000 reject_eps:", "0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series: - Test Series 7: <<:", "S07', 'Test Series 15 S05', 'Test Series 15 S04'], ),", "( 'test_next_series_seasons_season_pack_gap', ['Test Series 13 S02', 'Test Series 13 S06'],", "'Test Series 14 S06'], [ 'Test Series 14 S07', 'Test", "- Test Series 10 - Test Series 11 - Test", "7 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8 S02', 'Test", "identified_by: ep tracking: backfill begin: s04e01 season_packs: threshold: 1000 reject_eps:", "), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20 S02', 'Test Series 20", "Series 11: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series:", "packs aren't supported by guessit yet.\"\"\" return self._config def inject_series(self,", "Series 23 S03', 'Test Series 23 S01', ], ), (", "from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import", "test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 12: <<: *series_ep_tracking_pack_begin_s02e01", "max_reruns: 0 \"\"\" @pytest.fixture() def config(self): \"\"\"Season packs aren't supported", "['Test Series 15 S02', 'Test Series 15 S06'], ['Test Series", "Series 16 S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17 S02',", "), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18 S02', 'Test Series 18", "is a tuple of lists: [task name, list of series", "S03E01', 'Test Series 23 S06'], [ 'Test Series 23 S07',", "Series 21 S02', 'Test Series 21 S06', 'Test Series 21", "absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin", "24 S03E01', 'Test Series 24 S06'], ['Test Series 24 S07',", "*series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series: - Test Series", "Series 1: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series:", "series: - Test Series 20: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin:", "threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking: backfill", "12 S03'], ), ( 'test_next_series_seasons_season_pack_gap', ['Test Series 13 S02', 'Test", "S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17 S02', 'Test Series", "Test Series 20: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill", "Series 16: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series:", "yes series: - Test Series 13: <<: *series_ep_pack max_reruns: 0", "<<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series: - Test", "S03', 'Test Series 14 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test", "Series 24 - Test Series 25 - Test Series 50", "__future__ import unicode_literals, division, absolute_import from builtins import * #", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series: - Test", "- Test Series 9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<:", "S02'], ['Test Series 2 S01', 'Test Series 2 S03'], ),", "- Test Series 17: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<:", "<<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series: - Test", "'Test Series 15 S05', 'Test Series 15 S04'], ), (", "16 S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17 S02', 'Test", "reject_eps: yes tasks: inject_series: series: settings: test_series: season_packs: always test_series:", "S02', 'Test Series 16 S06'], ['Test Series 16 S07'], ),", "1000 reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep tracking: backfill season_packs:", "Series 9 - Test Series 10 - Test Series 11", "), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50 S02'], ['Test Series 50", "], ) def test_next_series_seasons(self, execute_task, task_name, inject, result_find): for entity_id", "<<: *nss_from_start series: - Test Series 4: <<: *series_ep_pack max_reruns:", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series", "Series 15 - Test Series 16 - Test Series 17", "20 S07', 'Test Series 20 S05', 'Test Series 20 S04',", "0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 24: <<:", "100 S02'], ], ) ], ) def test_next_series_seasons_multirun(self, execute_task, run_parameters):", "- Test Series 1 - Test Series 2 - Test", "'Test Series 12 S03E01'], ['Test Series 12 S03'], ), (", "0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 5: <<:", "series: settings: test_series: season_packs: always test_series: - Test Series 1", "S01', ], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15 S02', 'Test", "'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun', [],", "test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series: - Test Series 19: <<: *series_ep_pack", "), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24 S02', 'Test Series 24", "test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 17: <<: *series_ep_tracking_pack", "Test Series 6 - Test Series 7 - Test Series", "series: - Test Series 50: identified_by: ep begin: S02E01 season_packs:", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series: - Test Series 8:", "options={'inject': [Entry(title=release_name, url='')], 'disable_tracking': True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack',", "S02', 'Test Series 20 S06', 'Test Series 20 S07E01'], [", "), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17 S02', 'Test Series 17", "), ( 'test_next_series_seasons_season_pack_from_start', ['Test Series 4 S02'], ['Test Series 4", "be executed in order # Each run_parameter is a tuple", "S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8 S02', 'Test Series", "to inject, list of result(s) to find] @pytest.mark.parametrize( \"run_parameters\", [", "17 S02', 'Test Series 17 S06'], [ 'Test Series 17", "S07', 'Test Series 23 S05', 'Test Series 23 S04', 'Test", "S05', 'Test Series 23 S04', 'Test Series 23 S03', 'Test", "reject_eps: yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes series: -", "<<: *nss_backfill_from_start series: - Test Series 11: <<: *series_ep_tracking_pack max_reruns:", "Each run_parameter is a tuple of lists: [task name, list", "'Test Series 15 S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16", "- Test Series 12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons:", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series: - Test Series 20:", "22: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series: -", "6 S02'], ['Test Series 6 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep', ['Test", "'Test Series 8 S03E01'], ['Test Series 8 S01', 'Test Series", "import unicode_literals, division, absolute_import from builtins import * # noqa", "from __future__ import unicode_literals, division, absolute_import from builtins import *", "yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill: yes from_start: yes _series_ep_pack: &series_ep_pack", "[Entry(title=release_name, url='')], 'disable_tracking': True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test", "S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14 S02', 'Test Series", "S07', 'Test Series 18 S05', 'Test Series 18 S04'], ),", "*nss_from_start series: - Test Series 10: <<: *series_ep_pack max_reruns: 0", "Test Series 3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start", "Series 18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series:", "[ 'Test Series 23 S07', 'Test Series 23 S05', 'Test", "redefined-builtin import pytest from flexget.entry import Entry # TODO Add", "season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking:", "5 - Test Series 6 - Test Series 7 -", "'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12 S02', 'Test Series 12 S03E01'], ['Test", "Test Series 21 - Test Series 22 - Test Series", "S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9 S02', 'Test Series", "'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20 S02', 'Test Series 20 S06', 'Test", "'Test Series 20 S07', 'Test Series 20 S05', 'Test Series", "23 S02', 'Test Series 23 S03E01', 'Test Series 23 S06'],", "Series 5: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series:", "Series 100: <<: *series_ep_pack max_reruns: 0 \"\"\" @pytest.fixture() def config(self):", "pytest from flexget.entry import Entry # TODO Add more standard", "S02', 'Test Series 8 S03E01'], ['Test Series 8 S01', 'Test", "8 S03E01'], ['Test Series 8 S01', 'Test Series 8 S03'],", "23 S03E01', 'Test Series 23 S06'], [ 'Test Series 23", "- Test Series 25 - Test Series 50 - Test", "24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series: -", "Series 13 - Test Series 14 - Test Series 15", "50: identified_by: ep begin: S02E01 season_packs: threshold: 1000 reject_eps: yes", "15 - Test Series 16 - Test Series 17 -", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series: - Test Series 22:", "S02'], ['Test Series 6 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep', ['Test Series", "11 S03E01'], ['Test Series 11 S03', 'Test Series 11 S01'],", "- Test Series 6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons:", "), ], ) def test_next_series_seasons(self, execute_task, task_name, inject, result_find): for", "Series 15 S02', 'Test Series 15 S06'], ['Test Series 15", "- Test Series 5 - Test Series 6 - Test", "['Test Series 19 S02', 'Test Series 19 S06', 'Test Series", "['Test Series 5 S02'], ['Test Series 5 S03', 'Test Series", "8 - Test Series 9 - Test Series 10 -", "0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series: - Test Series 4: <<:", "Series 21 S06', 'Test Series 21 S07E01'], ['Test Series 21", "task = execute_task(this_test[0]) for result_title in this_test[2]: assert task.find_entry(title=result_title) assert", "14 S06'], [ 'Test Series 14 S07', 'Test Series 14", "ep tracking: backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack", "2: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series: -", "Series 19 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20 S02',", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series: - Test Series", "0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series: - Test Series 16: <<:", "10 S03E01'], ['Test Series 10 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test", "lists: [task name, list of series ID(s) to inject, list", "17 S05', 'Test Series 17 S04', 'Test Series 17 S03',", "guessit yet.\"\"\" return self._config def inject_series(self, execute_task, release_name): execute_task( 'inject_series',", "\"\"\" @pytest.fixture() def config(self): \"\"\"Season packs aren't supported by guessit", "for result_title in this_test[2]: assert task.find_entry(title=result_title) assert len(task.all_entries) == len(this_test[2])", "10: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series: -", "*series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series: - Test Series", "'Test Series 20 S04', 'Test Series 20 S03', 'Test Series", "\"\"\" templates: global: parsing: series: internal anchors: _nss_backfill: &nss_backfill next_series_seasons:", "S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12 S02', 'Test Series", "( 'test_next_series_seasons_season_pack_from_start', ['Test Series 4 S02'], ['Test Series 4 S03'],", "['Test Series 22 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23", "- Test Series 10: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<:", "( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23 S02', 'Test Series 23 S03E01',", "), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19 S02', 'Test Series 19", "[], ['Test Series 100 S02'], ], ) ], ) def", "0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series: - Test Series 3: <<:", "yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking: backfill begin: s04e01 season_packs:", "Test Series 9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start", "'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15 S02', 'Test Series 15 S06'], ['Test", "season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking:", "yes series: - Test Series 50: identified_by: ep begin: S02E01", "Test Series 18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes", "13 S06'], ['Test Series 13 S07'], ), ( 'test_next_series_seasons_season_pack_gap_backfill', ['Test", "S05', 'Test Series 18 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series", "11: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: -", "Series 10 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11 S02',", "20 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21 S02',", "3 - Test Series 4 - Test Series 5 -", "Test Series 24: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes", "'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22 S02', 'Test Series 22 S03E01', 'Test", "tasks to be executed in order # Each run_parameter is", "TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\" templates: global: parsing: series: internal anchors:", "tracking: backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by:", "config(self): \"\"\"Season packs aren't supported by guessit yet.\"\"\" return self._config", "'Test Series 14 S03', 'Test Series 14 S01', ], ),", "TODO Add more standard tests class TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\"", "S03', 'Test Series 17 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test", "22 S06'], ['Test Series 22 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test", "*nss_backfill_from_start series: - Test Series 18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0", "'Test Series 20 S06', 'Test Series 20 S07E01'], [ 'Test", "Test Series 13: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill", "3 S02'], ['Test Series 3 S03'], ), ( 'test_next_series_seasons_season_pack_from_start', ['Test", "Series 22 - Test Series 23 - Test Series 24", "- Test Series 50: identified_by: ep begin: S02E01 season_packs: threshold:", "max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes series: - Test Series", "= execute_task(this_test[0]) for result_title in this_test[2]: assert task.find_entry(title=result_title) assert len(task.all_entries)", "Test Series 4 - Test Series 5 - Test Series", "&nss_backfill_from_start next_series_seasons: backfill: yes from_start: yes _series_ep_pack: &series_ep_pack identified_by: ep", "7 - Test Series 8 - Test Series 9 -", "14 S02', 'Test Series 14 S06'], [ 'Test Series 14", "('test_next_series_seasons_season_pack', ['Test Series 1 S02'], ['Test Series 1 S03']), (", "'Test Series 10 S03E01'], ['Test Series 10 S03'], ), (", "'Test Series 16 S06'], ['Test Series 16 S07'], ), (", "'Test Series 17 S04', 'Test Series 17 S03', 'Test Series", "Series 24 S03E01', 'Test Series 24 S06'], ['Test Series 24", "multiple tasks to be executed in order # Each run_parameter", "in run_parameters: for entity_id in this_test[1]: self.inject_series(execute_task, entity_id) task =", "0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series: - Test Series 19: <<:", "<<: *nss_backfill_from_start series: - Test Series 17: <<: *series_ep_tracking_pack max_reruns:", "*nss_backfill_from_start series: - Test Series 17: <<: *series_ep_tracking_pack max_reruns: 0", "Series 23: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series:", "- Test Series 4: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<:", "( 'test_next_series_seasons_season_pack_gap_backfill', ['Test Series 14 S02', 'Test Series 14 S06'],", "12 S03E01'], ['Test Series 12 S03'], ), ( 'test_next_series_seasons_season_pack_gap', ['Test", "'test_next_series_seasons_season_pack_from_start', ['Test Series 4 S02'], ['Test Series 4 S03'], ),", "[], ['Test Series 100 S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test", "next_series_seasons: yes series: - Test Series 1: <<: *series_ep_pack max_reruns:", "S02', 'Test Series 22 S03E01', 'Test Series 22 S06'], ['Test", "( [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S01'], ], [", "'Test Series 14 S05', 'Test Series 14 S04', 'Test Series", "max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series: - Test Series 16:", "next_series_seasons: yes series: - Test Series 19: <<: *series_ep_pack max_reruns:", "S02', 'Test Series 11 S03E01'], ['Test Series 11 S03', 'Test", "0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 17: <<:", "Series 16 S02', 'Test Series 16 S06'], ['Test Series 16", "backfill begin: s02e01 season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01", "Test Series 21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start", "Series 20 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21", "18 S07', 'Test Series 18 S05', 'Test Series 18 S04'],", "19 S02', 'Test Series 19 S06', 'Test Series 19 S07E01'],", "global: parsing: series: internal anchors: _nss_backfill: &nss_backfill next_series_seasons: backfill: yes", "100 test_next_series_seasons_season_pack: next_series_seasons: yes series: - Test Series 1: <<:", "2 S01', 'Test Series 2 S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test", "S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test Series 2 S02'], ['Test Series 2", "0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 18: <<:", "Test Series 14: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill", "Series 18 S07', 'Test Series 18 S05', 'Test Series 18", "), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11 S02', 'Test Series 11", "Test Series 15 - Test Series 16 - Test Series", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series: - Test Series 19:", "Series 17 - Test Series 18 - Test Series 19", "23 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24 S02',", "run_parameter is a tuple of lists: [task name, list of", "Series 20 S06', 'Test Series 20 S07E01'], [ 'Test Series", "['Test Series 12 S02', 'Test Series 12 S03E01'], ['Test Series", "6 - Test Series 7 - Test Series 8 -", "- Test Series 14: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<:", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 11:", "next_series_seasons: yes series: - Test Series 50: identified_by: ep begin:", "Series 1 S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test Series 2 S02'], ['Test", "- Test Series 100: <<: *series_ep_pack max_reruns: 0 \"\"\" @pytest.fixture()", "task_name, inject, result_find): for entity_id in inject: self.inject_series(execute_task, entity_id) task", "test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes series: - Test Series 100: <<:", "inject, list of result(s) to find] @pytest.mark.parametrize( \"run_parameters\", [ (", "of result(s) to find] @pytest.mark.parametrize( \"run_parameters\", [ ( [ 'test_next_series_seasons_season_pack_from_start_multirun',", "Test Series 16: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start", "Series 2 S02'], ['Test Series 2 S01', 'Test Series 2", "20: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series: -", "'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3 S02'], ['Test Series 3 S03'], ),", "Series 2 S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3 S02'],", "2 - Test Series 3 - Test Series 4 -", "['Test Series 16 S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17", "25 - Test Series 50 - Test Series 100 test_next_series_seasons_season_pack:", "series: - Test Series 16: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill:", "<<: *nss_backfill series: - Test Series 8: <<: *series_ep_tracking_pack max_reruns:", "Series 10 S03E01'], ['Test Series 10 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill',", "yes tasks: inject_series: series: settings: test_series: season_packs: always test_series: -", "'Test Series 14 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series", "tracking: backfill begin: s02e01 season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s04e01:", "'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21 S02', 'Test Series 21 S06', 'Test", "['Test Series 15 S07', 'Test Series 15 S05', 'Test Series", "20 S04', 'Test Series 20 S03', 'Test Series 20 S01',", "- Test Series 4 - Test Series 5 - Test", "max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 5:", "builtins import * # noqa pylint: disable=unused-import, redefined-builtin import pytest", "23: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: -", "Series 18 S05', 'Test Series 18 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap',", "internal anchors: _nss_backfill: &nss_backfill next_series_seasons: backfill: yes _nss_from_start: &nss_from_start next_series_seasons:", "16 S02', 'Test Series 16 S06'], ['Test Series 16 S07'],", "Series 24 S07', 'Test Series 24 S05', 'Test Series 24", "@pytest.mark.parametrize( \"run_parameters\", [ ( [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100", "0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series: - Test Series 22: <<:", "= \"\"\" templates: global: parsing: series: internal anchors: _nss_backfill: &nss_backfill", "[ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun',", "&series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking: backfill begin: s02e01 season_packs: threshold: 1000", "next_series_seasons: from_start: yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill: yes from_start: yes", "50 - Test Series 100 test_next_series_seasons_season_pack: next_series_seasons: yes series: -", "Series 10 - Test Series 11 - Test Series 12", "*nss_backfill series: - Test Series 9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0", "yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking: backfill begin: s02e01 season_packs:", "division, absolute_import from builtins import * # noqa pylint: disable=unused-import,", "0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series: - Test Series 14: <<:", "S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin', ['Test Series 3 S02'], ['Test Series", "[task name, list of series ID(s) to inject, list of", "disable=unused-import, redefined-builtin import pytest from flexget.entry import Entry # TODO", "23 - Test Series 24 - Test Series 25 -", "Series 6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes series:", "max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series: - Test Series 50:", "), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9 S02', 'Test Series 9", "'Test Series 24 S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series: - Test Series", "*nss_from_start series: - Test Series 4: <<: *series_ep_pack max_reruns: 0", "return self._config def inject_series(self, execute_task, release_name): execute_task( 'inject_series', options={'inject': [Entry(title=release_name,", "Series 16 - Test Series 17 - Test Series 18", "import * # noqa pylint: disable=unused-import, redefined-builtin import pytest from", "0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series: - Test Series 2: <<:", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series", "( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11 S02', 'Test Series 11 S03E01'],", "'Test Series 18 S06'], ['Test Series 18 S07', 'Test Series", "S02'], ['Test Series 50 S03'], ), ], ) def test_next_series_seasons(self,", "list of result(s) to find] @pytest.mark.parametrize( \"run_parameters\", [ ( [", "'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23 S02', 'Test Series 23 S03E01', 'Test", "['Test Series 4 S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5", "\"\"\"Season packs aren't supported by guessit yet.\"\"\" return self._config def", "series: - Test Series 3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start:", "_nss_from_start: &nss_from_start next_series_seasons: from_start: yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill: yes", "flexget.entry import Entry # TODO Add more standard tests class", "len(task.all_entries) == len(result_find) # Tests which require multiple tasks to", "inject_series: series: settings: test_series: season_packs: always test_series: - Test Series", ") def test_next_series_seasons_multirun(self, execute_task, run_parameters): for this_test in run_parameters: for", "S06'], [ 'Test Series 14 S07', 'Test Series 14 S05',", "14 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15 S02',", "pylint: disable=unused-import, redefined-builtin import pytest from flexget.entry import Entry #", "begin: S02E01 season_packs: threshold: 1000 reject_eps: yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun:", "result_title in result_find: assert task.find_entry(title=result_title) assert len(task.all_entries) == len(result_find) #", "23 S07', 'Test Series 23 S05', 'Test Series 23 S04',", "Test Series 8 - Test Series 9 - Test Series", "Series 17 S03', 'Test Series 17 S01', ], ), (", "test_next_series_seasons_season_pack: next_series_seasons: yes series: - Test Series 1: <<: *series_ep_pack", "( 'test_next_series_seasons_season_pack_backfill', ['Test Series 2 S02'], ['Test Series 2 S01',", "5: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: -", "max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series: - Test Series 2:", "yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep tracking: backfill season_packs: threshold: 1000", "['Test Series 6 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep', ['Test Series 7", "4 S02'], ['Test Series 4 S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test", "entity_id) task = execute_task(task_name) for result_title in result_find: assert task.find_entry(title=result_title)", "Test Series 100: <<: *series_ep_pack max_reruns: 0 \"\"\" @pytest.fixture() def", "Series 12 S02', 'Test Series 12 S03E01'], ['Test Series 12", "test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 24: <<: *series_ep_tracking_pack_begin_s04e01", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test", "S07E01'], ['Test Series 21 S07', 'Test Series 21 S05', 'Test", "*nss_backfill series: - Test Series 21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0", "Series 16 S06'], ['Test Series 16 S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill',", "'inject_series', options={'inject': [Entry(title=release_name, url='')], 'disable_tracking': True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\", [", "'Test Series 24 S03E01', 'Test Series 24 S06'], ['Test Series", "], ) def test_next_series_seasons_multirun(self, execute_task, run_parameters): for this_test in run_parameters:", "Series 4 S02'], ['Test Series 4 S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill',", "Series 22 S06'], ['Test Series 22 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill',", "Test Series 100 test_next_series_seasons_season_pack: next_series_seasons: yes series: - Test Series", "23 S05', 'Test Series 23 S04', 'Test Series 23 S03',", "8 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9 S02', 'Test", "Series 9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series:", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series: - Test Series 10:", "series: - Test Series 23: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin:", "Test Series 12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes", "( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16 S02', 'Test Series 16 S06'],", "series: internal anchors: _nss_backfill: &nss_backfill next_series_seasons: backfill: yes _nss_from_start: &nss_from_start", "( 'test_next_series_seasons_season_pack_gap_backfill_and_begin', ['Test Series 15 S02', 'Test Series 15 S06'],", "url='')], 'disable_tracking': True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test Series", "0 test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series: - Test Series 10: <<:", "*series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series: - Test Series", "['Test Series 3 S02'], ['Test Series 3 S03'], ), (", "['Test Series 8 S02', 'Test Series 8 S03E01'], ['Test Series", "ep tracking: backfill begin: s02e01 season_packs: threshold: 1000 reject_eps: yes", "*nss_backfill series: - Test Series 14: <<: *series_ep_tracking_pack max_reruns: 0", "0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 6: <<:", "4 S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5 S02'], ['Test", "max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 18:", "13: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series: -", "S06'], [ 'Test Series 23 S07', 'Test Series 23 S05',", "'Test Series 7 S03E01'], ['Test Series 7 S03'], ), (", "Series 17: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series:", "15 S06'], ['Test Series 15 S07', 'Test Series 15 S05',", "max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series 6:", "Series 3 S03'], ), ( 'test_next_series_seasons_season_pack_from_start', ['Test Series 4 S02'],", "['Test Series 7 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8", "14 S04', 'Test Series 14 S03', 'Test Series 14 S01',", "- Test Series 7 - Test Series 8 - Test", "ep begin: S02E01 season_packs: threshold: 1000 reject_eps: yes max_reruns: 0", "23 S04', 'Test Series 23 S03', 'Test Series 23 S01',", "], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21 S02', 'Test Series", "Series 21 S05', 'Test Series 21 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start',", "S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill', ['Test Series 23 S02', 'Test Series", "Series 24 S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50 S02'],", "Series 20 - Test Series 21 - Test Series 22", "5 S03', 'Test Series 5 S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test", "18 S05', 'Test Series 18 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test", "21 - Test Series 22 - Test Series 23 -", "Test Series 19 - Test Series 20 - Test Series", "Series 24 S02', 'Test Series 24 S03E01', 'Test Series 24", "<<: *nss_backfill_from_start series: - Test Series 5: <<: *series_ep_tracking_pack max_reruns:", "S07', 'Test Series 24 S05', 'Test Series 24 S04'], ),", "0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 23: <<:", "19 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20 S02', 'Test", "aren't supported by guessit yet.\"\"\" return self._config def inject_series(self, execute_task,", "execute_task(this_test[0]) for result_title in this_test[2]: assert task.find_entry(title=result_title) assert len(task.all_entries) ==", "0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series: - Test Series 21: <<:", "S02'], ['Test Series 5 S03', 'Test Series 5 S01'], ),", "Series 23 S06'], [ 'Test Series 23 S07', 'Test Series", "entity_id) task = execute_task(this_test[0]) for result_title in this_test[2]: assert task.find_entry(title=result_title)", "series: - Test Series 18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap:", "0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes series: - Test Series 100:", "series: - Test Series 15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start:", "S03E01'], ['Test Series 8 S01', 'Test Series 8 S03'], ),", "Series 14: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series:", "['Test Series 50 S03'], ), ], ) def test_next_series_seasons(self, execute_task,", "Test Series 16 - Test Series 17 - Test Series", "yes series: - Test Series 7: <<: *series_ep_pack max_reruns: 0", "- Test Series 21 - Test Series 22 - Test", "[ 'Test Series 17 S07', 'Test Series 17 S05', 'Test", "1000 reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking: backfill begin:", "test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series: - Test Series 20: <<: *series_ep_tracking_pack", "def test_next_series_seasons(self, execute_task, task_name, inject, result_find): for entity_id in inject:", "- Test Series 5: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin: <<:", "*nss_backfill_from_start series: - Test Series 11: <<: *series_ep_tracking_pack max_reruns: 0", "max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series: - Test Series 14:", "2 S02'], ['Test Series 2 S01', 'Test Series 2 S03'],", "['Test Series 2 S02'], ['Test Series 2 S01', 'Test Series", "- Test Series 50 - Test Series 100 test_next_series_seasons_season_pack: next_series_seasons:", "['Test Series 24 S02', 'Test Series 24 S03E01', 'Test Series", "<<: *nss_backfill series: - Test Series 2: <<: *series_ep_tracking_pack max_reruns:", "== len(result_find) # Tests which require multiple tasks to be", "'Test Series 17 S06'], [ 'Test Series 17 S07', 'Test", "'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S02'], ], ) ], )", "'Test Series 23 S07', 'Test Series 23 S05', 'Test Series", "def test_next_series_seasons_multirun(self, execute_task, run_parameters): for this_test in run_parameters: for entity_id", "), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12 S02', 'Test Series 12", "S06'], ['Test Series 15 S07', 'Test Series 15 S05', 'Test", "'Test Series 19 S06', 'Test Series 19 S07E01'], ['Test Series", "tests class TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\" templates: global: parsing: series:", "test_next_series_seasons_season_pack_and_ep_from_start: <<: *nss_from_start series: - Test Series 10: <<: *series_ep_pack", "16 S06'], ['Test Series 16 S07'], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test", "0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes series: - Test Series 13: <<:", "test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series: - Test Series 14: <<: *series_ep_tracking_pack", "to find] @pytest.mark.parametrize( \"run_parameters\", [ ( [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test", "- Test Series 17 - Test Series 18 - Test", "begin: s02e01 season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by:", "S02'], ['Test Series 1 S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test Series 2", "<<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series: - Test", "( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10 S02', 'Test Series 10 S03E01'],", "0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<: *nss_backfill series: - Test Series 9: <<:", "'Test Series 8 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9", "['Test Series 7 S02', 'Test Series 7 S03E01'], ['Test Series", "'Test Series 17 S07', 'Test Series 17 S05', 'Test Series", "standard tests class TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\" templates: global: parsing:", "test_series: - Test Series 1 - Test Series 2 -", "- Test Series 23: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<:", "list of series ID(s) to inject, list of result(s) to", "), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test Series 8 S02', 'Test Series 8", "'Test Series 17 S05', 'Test Series 17 S04', 'Test Series", "S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11 S02', 'Test Series", "1: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<: *nss_backfill series: -", "Series 7: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series:", "20 S06', 'Test Series 20 S07E01'], [ 'Test Series 20", "Series 22 S03E01', 'Test Series 22 S06'], ['Test Series 22", "( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50 S02'], ['Test Series 50 S03'],", "S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21 S02', 'Test", "Series 11 S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12 S02',", "threshold: 1000 reject_eps: yes tasks: inject_series: series: settings: test_series: season_packs:", "7 S02', 'Test Series 7 S03E01'], ['Test Series 7 S03'],", "'Test Series 22 S06'], ['Test Series 22 S07'], ), (", "- Test Series 9 - Test Series 10 - Test", "series: - Test Series 6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep:", "entity_id in this_test[1]: self.inject_series(execute_task, entity_id) task = execute_task(this_test[0]) for result_title", "yes series: - Test Series 19: <<: *series_ep_pack max_reruns: 0", "season_packs: always test_series: - Test Series 1 - Test Series", "Test Series 23 - Test Series 24 - Test Series", "14 S07', 'Test Series 14 S05', 'Test Series 14 S04',", "Test Series 11: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start", "Test Series 17: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start", "Series 17 S02', 'Test Series 17 S06'], [ 'Test Series", "this_test[1]: self.inject_series(execute_task, entity_id) task = execute_task(this_test[0]) for result_title in this_test[2]:", "<<: *nss_from_start series: - Test Series 22: <<: *series_ep_pack max_reruns:", "S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22 S02', 'Test Series", "21 S07E01'], ['Test Series 21 S07', 'Test Series 21 S05',", "order # Each run_parameter is a tuple of lists: [task", "12 S02', 'Test Series 12 S03E01'], ['Test Series 12 S03'],", "_config = \"\"\" templates: global: parsing: series: internal anchors: _nss_backfill:", "identified_by: ep tracking: backfill begin: s02e01 season_packs: threshold: 1000 reject_eps:", "S06'], [ 'Test Series 17 S07', 'Test Series 17 S05',", "S03E01'], ['Test Series 10 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series", "executed in order # Each run_parameter is a tuple of", "S02', 'Test Series 13 S06'], ['Test Series 13 S07'], ),", "Series 5 - Test Series 6 - Test Series 7", "def config(self): \"\"\"Season packs aren't supported by guessit yet.\"\"\" return", "'test_next_series_seasons_season_pack_backfill', ['Test Series 2 S02'], ['Test Series 2 S01', 'Test", "15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series: -", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series: - Test Series", "next_series_seasons: from_start: yes series: - Test Series 100: <<: *series_ep_pack", "Series 3 S02'], ['Test Series 3 S03'], ), ( 'test_next_series_seasons_season_pack_from_start',", "S02', 'Test Series 23 S03E01', 'Test Series 23 S06'], [", "next_series_seasons: backfill: yes from_start: yes _series_ep_pack: &series_ep_pack identified_by: ep tracking:", "S02'], ['Test Series 3 S03'], ), ( 'test_next_series_seasons_season_pack_from_start', ['Test Series", "'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18 S02', 'Test Series 18 S06'], ['Test", "], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24 S02', 'Test Series", "Test Series 25 - Test Series 50 - Test Series", "# Each run_parameter is a tuple of lists: [task name,", "*series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test Series", "Series 10: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series:", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test", "Series 20: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin: <<: *nss_backfill series:", "Series 12 S03E01'], ['Test Series 12 S03'], ), ( 'test_next_series_seasons_season_pack_gap',", "this_test in run_parameters: for entity_id in this_test[1]: self.inject_series(execute_task, entity_id) task", "<<: *nss_backfill_from_start series: - Test Series 12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns:", "S04', 'Test Series 20 S03', 'Test Series 20 S01', ],", "Series 15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start series:", "Test Series 13 - Test Series 14 - Test Series", "15 S05', 'Test Series 15 S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test", "0 test_next_series_seasons_season_pack_and_ep_backfill: <<: *nss_backfill series: - Test Series 8: <<:", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test", "Series 20 S04', 'Test Series 20 S03', 'Test Series 20", "Series 23 S05', 'Test Series 23 S04', 'Test Series 23", "( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5 S02'], ['Test Series 5 S03',", "Series 14 S06'], [ 'Test Series 14 S07', 'Test Series", "ID(s) to inject, list of result(s) to find] @pytest.mark.parametrize( \"run_parameters\",", "# Tests which require multiple tasks to be executed in", "Test Series 18 - Test Series 19 - Test Series", "threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking: backfill", "), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6 S02'], ['Test Series 6", "Series 21 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22 S02',", "yes _nss_from_start: &nss_from_start next_series_seasons: from_start: yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill:", "Test Series 3 - Test Series 4 - Test Series", "in inject: self.inject_series(execute_task, entity_id) task = execute_task(task_name) for result_title in", "S07', 'Test Series 20 S05', 'Test Series 20 S04', 'Test", "S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series 50 S02'], ['Test Series", "backfill begin: s04e01 season_packs: threshold: 1000 reject_eps: yes tasks: inject_series:", "3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series: -", "- Test Series 1: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill: <<:", "22 S03E01', 'Test Series 22 S06'], ['Test Series 22 S07'],", "S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24 S02', 'Test", "to be executed in order # Each run_parameter is a", "'Test Series 23 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series", "S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20 S02', 'Test Series", "yes from_start: yes _series_ep_pack: &series_ep_pack identified_by: ep tracking: backfill season_packs:", "Test Series 2 - Test Series 3 - Test Series", "- Test Series 13 - Test Series 14 - Test", "*nss_from_start series: - Test Series 16: <<: *series_ep_pack max_reruns: 0", "Series 14 S03', 'Test Series 14 S01', ], ), (", "'Test Series 20 S07E01'], [ 'Test Series 20 S07', 'Test", "&series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking: backfill begin: s04e01 season_packs: threshold: 1000", "Series 11 - Test Series 12 - Test Series 13", "max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 23:", "Series 14 S02', 'Test Series 14 S06'], [ 'Test Series", "'Test Series 13 S06'], ['Test Series 13 S07'], ), (", "task.find_entry(title=result_title) assert len(task.all_entries) == len(result_find) # Tests which require multiple", "*series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes series: - Test Series", "21 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22 S02', 'Test", "anchors: _nss_backfill: &nss_backfill next_series_seasons: backfill: yes _nss_from_start: &nss_from_start next_series_seasons: from_start:", "Series 19 - Test Series 20 - Test Series 21", "15 S02', 'Test Series 15 S06'], ['Test Series 15 S07',", "S03', 'Test Series 5 S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series", "S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19 S02', 'Test Series", "Test Series 12 - Test Series 13 - Test Series", "backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep", "Series 12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap: next_series_seasons: yes series:", "- Test Series 18: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons:", "S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S02'], ],", "- Test Series 8: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill_and_begin: <<:", "_nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill: yes from_start: yes _series_ep_pack: &series_ep_pack identified_by:", "Series 7 - Test Series 8 - Test Series 9", "- Test Series 23 - Test Series 24 - Test", "Series 4 S03'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5 S02'],", "), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series 21 S02', 'Test Series 21", "self.inject_series(execute_task, entity_id) task = execute_task(task_name) for result_title in result_find: assert", "8 S01', 'Test Series 8 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test", "['Test Series 19 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test Series 20", "*series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series: - Test Series", "ep tracking: backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01", "<<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap: next_series_seasons: yes series: - Test", "['Test Series 11 S02', 'Test Series 11 S03E01'], ['Test Series", "9 S02', 'Test Series 9 S03E01'], ['Test Series 9 S03'],", "'Test Series 23 S04', 'Test Series 23 S03', 'Test Series", "identified_by: ep begin: S02E01 season_packs: threshold: 1000 reject_eps: yes max_reruns:", ") @pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test Series 1 S02'], ['Test", "entity_id in inject: self.inject_series(execute_task, entity_id) task = execute_task(task_name) for result_title", "S03', 'Test Series 20 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test", "series: - Test Series 12: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_gap:", "Series 1 - Test Series 2 - Test Series 3", "S02', 'Test Series 7 S03E01'], ['Test Series 7 S03'], ),", "['Test Series 10 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill', ['Test Series 11", "'test_next_series_seasons_season_pack_from_start_backfill', ['Test Series 5 S02'], ['Test Series 5 S03', 'Test", "test_series: season_packs: always test_series: - Test Series 1 - Test", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series", "max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series 17:", "*series_ep_pack max_reruns: 0 \"\"\" @pytest.fixture() def config(self): \"\"\"Season packs aren't", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series: - Test", "3 S03'], ), ( 'test_next_series_seasons_season_pack_from_start', ['Test Series 4 S02'], ['Test", "Series 4 - Test Series 5 - Test Series 6", "<<: *nss_backfill_from_start series: - Test Series 23: <<: *series_ep_tracking_pack max_reruns:", "Series 8 S03E01'], ['Test Series 8 S01', 'Test Series 8", "['Test Series 9 S02', 'Test Series 9 S03E01'], ['Test Series", "Series 18 S06'], ['Test Series 18 S07', 'Test Series 18", "Series 20 S03', 'Test Series 20 S01', ], ), (", "20 S05', 'Test Series 20 S04', 'Test Series 20 S03',", "Series 15 S05', 'Test Series 15 S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start',", "Series 23 S04', 'Test Series 23 S03', 'Test Series 23", "Series 21 - Test Series 22 - Test Series 23", "1000 reject_eps: yes tasks: inject_series: series: settings: test_series: season_packs: always", "'test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin', ['Test Series 24 S02', 'Test Series 24 S03E01', 'Test", "16: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<: *nss_backfill_from_start series: -", "Series 19: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series:", "series: - Test Series 11: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin:", "S02'], ], ) ], ) def test_next_series_seasons_multirun(self, execute_task, run_parameters): for", "in this_test[1]: self.inject_series(execute_task, entity_id) task = execute_task(this_test[0]) for result_title in", "18 S02', 'Test Series 18 S06'], ['Test Series 18 S07',", "19: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series: -", "S02', 'Test Series 21 S06', 'Test Series 21 S07E01'], ['Test", "'Test Series 23 S06'], [ 'Test Series 23 S07', 'Test", "S02', 'Test Series 14 S06'], [ 'Test Series 14 S07',", "series ID(s) to inject, list of result(s) to find] @pytest.mark.parametrize(", "'Test Series 23 S03', 'Test Series 23 S01', ], ),", "parsing: series: internal anchors: _nss_backfill: &nss_backfill next_series_seasons: backfill: yes _nss_from_start:", "Series 18 - Test Series 19 - Test Series 20", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill_and_begin: <<: *nss_backfill_from_start series: - Test", "Series 6 - Test Series 7 - Test Series 8", "['Test Series 50 S02'], ['Test Series 50 S03'], ), ],", "Series 21: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start: <<: *nss_from_start series:", "Series 17 S06'], [ 'Test Series 17 S07', 'Test Series", "Series 22 S02', 'Test Series 22 S03E01', 'Test Series 22", "14: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series: -", "<<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series: - Test", "19 S07E01'], ['Test Series 19 S07'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill', ['Test", "S02', 'Test Series 15 S06'], ['Test Series 15 S07', 'Test", "Series 15 S07', 'Test Series 15 S05', 'Test Series 15", "Series 18 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap', ['Test Series 19 S02',", "22 S02', 'Test Series 22 S03E01', 'Test Series 22 S06'],", "11 S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin', ['Test Series 12 S02', 'Test", "<<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill_and_begin: <<: *nss_backfill series: - Test", "4: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series: -", "Test Series 22: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start", "['Test Series 14 S02', 'Test Series 14 S06'], [ 'Test", "S05', 'Test Series 14 S04', 'Test Series 14 S03', 'Test", "Series 11 S03', 'Test Series 11 S01'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin',", "inject, result_find): for entity_id in inject: self.inject_series(execute_task, entity_id) task =", "- Test Series 12 - Test Series 13 - Test", "Series 9 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10 S02',", "class TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\" templates: global: parsing: series: internal", "Series 15 S04'], ), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16 S02',", "S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6 S02'], ['Test Series", "S05', 'Test Series 20 S04', 'Test Series 20 S03', 'Test", "S04', 'Test Series 17 S03', 'Test Series 17 S01', ],", "- Test Series 11: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start_backfill_and_begin: <<:", "Test Series 15: <<: *series_ep_tracking_pack_begin_s04e01 max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start: <<: *nss_from_start", "0 test_next_series_seasons_season_pack_and_ep_gap_backfill: <<: *nss_backfill series: - Test Series 20: <<:", "*nss_backfill series: - Test Series 20: <<: *series_ep_tracking_pack max_reruns: 0", "series: - Test Series 7: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_backfill:", "Series 5 S01'], ), ( 'test_next_series_seasons_season_pack_from_start_backfill_and_begin', ['Test Series 6 S02'],", "S02', 'Test Series 17 S06'], [ 'Test Series 17 S07',", "series: - Test Series 2: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin:", "\"run_parameters\", [ ( [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S01'],", "'Test Series 20 S01', ], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_backfill_and_begin', ['Test Series", "], ) ], ) def test_next_series_seasons_multirun(self, execute_task, run_parameters): for this_test", "templates: global: parsing: series: internal anchors: _nss_backfill: &nss_backfill next_series_seasons: backfill:", "S05', 'Test Series 24 S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test Series", "23 S06'], [ 'Test Series 23 S07', 'Test Series 23", "Series 23 - Test Series 24 - Test Series 25", "'Test Series 21 S05', 'Test Series 21 S04'], ), (", "['Test Series 100 S01'], ], [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series", "self.inject_series(execute_task, entity_id) task = execute_task(this_test[0]) for result_title in this_test[2]: assert", "'test_next_series_seasons_season_pack_gap_from_start_backfill', ['Test Series 17 S02', 'Test Series 17 S06'], [", "), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test Series 22 S02', 'Test Series 22", "Series 50 - Test Series 100 test_next_series_seasons_season_pack: next_series_seasons: yes series:", "['Test Series 20 S02', 'Test Series 20 S06', 'Test Series", "<<: *nss_backfill series: - Test Series 20: <<: *series_ep_tracking_pack max_reruns:", "name, list of series ID(s) to inject, list of result(s)", "season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep tracking:", "identified_by: ep tracking: backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_begin_s02e01:", "Series 14 S07', 'Test Series 14 S05', 'Test Series 14", "Series 17 S04', 'Test Series 17 S03', 'Test Series 17", "Series 100 test_next_series_seasons_season_pack: next_series_seasons: yes series: - Test Series 1:", "Series 10 S02', 'Test Series 10 S03E01'], ['Test Series 10", "threshold: 1000 reject_eps: yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons: from_start: yes", "Series 18 S02', 'Test Series 18 S06'], ['Test Series 18", "21 S07', 'Test Series 21 S05', 'Test Series 21 S04'],", "_series_ep_tracking_begin_s04e01: &series_ep_tracking_pack_begin_s04e01 identified_by: ep tracking: backfill begin: s04e01 season_packs: threshold:", "Test Series 50 - Test Series 100 test_next_series_seasons_season_pack: next_series_seasons: yes", "19 S06', 'Test Series 19 S07E01'], ['Test Series 19 S07'],", "Series 7 S02', 'Test Series 7 S03E01'], ['Test Series 7", "threshold: 1000 reject_eps: yes _series_ep_tracking_pack: &series_ep_tracking_pack identified_by: ep tracking: backfill", "'disable_tracking': True}, ) @pytest.mark.parametrize( \"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test Series 1", "['Test Series 9 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_from_start', ['Test Series 10", "['Test Series 11 S03', 'Test Series 11 S01'], ), (", "Series 24 S05', 'Test Series 24 S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed',", "series: - Test Series 5: <<: *series_ep_tracking_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill_and_begin:", "Series 50 S03'], ), ], ) def test_next_series_seasons(self, execute_task, task_name,", "7 S03E01'], ['Test Series 7 S03'], ), ( 'test_next_series_seasons_season_pack_and_ep_backfill', ['Test", "21 S05', 'Test Series 21 S04'], ), ( 'test_next_series_seasons_season_pack_and_ep_gap_from_start', ['Test", "24 S05', 'Test Series 24 S04'], ), ( 'test_next_series_seasons_season_pack_begin_completed', ['Test", "Tests which require multiple tasks to be executed in order", "], [ 'test_next_series_seasons_season_pack_from_start_multirun', [], ['Test Series 100 S02'], ], )", "['Test Series 1 S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test Series 2 S02'],", "more standard tests class TestNextSeriesSeasonSeasonsPack(object): _config = \"\"\" templates: global:", "* # noqa pylint: disable=unused-import, redefined-builtin import pytest from flexget.entry", "<<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_backfill: <<: *nss_backfill series: - Test", "['Test Series 3 S03'], ), ( 'test_next_series_seasons_season_pack_from_start', ['Test Series 4", "series: - Test Series 22: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill:", "\"task_name,inject,result_find\", [ ('test_next_series_seasons_season_pack', ['Test Series 1 S02'], ['Test Series 1", "Series 3: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_from_start: <<: *nss_from_start series:", "Series 22: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_and_ep_gap_from_start_backfill: <<: *nss_backfill_from_start series:", "1 S03']), ( 'test_next_series_seasons_season_pack_backfill', ['Test Series 2 S02'], ['Test Series", "['Test Series 5 S03', 'Test Series 5 S01'], ), (", "S02E01 season_packs: threshold: 1000 reject_eps: yes max_reruns: 0 test_next_series_seasons_season_pack_from_start_multirun: next_series_seasons:", "Series 13 S02', 'Test Series 13 S06'], ['Test Series 13", "17 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_from_start_backfill_and_begin', ['Test Series 18 S02',", "execute_task(task_name) for result_title in result_find: assert task.find_entry(title=result_title) assert len(task.all_entries) ==", "identified_by: ep tracking: backfill season_packs: threshold: 1000 reject_eps: yes _series_ep_tracking_pack:", "series: - Test Series 9: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep_from_start:", "yes _series_ep_pack: &series_ep_pack identified_by: ep tracking: backfill season_packs: threshold: 1000", "- Test Series 22 - Test Series 23 - Test", "'test_next_series_seasons_season_pack_and_ep_backfill_and_begin', ['Test Series 9 S02', 'Test Series 9 S03E01'], ['Test", "in order # Each run_parameter is a tuple of lists:", "Test Series 14 - Test Series 15 - Test Series", "reject_eps: yes _series_ep_tracking_begin_s02e01: &series_ep_tracking_pack_begin_s02e01 identified_by: ep tracking: backfill begin: s02e01", "_series_ep_pack: &series_ep_pack identified_by: ep tracking: backfill season_packs: threshold: 1000 reject_eps:", "['Test Series 6 S02'], ['Test Series 6 S03'], ), (", "20 S02', 'Test Series 20 S06', 'Test Series 20 S07E01'],", "&nss_from_start next_series_seasons: from_start: yes _nss_backfill_from_start: &nss_backfill_from_start next_series_seasons: backfill: yes from_start:", "Test Series 6: <<: *series_ep_tracking_pack_begin_s02e01 max_reruns: 0 test_next_series_seasons_season_pack_and_ep: next_series_seasons: yes", "*series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_from_start_backfill: <<: *nss_backfill_from_start series: - Test Series", "0 test_next_series_seasons_season_pack_begin_completed: next_series_seasons: yes series: - Test Series 50: identified_by:", "- Test Series 16: <<: *series_ep_pack max_reruns: 0 test_next_series_seasons_season_pack_gap_from_start_backfill: <<:", "- Test Series 20 - Test Series 21 - Test", "noqa pylint: disable=unused-import, redefined-builtin import pytest from flexget.entry import Entry", "Series 8 - Test Series 9 - Test Series 10", "Series 17 S07', 'Test Series 17 S05', 'Test Series 17", "17 S04', 'Test Series 17 S03', 'Test Series 17 S01',", "which require multiple tasks to be executed in order #", "yet.\"\"\" return self._config def inject_series(self, execute_task, release_name): execute_task( 'inject_series', options={'inject':", "), ( 'test_next_series_seasons_season_pack_gap_from_start', ['Test Series 16 S02', 'Test Series 16", "['Test Series 1 S02'], ['Test Series 1 S03']), ( 'test_next_series_seasons_season_pack_backfill',", "14 S03', 'Test Series 14 S01', ], ), ( 'test_next_series_seasons_season_pack_gap_backfill_and_begin',", "S07', 'Test Series 14 S05', 'Test Series 14 S04', 'Test", "Series 2 S01', 'Test Series 2 S03'], ), ( 'test_next_series_seasons_season_pack_backfill_and_begin',", "max_reruns: 0 test_next_series_seasons_season_pack_backfill_and_begin: <<: *nss_backfill series: - Test Series 3:" ]
[ "\"\"\" Given a list of coords for 3 points, Compute", "= miller self.points = [] self.outer_lines = [] class WulffShape:", "of the Wulffshape when the Wulffshape is approximated as a", "energies, and the total area and volume of the wulff", "# 3. consider the dual condition dual_pts = [x.dual_pt for", "= 1, e_surf is plane's distance to (0, 0, 0),", "self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl, energy) in enumerate(zip(self.hkl_list,", "|normal| = 1, e_surf is plane's distance to (0, 0,", "ranges of x, y, z # find the largest distance", "is plane's distance to (0, 0, 0), plane function: normal[0]x", ".. attribute:: on_wulff list for all input_miller, True is on", "plot from the sorted pts from [simpx] tri = mpl3.art3d.Poly3DCollection([pt])", "shape. \"\"\" return sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl", "off wulff .. attribute:: structure Structure object, input conventional unit", "dual_cv_simp simplices from the dual convex hull (dual_pt) .. attribute::", "* area_hkl)/ sum(area_hkl) \"\"\" return self.total_surface_energy / self.surface_area @property def", "lines.pop(i) if l[1] == prev: l.reverse() break # make sure", "alpha transparency .. attribute:: color_set .. attribute:: grid_off (bool) ..", "energy, the anisotropy and shape_factor can also be calculated. In", "class to generate the Wulff shape from a lattice, a", "reverse=False) e_surf_on_wulff_list = [x[1] for x in e_surf_on_wulff] if len(e_surf_on_wulff)", "1 (float), default is 1 off_color: Default color for facets", "= [] miller_on_wulff = [] e_surf_on_wulff = [(i, e_surf) for", "\"\"\" Volume of the Wulff shape \"\"\" return self.wulff_convex.volume @property", "z # find the largest distance between on_wulff pts and", "__copyright__ = 'Copyright 2013, The Materials Virtual Lab' __version__ =", "simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) # already find the plane,", "Returns the number of vertices in the convex hull. Useful", "total area on wulff, off_wulff = 0. .. attribute:: miller_area", "wulff_pt_list .. attribute:: wulff_cv_simp simplices from the convex hull of", "l = lines.pop(0) else: for i, l in enumerate(lines): if", "hkl: if x < 0: str_format += '\\\\overline{' + str(-x)", "...]: list of hkl or hkil for hcp e_surf_list ([float]):", "0, 0), normal[0]x + normal[1]y + normal[2]z = e_surf return:", "is from the conventional unit cell, and (hkil) for hexagonal", "pts[2] v1 = np.array(b) - np.array(a) v2 = np.array(c) -", "def _get_simpx_plane(self): \"\"\" Locate the plane for simpx of on", "with the plane functions. \"\"\" on_wulff = [False] * len(self.miller_list)", "miller_area ($hkl$): area for all input_miller \"\"\" def __init__(self, lattice,", "True axis_off (bool): default is Ture show_area (bool): default is", "warnings __author__ = '<NAME>, <NAME>, <NAME>' __copyright__ = 'Copyright 2013,", "The ideal sphere is 0. \"\"\" square_diff_energy = 0 weighted_energy", "for determining the critical nucleus size. A large shape factor", "with a dictionary. The key is the corresponding Miller index", "miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl] - weighted_energy) \\ ** 2 *", "it probably won't make any sense to have the color", "color for facets not present on the Wulff shape. direction:", "@property def effective_radius(self): \"\"\" Radius of the Wulffshape when the", "find the way covering all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist())", "input lattice for the conventional unit cell .. attribute:: facets", "= list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x) for x in miller_list] #", "Ture show_area (bool): default is False alpha (float): chosen from", "azim=azim, elev=elev) for plane in self.facets: # check whether [pts]", "distance to (0, 0, 0), normal[0]x + normal[1]y + normal[2]z", "of vertices in the convex hull. Useful for identifying catalytically", "not direction: # If direction is not specified, use the", "distance between on_wulff pts and the origin, # to ensure", "get all the miller index, then get normal, get all", "on_wulff, surface_area def _get_colors(self, color_set, alpha, off_color, custom_colors={}): \"\"\" assign", "sphere is 0. \"\"\" square_diff_energy = 0 weighted_energy = self.weighted_surface_energy", "Copyright (c) Pymatgen Development Team. # Distributed under the terms", "(0, 0, 0), normal[0]x + normal[1]y + normal[2]z = e_surf", "# get cross point from the simplices of the dual", "the lines are connected one by one. # find the", "self.normal_pt = normal_pt self.dual_pt = dual_pt self.index = index self.m_ind_orig", "Scientific Data. \"\"\" from pymatgen.core.structure import Structure from pymatgen.util.coord import", "= get_angle([cart[0], cart[1], 0], (1, 0, 0)) v = [cart[0],", "cell (with H ) from lattice .. attribute:: miller_list list", "<NAME>. (2016). Surface energies of elemental crystals. Scientific Data. \"\"\"", ".. attribute:: dual_cv_simp simplices from the dual convex hull (dual_pt)", "sphere. Returns: (float) radius. \"\"\" return ((3 / 4) *", "of input miller index, for hcp in the form of", "l: l = lines.pop(i) if l[1] == prev: l.reverse() break", "return pt def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red',", "* 1.1, r_range * 1.1]) ax.set_ylim([-r_range * 1.1, r_range *", "attribute:: grid_off (bool) .. attribute:: axis_off (bool) .. attribute:: show_area", "Structure from pymatgen.util.coord import get_angle import numpy as np import", "def get_line_in_facet(self, facet): \"\"\" Returns the sorted pts in a", "miller_index == (0, 0, 0, 1): return 0, 90 else:", "p in enumerate(lines): if p not in all_edges: edges.append(p) all_edges.extend(edges)", "def surface_area(self): \"\"\" Total surface area of Wulff shape. \"\"\"", "abs_diff < 1e-5: on_wulff[plane.index] = True surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts)", "the color_list for on_wulff plane_color = color_list[plane.index] pt = self.get_line_in_facet(plane)", "Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl) \"\"\" tot_surface_energy =", "0], (1, 0, 0)) v = [cart[0], cart[1], 0] elev", "facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\" import matplotlib", "\"\"\" if miller_index == (0, 0, 1) or miller_index ==", "unit cell .. attribute:: facets [WulffFacet] for all facets considering", "<NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. (2016). Surface energies of", "modify hkill to hkl, in the same order with input_miller", "is True aspect_ratio: default is (8, 8) custom_colors ({(h,k,l}: [r,g,b,alpha}):", "= tuple([int(x) for x in op.operate(hkl)]) if miller not in", "in color_list] return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def show(self,", "bounds + [10], extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical') units = \"$J/m^2$\"", "__init__(self, normal, e_surf, normal_pt, dual_pt, index, m_ind_orig, miller): \"\"\" :param", "surface energies, with given conventional unit cell. surface energy (Jm^2)", "on_wulff list for all input_miller, True is on wulff. ..", "self.dual_cv_simp = dual_cv_simp self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp = wulff_cv_simp self.wulff_convex", "tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set ranges of", "for hcp e_surf_list ([float]): list of corresponding surface energies symprec", "# add legend if legend_on: color_proxy = color_proxy if show_area:", "else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True, shadow=False)", "determining the critical nucleus size. A large shape factor indicates", ".. attribute:: hkl_list modify hkill to hkl, in the same", "all facets considering symm .. attribute:: dual_cv_simp simplices from the", "Returns: (float) Shape factor. \"\"\" return self.surface_area / (self.volume **", "Data. \"\"\" from pymatgen.core.structure import Structure from pymatgen.util.coord import get_angle", "for all input_miller, total area on wulff, off_wulff = 0.", "= lattice self.symprec = symprec # 2. get all the", ":param dual_pt: :param index: :param m_ind_orig: :param miller: \"\"\" self.normal", "the length of normal. Wulff shape is the convex hull.", "self.structure = Structure(lattice, [\"H\"], [[0, 0, 0]]) self.miller_list = tuple([tuple(x)", "\"\"\" Get the Wulff shape plot. Args: color_set: default is", "op.operate(hkl)]) if miller not in all_hkl: all_hkl.append(miller) normal = recp.get_cartesian_coords(miller)", "and volume of the wulff shape,the weighted surface energy, the", "r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)' % (units), fontsize=100) if grid_off: ax.grid('off')", "miller index, then get normal, get all the facets functions", "1): return 0, 90 else: cart = self.lattice.get_cartesian_coords(miller_index) azim =", "= plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds = [round(e, 2) for e", "[plt.Rectangle((2, 2), 1, 1, fc=x, alpha=alpha) for x in color_list]", "for hkl in miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl] - weighted_energy) \\", "cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map =", "# If direction is not specified, use the miller indices", "of coords for 3 points, Compute the area of this", "0: str_format += '\\\\overline{' + str(-x) + '}' else: str_format", "ideal sphere is 0. \"\"\" square_diff_energy = 0 weighted_energy =", "not on_wulff. continue # assign the color for on_wulff facets", "unit cell. surface energy (Jm^2) is the length of normal.", "# recalculate the dual of dual, get the wulff shape.", "se in e_surf_list]): warnings.warn(\"Unphysical (negative) surface energy detected.\") self.color_ind =", "function: normal[0]x + normal[1]y + normal[2]z = e_surf from self:", "matplotlib as mpl import matplotlib.pyplot as plt color_list = [off_color]", "# Add colorbar if bar_on: cmap = plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75')", "normal. Wulff shape is the convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html", "mpl import matplotlib.pyplot as plt color_list = [off_color] * len(self.hkl_list)", "area_fraction_dict(self): \"\"\" Returns: (dict): {hkl: area_hkl/total area on wulff} \"\"\"", "scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append(", "a line \"\"\" lines = list(facet.outer_lines) pt = [] prev", "energies, with given conventional unit cell. surface energy (Jm^2) is", "of on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\"", "for wulff shape calculation: |normal| = 1, e_surf is plane's", "simplices is on one plane for plane in self.facets: abs_diff", "Returns: (dict): {hkl: area_hkl/total area on wulff} \"\"\" return {hkl:", "plane, move to the next simplices break for plane in", "cell .. attribute:: facets [WulffFacet] for all facets considering symm", "pts[1], pts[2] v1 = np.array(b) - np.array(a) v2 = np.array(c)", "is 0. \"\"\" square_diff_energy = 0 weighted_energy = self.weighted_surface_energy area_frac_dict", "lattice, miller_list, e_surf_list, symprec=1e-5): \"\"\" Args: lattice: Lattice object of", "in a facet used to draw a line \"\"\" lines", "and other properties .. attribute:: debug (bool) .. attribute:: alpha", "the wulff shape. # conner <-> surface # get cross", "input miller index, for hcp in the form of hkil", "in plane.outer_lines if plane.outer_lines.count(line) != 2] return on_wulff, surface_area def", "# check whether the center of the simplices is on", "plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds = [round(e, 2) for e in", "in normal] color_plane = color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt, dual_pt,", "\"\"\" Returns: sum(surface_energy_hkl * area_hkl)/ sum(area_hkl) \"\"\" return self.total_surface_energy /", "Distributed under the terms of the MIT License. \"\"\" This", "[] recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl,", "return cross_pt def _get_simpx_plane(self): \"\"\" Locate the plane for simpx", "surface energy_hkl} \"\"\" return dict(zip(self.miller_list, self.e_surf_list)) @property def surface_area(self): \"\"\"", "mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm, boundaries=[0] + bounds + [10], extend='both',", "* len(self.miller_list) for simpx in self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]] for", "Energies (%s)' % (units), fontsize=100) if grid_off: ax.grid('off') if axis_off:", "5 2016' logger = logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\" Prepare for", "only one hkl on wulff, choose the color of the", "% (units), fontsize=100) if grid_off: ax.grid('off') if axis_off: ax.axis('off') return", "(miller_energy_dict[hkl] - weighted_energy) \\ ** 2 * area_frac_dict[hkl] return np.sqrt(square_diff_energy)", "l) \"\"\" str_format = '($' for x in hkl: if", "miller_index: viewing direction Returns: azim, elev for plotting \"\"\" if", ".. attribute:: off_color color of facets off wulff .. attribute::", "center) - plane.e_surf) if abs_diff < 1e-5: on_wulff[plane.index] = True", "self.facets = self._get_all_miller_e() logger.debug(len(self.facets)) # 3. consider the dual condition", "prev: l.reverse() break # make sure the lines are connected", "# conner <-> surface # get cross point from the", "dict(zip(self.miller_list, self.color_area)) @property def miller_energy_dict(self): \"\"\" Returns {hkl: surface energy_hkl}", "plt color_list = [off_color] * len(self.hkl_list) color_proxy_on_wulff = [] miller_on_wulff", "1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x in e_surf_on_wulff]) color_proxy", "(ndarray of ints, shape (nfacet, ndim)) # list of [i,", "of hkil .. attribute:: hkl_list modify hkill to hkl, in", "[] for m, in_mill_fig in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig + '", "surface energy The ideal sphere is 0. \"\"\" square_diff_energy =", "ticks=bounds[:-1], spacing='proportional', orientation='vertical') units = \"$J/m^2$\" if units_in_JPERM2 else r\"$eV/\\AA^2$\"", "/ 3) @property def total_surface_energy(self): \"\"\" Total surface energy of", "surface energy, the anisotropy and shape_factor can also be calculated.", "use default color site. Note: If you decide to set", "i, j, k: plane index(same order in normal_e_m) \"\"\" matrix_surfs", "points, Compute the area of this triangle. Args: pts: [a,", "\"\"\" all_hkl = [] color_ind = self.color_ind planes = []", "np.pi)) ** (1 / 3) @property def total_surface_energy(self): \"\"\" Total", "edges = [] pt = self.get_line_in_facet(facet) lines = [] for", "shape is the convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1.", "whether the center of the simplices is on one plane", "surface_area(self): \"\"\" Total surface area of Wulff shape. \"\"\" return", "hull. Useful for identifying catalytically active sites. \"\"\" all_edges =", "+ normal[1]y + normal[2]z = e_surf return: [WulffFacet] \"\"\" all_hkl", "for x in normal] color_plane = color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy,", "already find the plane, move to the next simplices break", "support of plotting from a given view in terms of", "Radius of the Wulffshape when the Wulffshape is approximated as", "plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) # already find the plane, move", "on. Return: (matplotlib.pyplot) \"\"\" import matplotlib as mpl import matplotlib.pyplot", "is the length of normal. Wulff shape is the convex", "for i, p in enumerate(lines): if p not in all_edges:", "area of Wulff shape. \"\"\" return sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self):", "* bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # display surface energies", "the median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list) + 0.1)", "normal, get all the facets functions for wulff shape calculation:", "= abs(np.dot(plane.normal, center) - plane.e_surf) if abs_diff < 1e-5: on_wulff[plane.index]", "\"\"\" on_wulff = [False] * len(self.miller_list) surface_area = [0.0] *", "r_range * 1.1]) ax.set_ylim([-r_range * 1.1, r_range * 1.1]) ax.set_zlim([-r_range", "Wulff shape is the convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process:", "will use default color site. Note: If you decide to", "in e_surf_list]): warnings.warn(\"Unphysical (negative) surface energy detected.\") self.color_ind = list(range(len(miller_list)))", "[0.75, 0.15, 0.05, 0.65] bar_on (bool): default is False legend_on", "for i, e_surf in e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha) if", "of corresponding surface energies symprec (float): for recp_operation, default is", "find the largest distance between on_wulff pts and the origin,", "anisotropy(self): \"\"\" Returns: (float) Coefficient of Variation from weighted surface", "if grid_off: ax.grid('off') if axis_off: ax.axis('off') return plt def _get_azimuth_elev(self,", "[cart[0], cart[1], 0] elev = get_angle(cart, v) return azim, elev", "- plane.e_surf) if abs_diff < 1e-5: on_wulff[plane.index] = True surface_area[plane.index]", "cell miller_list ([(hkl), ...]: list of hkl or hkil for", "(color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\" import matplotlib as mpl", "e_surf_list, symprec=1e-5): \"\"\" Args: lattice: Lattice object of the conventional", "use this code extensively, consider citing the following: <NAME>.; <NAME>.;", "color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors( color_set, alpha, off_color, custom_colors=custom_colors)", "to get_plot. **kwargs: Passed to get_plot. \"\"\" self.get_plot(*args, **kwargs).show() def", "azim, elev = self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list = self.wulff_pt_list ax", "line in plane.outer_lines if plane.outer_lines.count(line) != 2] return on_wulff, surface_area", "miller_list] # store input data self.structure = Structure(lattice, [\"H\"], [[0,", "\"\"\" Returns {hkl: surface energy_hkl} \"\"\" return dict(zip(self.miller_list, self.e_surf_list)) @property", "= [x[1] for x in e_surf_on_wulff] if len(e_surf_on_wulff) > 1:", "following: <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. (2016). Surface energies", "wulff .. attribute:: structure Structure object, input conventional unit cell", ".. attribute:: wulff_cv_simp simplices from the convex hull of wulff_pt_list", "= get_angle(cart, v) return azim, elev @property def volume(self): \"\"\"", "# display surface energies ax1 = fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase(", "of the simpx triangle with the plane functions. \"\"\" on_wulff", "the MIT License. \"\"\" This module define a WulffShape class", "for plane in self.facets: abs_diff = abs(np.dot(plane.normal, center) - plane.e_surf)", "wulff_pt_list = self.wulff_pt_list ax = mpl3.Axes3D(fig, azim=azim, elev=elev) for plane", "< 1e-5: on_wulff[plane.index] = True surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0],", "if l[1] == prev: l.reverse() break # make sure the", "wulff_cv_simp])) # store simplices and convex self.dual_cv_simp = dual_cv_simp self.wulff_pt_list", "input surface energies, in the same order with input_miller ..", "recp_operation, default is 1e-5. \"\"\" if any([se < 0 for", "dual_simp): \"\"\" |normal| = 1, e_surf is plane's distance to", "continue # assign the color for on_wulff facets according to", "+= self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl] return tot_surface_energy @property def tot_corner_sites(self):", "/ 4) * (self.volume / np.pi)) ** (1 / 3)", "or (h, k, l) \"\"\" str_format = '($' for x", ".. attribute:: alpha transparency .. attribute:: color_set .. attribute:: grid_off", "else: cart = self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0], cart[1], 0], (1,", "normal[2]z = e_surf return: [WulffFacet] \"\"\" all_hkl = [] color_ind", "all the data for wulff construction # get all the", "cbar = mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm, boundaries=[0] + bounds +", "\"\"\" def __init__(self, lattice, miller_list, e_surf_list, symprec=1e-5): \"\"\" Args: lattice:", "color site. Note: If you decide to set your own", "fc=x, alpha=alpha) for x in color_list] return color_list, color_proxy, color_proxy_on_wulff,", "= '0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__ =", "normal[1]y + normal[2]z = e_surf from self: normal_e_m to get", "as a sphere. Returns: (float) radius. \"\"\" return ((3 /", "normal_pt: :param dual_pt: :param index: :param m_ind_orig: :param miller: \"\"\"", "+ 1])])))) for i, p in enumerate(lines): if p not", "vmax=max(e_surf_on_wulff_list)) else: # if there is only one hkl on", "Materials Virtual Lab' __version__ = '0.1' __maintainer__ = '<NAME>' __email__", "self.e_surf_list)) @property def surface_area(self): \"\"\" Total surface area of Wulff", "plane in self.facets: plane.outer_lines.sort() plane.outer_lines = [line for line in", "# coding: utf-8 # Copyright (c) Pymatgen Development Team. #", "break for plane in self.facets: plane.outer_lines.sort() plane.outer_lines = [line for", "[10], extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical') units = \"$J/m^2$\" if units_in_JPERM2", "wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for x in wulff_cv_simp])) # store simplices", "= dual_convex.simplices # simplices (ndarray of ints, shape (nfacet, ndim))", "dual_pt self.index = index self.m_ind_orig = m_ind_orig self.miller = miller", "__version__ = '0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__", "elev=elev) for plane in self.facets: # check whether [pts] is", "simplices (ndarray of ints, shape (nfacet, ndim)) # list of", "normal = recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal) normal_pt = [x *", "apply symmops to get all the miller index, then get", "list of indices and their corresponding surface energies, and the", ".. attribute:: structure Structure object, input conventional unit cell (with", "wulff shape calculation: |normal| = 1, e_surf is plane's distance", "if plane.outer_lines.count(line) != 2] return on_wulff, surface_area def _get_colors(self, color_set,", "triangle with the plane functions. \"\"\" on_wulff = [False] *", "[\"H\"], [[0, 0, 0]]) self.miller_list = tuple([tuple(x) for x in", "= l[1] return pt def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False,", "= list(facet.outer_lines) pt = [] prev = None while len(lines)", "e_surf_list ([float]): list of corresponding surface energies symprec (float): for", "x[1], reverse=False) e_surf_on_wulff_list = [x[1] for x in e_surf_on_wulff] if", "of indices and their corresponding surface energies, and the total", "normal] dual_pt = [x / energy for x in normal]", "pymatgen.util.coord import get_angle import numpy as np import scipy as", "e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i]", "def get_tri_area(pts): \"\"\" Given a list of coords for 3", "= None while len(lines) > 0: if prev is None:", "l] or (h, k, l) \"\"\" str_format = '($' for", "3. get wulff_area and other properties .. attribute:: debug (bool)", "dual_pt = [x / energy for x in normal] color_plane", "planes.append(WulffFacet(normal, energy, normal_pt, dual_pt, color_plane, i, hkl)) # sort by", "def _get_azimuth_elev(self, miller_index): \"\"\" Args: miller_index: viewing direction Returns: azim,", "vertices in the convex hull. Useful for identifying catalytically active", "e_surf in e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i]) in", "= 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl] *", "aspect_ratio=(8, 8), custom_colors={}): \"\"\" Get the Wulff shape plot. Args:", "for surfaces Agrs: hkl: in the form of [h, k,", "index, m_ind_orig, miller): \"\"\" :param normal: :param e_surf: :param normal_pt:", "is the convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get", "is False alpha (float): chosen from 0 to 1 (float),", "< 0: str_format += '\\\\overline{' + str(-x) + '}' else:", ":param normal_pt: :param dual_pt: :param index: :param m_ind_orig: :param miller:", "is not specified, use the miller indices of # maximum", "for plane in self.facets: # check whether [pts] is empty", "get all the surface normal from get_all_miller_e() self.facets = self._get_all_miller_e()", "i == len(pt) / 2: break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i", "index(same order in normal_e_m) \"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal for i", "Miller index and value is the color. Undefined facets will", "cbar.set_label('Surface Energies (%s)' % (units), fontsize=100) if grid_off: ax.grid('off') if", "colors, it probably won't make any sense to have the", "ax.axis('off') return plt def _get_azimuth_elev(self, miller_index): \"\"\" Args: miller_index: viewing", "= [line for line in plane.outer_lines if plane.outer_lines.count(line) != 2]", "in enumerate(pt): if i == len(pt) / 2: break lines.append(tuple(sorted(tuple([tuple(pt[i", "for display on plots \"(hkl)\" for surfaces Agrs: hkl: in", "(float) radius. \"\"\" return ((3 / 4) * (self.volume /", "facet in self.facets: edges = [] pt = self.get_line_in_facet(facet) lines", "the number of vertices in the convex hull. Useful for", "aspect_ratio: default is (8, 8) custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize color", "ind for normal_e_m # recalculate the dual of dual, get", "fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm, boundaries=[0] + bounds", "get_angle([cart[0], cart[1], 0], (1, 0, 0)) v = [cart[0], cart[1],", "tuple([tuple(x) for x in miller_list]) self.hkl_list = tuple([(x[0], x[1], x[-1])", "detected.\") self.color_ind = list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x) for x in", "simplices from the dual convex hull (dual_pt) .. attribute:: wulff_pt_list", "e_surf: :param normal_pt: :param dual_pt: :param index: :param m_ind_orig: :param", "Development Team. # Distributed under the terms of the MIT", "90 else: cart = self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0], cart[1], 0],", "of [i, j, k] , ndim = 3 # i,", "plot. Args: color_set: default is 'PuBu' grid_off (bool): default is", "def shape_factor(self): \"\"\" This is useful for determining the critical", "1.1, r_range * 1.1]) ax.set_zlim([-r_range * 1.1, r_range * 1.1])", "\"\"\" Generate Wulff Shape from list of miller index and", "normal_pt = [x * energy for x in normal] dual_pt", "* (self.volume / np.pi)) ** (1 / 3) @property def", "self.symprec = symprec # 2. get all the data for", "= recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal) normal_pt = [x * energy", "(1, 1, 1) bar_pos: default is [0.75, 0.15, 0.05, 0.65]", "plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False) e_surf_on_wulff_list = [x[1] for x", ") from lattice .. attribute:: miller_list list of input miller", "import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as mpl3 color_list, color_proxy,", "if miller_index == (0, 0, 1) or miller_index == (0,", "= dual_pt self.index = index self.m_ind_orig = m_ind_orig self.miller =", "for x in self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices", "simpx triangle with the plane functions. \"\"\" on_wulff = [False]", "default color site. Note: If you decide to set your", "Surface energies of elemental crystals. Scientific Data. \"\"\" from pymatgen.core.structure", "logger = logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\" Prepare for display on", "each Wulff plane. \"\"\" def __init__(self, normal, e_surf, normal_pt, dual_pt,", "<NAME>.; <NAME>.; <NAME>. (2016). Surface energies of elemental crystals. Scientific", "0 weighted_energy = self.weighted_surface_energy area_frac_dict = self.area_fraction_dict miller_energy_dict = self.miller_energy_dict", "the color. Undefined facets will use default color site. Note:", "hcp in the form of hkil .. attribute:: hkl_list modify", "for all facets considering symm .. attribute:: dual_cv_simp simplices from", "bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Add", "shape_factor(self): \"\"\" This is useful for determining the critical nucleus", "/ self.surface_area for hkl in self.miller_area_dict.keys()} @property def anisotropy(self): \"\"\"", "c] three points \"\"\" a, b, c = pts[0], pts[1],", "maximum area. direction = max(self.area_fraction_dict.items(), key=lambda x: x[1])[0] fig =", "0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}): \"\"\" Get the", "Args: pts: [a, b, c] three points \"\"\" a, b,", "1e-5. \"\"\" if any([se < 0 for se in e_surf_list]):", "the conventional unit cell .. attribute:: facets [WulffFacet] for all", "nucleus size. A large shape factor indicates great anisotropy. See", ".. attribute:: e_surf_list list of input surface energies, in the", "recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal) normal_pt = [x * energy for", "default is False alpha (float): chosen from 0 to 1", "units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)' % (units), fontsize=100) if", "e_surf in enumerate(self.e_surf_list) if self.on_wulff[i]] c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x:", "the conventional unit cell, and (hkil) for hexagonal lattices. If", "hkl: in the form of [h, k, l] or (h,", "i, p in enumerate(lines): if p not in all_edges: edges.append(p)", "weighted_energy) \\ ** 2 * area_frac_dict[hkl] return np.sqrt(square_diff_energy) / weighted_energy", "facets off wulff .. attribute:: structure Structure object, input conventional", "is useful for determining the critical nucleus size. A large", "the wulff shape,the weighted surface energy, the anisotropy and shape_factor", "e_surf return: [WulffFacet] \"\"\" all_hkl = [] color_ind = self.color_ind", "hkil for hcp e_surf_list ([float]): list of corresponding surface energies", "color_list] return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def show(self, *args,", "identifying catalytically active sites. \"\"\" all_edges = [] for facet", "v1 = np.array(b) - np.array(a) v2 = np.array(c) - np.array(a)", "self.miller_area_dict.keys()} @property def anisotropy(self): \"\"\" Returns: (float) Coefficient of Variation", "color_list for on_wulff plane_color = color_list[plane.index] pt = self.get_line_in_facet(plane) #", "for hkl in self.miller_area_dict.keys()} @property def anisotropy(self): \"\"\" Returns: (float)", "def _get_all_miller_e(self): \"\"\" from self: get miller_list(unique_miller), e_surf_list and symmetry", "by comparing the center of the simpx triangle with the", "Lattice object of the conventional unit cell miller_list ([(hkl), ...]:", "if not direction: # If direction is not specified, use", "plane.outer_lines if plane.outer_lines.count(line) != 2] return on_wulff, surface_area def _get_colors(self,", "square_diff_energy = 0 weighted_energy = self.weighted_surface_energy area_frac_dict = self.area_fraction_dict miller_energy_dict", "list of hkl or hkil for hcp e_surf_list ([float]): list", "display for all directions r_range = max([np.linalg.norm(x) for x in", "H ) from lattice .. attribute:: miller_list list of input", "= logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\" Prepare for display on plots", "index: :param m_ind_orig: :param miller: \"\"\" self.normal = normal self.e_surf", "x in miller_list]) self.e_surf_list = tuple(e_surf_list) self.lattice = lattice self.symprec", "shape (nfacet, ndim)) # list of [i, j, k] ,", "import warnings __author__ = '<NAME>, <NAME>, <NAME>' __copyright__ = 'Copyright", "be calculated. In support of plotting from a given view", "view in terms of miller index. The lattice is from", "list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x) for x in miller_list] # store", "hkl in miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl] - weighted_energy) \\ **", "self.miller_list = tuple([tuple(x) for x in miller_list]) self.hkl_list = tuple([(x[0],", "if units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)' % (units), fontsize=100)", "WulffFacet: \"\"\" Helper container for each Wulff plane. \"\"\" def", "you use this code extensively, consider citing the following: <NAME>.;", "= custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1, 1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i])", "= self.miller_energy_dict for hkl in miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl] -", "k: plane index(same order in normal_e_m) \"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal", "hull (dual_pt) .. attribute:: wulff_pt_list .. attribute:: wulff_cv_simp simplices from", "list of input surface energies, in the same order with", "self.color_area = self._get_simpx_plane() miller_area = [] for m, in_mill_fig in", "ax = mpl3.Axes3D(fig, azim=azim, elev=elev) for plane in self.facets: #", "/ energy for x in normal] color_plane = color_ind[divmod(i, len(color_ind))[1]]", "between on_wulff pts and the origin, # to ensure complete", "ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Add colorbar if", "area and volume of the wulff shape,the weighted surface energy,", "from the sorted pts from [simpx] tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color)", "len(pt) / 2: break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i * 2", "0, 0)) v = [cart[0], cart[1], 0] elev = get_angle(cart,", "len(plane.points) < 1: # empty, plane is not on_wulff. continue", "to lattice apply symmops to get all the miller index,", "for x in e_surf_on_wulff] if len(e_surf_on_wulff) > 1: cnorm =", "square_diff_energy += (miller_energy_dict[hkl] - weighted_energy) \\ ** 2 * area_frac_dict[hkl]", "1, 1) bar_pos: default is [0.75, 0.15, 0.05, 0.65] bar_on", "self.wulff_convex.volume @property def miller_area_dict(self): \"\"\" Returns {hkl: area_hkl on wulff}", "dual convex hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for dual_simp in dual_cv_simp]", "0 for se in e_surf_list]): warnings.warn(\"Unphysical (negative) surface energy detected.\")", "prev = None while len(lines) > 0: if prev is", "functions. \"\"\" on_wulff = [False] * len(self.miller_list) surface_area = [0.0]", "object, input conventional unit cell (with H ) from lattice", "\"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal for i in range(3)] matrix_e =", "= self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0], cart[1], 0], (1, 0, 0))", "miller_energy_dict(self): \"\"\" Returns {hkl: surface energy_hkl} \"\"\" return dict(zip(self.miller_list, self.e_surf_list))", "0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}): \"\"\"", "area on wulff} \"\"\" return {hkl: self.miller_area_dict[hkl] / self.surface_area for", "return {hkl: self.miller_area_dict[hkl] / self.surface_area for hkl in self.miller_area_dict.keys()} @property", "self.outer_lines = [] class WulffShape: \"\"\" Generate Wulff Shape from", "surface energies of on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff,", "in self.facets: edges = [] pt = self.get_line_in_facet(facet) lines =", "Virtual Lab' __version__ = '0.1' __maintainer__ = '<NAME>' __email__ =", "the convex hull of wulff_pt_list .. attribute:: on_wulff list for", "simplices from the dual convex hull i, j, k: plane", "miller_index): \"\"\" Args: miller_index: viewing direction Returns: azim, elev for", "1, e_surf is plane's distance to (0, 0, 0), normal[0]x", "boundaries=[0] + bounds + [10], extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical') units", "= Structure(lattice, [\"H\"], [[0, 0, 0]]) self.miller_list = tuple([tuple(x) for", "of hkl or hkil for hcp e_surf_list ([float]): list of", ":param e_surf: :param normal_pt: :param dual_pt: :param index: :param m_ind_orig:", "area for all input_miller \"\"\" def __init__(self, lattice, miller_list, e_surf_list,", "# check whether [pts] is empty if len(plane.points) < 1:", "(i, j, k) simplices from the dual convex hull i,", "label with color 3. get wulff_area and other properties ..", "in e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i]) in custom_colors.keys():", "= miller_area def _get_all_miller_e(self): \"\"\" from self: get miller_list(unique_miller), e_surf_list", "self.color_ind planes = [] recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec)", "energies symprec (float): for recp_operation, default is 1e-5. \"\"\" if", "return len(self.wulff_convex.vertices) @property def tot_edges(self): \"\"\" Returns the number of", "'($' for x in hkl: if x < 0: str_format", "/ self.surface_area @property def area_fraction_dict(self): \"\"\" Returns: (dict): {hkl: area_hkl/total", "unit cell, and (hkil) for hexagonal lattices. If you use", "color_proxy = color_proxy if show_area: ax.legend(color_proxy, self.miller_area, loc='upper left', bbox_to_anchor=(0,", "input data self.structure = Structure(lattice, [\"H\"], [[0, 0, 0]]) self.miller_list", "while len(lines) > 0: if prev is None: l =", "3)) @property def effective_radius(self): \"\"\" Radius of the Wulffshape when", "= self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl, energy) in enumerate(zip(self.hkl_list, self.e_surf_list)): for", "bar_pos: default is [0.75, 0.15, 0.05, 0.65] bar_on (bool): default", "this code extensively, consider citing the following: <NAME>.; <NAME>.; <NAME>.;", "shape \"\"\" return self.wulff_convex.volume @property def miller_area_dict(self): \"\"\" Returns {hkl:", "convex hull of wulff_pt_list .. attribute:: on_wulff list for all", "= self._get_colors( color_set, alpha, off_color, custom_colors=custom_colors) if not direction: #", "dual condition dual_pts = [x.dual_pt for x in self.facets] dual_convex", "self.surface_area for hkl in self.miller_area_dict.keys()} @property def anisotropy(self): \"\"\" Returns:", "if x < 0: str_format += '\\\\overline{' + str(-x) +", "shape_factor can also be calculated. In support of plotting from", "= [] class WulffShape: \"\"\" Generate Wulff Shape from list", "attribute:: alpha transparency .. attribute:: color_set .. attribute:: grid_off (bool)", "normal[1]y + normal[2]z = e_surf return: [WulffFacet] \"\"\" all_hkl =", "1, fc=x, alpha=alpha) for x in color_list] return color_list, color_proxy,", "area_hkl) \"\"\" tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy", "'<NAME>, <NAME>, <NAME>' __copyright__ = 'Copyright 2013, The Materials Virtual", "facets will use default color site. Note: If you decide", "plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from", "normal[0]x + normal[1]y + normal[2]z = e_surf return: [WulffFacet] \"\"\"", "numpy as np import scipy as sp from scipy.spatial import", "color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors( color_set, alpha, off_color, custom_colors=custom_colors) if", "add legend if legend_on: color_proxy = color_proxy if show_area: ax.legend(color_proxy,", "to have the color bar on. Return: (matplotlib.pyplot) \"\"\" import", "weighted_energy @property def shape_factor(self): \"\"\" This is useful for determining", "c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False) e_surf_on_wulff_list = [x[1]", "c = pts[0], pts[1], pts[2] v1 = np.array(b) - np.array(a)", "0), normal[0]x + normal[1]y + normal[2]z = e_surf return: [WulffFacet]", "of the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl) \"\"\"", "on the Wulff shape. direction: default is (1, 1, 1)", "to get_plot. \"\"\" self.get_plot(*args, **kwargs).show() def get_line_in_facet(self, facet): \"\"\" Returns", "attribute:: wulff_pt_list .. attribute:: wulff_cv_simp simplices from the convex hull", "in wulff_cv_simp])) # store simplices and convex self.dual_cv_simp = dual_cv_simp", "= mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: # if there is only one", "* 1.1, r_range * 1.1]) ax.set_zlim([-r_range * 1.1, r_range *", "a facet used to draw a line \"\"\" lines =", "** (2 / 3)) @property def effective_radius(self): \"\"\" Radius of", "for x in wulff_pt_list]) ax.set_xlim([-r_range * 1.1, r_range * 1.1])", "default is True axis_off (bool): default is Ture show_area (bool):", "3 # i, j, k: ind for normal_e_m # recalculate", "area on wulff, off_wulff = 0. .. attribute:: miller_area ($hkl$):", "sort by e_surf planes.sort(key=lambda x: x.e_surf) return planes def _get_cross_pt_dual_simp(self,", "corresponding surface energies symprec (float): for recp_operation, default is 1e-5.", "= plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False) e_surf_on_wulff_list = [x[1] for", "self.surface_area @property def area_fraction_dict(self): \"\"\" Returns: (dict): {hkl: area_hkl/total area", "return dict(zip(self.miller_list, self.color_area)) @property def miller_energy_dict(self): \"\"\" Returns {hkl: surface", "Returns: (float) radius. \"\"\" return ((3 / 4) * (self.volume", "plotting \"\"\" if miller_index == (0, 0, 1) or miller_index", "is plane's distance to (0, 0, 0), normal[0]x + normal[1]y", "decide to set your own colors, it probably won't make", "in enumerate(lines): if prev in l: l = lines.pop(i) if", "sites. \"\"\" all_edges = [] for facet in self.facets: edges", "np import scipy as sp from scipy.spatial import ConvexHull import", "Args: *args: Passed to get_plot. **kwargs: Passed to get_plot. \"\"\"", "for dual_simp in dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices", "Note: If you decide to set your own colors, it", "extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical') units = \"$J/m^2$\" if units_in_JPERM2 else", "a lattice, a list of indices and their corresponding surface", "[0.0] * len(self.miller_list) for simpx in self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]]", "to hkl, in the same order with input_miller .. attribute::", "np.sum(pts, 0) / 3.0 # check whether the center of", "data for wulff construction # get all the surface normal", "= ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices # simplices (ndarray of ints,", "all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return", "<NAME>., <NAME>. & <NAME>. Kinetics of Materials. (<NAME>, 2005), p.461", "+ 0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i, e_surf in", "covering all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1]", "on_wulff plane_color = color_list[plane.index] pt = self.get_line_in_facet(plane) # plot from", "1.1]) ax.set_zlim([-r_range * 1.1, r_range * 1.1]) # add legend", "abs_diff = abs(np.dot(plane.normal, center) - plane.e_surf) if abs_diff < 1e-5:", "# find the way covering all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist())", "dual_simp in dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices logger.debug(\",", "the anisotropy and shape_factor can also be calculated. In support", "e_surf) for i, e_surf in enumerate(self.e_surf_list) if self.on_wulff[i]] c_map =", "len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt, dual_pt, color_plane, i, hkl)) # sort", "miller_list]) self.e_surf_list = tuple(e_surf_list) self.lattice = lattice self.symprec = symprec", "\"\"\" a, b, c = pts[0], pts[1], pts[2] v1 =", "dual, get the wulff shape. # conner <-> surface #", "'}' else: str_format += str(x) str_format += '$)' return str_format", "(float): for recp_operation, default is 1e-5. \"\"\" if any([se <", "attribute:: color_set .. attribute:: grid_off (bool) .. attribute:: axis_off (bool)", "get miller_list(unique_miller), e_surf_list and symmetry operations(symmops) according to lattice apply", "simplices 2. label with color 3. get wulff_area and other", "given view in terms of miller index. The lattice is", "facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return pt def get_plot(self,", "legend_on: color_proxy = color_proxy if show_area: ax.legend(color_proxy, self.miller_area, loc='upper left',", "plane functions. \"\"\" on_wulff = [False] * len(self.miller_list) surface_area =", "/ (self.volume ** (2 / 3)) @property def effective_radius(self): \"\"\"", "self.e_surf_list = tuple(e_surf_list) self.lattice = lattice self.symprec = symprec #", "i, l in enumerate(lines): if prev in l: l =", "of the wulff shape,the weighted surface energy, the anisotropy and", "_get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal| = 1, e_surf is plane's distance", "custom_colors={}): \"\"\" assign colors according to the surface energies of", ":param miller: \"\"\" self.normal = normal self.e_surf = e_surf self.normal_pt", "Compute the area of this triangle. Args: pts: [a, b,", "color for on_wulff facets according to its # index and", "normal from get_all_miller_e() self.facets = self._get_all_miller_e() logger.debug(len(self.facets)) # 3. consider", "is 'PuBu' grid_off (bool): default is True axis_off (bool): default", "for identifying catalytically active sites. \"\"\" return len(self.wulff_convex.vertices) @property def", "to (0, 0, 0), normal[0]x + normal[1]y + normal[2]z =", "x in e_surf_on_wulff] if len(e_surf_on_wulff) > 1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list),", "shape. Returns: (float) sum(surface_energy_hkl * area_hkl) \"\"\" tot_surface_energy = 0", "[] color_ind = self.color_ind planes = [] recp = self.structure.lattice.reciprocal_lattice_crystallographic", "Useful for identifying catalytically active sites. \"\"\" all_edges = []", "a WulffShape class to generate the Wulff shape from a", "k] , ndim = 3 # i, j, k: ind", "ax.grid('off') if axis_off: ax.axis('off') return plt def _get_azimuth_elev(self, miller_index): \"\"\"", "color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\" import matplotlib as mpl import", "of Variation from weighted surface energy The ideal sphere is", "get_line_in_facet(self, facet): \"\"\" Returns the sorted pts in a facet", "\"\"\" return ((3 / 4) * (self.volume / np.pi)) **", "on_wulff = [False] * len(self.miller_list) surface_area = [0.0] * len(self.miller_list)", "tot_surface_energy @property def tot_corner_sites(self): \"\"\" Returns the number of vertices", "\"\"\" return {hkl: self.miller_area_dict[hkl] / self.surface_area for hkl in self.miller_area_dict.keys()}", "= [(i, e_surf) for i, e_surf in enumerate(self.e_surf_list) if self.on_wulff[i]]", "make sure the lines are connected one by one. #", "warnings.warn(\"Unphysical (negative) surface energy detected.\") self.color_ind = list(range(len(miller_list))) self.input_miller_fig =", "great anisotropy. See <NAME>., <NAME>. & <NAME>. Kinetics of Materials.", "ConvexHull import logging import warnings __author__ = '<NAME>, <NAME>, <NAME>'", "if self.on_wulff[i]] c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False) e_surf_on_wulff_list", "miller indices of # maximum area. direction = max(self.area_fraction_dict.items(), key=lambda", "# store input data self.structure = Structure(lattice, [\"H\"], [[0, 0,", "ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for x in wulff_cv_simp]))", "default is 1 off_color: Default color for facets not present", "- 0.1, vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for", "(h, k, l) \"\"\" str_format = '($' for x in", "'\\\\overline{' + str(-x) + '}' else: str_format += str(x) str_format", "(self.volume / np.pi)) ** (1 / 3) @property def total_surface_energy(self):", "@property def miller_energy_dict(self): \"\"\" Returns {hkl: surface energy_hkl} \"\"\" return", ".. attribute:: lattice Lattice object, the input lattice for the", "color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def show(self, *args, **kwargs): r\"\"\" Show", "get the plane functions dual_simp: (i, j, k) simplices from", "x < 0: str_format += '\\\\overline{' + str(-x) + '}'", ":param m_ind_orig: :param miller: \"\"\" self.normal = normal self.e_surf =", "- np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri", "wulff_convex self.on_wulff, self.color_area = self._get_simpx_plane() miller_area = [] for m,", "If you use this code extensively, consider citing the following:", "x.e_surf) return planes def _get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal| = 1,", "legend if legend_on: color_proxy = color_proxy if show_area: ax.legend(color_proxy, self.miller_area,", "Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get wulff simplices 2. label", "mpl_toolkits.mplot3d as mpl3 color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors(", "all input_miller, total area on wulff, off_wulff = 0. ..", "plane functions dual_simp: (i, j, k) simplices from the dual", "pts[0], pts[1], pts[2] v1 = np.array(b) - np.array(a) v2 =", "**kwargs).show() def get_line_in_facet(self, facet): \"\"\" Returns the sorted pts in", "\"\"\" Total surface energy of the Wulff shape. Returns: (float)", "self.input_miller_fig = [hkl_tuple_to_str(x) for x in miller_list] # store input", "str_format += '$)' return str_format def get_tri_area(pts): \"\"\" Given a", "= mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm, boundaries=[0] + bounds + [10],", "ax.set_ylabel('y') ax.set_zlabel('z') # Add colorbar if bar_on: cmap = plt.get_cmap(color_set)", "str_format = '($' for x in hkl: if x <", "Pymatgen Development Team. # Distributed under the terms of the", "[self.facets[dual_simp[i]].normal for i in range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf for i", "* energy for x in normal] dual_pt = [x /", "r_range * 1.1]) # add legend if legend_on: color_proxy =", "in all_hkl: all_hkl.append(miller) normal = recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal) normal_pt", "on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get wulff simplices 2. label with", "in range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt def _get_simpx_plane(self):", "dual_pt, color_plane, i, hkl)) # sort by e_surf planes.sort(key=lambda x:", "return str_format def get_tri_area(pts): \"\"\" Given a list of coords", "Lab' __version__ = '0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>'", "plane in self.facets: abs_diff = abs(np.dot(plane.normal, center) - plane.e_surf) if", "[] self.outer_lines = [] class WulffShape: \"\"\" Generate Wulff Shape", "\"\"\" Args: lattice: Lattice object of the conventional unit cell", "e_surf_list]): warnings.warn(\"Unphysical (negative) surface energy detected.\") self.color_ind = list(range(len(miller_list))) self.input_miller_fig", "miller): \"\"\" :param normal: :param e_surf: :param normal_pt: :param dual_pt:", "convex hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for dual_simp in dual_cv_simp] wulff_convex", ".. attribute:: axis_off (bool) .. attribute:: show_area .. attribute:: off_color", "shape. direction: default is (1, 1, 1) bar_pos: default is", "weighted_energy = self.weighted_surface_energy area_frac_dict = self.area_fraction_dict miller_energy_dict = self.miller_energy_dict for", "[(i, e_surf) for i, e_surf in enumerate(self.e_surf_list) if self.on_wulff[i]] c_map", "simpx of on wulff_cv, by comparing the center of the", "wulff_cv, by comparing the center of the simpx triangle with", "shape from a lattice, a list of indices and their", "the dual convex hull i, j, k: plane index(same order", "[off_color] * len(self.hkl_list) color_proxy_on_wulff = [] miller_on_wulff = [] e_surf_on_wulff", "2: break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i * 2 + 1])]))))", "attribute:: off_color color of facets off wulff .. attribute:: structure", "pts and the origin, # to ensure complete and consistent", "in the same order with input_miller .. attribute:: lattice Lattice", "pts: [a, b, c] three points \"\"\" a, b, c", "<NAME>.; <NAME>.; <NAME>.; <NAME>. (2016). Surface energies of elemental crystals.", "simplices and convex self.dual_cv_simp = dual_cv_simp self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp", "dual_pt: :param index: :param m_ind_orig: :param miller: \"\"\" self.normal =", "self.color_ind = list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x) for x in miller_list]", "a list of indices and their corresponding surface energies, and", "the convex hull. Useful for identifying catalytically active sites. \"\"\"", "+ normal[1]y + normal[2]z = e_surf from self: normal_e_m to", "mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map)", "grid_off: ax.grid('off') if axis_off: ax.axis('off') return plt def _get_azimuth_elev(self, miller_index):", "== len(pt) / 2: break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i *", "edges in the convex hull. Useful for identifying catalytically active", "approximated as a sphere. Returns: (float) radius. \"\"\" return ((3", "of the median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list) +", "the miller indices of # maximum area. direction = max(self.area_fraction_dict.items(),", "viewing direction Returns: azim, elev for plotting \"\"\" if miller_index", "hkl in self.miller_area_dict.keys()} @property def anisotropy(self): \"\"\" Returns: (float) Coefficient", "e_surf_on_wulff = [(i, e_surf) for i, e_surf in enumerate(self.e_surf_list) if", "center of the simplices is on one plane for plane", "the simpx triangle with the plane functions. \"\"\" on_wulff =", "area. direction = max(self.area_fraction_dict.items(), key=lambda x: x[1])[0] fig = plt.figure()", "self.facets: # check whether [pts] is empty if len(plane.points) <", "def show(self, *args, **kwargs): r\"\"\" Show the Wulff plot. Args:", "energy) in enumerate(zip(self.hkl_list, self.e_surf_list)): for op in recp_symmops: miller =", "self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl] return tot_surface_energy @property", "# list of [i, j, k] , ndim = 3", "WulffShape class to generate the Wulff shape from a lattice,", "return np.sqrt(square_diff_energy) / weighted_energy @property def shape_factor(self): \"\"\" This is", "find the plane, move to the next simplices break for", "facets considering symm .. attribute:: dual_cv_simp simplices from the dual", "lattice Lattice object, the input lattice for the conventional unit", "(bool): default is True axis_off (bool): default is Ture show_area", "is False legend_on (bool): default is True aspect_ratio: default is", "default is 1e-5. \"\"\" if any([se < 0 for se", "set your own colors, it probably won't make any sense", "choose the color of the median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) -", "e_surf_on_wulff] bounds.append(1.2 * bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # display", "\"\"\" Returns the number of vertices in the convex hull.", "str(x) str_format += '$)' return str_format def get_tri_area(pts): \"\"\" Given", "* 1.1]) ax.set_zlim([-r_range * 1.1, r_range * 1.1]) # add", "import matplotlib as mpl import matplotlib.pyplot as plt color_list =", "\"\"\" Returns {hkl: area_hkl on wulff} \"\"\" return dict(zip(self.miller_list, self.color_area))", "See <NAME>., <NAME>. & <NAME>. Kinetics of Materials. (<NAME>, 2005),", "def volume(self): \"\"\" Volume of the Wulff shape \"\"\" return", "= '<EMAIL>' __date__ = 'May 5 2016' logger = logging.getLogger(__name__)", "= max([np.linalg.norm(x) for x in wulff_pt_list]) ax.set_xlim([-r_range * 1.1, r_range", "return: [WulffFacet] \"\"\" all_hkl = [] color_ind = self.color_ind planes", "is 1e-5. \"\"\" if any([se < 0 for se in", "<-> surface # get cross point from the simplices of", "triangle. Args: pts: [a, b, c] three points \"\"\" a,", "normal] color_plane = color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt, dual_pt, color_plane,", "for all input_miller, True is on wulff. .. attribute:: color_area", "(hkl, energy) in enumerate(zip(self.hkl_list, self.e_surf_list)): for op in recp_symmops: miller", "active sites. \"\"\" return len(self.wulff_convex.vertices) @property def tot_edges(self): \"\"\" Returns", "pymatgen.core.structure import Structure from pymatgen.util.coord import get_angle import numpy as", "return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def show(self, *args, **kwargs):", "'<NAME>' __email__ = '<EMAIL>' __date__ = 'May 5 2016' logger", "= self.color_ind planes = [] recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops =", "the center of the simplices is on one plane for", "= wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for x in wulff_cv_simp])) # store", "from list of miller index and surface energies, with given", "sites. \"\"\" return len(self.wulff_convex.vertices) @property def tot_edges(self): \"\"\" Returns the", "m_ind_orig self.miller = miller self.points = [] self.outer_lines = []", "a sphere. Returns: (float) radius. \"\"\" return ((3 / 4)", "color_set, alpha, off_color, custom_colors={}): \"\"\" assign colors according to the", "\"\"\" square_diff_energy = 0 weighted_energy = self.weighted_surface_energy area_frac_dict = self.area_fraction_dict", "k) simplices from the dual convex hull i, j, k:", "for i, l in enumerate(lines): if prev in l: l", "colorbar if bar_on: cmap = plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds =", "sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl * area_hkl)/ sum(area_hkl)", "calculated. In support of plotting from a given view in", "miller_area.append( in_mill_fig + ' : ' + str(round(self.color_area[m], 4))) self.miller_area", "(float), default is 1 off_color: Default color for facets not", "8) custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize color of each facet with", "ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices # simplices (ndarray of ints, shape", "dual_simp: (i, j, k) simplices from the dual convex hull", "plane's distance to (0, 0, 0), plane function: normal[0]x +", "all_hkl: all_hkl.append(miller) normal = recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal) normal_pt =", "0 to 1 (float), default is 1 off_color: Default color", "and the total area and volume of the wulff shape,the", "cart[1], 0], (1, 0, 0)) v = [cart[0], cart[1], 0]", "for op in recp_symmops: miller = tuple([int(x) for x in", "input conventional unit cell (with H ) from lattice ..", "= color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt, dual_pt, color_plane, i, hkl))", "= pts[0], pts[1], pts[2] v1 = np.array(b) - np.array(a) v2", "([(hkl), ...]: list of hkl or hkil for hcp e_surf_list", "is 1 off_color: Default color for facets not present on", "In support of plotting from a given view in terms", "to (0, 0, 0), plane function: normal[0]x + normal[1]y +", "import scipy as sp from scipy.spatial import ConvexHull import logging", "x: x.e_surf) return planes def _get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal| =", "e_surf_on_wulff_list def show(self, *args, **kwargs): r\"\"\" Show the Wulff plot.", "the terms of the MIT License. \"\"\" This module define", "= sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt def _get_simpx_plane(self): \"\"\" Locate the", "normal_e_m) \"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal for i in range(3)] matrix_e", "dual convex hull (dual_pt) .. attribute:: wulff_pt_list .. attribute:: wulff_cv_simp", "# already find the plane, move to the next simplices", "lines = [] for i, p in enumerate(pt): if i", "miller_area def _get_all_miller_e(self): \"\"\" from self: get miller_list(unique_miller), e_surf_list and", "max(self.area_fraction_dict.items(), key=lambda x: x[1])[0] fig = plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim,", "= [] pt = self.get_line_in_facet(facet) lines = [] for i,", "np.sqrt(square_diff_energy) / weighted_energy @property def shape_factor(self): \"\"\" This is useful", "store input data self.structure = Structure(lattice, [\"H\"], [[0, 0, 0]])", "miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x in e_surf_on_wulff]) color_proxy = [plt.Rectangle((2, 2),", "each facet with a dictionary. The key is the corresponding", "plane.outer_lines = [line for line in plane.outer_lines if plane.outer_lines.count(line) !=", "\"\"\" Prepare for display on plots \"(hkl)\" for surfaces Agrs:", "axis_off (bool): default is Ture show_area (bool): default is False", "ax.set_zlim([-r_range * 1.1, r_range * 1.1]) # add legend if", "http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get wulff simplices 2. label with color", "(bool) .. attribute:: alpha transparency .. attribute:: color_set .. attribute::", "/ 3)) @property def effective_radius(self): \"\"\" Radius of the Wulffshape", "= lines.pop(0) else: for i, l in enumerate(lines): if prev", "return self.surface_area / (self.volume ** (2 / 3)) @property def", "bounds = [round(e, 2) for e in e_surf_on_wulff] bounds.append(1.2 *", "and their corresponding surface energies, and the total area and", "weighted surface energy The ideal sphere is 0. \"\"\" square_diff_energy", "the color for on_wulff facets according to its # index", "to ensure complete and consistent display for all directions r_range", "hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for dual_simp in dual_cv_simp] wulff_convex =", "conventional unit cell. surface energy (Jm^2) is the length of", "units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}): \"\"\" Get the Wulff shape", "0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl] * \\", "= [x.dual_pt for x in self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp", "tot_corner_sites(self): \"\"\" Returns the number of vertices in the convex", "of Wulff shape. \"\"\" return sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self): \"\"\"", "get_plot. \"\"\" self.get_plot(*args, **kwargs).show() def get_line_in_facet(self, facet): \"\"\" Returns the", "= wulff_convex self.on_wulff, self.color_area = self._get_simpx_plane() miller_area = [] for", "i, j, k: ind for normal_e_m # recalculate the dual", "list of miller index and surface energies, with given conventional", "simplices of the dual convex hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for", "j, k: ind for normal_e_m # recalculate the dual of", "and shape_factor can also be calculated. In support of plotting", "the Wulff shape plot. Args: color_set: default is 'PuBu' grid_off", "custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1, 1, fc=color_list[i],", "\"\"\" return self.wulff_convex.volume @property def miller_area_dict(self): \"\"\" Returns {hkl: area_hkl", "= '<NAME>' __email__ = '<EMAIL>' __date__ = 'May 5 2016'", "get_angle(cart, v) return azim, elev @property def volume(self): \"\"\" Volume", "on_wulff[plane.index] = True surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1],", "miller_on_wulff, e_surf_on_wulff_list) \"\"\" import matplotlib as mpl import matplotlib.pyplot as", "cmap.set_under('0.75') bounds = [round(e, 2) for e in e_surf_on_wulff] bounds.append(1.2", "normal_e_m # recalculate the dual of dual, get the wulff", "facets according to its # index and the color_list for", "hkl or hkil for hcp e_surf_list ([float]): list of corresponding", "in normal] dual_pt = [x / energy for x in", "cmap.N) # display surface energies ax1 = fig.add_axes(bar_pos) cbar =", "The lattice is from the conventional unit cell, and (hkil)", "import Structure from pymatgen.util.coord import get_angle import numpy as np", "next simplices break for plane in self.facets: plane.outer_lines.sort() plane.outer_lines =", "== (0, 0, 1) or miller_index == (0, 0, 0,", "A large shape factor indicates great anisotropy. See <NAME>., <NAME>.", "self.e_surf_list)): for op in recp_symmops: miller = tuple([int(x) for x", "Returns the number of edges in the convex hull. Useful", "i, hkl)) # sort by e_surf planes.sort(key=lambda x: x.e_surf) return", "miller_list ([(hkl), ...]: list of hkl or hkil for hcp", "bar_on (bool): default is False legend_on (bool): default is True", "\"(hkl)\" for surfaces Agrs: hkl: in the form of [h,", "= [] for m, in_mill_fig in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig +", "off_color: Default color for facets not present on the Wulff", "= [x * energy for x in normal] dual_pt =", "the color of the median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1,", "x in wulff_pt_list]) ax.set_xlim([-r_range * 1.1, r_range * 1.1]) ax.set_ylim([-r_range", "import logging import warnings __author__ = '<NAME>, <NAME>, <NAME>' __copyright__", "for plotting \"\"\" if miller_index == (0, 0, 1) or", "mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set ranges of x, y,", "# make sure the lines are connected one by one.", "[pts] is empty if len(plane.points) < 1: # empty, plane", "get normal, get all the facets functions for wulff shape", "e_surf self.normal_pt = normal_pt self.dual_pt = dual_pt self.index = index", "in miller_list] # store input data self.structure = Structure(lattice, [\"H\"],", "4))) self.miller_area = miller_area def _get_all_miller_e(self): \"\"\" from self: get", "one. # find the way covering all pts and facets", "__maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__ = 'May 5", "color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def show(self, *args, **kwargs): r\"\"\" Show the", "direction is not specified, use the miller indices of #", "is not on_wulff. continue # assign the color for on_wulff", "self.miller_energy_dict for hkl in miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl] - weighted_energy)", "= np.sum(pts, 0) / 3.0 # check whether the center", "(nfacet, ndim)) # list of [i, j, k] , ndim", "True aspect_ratio: default is (8, 8) custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize", "the area of this triangle. Args: pts: [a, b, c]", "= self.area_fraction_dict miller_energy_dict = self.miller_energy_dict for hkl in miller_energy_dict.keys(): square_diff_energy", "all the surface normal from get_all_miller_e() self.facets = self._get_all_miller_e() logger.debug(len(self.facets))", "surface energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl *", "get wulff simplices 2. label with color 3. get wulff_area", "in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl] return tot_surface_energy", "(units), fontsize=100) if grid_off: ax.grid('off') if axis_off: ax.axis('off') return plt", "**kwargs: Passed to get_plot. \"\"\" self.get_plot(*args, **kwargs).show() def get_line_in_facet(self, facet):", "is Ture show_area (bool): default is False alpha (float): chosen", "vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i, e_surf", "in self.facets: # check whether [pts] is empty if len(plane.points)", "normal /= sp.linalg.norm(normal) normal_pt = [x * energy for x", "def area_fraction_dict(self): \"\"\" Returns: (dict): {hkl: area_hkl/total area on wulff}", "shape calculation: |normal| = 1, e_surf is plane's distance to", "attribute:: dual_cv_simp simplices from the dual convex hull (dual_pt) ..", "Wulff plot. Args: *args: Passed to get_plot. **kwargs: Passed to", "normal self.e_surf = e_surf self.normal_pt = normal_pt self.dual_pt = dual_pt", "whether [pts] is empty if len(plane.points) < 1: # empty,", "is (1, 1, 1) bar_pos: default is [0.75, 0.15, 0.05,", "return self.total_surface_energy / self.surface_area @property def area_fraction_dict(self): \"\"\" Returns: (dict):", "wulff_cv_simp simplices from the convex hull of wulff_pt_list .. attribute::", "factor. \"\"\" return self.surface_area / (self.volume ** (2 / 3))", "facet used to draw a line \"\"\" lines = list(facet.outer_lines)", "[round(e, 2) for e in e_surf_on_wulff] bounds.append(1.2 * bounds[-1]) norm", "# plot from the sorted pts from [simpx] tri =", "energies of elemental crystals. Scientific Data. \"\"\" from pymatgen.core.structure import", "by one. # find the way covering all pts and", "'<EMAIL>' __date__ = 'May 5 2016' logger = logging.getLogger(__name__) def", "[a, b, c] three points \"\"\" a, b, c =", "Wulffshape when the Wulffshape is approximated as a sphere. Returns:", "= self._get_all_miller_e() logger.debug(len(self.facets)) # 3. consider the dual condition dual_pts", "fontsize=100) if grid_off: ax.grid('off') if axis_off: ax.axis('off') return plt def", "self: get miller_list(unique_miller), e_surf_list and symmetry operations(symmops) according to lattice", "citing the following: <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. (2016).", "fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x in e_surf_on_wulff]) color_proxy =", "The key is the corresponding Miller index and value is", "v2)) / 2) return area_tri class WulffFacet: \"\"\" Helper container", "for x in hkl: if x < 0: str_format +=", "not in all_hkl: all_hkl.append(miller) normal = recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal)", "in enumerate(self.e_surf_list) if self.on_wulff[i]] c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1],", "\"\"\" self.get_plot(*args, **kwargs).show() def get_line_in_facet(self, facet): \"\"\" Returns the sorted", "the plane functions dual_simp: (i, j, k) simplices from the", "lattice self.symprec = symprec # 2. get all the data", "= mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm,", "# empty, plane is not on_wulff. continue # assign the", "b, c = pts[0], pts[1], pts[2] v1 = np.array(b) -", "on wulff} \"\"\" return dict(zip(self.miller_list, self.color_area)) @property def miller_energy_dict(self): \"\"\"", "of the Wulff shape \"\"\" return self.wulff_convex.volume @property def miller_area_dict(self):", "alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True,", "@property def tot_corner_sites(self): \"\"\" Returns the number of vertices in", "** (1 / 3) @property def total_surface_energy(self): \"\"\" Total surface", "color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05,", "({(h,k,l}: [r,g,b,alpha}): Customize color of each facet with a dictionary.", "miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y')", "for hcp in the form of hkil .. attribute:: hkl_list", "symmops to get all the miller index, then get normal,", "If direction is not specified, use the miller indices of", "1 off_color: Default color for facets not present on the", "plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev = self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list", "The Materials Virtual Lab' __version__ = '0.1' __maintainer__ = '<NAME>'", "= wulff_cv_simp self.wulff_convex = wulff_convex self.on_wulff, self.color_area = self._get_simpx_plane() miller_area", "0, 1): return 0, 90 else: cart = self.lattice.get_cartesian_coords(miller_index) azim", "[h, k, l] or (h, k, l) \"\"\" str_format =", "class WulffFacet: \"\"\" Helper container for each Wulff plane. \"\"\"", "+= '$)' return str_format def get_tri_area(pts): \"\"\" Given a list", "def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75,", "the critical nucleus size. A large shape factor indicates great", "wulff_cv_simp = wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for x in wulff_cv_simp])) #", "to get the plane functions dual_simp: (i, j, k) simplices", "for e in e_surf_on_wulff] bounds.append(1.2 * bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds,", "(<NAME>, 2005), p.461 Returns: (float) Shape factor. \"\"\" return self.surface_area", "lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i * 2 + 1])])))) for i,", "# Distributed under the terms of the MIT License. \"\"\"", "color bar on. Return: (matplotlib.pyplot) \"\"\" import matplotlib as mpl", "conventional unit cell, and (hkil) for hexagonal lattices. If you", "area_frac_dict = self.area_fraction_dict miller_energy_dict = self.miller_energy_dict for hkl in miller_energy_dict.keys():", "2016' logger = logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\" Prepare for display", "alpha=alpha) for x in color_list] return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff,", "Returns: sum(surface_energy_hkl * area_hkl)/ sum(area_hkl) \"\"\" return self.total_surface_energy / self.surface_area", "matplotlib as mpl import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as", "bbox_to_anchor=(0, 1), fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5,", "as plt color_list = [off_color] * len(self.hkl_list) color_proxy_on_wulff = []", ".. attribute:: color_set .. attribute:: grid_off (bool) .. attribute:: axis_off", "energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl)", "/ weighted_energy @property def shape_factor(self): \"\"\" This is useful for", "0.1, vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i,", "is empty if len(plane.points) < 1: # empty, plane is", "(8, 8) custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize color of each facet", "= mpl.colors.BoundaryNorm(bounds, cmap.N) # display surface energies ax1 = fig.add_axes(bar_pos)", "& <NAME>. Kinetics of Materials. (<NAME>, 2005), p.461 Returns: (float)", "+ str(round(self.color_area[m], 4))) self.miller_area = miller_area def _get_all_miller_e(self): \"\"\" from", "\"\"\" from self: get miller_list(unique_miller), e_surf_list and symmetry operations(symmops) according", "{hkl: area_hkl/total area on wulff} \"\"\" return {hkl: self.miller_area_dict[hkl] /", "in the convex hull. Useful for identifying catalytically active sites.", "[False] * len(self.miller_list) surface_area = [0.0] * len(self.miller_list) for simpx", "if prev in l: l = lines.pop(i) if l[1] ==", "(bool): default is Ture show_area (bool): default is False alpha", "azim, elev @property def volume(self): \"\"\" Volume of the Wulff", "pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return pt", "= normal_pt self.dual_pt = dual_pt self.index = index self.m_ind_orig =", "extensively, consider citing the following: <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.;", "shape. # conner <-> surface # get cross point from", "License. \"\"\" This module define a WulffShape class to generate", "according to its # index and the color_list for on_wulff", "form of hkil .. attribute:: hkl_list modify hkill to hkl,", "ax.set_zlabel('z') # Add colorbar if bar_on: cmap = plt.get_cmap(color_set) cmap.set_over('0.25')", "= e_surf self.normal_pt = normal_pt self.dual_pt = dual_pt self.index =", "from the dual convex hull (dual_pt) .. attribute:: wulff_pt_list ..", "dual_convex.simplices # simplices (ndarray of ints, shape (nfacet, ndim)) #", "e_surf_list and symmetry operations(symmops) according to lattice apply symmops to", "([float]): list of corresponding surface energies symprec (float): for recp_operation,", "identifying catalytically active sites. \"\"\" return len(self.wulff_convex.vertices) @property def tot_edges(self):", "hkil .. attribute:: hkl_list modify hkill to hkl, in the", "(bool) .. attribute:: show_area .. attribute:: off_color color of facets", "color_proxy if show_area: ax.legend(color_proxy, self.miller_area, loc='upper left', bbox_to_anchor=(0, 1), fancybox=True,", "wulff_pt_list .. attribute:: on_wulff list for all input_miller, True is", "self.facets: plane.outer_lines.sort() plane.outer_lines = [line for line in plane.outer_lines if", "e_surf planes.sort(key=lambda x: x.e_surf) return planes def _get_cross_pt_dual_simp(self, dual_simp): \"\"\"", "= [] for facet in self.facets: edges = [] pt", "indicates great anisotropy. See <NAME>., <NAME>. & <NAME>. Kinetics of", "self.miller_area_dict[hkl] return tot_surface_energy @property def tot_corner_sites(self): \"\"\" Returns the number", "max([np.linalg.norm(x) for x in wulff_pt_list]) ax.set_xlim([-r_range * 1.1, r_range *", "1), ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Add colorbar", "bounds.append(1.2 * bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # display surface", "planes.sort(key=lambda x: x.e_surf) return planes def _get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal|", "miller_list]) self.hkl_list = tuple([(x[0], x[1], x[-1]) for x in miller_list])", "unit cell (with H ) from lattice .. attribute:: miller_list", "color_plane, i, hkl)) # sort by e_surf planes.sort(key=lambda x: x.e_surf)", "area_frac_dict[hkl] return np.sqrt(square_diff_energy) / weighted_energy @property def shape_factor(self): \"\"\" This", "@property def total_surface_energy(self): \"\"\" Total surface energy of the Wulff", "= index self.m_ind_orig = m_ind_orig self.miller = miller self.points =", "ax.legend(color_proxy, self.miller_area, loc='upper left', bbox_to_anchor=(0, 1), fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff,", "for facets not present on the Wulff shape. direction: default", "<NAME>. & <NAME>. Kinetics of Materials. (<NAME>, 2005), p.461 Returns:", "in miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl] - weighted_energy) \\ ** 2", "miller not in all_hkl: all_hkl.append(miller) normal = recp.get_cartesian_coords(miller) normal /=", "x in color_list] return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def", "(with H ) from lattice .. attribute:: miller_list list of", "self.miller_area = miller_area def _get_all_miller_e(self): \"\"\" from self: get miller_list(unique_miller),", "\"\"\" Locate the plane for simpx of on wulff_cv, by", "total_surface_energy(self): \"\"\" Total surface energy of the Wulff shape. Returns:", "facets [WulffFacet] for all facets considering symm .. attribute:: dual_cv_simp", "/ 2) return area_tri class WulffFacet: \"\"\" Helper container for", "plt.Rectangle((2, 2), 1, 1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x", "** 2 * area_frac_dict[hkl] return np.sqrt(square_diff_energy) / weighted_energy @property def", "1, 1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x in e_surf_on_wulff])", "ax.set_xlim([-r_range * 1.1, r_range * 1.1]) ax.set_ylim([-r_range * 1.1, r_range", "list for all input_miller, total area on wulff, off_wulff =", "facet): \"\"\" Returns the sorted pts in a facet used", "attribute:: show_area .. attribute:: off_color color of facets off wulff", "2) return area_tri class WulffFacet: \"\"\" Helper container for each", "Helper container for each Wulff plane. \"\"\" def __init__(self, normal,", "= self.wulff_pt_list ax = mpl3.Axes3D(fig, azim=azim, elev=elev) for plane in", "= 0 weighted_energy = self.weighted_surface_energy area_frac_dict = self.area_fraction_dict miller_energy_dict =", "0) / 3.0 # check whether the center of the", "\\ ** 2 * area_frac_dict[hkl] return np.sqrt(square_diff_energy) / weighted_energy @property", "direction: default is (1, 1, 1) bar_pos: default is [0.75,", "Kinetics of Materials. (<NAME>, 2005), p.461 Returns: (float) Shape factor.", "to draw a line \"\"\" lines = list(facet.outer_lines) pt =", "structure Structure object, input conventional unit cell (with H )", "[] for i, p in enumerate(pt): if i == len(pt)", "in e_surf_on_wulff] bounds.append(1.2 * bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) #", "dual convex hull i, j, k: plane index(same order in", "from get_all_miller_e() self.facets = self._get_all_miller_e() logger.debug(len(self.facets)) # 3. consider the", "self.area_fraction_dict miller_energy_dict = self.miller_energy_dict for hkl in miller_energy_dict.keys(): square_diff_energy +=", "fig = plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev = self._get_azimuth_elev([direction[0], direction[1],", "with color 3. get wulff_area and other properties .. attribute::", "plotting from a given view in terms of miller index.", "if i == len(pt) / 2: break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]),", "normal_pt, dual_pt, index, m_ind_orig, miller): \"\"\" :param normal: :param e_surf:", "0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}): \"\"\" Get", "x, y, z # find the largest distance between on_wulff", "any sense to have the color bar on. Return: (matplotlib.pyplot)", "wulff shape,the weighted surface energy, the anisotropy and shape_factor can", "is (8, 8) custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize color of each", "if show_area: ax.legend(color_proxy, self.miller_area, loc='upper left', bbox_to_anchor=(0, 1), fancybox=True, shadow=False)", "else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)' % (units), fontsize=100) if grid_off:", "return dict(zip(self.miller_list, self.e_surf_list)) @property def surface_area(self): \"\"\" Total surface area", "len(self.miller_list) surface_area = [0.0] * len(self.miller_list) for simpx in self.wulff_cv_simp:", "\"\"\" return sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl *", "surface normal from get_all_miller_e() self.facets = self._get_all_miller_e() logger.debug(len(self.facets)) # 3.", "value is the color. Undefined facets will use default color", "number of vertices in the convex hull. Useful for identifying", "useful for determining the critical nucleus size. A large shape", "the sorted pts from [simpx] tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\")", "largest distance between on_wulff pts and the origin, # to", "the surface normal from get_all_miller_e() self.facets = self._get_all_miller_e() logger.debug(len(self.facets)) #", "scipy as sp from scipy.spatial import ConvexHull import logging import", "self.get_plot(*args, **kwargs).show() def get_line_in_facet(self, facet): \"\"\" Returns the sorted pts", "unit cell miller_list ([(hkl), ...]: list of hkl or hkil", "energy (Jm^2) is the length of normal. Wulff shape is", "miller_list(unique_miller), e_surf_list and symmetry operations(symmops) according to lattice apply symmops", "* 1.1]) ax.set_ylim([-r_range * 1.1, r_range * 1.1]) ax.set_zlim([-r_range *", "0: if prev is None: l = lines.pop(0) else: for", "cmap.set_over('0.25') cmap.set_under('0.75') bounds = [round(e, 2) for e in e_surf_on_wulff]", "!= 2] return on_wulff, surface_area def _get_colors(self, color_set, alpha, off_color,", "lines are connected one by one. # find the way", "# index and the color_list for on_wulff plane_color = color_list[plane.index]", "= [cart[0], cart[1], 0] elev = get_angle(cart, v) return azim,", "($hkl$): area for all input_miller \"\"\" def __init__(self, lattice, miller_list,", "the way covering all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev", "color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list def show(self, *args, **kwargs): r\"\"\"", "is True axis_off (bool): default is Ture show_area (bool): default", "plot. Args: *args: Passed to get_plot. **kwargs: Passed to get_plot.", "return 0, 90 else: cart = self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0],", "= np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)", "for x in normal] dual_pt = [x / energy for", "tuple([(x[0], x[1], x[-1]) for x in miller_list]) self.e_surf_list = tuple(e_surf_list)", "scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i, e_surf in e_surf_on_wulff: color_list[i]", "in self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]] for i in range(3)] center", "the data for wulff construction # get all the surface", "normal[2]z = e_surf from self: normal_e_m to get the plane", "plots \"(hkl)\" for surfaces Agrs: hkl: in the form of", "def __init__(self, normal, e_surf, normal_pt, dual_pt, index, m_ind_orig, miller): \"\"\"", "2. get all the data for wulff construction # get", "logger.debug(\", \".join([str(len(x)) for x in wulff_cv_simp])) # store simplices and", "[] miller_on_wulff = [] e_surf_on_wulff = [(i, e_surf) for i,", "sense to have the color bar on. Return: (matplotlib.pyplot) \"\"\"", "l = lines.pop(i) if l[1] == prev: l.reverse() break #", "for wulff construction # get all the surface normal from", "= '<NAME>, <NAME>, <NAME>' __copyright__ = 'Copyright 2013, The Materials", "Structure(lattice, [\"H\"], [[0, 0, 0]]) self.miller_list = tuple([tuple(x) for x", "if axis_off: ax.axis('off') return plt def _get_azimuth_elev(self, miller_index): \"\"\" Args:", "by e_surf planes.sort(key=lambda x: x.e_surf) return planes def _get_cross_pt_dual_simp(self, dual_simp):", "\"\"\" This is useful for determining the critical nucleus size.", "lattice for the conventional unit cell .. attribute:: facets [WulffFacet]", "have the color bar on. Return: (matplotlib.pyplot) \"\"\" import matplotlib", "in recp_symmops: miller = tuple([int(x) for x in op.operate(hkl)]) if", "prev is None: l = lines.pop(0) else: for i, l", "and value is the color. Undefined facets will use default", "color of each facet with a dictionary. The key is", "x in miller_list] # store input data self.structure = Structure(lattice,", "* 2 + 1])])))) for i, p in enumerate(lines): if", "(bool): default is False legend_on (bool): default is True aspect_ratio:", "miller index and surface energies, with given conventional unit cell.", "off_color, custom_colors={}): \"\"\" assign colors according to the surface energies", "energy_hkl} \"\"\" return dict(zip(self.miller_list, self.e_surf_list)) @property def surface_area(self): \"\"\" Total", "get_plot. **kwargs: Passed to get_plot. \"\"\" self.get_plot(*args, **kwargs).show() def get_line_in_facet(self,", "= tuple(e_surf_list) self.lattice = lattice self.symprec = symprec # 2.", "for i in range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt", "all_hkl.append(miller) normal = recp.get_cartesian_coords(miller) normal /= sp.linalg.norm(normal) normal_pt = [x", "won't make any sense to have the color bar on.", "store simplices and convex self.dual_cv_simp = dual_cv_simp self.wulff_pt_list = wulff_pt_list", "conventional unit cell (with H ) from lattice .. attribute::", "for x in color_list] return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list", "\"\"\" all_edges = [] for facet in self.facets: edges =", "the input lattice for the conventional unit cell .. attribute::", ".. attribute:: facets [WulffFacet] for all facets considering symm ..", "hkl)) # sort by e_surf planes.sort(key=lambda x: x.e_surf) return planes", "color of facets off wulff .. attribute:: structure Structure object,", "the dual convex hull (dual_pt) .. attribute:: wulff_pt_list .. attribute::", "Generate Wulff Shape from list of miller index and surface", "with input_miller .. attribute:: lattice Lattice object, the input lattice", "\"\"\" :param normal: :param e_surf: :param normal_pt: :param dual_pt: :param", "color_proxy_on_wulff = [] miller_on_wulff = [] e_surf_on_wulff = [(i, e_surf)", "(hkil) for hexagonal lattices. If you use this code extensively,", "center of the simpx triangle with the plane functions. \"\"\"", "one by one. # find the way covering all pts", "e_surf, normal_pt, dual_pt, index, m_ind_orig, miller): \"\"\" :param normal: :param", "plt def _get_azimuth_elev(self, miller_index): \"\"\" Args: miller_index: viewing direction Returns:", "azim, elev for plotting \"\"\" if miller_index == (0, 0,", "off_color, custom_colors=custom_colors) if not direction: # If direction is not", "terms of miller index. The lattice is from the conventional", "{hkl: area_hkl on wulff} \"\"\" return dict(zip(self.miller_list, self.color_area)) @property def", "in enumerate(zip(self.hkl_list, self.e_surf_list)): for op in recp_symmops: miller = tuple([int(x)", "cross point from the simplices of the dual convex hull", "form of [h, k, l] or (h, k, l) \"\"\"", "\"\"\" Total surface area of Wulff shape. \"\"\" return sum(self.miller_area_dict.values())", "direction Returns: azim, elev for plotting \"\"\" if miller_index ==", "list for all input_miller, True is on wulff. .. attribute::", "orientation='vertical') units = \"$J/m^2$\" if units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies", "color_area list for all input_miller, total area on wulff, off_wulff", "area of this triangle. Args: pts: [a, b, c] three", "enumerate(pt): if i == len(pt) / 2: break lines.append(tuple(sorted(tuple([tuple(pt[i *", "matrix_e = [self.facets[dual_simp[i]].e_surf for i in range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs),", "attribute:: debug (bool) .. attribute:: alpha transparency .. attribute:: color_set", "ax.add_collection3d(tri) # set ranges of x, y, z # find", "convex hull (dual_pt) .. attribute:: wulff_pt_list .. attribute:: wulff_cv_simp simplices", "on wulff, choose the color of the median cnorm =", "cell, and (hkil) for hexagonal lattices. If you use this", "3 points, Compute the area of this triangle. Args: pts:", "hull i, j, k: plane index(same order in normal_e_m) \"\"\"", "= tuple([tuple(x) for x in miller_list]) self.hkl_list = tuple([(x[0], x[1],", "default is (8, 8) custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize color of", "for m, in_mill_fig in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig + ' :", "radius. \"\"\" return ((3 / 4) * (self.volume / np.pi))", "1. get wulff simplices 2. label with color 3. get", "Wulff Shape from list of miller index and surface energies,", "color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors( color_set, alpha, off_color,", "@property def shape_factor(self): \"\"\" This is useful for determining the", "range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf for i in range(3)] cross_pt =", "energies, in the same order with input_miller .. attribute:: lattice", "wulff construction # get all the surface normal from get_all_miller_e()", "points \"\"\" a, b, c = pts[0], pts[1], pts[2] v1", ".. attribute:: show_area .. attribute:: off_color color of facets off", "l.reverse() break # make sure the lines are connected one", "+= (miller_energy_dict[hkl] - weighted_energy) \\ ** 2 * area_frac_dict[hkl] return", "\"\"\" return dict(zip(self.miller_list, self.color_area)) @property def miller_energy_dict(self): \"\"\" Returns {hkl:", "plane index(same order in normal_e_m) \"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal for", "all input_miller \"\"\" def __init__(self, lattice, miller_list, e_surf_list, symprec=1e-5): \"\"\"", "for line in plane.outer_lines if plane.outer_lines.count(line) != 2] return on_wulff,", "of the MIT License. \"\"\" This module define a WulffShape", "weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl * area_hkl)/ sum(area_hkl) \"\"\" return self.total_surface_energy", "attribute:: color_area list for all input_miller, total area on wulff,", "effective_radius(self): \"\"\" Radius of the Wulffshape when the Wulffshape is", "sum(surface_energy_hkl * area_hkl)/ sum(area_hkl) \"\"\" return self.total_surface_energy / self.surface_area @property", "module define a WulffShape class to generate the Wulff shape", "[r,g,b,alpha}): Customize color of each facet with a dictionary. The", "* \\ self.miller_area_dict[hkl] return tot_surface_energy @property def tot_corner_sites(self): \"\"\" Returns", "self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices # simplices (ndarray", "1.1, r_range * 1.1]) # add legend if legend_on: color_proxy", "enumerate(self.input_miller_fig): miller_area.append( in_mill_fig + ' : ' + str(round(self.color_area[m], 4)))", "sorted pts from [simpx] tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri)", "the conventional unit cell miller_list ([(hkl), ...]: list of hkl", "left', bbox_to_anchor=(0, 1), fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center',", "This module define a WulffShape class to generate the Wulff", "= 3 # i, j, k: ind for normal_e_m #", "given conventional unit cell. surface energy (Jm^2) is the length", "conner <-> surface # get cross point from the simplices", "* area_frac_dict[hkl] return np.sqrt(square_diff_energy) / weighted_energy @property def shape_factor(self): \"\"\"", "plane's distance to (0, 0, 0), normal[0]x + normal[1]y +", "all_hkl = [] color_ind = self.color_ind planes = [] recp", "the same order with input_miller .. attribute:: lattice Lattice object,", "catalytically active sites. \"\"\" return len(self.wulff_convex.vertices) @property def tot_edges(self): \"\"\"", "2 + 1])])))) for i, p in enumerate(lines): if p", "energy for x in normal] dual_pt = [x / energy", "_get_azimuth_elev(self, miller_index): \"\"\" Args: miller_index: viewing direction Returns: azim, elev", "color_proxy = [plt.Rectangle((2, 2), 1, 1, fc=x, alpha=alpha) for x", "2]), tuple(pt[i * 2 + 1])])))) for i, p in", "(0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z", "[self.wulff_pt_list[simpx[i]] for i in range(3)] center = np.sum(pts, 0) /", "< 0 for se in e_surf_list]): warnings.warn(\"Unphysical (negative) surface energy", "x: x[1])[0] fig = plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev =", "== prev: l.reverse() break # make sure the lines are", "e_surf_on_wulff_list) \"\"\" import matplotlib as mpl import matplotlib.pyplot as plt", "str(round(self.color_area[m], 4))) self.miller_area = miller_area def _get_all_miller_e(self): \"\"\" from self:", "Wulff shape plot. Args: color_set: default is 'PuBu' grid_off (bool):", "for all input_miller \"\"\" def __init__(self, lattice, miller_list, e_surf_list, symprec=1e-5):", "a dictionary. The key is the corresponding Miller index and", "@property def miller_area_dict(self): \"\"\" Returns {hkl: area_hkl on wulff} \"\"\"", "surface_area def _get_colors(self, color_set, alpha, off_color, custom_colors={}): \"\"\" assign colors", "if len(plane.points) < 1: # empty, plane is not on_wulff.", "0, 90 else: cart = self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0], cart[1],", "\"\"\" Helper container for each Wulff plane. \"\"\" def __init__(self,", "and the origin, # to ensure complete and consistent display", "the form of [h, k, l] or (h, k, l)", "axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False,", "in self.facets: plane.outer_lines.sort() plane.outer_lines = [line for line in plane.outer_lines", "def _get_colors(self, color_set, alpha, off_color, custom_colors={}): \"\"\" assign colors according", "[i, j, k] , ndim = 3 # i, j,", "on wulff. .. attribute:: color_area list for all input_miller, total", "plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) # already find", "[self._get_cross_pt_dual_simp(dual_simp) for dual_simp in dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp =", "for each Wulff plane. \"\"\" def __init__(self, normal, e_surf, normal_pt,", "(bool): default is True aspect_ratio: default is (8, 8) custom_colors", "\"\"\" import matplotlib as mpl import matplotlib.pyplot as plt import", "\"\"\" lines = list(facet.outer_lines) pt = [] prev = None", "all the facets functions for wulff shape calculation: |normal| =", "for x in wulff_cv_simp])) # store simplices and convex self.dual_cv_simp", "x in miller_list]) self.hkl_list = tuple([(x[0], x[1], x[-1]) for x", "symmetry operations(symmops) according to lattice apply symmops to get all", "convex hull. Useful for identifying catalytically active sites. \"\"\" all_edges", "= [] prev = None while len(lines) > 0: if", "for i in range(3)] center = np.sum(pts, 0) / 3.0", "@property def anisotropy(self): \"\"\" Returns: (float) Coefficient of Variation from", "j, k: plane index(same order in normal_e_m) \"\"\" matrix_surfs =", "from the convex hull of wulff_pt_list .. attribute:: on_wulff list", "bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}):", "from weighted surface energy The ideal sphere is 0. \"\"\"", "elemental crystals. Scientific Data. \"\"\" from pymatgen.core.structure import Structure from", "legend_on (bool): default is True aspect_ratio: default is (8, 8)", "energy for x in normal] color_plane = color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal,", "default is 'PuBu' grid_off (bool): default is True axis_off (bool):", "= normal self.e_surf = e_surf self.normal_pt = normal_pt self.dual_pt =", "+= get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) #", "self.index = index self.m_ind_orig = m_ind_orig self.miller = miller self.points", "to the surface energies of on_wulff facets. return: (color_list, color_proxy,", "calculation: |normal| = 1, e_surf is plane's distance to (0,", "surface energy (Jm^2) is the length of normal. Wulff shape", ".. attribute:: wulff_pt_list .. attribute:: wulff_cv_simp simplices from the convex", "Returns: azim, elev for plotting \"\"\" if miller_index == (0,", "define a WulffShape class to generate the Wulff shape from", "the plane for simpx of on wulff_cv, by comparing the", "pt = self.get_line_in_facet(plane) # plot from the sorted pts from", "= [round(e, 2) for e in e_surf_on_wulff] bounds.append(1.2 * bounds[-1])", "for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl]", "else: str_format += str(x) str_format += '$)' return str_format def", "from the simplices of the dual convex hull wulff_pt_list =", "Wulff plane. \"\"\" def __init__(self, normal, e_surf, normal_pt, dual_pt, index,", "according to lattice apply symmops to get all the miller", "Shape from list of miller index and surface energies, with", "(matplotlib.pyplot) \"\"\" import matplotlib as mpl import matplotlib.pyplot as plt", "= abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri class WulffFacet: \"\"\"", "tuple([int(x) for x in op.operate(hkl)]) if miller not in all_hkl:", "is [0.75, 0.15, 0.05, 0.65] bar_on (bool): default is False", "if bar_on: cmap = plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds = [round(e,", "surface energies ax1 = fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase( ax1, cmap=cmap,", "the surface energies of on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff,", "comparing the center of the simpx triangle with the plane", "attribute:: lattice Lattice object, the input lattice for the conventional", "= self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl, energy) in", "input_miller .. attribute:: e_surf_list list of input surface energies, in", "Given a list of coords for 3 points, Compute the", "probably won't make any sense to have the color bar", "= self.get_line_in_facet(plane) # plot from the sorted pts from [simpx]", "mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: # if there is only one hkl", "i, e_surf in e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i])", "on_wulff facets according to its # index and the color_list", "symm .. attribute:: dual_cv_simp simplices from the dual convex hull", "prev = l[1] return pt def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True,", "\"\"\" return dict(zip(self.miller_list, self.e_surf_list)) @property def surface_area(self): \"\"\" Total surface", "= lines.pop(i) if l[1] == prev: l.reverse() break # make", "(2 / 3)) @property def effective_radius(self): \"\"\" Radius of the", "3.0 # check whether the center of the simplices is", "mpl import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as mpl3 color_list,", "simpx[2]]) # already find the plane, move to the next", "Materials. (<NAME>, 2005), p.461 Returns: (float) Shape factor. \"\"\" return", "of edges in the convex hull. Useful for identifying catalytically", "site. Note: If you decide to set your own colors,", "str_format += str(x) str_format += '$)' return str_format def get_tri_area(pts):", "axis_off: ax.axis('off') return plt def _get_azimuth_elev(self, miller_index): \"\"\" Args: miller_index:", "k, l) \"\"\" str_format = '($' for x in hkl:", "symprec=1e-5): \"\"\" Args: lattice: Lattice object of the conventional unit", "len(self.hkl_list) color_proxy_on_wulff = [] miller_on_wulff = [] e_surf_on_wulff = [(i,", ".. attribute:: color_area list for all input_miller, total area on", "normal: :param e_surf: :param normal_pt: :param dual_pt: :param index: :param", "attribute:: axis_off (bool) .. attribute:: show_area .. attribute:: off_color color", "lattice is from the conventional unit cell, and (hkil) for", "\"\"\" def __init__(self, normal, e_surf, normal_pt, dual_pt, index, m_ind_orig, miller):", "or miller_index == (0, 0, 0, 1): return 0, 90", "consistent display for all directions r_range = max([np.linalg.norm(x) for x", "the Wulff shape \"\"\" return self.wulff_convex.volume @property def miller_area_dict(self): \"\"\"", "np.array(b) - np.array(a) v2 = np.array(c) - np.array(a) area_tri =", "miller index, for hcp in the form of hkil ..", "shape plot. Args: color_set: default is 'PuBu' grid_off (bool): default", "\"\"\" return self.total_surface_energy / self.surface_area @property def area_fraction_dict(self): \"\"\" Returns:", "the same order with input_miller .. attribute:: e_surf_list list of", "# sort by e_surf planes.sort(key=lambda x: x.e_surf) return planes def", "= [off_color] * len(self.hkl_list) color_proxy_on_wulff = [] miller_on_wulff = []", "show_area .. attribute:: off_color color of facets off wulff ..", ".. attribute:: grid_off (bool) .. attribute:: axis_off (bool) .. attribute::", "to its # index and the color_list for on_wulff plane_color", "connected one by one. # find the way covering all", "on_wulff pts and the origin, # to ensure complete and", "self.miller = miller self.points = [] self.outer_lines = [] class", "\"\"\" |normal| = 1, e_surf is plane's distance to (0,", "its # index and the color_list for on_wulff plane_color =", "is the corresponding Miller index and value is the color.", "color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i] =", "[hkl_tuple_to_str(x) for x in miller_list] # store input data self.structure", "attribute:: facets [WulffFacet] for all facets considering symm .. attribute::", "self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]] for i in range(3)] center =", "if miller not in all_hkl: all_hkl.append(miller) normal = recp.get_cartesian_coords(miller) normal", "Returns: (float) Coefficient of Variation from weighted surface energy The", "def tot_edges(self): \"\"\" Returns the number of edges in the", "catalytically active sites. \"\"\" all_edges = [] for facet in", "Passed to get_plot. **kwargs: Passed to get_plot. \"\"\" self.get_plot(*args, **kwargs).show()", "list(facet.outer_lines) pt = [] prev = None while len(lines) >", "scalar_map.set_array([x[1] for x in e_surf_on_wulff]) color_proxy = [plt.Rectangle((2, 2), 1,", "{hkl: surface energy_hkl} \"\"\" return dict(zip(self.miller_list, self.e_surf_list)) @property def surface_area(self):", "= mpl3.Axes3D(fig, azim=azim, elev=elev) for plane in self.facets: # check", "1.1, r_range * 1.1]) ax.set_ylim([-r_range * 1.1, r_range * 1.1])", "index and the color_list for on_wulff plane_color = color_list[plane.index] pt", "range(3)] center = np.sum(pts, 0) / 3.0 # check whether", "self.hkl_list = tuple([(x[0], x[1], x[-1]) for x in miller_list]) self.e_surf_list", "in self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices # simplices", "Useful for identifying catalytically active sites. \"\"\" return len(self.wulff_convex.vertices) @property", "cmap = plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds = [round(e, 2) for", "ax1 = fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm, boundaries=[0]", "lattice: Lattice object of the conventional unit cell miller_list ([(hkl),", "for i, e_surf in enumerate(self.e_surf_list) if self.on_wulff[i]] c_map = plt.get_cmap(color_set)", "list of input miller index, for hcp in the form", "for all directions r_range = max([np.linalg.norm(x) for x in wulff_pt_list])", "Returns: (float) sum(surface_energy_hkl * area_hkl) \"\"\" tot_surface_energy = 0 for", "@property def area_fraction_dict(self): \"\"\" Returns: (dict): {hkl: area_hkl/total area on", "- weighted_energy) \\ ** 2 * area_frac_dict[hkl] return np.sqrt(square_diff_energy) /", "= fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm, boundaries=[0] +", "lines = list(facet.outer_lines) pt = [] prev = None while", "' : ' + str(round(self.color_area[m], 4))) self.miller_area = miller_area def", "is approximated as a sphere. Returns: (float) radius. \"\"\" return", "<NAME>.; <NAME>. (2016). Surface energies of elemental crystals. Scientific Data.", "(self.volume ** (2 / 3)) @property def effective_radius(self): \"\"\" Radius", "[x * energy for x in normal] dual_pt = [x", ":param normal: :param e_surf: :param normal_pt: :param dual_pt: :param index:", "factor indicates great anisotropy. See <NAME>., <NAME>. & <NAME>. Kinetics", "wulff. .. attribute:: color_area list for all input_miller, total area", "prev in l: l = lines.pop(i) if l[1] == prev:", "the sorted pts in a facet used to draw a", "wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for x", "[] e_surf_on_wulff = [(i, e_surf) for i, e_surf in enumerate(self.e_surf_list)", "= wulff_pt_list self.wulff_cv_simp = wulff_cv_simp self.wulff_convex = wulff_convex self.on_wulff, self.color_area", "'0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __date__ = 'May", "other properties .. attribute:: debug (bool) .. attribute:: alpha transparency", "simplices from the convex hull of wulff_pt_list .. attribute:: on_wulff", "m_ind_orig, miller): \"\"\" :param normal: :param e_surf: :param normal_pt: :param", "to get all the miller index, then get normal, get", "False alpha (float): chosen from 0 to 1 (float), default", "for simpx in self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]] for i in", "energy detected.\") self.color_ind = list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x) for x", "dual_cv_simp = dual_convex.simplices # simplices (ndarray of ints, shape (nfacet,", "matplotlib.pyplot as plt color_list = [off_color] * len(self.hkl_list) color_proxy_on_wulff =", "on wulff} \"\"\" return {hkl: self.miller_area_dict[hkl] / self.surface_area for hkl", "b, c] three points \"\"\" a, b, c = pts[0],", "x in op.operate(hkl)]) if miller not in all_hkl: all_hkl.append(miller) normal", "(float): chosen from 0 to 1 (float), default is 1", "and symmetry operations(symmops) according to lattice apply symmops to get", "hull. Useful for identifying catalytically active sites. \"\"\" return len(self.wulff_convex.vertices)", "for plane in self.facets: plane.outer_lines.sort() plane.outer_lines = [line for line", "off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8,", "plane is not on_wulff. continue # assign the color for", "abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri class WulffFacet: \"\"\" Helper", "None while len(lines) > 0: if prev is None: l", "self.points = [] self.outer_lines = [] class WulffShape: \"\"\" Generate", "'$)' return str_format def get_tri_area(pts): \"\"\" Given a list of", "Args: color_set: default is 'PuBu' grid_off (bool): default is True", "three points \"\"\" a, b, c = pts[0], pts[1], pts[2]", "of facets off wulff .. attribute:: structure Structure object, input", "dual_convex = ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices # simplices (ndarray of", "miller_list, e_surf_list, symprec=1e-5): \"\"\" Args: lattice: Lattice object of the", "miller_area = [] for m, in_mill_fig in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig", "_get_all_miller_e(self): \"\"\" from self: get miller_list(unique_miller), e_surf_list and symmetry operations(symmops)", "the dual of dual, get the wulff shape. # conner", "surface # get cross point from the simplices of the", "sum(surface_energy_hkl * area_hkl) \"\"\" tot_surface_energy = 0 for hkl in", "when the Wulffshape is approximated as a sphere. Returns: (float)", "_get_colors(self, color_set, alpha, off_color, custom_colors={}): \"\"\" assign colors according to", "input_miller, total area on wulff, off_wulff = 0. .. attribute::", "np.array(a) v2 = np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2))", "considering symm .. attribute:: dual_cv_simp simplices from the dual convex", "in e_surf_on_wulff]) color_proxy = [plt.Rectangle((2, 2), 1, 1, fc=x, alpha=alpha)", "line \"\"\" lines = list(facet.outer_lines) pt = [] prev =", "Wulff shape. direction: default is (1, 1, 1) bar_pos: default", "hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get wulff simplices 2.", "e_surf is plane's distance to (0, 0, 0), normal[0]x +", "lattices. If you use this code extensively, consider citing the", "Process: 1. get wulff simplices 2. label with color 3.", "x[1], x[-1]) for x in miller_list]) self.e_surf_list = tuple(e_surf_list) self.lattice", "dict(zip(self.miller_list, self.e_surf_list)) @property def surface_area(self): \"\"\" Total surface area of", "alpha (float): chosen from 0 to 1 (float), default is", "area_tri class WulffFacet: \"\"\" Helper container for each Wulff plane.", "return on_wulff, surface_area def _get_colors(self, color_set, alpha, off_color, custom_colors={}): \"\"\"", "Customize color of each facet with a dictionary. The key", "+ normal[2]z = e_surf from self: normal_e_m to get the", "then get normal, get all the facets functions for wulff", "to the next simplices break for plane in self.facets: plane.outer_lines.sort()", "surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]])", "dual_pts = [x.dual_pt for x in self.facets] dual_convex = ConvexHull(dual_pts)", "indices of # maximum area. direction = max(self.area_fraction_dict.items(), key=lambda x:", "index, then get normal, get all the facets functions for", "mpl3.Axes3D(fig, azim=azim, elev=elev) for plane in self.facets: # check whether", "lines.pop(0) else: for i, l in enumerate(lines): if prev in", "for on_wulff facets according to its # index and the", "order with input_miller .. attribute:: e_surf_list list of input surface", "surfaces Agrs: hkl: in the form of [h, k, l]", "cmap=cmap, norm=norm, boundaries=[0] + bounds + [10], extend='both', ticks=bounds[:-1], spacing='proportional',", "sum(area_hkl) \"\"\" return self.total_surface_energy / self.surface_area @property def area_fraction_dict(self): \"\"\"", "\\ self.miller_area_dict[hkl] return tot_surface_energy @property def tot_corner_sites(self): \"\"\" Returns the", "import numpy as np import scipy as sp from scipy.spatial", "str_format += '\\\\overline{' + str(-x) + '}' else: str_format +=", "the Wulffshape when the Wulffshape is approximated as a sphere.", "draw a line \"\"\" lines = list(facet.outer_lines) pt = []", "else: # if there is only one hkl on wulff,", "* 2]), tuple(pt[i * 2 + 1])])))) for i, p", "normal_e_m to get the plane functions dual_simp: (i, j, k)", "# find the largest distance between on_wulff pts and the", "self.dual_pt = dual_pt self.index = index self.m_ind_orig = m_ind_orig self.miller", "in hkl: if x < 0: str_format += '\\\\overline{' +", "2] return on_wulff, surface_area def _get_colors(self, color_set, alpha, off_color, custom_colors={}):", "\"\"\" Returns: (float) Coefficient of Variation from weighted surface energy", "\"\"\" Radius of the Wulffshape when the Wulffshape is approximated", "Args: lattice: Lattice object of the conventional unit cell miller_list", "active sites. \"\"\" all_edges = [] for facet in self.facets:", "cross_pt def _get_simpx_plane(self): \"\"\" Locate the plane for simpx of", "attribute:: miller_area ($hkl$): area for all input_miller \"\"\" def __init__(self,", "return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\" import matplotlib as", "origin, # to ensure complete and consistent display for all", "[x / energy for x in normal] color_plane = color_ind[divmod(i,", "return area_tri class WulffFacet: \"\"\" Helper container for each Wulff", "data self.structure = Structure(lattice, [\"H\"], [[0, 0, 0]]) self.miller_list =", "j, k] , ndim = 3 # i, j, k:", "+ ' : ' + str(round(self.color_area[m], 4))) self.miller_area = miller_area", "under the terms of the MIT License. \"\"\" This module", "self.wulff_convex = wulff_convex self.on_wulff, self.color_area = self._get_simpx_plane() miller_area = []", "ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x')", "energy, normal_pt, dual_pt, color_plane, i, hkl)) # sort by e_surf", "cmap=c_map) for i, e_surf in e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha)", "MIT License. \"\"\" This module define a WulffShape class to", "logging import warnings __author__ = '<NAME>, <NAME>, <NAME>' __copyright__ =", "> 0: if prev is None: l = lines.pop(0) else:", "a, b, c = pts[0], pts[1], pts[2] v1 = np.array(b)", "wulff shape. # conner <-> surface # get cross point", "(%s)' % (units), fontsize=100) if grid_off: ax.grid('off') if axis_off: ax.axis('off')", "in self.miller_area_dict.keys()} @property def anisotropy(self): \"\"\" Returns: (float) Coefficient of", "\"\"\" This module define a WulffShape class to generate the", "Prepare for display on plots \"(hkl)\" for surfaces Agrs: hkl:", "elev @property def volume(self): \"\"\" Volume of the Wulff shape", "self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0], cart[1], 0], (1, 0, 0)) v", "planes = [] recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for", "[self.facets[dual_simp[i]].e_surf for i in range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return", "= self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list = self.wulff_pt_list ax = mpl3.Axes3D(fig,", "self.get_line_in_facet(plane) # plot from the sorted pts from [simpx] tri", "wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for dual_simp in dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list)", "the facets functions for wulff shape calculation: |normal| = 1,", "color of the median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list)", "color_ind = self.color_ind planes = [] recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops", "self.on_wulff, self.color_area = self._get_simpx_plane() miller_area = [] for m, in_mill_fig", "recalculate the dual of dual, get the wulff shape. #", "for se in e_surf_list]): warnings.warn(\"Unphysical (negative) surface energy detected.\") self.color_ind", "transparency .. attribute:: color_set .. attribute:: grid_off (bool) .. attribute::", "+ '}' else: str_format += str(x) str_format += '$)' return", "- np.array(a) v2 = np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1,", "debug (bool) .. attribute:: alpha transparency .. attribute:: color_set ..", "own colors, it probably won't make any sense to have", "units = \"$J/m^2$\" if units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)'", "x[1])[0] fig = plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev = self._get_azimuth_elev([direction[0],", "miller_list list of input miller index, for hcp in the", "the Wulff plot. Args: *args: Passed to get_plot. **kwargs: Passed", "r_range = max([np.linalg.norm(x) for x in wulff_pt_list]) ax.set_xlim([-r_range * 1.1,", "properties .. attribute:: debug (bool) .. attribute:: alpha transparency ..", "check whether the center of the simplices is on one", "hexagonal lattices. If you use this code extensively, consider citing", "coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed", "0.1) scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i, e_surf in e_surf_on_wulff:", "@property def weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl * area_hkl)/ sum(area_hkl) \"\"\"", "elev for plotting \"\"\" if miller_index == (0, 0, 1)", "simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) # already find the plane, move to", "\"\"\" import matplotlib as mpl import matplotlib.pyplot as plt color_list", "normal_pt, dual_pt, color_plane, i, hkl)) # sort by e_surf planes.sort(key=lambda", "center = np.sum(pts, 0) / 3.0 # check whether the", "legend_on=True, aspect_ratio=(8, 8), custom_colors={}): \"\"\" Get the Wulff shape plot.", "get the wulff shape. # conner <-> surface # get", "= [x / energy for x in normal] color_plane =", "as mpl3 color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors( color_set,", "= color_list[plane.index] pt = self.get_line_in_facet(plane) # plot from the sorted", "(0, 0, 1) or miller_index == (0, 0, 0, 1):", "if abs_diff < 1e-5: on_wulff[plane.index] = True surface_area[plane.index] += get_tri_area(pts)", "anisotropy. See <NAME>., <NAME>. & <NAME>. Kinetics of Materials. (<NAME>,", "in op.operate(hkl)]) if miller not in all_hkl: all_hkl.append(miller) normal =", "op in recp_symmops: miller = tuple([int(x) for x in op.operate(hkl)])", "2 * area_frac_dict[hkl] return np.sqrt(square_diff_energy) / weighted_energy @property def shape_factor(self):", "recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl, energy) in enumerate(zip(self.hkl_list, self.e_surf_list)):", "miller = tuple([int(x) for x in op.operate(hkl)]) if miller not", "Wulff shape \"\"\" return self.wulff_convex.volume @property def miller_area_dict(self): \"\"\" Returns", "use the miller indices of # maximum area. direction =", "e_surf_on_wulff = self._get_colors( color_set, alpha, off_color, custom_colors=custom_colors) if not direction:", "r\"\"\" Show the Wulff plot. Args: *args: Passed to get_plot.", "in the same order with input_miller .. attribute:: e_surf_list list", "tuple(e_surf_list) self.lattice = lattice self.symprec = symprec # 2. get", "direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8),", "= tuple([(x[0], x[1], x[-1]) for x in miller_list]) self.e_surf_list =", "the convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get wulff", "dual_pt, index, m_ind_orig, miller): \"\"\" :param normal: :param e_surf: :param", "[simpx] tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set ranges", "= color_proxy if show_area: ax.legend(color_proxy, self.miller_area, loc='upper left', bbox_to_anchor=(0, 1),", "in custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1, 1,", "<NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. (2016). Surface energies of elemental", "area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri class WulffFacet:", "plane for simpx of on wulff_cv, by comparing the center", ", ndim = 3 # i, j, k: ind for", "dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for", "Show the Wulff plot. Args: *args: Passed to get_plot. **kwargs:", "norm=norm, boundaries=[0] + bounds + [10], extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical')", "color. Undefined facets will use default color site. Note: If", "your own colors, it probably won't make any sense to", "recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl, energy)", "True surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0],", "import matplotlib.pyplot as plt color_list = [off_color] * len(self.hkl_list) color_proxy_on_wulff", "1) or miller_index == (0, 0, 0, 1): return 0,", "convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: 1. get wulff simplices", "surface energies symprec (float): for recp_operation, default is 1e-5. \"\"\"", "1e-5: on_wulff[plane.index] = True surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]])", "the largest distance between on_wulff pts and the origin, #", ":param index: :param m_ind_orig: :param miller: \"\"\" self.normal = normal", "is None: l = lines.pop(0) else: for i, l in", "self.get_line_in_facet(facet) lines = [] for i, p in enumerate(pt): if", "2), 1, 1, fc=x, alpha=alpha) for x in color_list] return", "hkl_list modify hkill to hkl, in the same order with", "miller: \"\"\" self.normal = normal self.e_surf = e_surf self.normal_pt =", "off_color color of facets off wulff .. attribute:: structure Structure", "fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5, 1), ncol=3,", "operations(symmops) according to lattice apply symmops to get all the", ".. attribute:: debug (bool) .. attribute:: alpha transparency .. attribute::", "<NAME>, <NAME>' __copyright__ = 'Copyright 2013, The Materials Virtual Lab'", "this triangle. Args: pts: [a, b, c] three points \"\"\"", "Volume of the Wulff shape \"\"\" return self.wulff_convex.volume @property def", "or hkil for hcp e_surf_list ([float]): list of corresponding surface", "break # make sure the lines are connected one by", "x in hkl: if x < 0: str_format += '\\\\overline{'", "i in range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt def", "get wulff_area and other properties .. attribute:: debug (bool) ..", "self.lattice.get_recp_symmetry_operation(self.symprec) for i, (hkl, energy) in enumerate(zip(self.hkl_list, self.e_surf_list)): for op", "(2016). Surface energies of elemental crystals. Scientific Data. \"\"\" from", "sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt def _get_simpx_plane(self): \"\"\" Locate the plane", "v = [cart[0], cart[1], 0] elev = get_angle(cart, v) return", "of this triangle. Args: pts: [a, b, c] three points", "v) return azim, elev @property def volume(self): \"\"\" Volume of", "corresponding Miller index and value is the color. Undefined facets", "range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt def _get_simpx_plane(self): \"\"\"", "empty, plane is not on_wulff. continue # assign the color", "present on the Wulff shape. direction: default is (1, 1,", "conventional unit cell .. attribute:: facets [WulffFacet] for all facets", "in the form of hkil .. attribute:: hkl_list modify hkill", "# 2. get all the data for wulff construction #", "__email__ = '<EMAIL>' __date__ = 'May 5 2016' logger =", "\"\"\" self.normal = normal self.e_surf = e_surf self.normal_pt = normal_pt", "the simplices is on one plane for plane in self.facets:", "3) @property def total_surface_energy(self): \"\"\" Total surface energy of the", "e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False) e_surf_on_wulff_list = [x[1] for x in", "wulff_cv_simp self.wulff_convex = wulff_convex self.on_wulff, self.color_area = self._get_simpx_plane() miller_area =", "# simplices (ndarray of ints, shape (nfacet, ndim)) # list", "x in normal] color_plane = color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt,", "return ((3 / 4) * (self.volume / np.pi)) ** (1", "of x, y, z # find the largest distance between", "used to draw a line \"\"\" lines = list(facet.outer_lines) pt", "\"\"\" return len(self.wulff_convex.vertices) @property def tot_edges(self): \"\"\" Returns the number", "# assign the color for on_wulff facets according to its", "@property def volume(self): \"\"\" Volume of the Wulff shape \"\"\"", "all the miller index, then get normal, get all the", "plt import mpl_toolkits.mplot3d as mpl3 color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff", "def hkl_tuple_to_str(hkl): \"\"\" Prepare for display on plots \"(hkl)\" for", "= max(self.area_fraction_dict.items(), key=lambda x: x[1])[0] fig = plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1])", "pts = [self.wulff_pt_list[simpx[i]] for i in range(3)] center = np.sum(pts,", "/ np.pi)) ** (1 / 3) @property def total_surface_energy(self): \"\"\"", "(dual_pt) .. attribute:: wulff_pt_list .. attribute:: wulff_cv_simp simplices from the", "ensure complete and consistent display for all directions r_range =", "# get all the surface normal from get_all_miller_e() self.facets =", "= [] for i, p in enumerate(pt): if i ==", "corresponding surface energies, and the total area and volume of", "e_surf_on_wulff] if len(e_surf_on_wulff) > 1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else:", "simplices break for plane in self.facets: plane.outer_lines.sort() plane.outer_lines = [line", "with input_miller .. attribute:: e_surf_list list of input surface energies,", "the plane functions. \"\"\" on_wulff = [False] * len(self.miller_list) surface_area", "self: normal_e_m to get the plane functions dual_simp: (i, j,", "= 0. .. attribute:: miller_area ($hkl$): area for all input_miller", "i in range(3)] center = np.sum(pts, 0) / 3.0 #", "0. \"\"\" square_diff_energy = 0 weighted_energy = self.weighted_surface_energy area_frac_dict =", "pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return pt def get_plot(self, color_set='PuBu',", "hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl] return", "if tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2),", "for normal_e_m # recalculate the dual of dual, get the", "for x in e_surf_on_wulff]) color_proxy = [plt.Rectangle((2, 2), 1, 1,", "Passed to get_plot. \"\"\" self.get_plot(*args, **kwargs).show() def get_line_in_facet(self, facet): \"\"\"", "* 1.1]) # add legend if legend_on: color_proxy = color_proxy", "0. .. attribute:: miller_area ($hkl$): area for all input_miller \"\"\"", "8), custom_colors={}): \"\"\" Get the Wulff shape plot. Args: color_set:", "display on plots \"(hkl)\" for surfaces Agrs: hkl: in the", "len(e_surf_on_wulff) > 1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: # if", "wulff, choose the color of the median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list)", "/ 2: break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i * 2 +", "= ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices logger.debug(\", \".join([str(len(x)) for x in", "= np.array(b) - np.array(a) v2 = np.array(c) - np.array(a) area_tri", "(float) Coefficient of Variation from weighted surface energy The ideal", "[[0, 0, 0]]) self.miller_list = tuple([tuple(x) for x in miller_list])", "return planes def _get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal| = 1, e_surf", "'PuBu' grid_off (bool): default is True axis_off (bool): default is", "is on one plane for plane in self.facets: abs_diff =", "grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65),", "0, 0, 1): return 0, 90 else: cart = self.lattice.get_cartesian_coords(miller_index)", "can also be calculated. In support of plotting from a", "scipy.spatial import ConvexHull import logging import warnings __author__ = '<NAME>,", "bar_on=False, units_in_JPERM2=True, legend_on=True, aspect_ratio=(8, 8), custom_colors={}): \"\"\" Get the Wulff", "surface energies, and the total area and volume of the", "input_miller .. attribute:: lattice Lattice object, the input lattice for", "hull of wulff_pt_list .. attribute:: on_wulff list for all input_miller,", "*args, **kwargs): r\"\"\" Show the Wulff plot. Args: *args: Passed", "normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m", "miller_energy_dict = self.miller_energy_dict for hkl in miller_energy_dict.keys(): square_diff_energy += (miller_energy_dict[hkl]", "on wulff_cv, by comparing the center of the simpx triangle", "self.miller_area, loc='upper left', bbox_to_anchor=(0, 1), fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff,", "the total area and volume of the wulff shape,the weighted", "conventional unit cell miller_list ([(hkl), ...]: list of hkl or", "Shape factor. \"\"\" return self.surface_area / (self.volume ** (2 /", "def __init__(self, lattice, miller_list, e_surf_list, symprec=1e-5): \"\"\" Args: lattice: Lattice", "<NAME>. Kinetics of Materials. (<NAME>, 2005), p.461 Returns: (float) Shape", "azim = get_angle([cart[0], cart[1], 0], (1, 0, 0)) v =", "energies of on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list)", "same order with input_miller .. attribute:: e_surf_list list of input", "(1 / 3) @property def total_surface_energy(self): \"\"\" Total surface energy", "x: x[1], reverse=False) e_surf_on_wulff_list = [x[1] for x in e_surf_on_wulff]", "convex hull i, j, k: plane index(same order in normal_e_m)", "def total_surface_energy(self): \"\"\" Total surface energy of the Wulff shape.", "if legend_on: color_proxy = color_proxy if show_area: ax.legend(color_proxy, self.miller_area, loc='upper", "Return: (matplotlib.pyplot) \"\"\" import matplotlib as mpl import matplotlib.pyplot as", "one hkl on wulff, choose the color of the median", "* 1.1, r_range * 1.1]) # add legend if legend_on:", "[] prev = None while len(lines) > 0: if prev", "in terms of miller index. The lattice is from the", "not present on the Wulff shape. direction: default is (1,", "show(self, *args, **kwargs): r\"\"\" Show the Wulff plot. Args: *args:", "on one plane for plane in self.facets: abs_diff = abs(np.dot(plane.normal,", "e_surf_on_wulff_list = [x[1] for x in e_surf_on_wulff] if len(e_surf_on_wulff) >", "self.on_wulff[i]] c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False) e_surf_on_wulff_list =", "m, in_mill_fig in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig + ' : '", "self.surface_area / (self.volume ** (2 / 3)) @property def effective_radius(self):", "miller self.points = [] self.outer_lines = [] class WulffShape: \"\"\"", "to generate the Wulff shape from a lattice, a list", "point from the simplices of the dual convex hull wulff_pt_list", "alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x in e_surf_on_wulff]) color_proxy = [plt.Rectangle((2,", "the dual condition dual_pts = [x.dual_pt for x in self.facets]", "# to ensure complete and consistent display for all directions", "\"$J/m^2$\" if units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)' % (units),", "((3 / 4) * (self.volume / np.pi)) ** (1 /", "0, 0]]) self.miller_list = tuple([tuple(x) for x in miller_list]) self.hkl_list", "get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15,", "the origin, # to ensure complete and consistent display for", "[line for line in plane.outer_lines if plane.outer_lines.count(line) != 2] return", "return sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl * area_hkl)/", "matrix_e) return cross_pt def _get_simpx_plane(self): \"\"\" Locate the plane for", "This is useful for determining the critical nucleus size. A", "WulffShape: \"\"\" Generate Wulff Shape from list of miller index", "pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return pt def get_plot(self, color_set='PuBu', grid_off=True,", "hkl on wulff, choose the color of the median cnorm", "+ normal[2]z = e_surf return: [WulffFacet] \"\"\" all_hkl = []", "len(self.miller_list) for simpx in self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]] for i", "alpha, off_color, custom_colors=custom_colors) if not direction: # If direction is", "np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri class", "of elemental crystals. Scientific Data. \"\"\" from pymatgen.core.structure import Structure", "energy The ideal sphere is 0. \"\"\" square_diff_energy = 0", "/= sp.linalg.norm(normal) normal_pt = [x * energy for x in", "plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) # already find the", "self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl] return tot_surface_energy @property def tot_corner_sites(self): \"\"\"", "import ConvexHull import logging import warnings __author__ = '<NAME>, <NAME>,", "consider citing the following: <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.", "matrix_surfs = [self.facets[dual_simp[i]].normal for i in range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf", "of the conventional unit cell miller_list ([(hkl), ...]: list of", "(float) Shape factor. \"\"\" return self.surface_area / (self.volume ** (2", "Args: miller_index: viewing direction Returns: azim, elev for plotting \"\"\"", "generate the Wulff shape from a lattice, a list of", "mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i, e_surf in e_surf_on_wulff: color_list[i] = scalar_map.to_rgba(e_surf,", "functions dual_simp: (i, j, k) simplices from the dual convex", "plane for plane in self.facets: abs_diff = abs(np.dot(plane.normal, center) -", "*args: Passed to get_plot. **kwargs: Passed to get_plot. \"\"\" self.get_plot(*args,", "self.miller_area_dict[hkl] / self.surface_area for hkl in self.miller_area_dict.keys()} @property def anisotropy(self):", "def weighted_surface_energy(self): \"\"\" Returns: sum(surface_energy_hkl * area_hkl)/ sum(area_hkl) \"\"\" return", "= 'May 5 2016' logger = logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\"", "class WulffShape: \"\"\" Generate Wulff Shape from list of miller", "large shape factor indicates great anisotropy. See <NAME>., <NAME>. &", "for identifying catalytically active sites. \"\"\" all_edges = [] for", "for simpx of on wulff_cv, by comparing the center of", "+ [10], extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical') units = \"$J/m^2$\" if", "j, k) simplices from the dual convex hull i, j,", "dual of dual, get the wulff shape. # conner <->", "ax1, cmap=cmap, norm=norm, boundaries=[0] + bounds + [10], extend='both', ticks=bounds[:-1],", "(1, 0, 0)) v = [cart[0], cart[1], 0] elev =", "1, 1, fc=x, alpha=alpha) for x in color_list] return color_list,", "color_set .. attribute:: grid_off (bool) .. attribute:: axis_off (bool) ..", "miller index. The lattice is from the conventional unit cell,", "of # maximum area. direction = max(self.area_fraction_dict.items(), key=lambda x: x[1])[0]", "aspect_ratio[1]) azim, elev = self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list = self.wulff_pt_list", "the simplices of the dual convex hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp)", "list of corresponding surface energies symprec (float): for recp_operation, default", "to 1 (float), default is 1 off_color: Default color for", "ax.set_ylim([-r_range * 1.1, r_range * 1.1]) ax.set_zlim([-r_range * 1.1, r_range", "code extensively, consider citing the following: <NAME>.; <NAME>.; <NAME>.; <NAME>.;", "self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp = wulff_cv_simp self.wulff_convex = wulff_convex self.on_wulff,", "custom_colors={}): \"\"\" Get the Wulff shape plot. Args: color_set: default", "construction # get all the surface normal from get_all_miller_e() self.facets", "the miller index, then get normal, get all the facets", "0] elev = get_angle(cart, v) return azim, elev @property def", "__date__ = 'May 5 2016' logger = logging.getLogger(__name__) def hkl_tuple_to_str(hkl):", "from pymatgen.util.coord import get_angle import numpy as np import scipy", "* len(self.hkl_list) color_proxy_on_wulff = [] miller_on_wulff = [] e_surf_on_wulff =", "dictionary. The key is the corresponding Miller index and value", "cell. surface energy (Jm^2) is the length of normal. Wulff", "the dual convex hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for dual_simp in", "# i, j, k: ind for normal_e_m # recalculate the", "# set ranges of x, y, z # find the", "None: l = lines.pop(0) else: for i, l in enumerate(lines):", "of dual, get the wulff shape. # conner <-> surface", "\".join([str(len(x)) for x in wulff_cv_simp])) # store simplices and convex", "plane.outer_lines.append([simpx[0], simpx[2]]) # already find the plane, move to the", "for x in miller_list]) self.e_surf_list = tuple(e_surf_list) self.lattice = lattice", "show_area=False, alpha=1, off_color='red', direction=None, bar_pos=(0.75, 0.15, 0.05, 0.65), bar_on=False, units_in_JPERM2=True,", "= [plt.Rectangle((2, 2), 1, 1, fc=x, alpha=alpha) for x in", "Lattice object, the input lattice for the conventional unit cell", "axis_off (bool) .. attribute:: show_area .. attribute:: off_color color of", "number of edges in the convex hull. Useful for identifying", "of normal. Wulff shape is the convex hull. Based on:", "lattice apply symmops to get all the miller index, then", "logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\" Prepare for display on plots \"(hkl)\"", "distance to (0, 0, 0), plane function: normal[0]x + normal[1]y", "the color bar on. Return: (matplotlib.pyplot) \"\"\" import matplotlib as", "Structure object, input conventional unit cell (with H ) from", "plane.outer_lines.sort() plane.outer_lines = [line for line in plane.outer_lines if plane.outer_lines.count(line)", "cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e) return cross_pt def _get_simpx_plane(self): \"\"\" Locate", "assign colors according to the surface energies of on_wulff facets.", "(dict): {hkl: area_hkl/total area on wulff} \"\"\" return {hkl: self.miller_area_dict[hkl]", "Returns {hkl: area_hkl on wulff} \"\"\" return dict(zip(self.miller_list, self.color_area)) @property", "in dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp = wulff_convex.simplices logger.debug(\", \".join([str(len(x))", "x in wulff_cv_simp])) # store simplices and convex self.dual_cv_simp =", "\"\"\" tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy +=", "pts in a facet used to draw a line \"\"\"", "the number of edges in the convex hull. Useful for", "= [self.facets[dual_simp[i]].e_surf for i in range(3)] cross_pt = sp.dot(sp.linalg.inv(matrix_surfs), matrix_e)", "Locate the plane for simpx of on wulff_cv, by comparing", "e_surf_list list of input surface energies, in the same order", "for i in range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf for i in", "there is only one hkl on wulff, choose the color", "return plt def _get_azimuth_elev(self, miller_index): \"\"\" Args: miller_index: viewing direction", "= 'Copyright 2013, The Materials Virtual Lab' __version__ = '0.1'", "symprec # 2. get all the data for wulff construction", "attribute:: e_surf_list list of input surface energies, in the same", "in miller_list]) self.hkl_list = tuple([(x[0], x[1], x[-1]) for x in", "@property def surface_area(self): \"\"\" Total surface area of Wulff shape.", "from a lattice, a list of indices and their corresponding", "from [simpx] tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set", "self.weighted_surface_energy area_frac_dict = self.area_fraction_dict miller_energy_dict = self.miller_energy_dict for hkl in", "Agrs: hkl: in the form of [h, k, l] or", "default is True aspect_ratio: default is (8, 8) custom_colors ({(h,k,l}:", "crystals. Scientific Data. \"\"\" from pymatgen.core.structure import Structure from pymatgen.util.coord", "abs(np.dot(plane.normal, center) - plane.e_surf) if abs_diff < 1e-5: on_wulff[plane.index] =", "0, 0), plane function: normal[0]x + normal[1]y + normal[2]z =", "fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Add colorbar if bar_on:", "not specified, use the miller indices of # maximum area.", "on plots \"(hkl)\" for surfaces Agrs: hkl: in the form", "= plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev = self._get_azimuth_elev([direction[0], direction[1], direction[-1]])", "surface_area = [0.0] * len(self.miller_list) for simpx in self.wulff_cv_simp: pts", "shape,the weighted surface energy, the anisotropy and shape_factor can also", "index, for hcp in the form of hkil .. attribute::", "wulff_pt_list self.wulff_cv_simp = wulff_cv_simp self.wulff_convex = wulff_convex self.on_wulff, self.color_area =", "mpl.colors.BoundaryNorm(bounds, cmap.N) # display surface energies ax1 = fig.add_axes(bar_pos) cbar", "recp_symmops: miller = tuple([int(x) for x in op.operate(hkl)]) if miller", "size. A large shape factor indicates great anisotropy. See <NAME>.,", "[] pt = self.get_line_in_facet(facet) lines = [] for i, p", "the Wulff shape. direction: default is (1, 1, 1) bar_pos:", "# Copyright (c) Pymatgen Development Team. # Distributed under the", "fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev = self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list =", "one plane for plane in self.facets: abs_diff = abs(np.dot(plane.normal, center)", "utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under", "import matplotlib as mpl import matplotlib.pyplot as plt import mpl_toolkits.mplot3d", "len(lines) > 0: if prev is None: l = lines.pop(0)", "1), fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5, 1),", "self.e_surf = e_surf self.normal_pt = normal_pt self.dual_pt = dual_pt self.index", "color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1, 1, fc=color_list[i], alpha=alpha))", "= e_surf from self: normal_e_m to get the plane functions", "cart[1], 0] elev = get_angle(cart, v) return azim, elev @property", "make any sense to have the color bar on. Return:", "= e_surf return: [WulffFacet] \"\"\" all_hkl = [] color_ind =", "in self.facets: abs_diff = abs(np.dot(plane.normal, center) - plane.e_surf) if abs_diff", "for hexagonal lattices. If you use this code extensively, consider", "energies ax1 = fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase( ax1, cmap=cmap, norm=norm,", "from pymatgen.core.structure import Structure from pymatgen.util.coord import get_angle import numpy", "sorted pts in a facet used to draw a line", "__author__ = '<NAME>, <NAME>, <NAME>' __copyright__ = 'Copyright 2013, The", "enumerate(zip(self.hkl_list, self.e_surf_list)): for op in recp_symmops: miller = tuple([int(x) for", "1.1]) # add legend if legend_on: color_proxy = color_proxy if", "bar_on: cmap = plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds = [round(e, 2)", "attribute:: wulff_cv_simp simplices from the convex hull of wulff_pt_list ..", "= scalar_map.to_rgba(e_surf, alpha=alpha) if tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])]", "[] class WulffShape: \"\"\" Generate Wulff Shape from list of", "and (hkil) for hexagonal lattices. If you use this code", "object, the input lattice for the conventional unit cell ..", "1: # empty, plane is not on_wulff. continue # assign", "shape factor indicates great anisotropy. See <NAME>., <NAME>. & <NAME>.", "and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return pt def", "get all the facets functions for wulff shape calculation: |normal|", "on_wulff. continue # assign the color for on_wulff facets according", "plane.e_surf) if abs_diff < 1e-5: on_wulff[plane.index] = True surface_area[plane.index] +=", "Wulff shape. \"\"\" return sum(self.miller_area_dict.values()) @property def weighted_surface_energy(self): \"\"\" Returns:", "x in self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp = dual_convex.simplices #", "default is (1, 1, 1) bar_pos: default is [0.75, 0.15,", "= mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map) for i, e_surf in e_surf_on_wulff: color_list[i] =", "np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return", "i in range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf for i in range(3)]", "i, p in enumerate(pt): if i == len(pt) / 2:", "wulff} \"\"\" return {hkl: self.miller_area_dict[hkl] / self.surface_area for hkl in", "for x in miller_list]) self.hkl_list = tuple([(x[0], x[1], x[-1]) for", "tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys(): tot_surface_energy += self.miller_energy_dict[hkl]", "cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: # if there is only", "= [0.0] * len(self.miller_list) for simpx in self.wulff_cv_simp: pts =", "from a given view in terms of miller index. The", "of each facet with a dictionary. The key is the", "of miller index. The lattice is from the conventional unit", "attribute:: on_wulff list for all input_miller, True is on wulff.", "miller_on_wulff, e_surf_on_wulff_list def show(self, *args, **kwargs): r\"\"\" Show the Wulff", "default is [0.75, 0.15, 0.05, 0.65] bar_on (bool): default is", "l in enumerate(lines): if prev in l: l = lines.pop(i)", "of input surface energies, in the same order with input_miller", "default is False legend_on (bool): default is True aspect_ratio: default", "a given view in terms of miller index. The lattice", "If you decide to set your own colors, it probably", "[x[1] for x in e_surf_on_wulff] if len(e_surf_on_wulff) > 1: cnorm", "if there is only one hkl on wulff, choose the", "hkill to hkl, in the same order with input_miller ..", "directions r_range = max([np.linalg.norm(x) for x in wulff_pt_list]) ax.set_xlim([-r_range *", "complete and consistent display for all directions r_range = max([np.linalg.norm(x)", "terms of the MIT License. \"\"\" This module define a", "1) bar_pos: default is [0.75, 0.15, 0.05, 0.65] bar_on (bool):", "= [self.wulff_pt_list[simpx[i]] for i in range(3)] center = np.sum(pts, 0)", "e_surf is plane's distance to (0, 0, 0), plane function:", "ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Add colorbar if bar_on: cmap =", "(float) sum(surface_energy_hkl * area_hkl) \"\"\" tot_surface_energy = 0 for hkl", "on wulff, off_wulff = 0. .. attribute:: miller_area ($hkl$): area", "plane in self.facets: # check whether [pts] is empty if", "grid_off (bool) .. attribute:: axis_off (bool) .. attribute:: show_area ..", "as np import scipy as sp from scipy.spatial import ConvexHull", "center', bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') #", "def miller_energy_dict(self): \"\"\" Returns {hkl: surface energy_hkl} \"\"\" return dict(zip(self.miller_list,", "if len(e_surf_on_wulff) > 1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: #", "normal, e_surf, normal_pt, dual_pt, index, m_ind_orig, miller): \"\"\" :param normal:", "i, (hkl, energy) in enumerate(zip(self.hkl_list, self.e_surf_list)): for op in recp_symmops:", "of plotting from a given view in terms of miller", "[WulffFacet] for all facets considering symm .. attribute:: dual_cv_simp simplices", "= True surface_area[plane.index] += get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]])", "(bool) .. attribute:: axis_off (bool) .. attribute:: show_area .. attribute::", "\"\"\" from pymatgen.core.structure import Structure from pymatgen.util.coord import get_angle import", "colors according to the surface energies of on_wulff facets. return:", "and convex self.dual_cv_simp = dual_cv_simp self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp =", "direction[-1]]) wulff_pt_list = self.wulff_pt_list ax = mpl3.Axes3D(fig, azim=azim, elev=elev) for", "plane_color = color_list[plane.index] pt = self.get_line_in_facet(plane) # plot from the", "cart = self.lattice.get_cartesian_coords(miller_index) azim = get_angle([cart[0], cart[1], 0], (1, 0,", "the form of hkil .. attribute:: hkl_list modify hkill to", "hkl, in the same order with input_miller .. attribute:: e_surf_list", "set ranges of x, y, z # find the largest", "anisotropy and shape_factor can also be calculated. In support of", "assign the color for on_wulff facets according to its #", "self.color_area)) @property def miller_energy_dict(self): \"\"\" Returns {hkl: surface energy_hkl} \"\"\"", "2005), p.461 Returns: (float) Shape factor. \"\"\" return self.surface_area /", "(Jm^2) is the length of normal. Wulff shape is the", "v2 = np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) /", "= [False] * len(self.miller_list) surface_area = [0.0] * len(self.miller_list) for", "critical nucleus size. A large shape factor indicates great anisotropy.", "import mpl_toolkits.mplot3d as mpl3 color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff =", "check whether [pts] is empty if len(plane.points) < 1: #", "consider the dual condition dual_pts = [x.dual_pt for x in", "= [] e_surf_on_wulff = [(i, e_surf) for i, e_surf in", "i, e_surf in enumerate(self.e_surf_list) if self.on_wulff[i]] c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda", "Coefficient of Variation from weighted surface energy The ideal sphere", "= [hkl_tuple_to_str(x) for x in miller_list] # store input data", "sure the lines are connected one by one. # find", "self.facets: abs_diff = abs(np.dot(plane.normal, center) - plane.e_surf) if abs_diff <", "area_hkl/total area on wulff} \"\"\" return {hkl: self.miller_area_dict[hkl] / self.surface_area", "wulff_area and other properties .. attribute:: debug (bool) .. attribute::", "if prev is None: l = lines.pop(0) else: for i,", "color 3. get wulff_area and other properties .. attribute:: debug", "the Wulffshape is approximated as a sphere. Returns: (float) radius.", "miller_index == (0, 0, 1) or miller_index == (0, 0,", "@property def tot_edges(self): \"\"\" Returns the number of edges in", "for the conventional unit cell .. attribute:: facets [WulffFacet] for", "__init__(self, lattice, miller_list, e_surf_list, symprec=1e-5): \"\"\" Args: lattice: Lattice object", "the center of the simpx triangle with the plane functions.", "in enumerate(lines): if p not in all_edges: edges.append(p) all_edges.extend(edges) return", "= symprec # 2. get all the data for wulff", "enumerate(lines): if prev in l: l = lines.pop(i) if l[1]", "ndim = 3 # i, j, k: ind for normal_e_m", "key=lambda x: x[1])[0] fig = plt.figure() fig.set_size_inches(aspect_ratio[0], aspect_ratio[1]) azim, elev", "self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list = self.wulff_pt_list ax = mpl3.Axes3D(fig, azim=azim,", "order with input_miller .. attribute:: lattice Lattice object, the input", "[x.dual_pt for x in self.facets] dual_convex = ConvexHull(dual_pts) dual_cv_simp =", "surface area of Wulff shape. \"\"\" return sum(self.miller_area_dict.values()) @property def", "Wulffshape is approximated as a sphere. Returns: (float) radius. \"\"\"", "def effective_radius(self): \"\"\" Radius of the Wulffshape when the Wulffshape", "x in normal] dual_pt = [x / energy for x", "coords for 3 points, Compute the area of this triangle.", "2) for e in e_surf_on_wulff] bounds.append(1.2 * bounds[-1]) norm =", "alpha=alpha) if tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2,", "= [] color_ind = self.color_ind planes = [] recp =", "pts from [simpx] tri = mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) #", "total area and volume of the wulff shape,the weighted surface", "all directions r_range = max([np.linalg.norm(x) for x in wulff_pt_list]) ax.set_xlim([-r_range", "of ints, shape (nfacet, ndim)) # list of [i, j,", "def _get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal| = 1, e_surf is plane's", "direction = max(self.area_fraction_dict.items(), key=lambda x: x[1])[0] fig = plt.figure() fig.set_size_inches(aspect_ratio[0],", "enumerate(self.e_surf_list) if self.on_wulff[i]] c_map = plt.get_cmap(color_set) e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False)", "display surface energies ax1 = fig.add_axes(bar_pos) cbar = mpl.colorbar.ColorbarBase( ax1,", "# store simplices and convex self.dual_cv_simp = dual_cv_simp self.wulff_pt_list =", "index and surface energies, with given conventional unit cell. surface", "get_tri_area(pts) plane.points.append(pts) plane.outer_lines.append([simpx[0], simpx[1]]) plane.outer_lines.append([simpx[1], simpx[2]]) plane.outer_lines.append([simpx[0], simpx[2]]) # already", "facet with a dictionary. The key is the corresponding Miller", "miller_on_wulff, e_surf_on_wulff = self._get_colors( color_set, alpha, off_color, custom_colors=custom_colors) if not", "str(-x) + '}' else: str_format += str(x) str_format += '$)'", "symprec (float): for recp_operation, default is 1e-5. \"\"\" if any([se", "functions for wulff shape calculation: |normal| = 1, e_surf is", "of on wulff_cv, by comparing the center of the simpx", "from self: get miller_list(unique_miller), e_surf_list and symmetry operations(symmops) according to", "get_all_miller_e() self.facets = self._get_all_miller_e() logger.debug(len(self.facets)) # 3. consider the dual", "color_list[plane.index] pt = self.get_line_in_facet(plane) # plot from the sorted pts", "for 3 points, Compute the area of this triangle. Args:", "tuple(self.miller_list[i]) in custom_colors.keys(): color_list[i] = custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1,", "list of [i, j, k] , ndim = 3 #", "the Wulff shape from a lattice, a list of indices", "\"\"\" return self.surface_area / (self.volume ** (2 / 3)) @property", "their corresponding surface energies, and the total area and volume", "'May 5 2016' logger = logging.getLogger(__name__) def hkl_tuple_to_str(hkl): \"\"\" Prepare", "= mpl3.art3d.Poly3DCollection([pt]) tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set ranges of x,", "2), 1, 1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for x in", "= [self._get_cross_pt_dual_simp(dual_simp) for dual_simp in dual_cv_simp] wulff_convex = ConvexHull(wulff_pt_list) wulff_cv_simp", "e_surf_on_wulff]) color_proxy = [plt.Rectangle((2, 2), 1, 1, fc=x, alpha=alpha) for", "custom_colors[tuple(self.miller_list[i])] color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1, 1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1]", "k: ind for normal_e_m # recalculate the dual of dual,", "l[1] return pt def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1,", "0.65] bar_on (bool): default is False legend_on (bool): default is", "m_ind_orig: :param miller: \"\"\" self.normal = normal self.e_surf = e_surf", "default is Ture show_area (bool): default is False alpha (float):", "color_list = [off_color] * len(self.hkl_list) color_proxy_on_wulff = [] miller_on_wulff =", "p in enumerate(pt): if i == len(pt) / 2: break", "y, z # find the largest distance between on_wulff pts", "way covering all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev =", "also be calculated. In support of plotting from a given", "_get_simpx_plane(self): \"\"\" Locate the plane for simpx of on wulff_cv,", "chosen from 0 to 1 (float), default is 1 off_color:", "color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt, dual_pt, color_plane, i, hkl)) #", "you decide to set your own colors, it probably won't", "lattice, a list of indices and their corresponding surface energies,", "custom_colors ({(h,k,l}: [r,g,b,alpha}): Customize color of each facet with a", "pt = [] prev = None while len(lines) > 0:", "0)) v = [cart[0], cart[1], 0] elev = get_angle(cart, v)", "# maximum area. direction = max(self.area_fraction_dict.items(), key=lambda x: x[1])[0] fig", "volume(self): \"\"\" Volume of the Wulff shape \"\"\" return self.wulff_convex.volume", "(c) Pymatgen Development Team. # Distributed under the terms of", "direction: # If direction is not specified, use the miller", "1.1]) ax.set_ylim([-r_range * 1.1, r_range * 1.1]) ax.set_zlim([-r_range * 1.1,", "p.461 Returns: (float) Shape factor. \"\"\" return self.surface_area / (self.volume", "tot_surface_energy += self.miller_energy_dict[hkl] * \\ self.miller_area_dict[hkl] return tot_surface_energy @property def", "/ 3.0 # check whether the center of the simplices", "' + str(round(self.color_area[m], 4))) self.miller_area = miller_area def _get_all_miller_e(self): \"\"\"", "loc='upper left', bbox_to_anchor=(0, 1), fancybox=True, shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper", "as mpl import matplotlib.pyplot as plt color_list = [off_color] *", "0, 1) or miller_index == (0, 0, 0, 1): return", "of wulff_pt_list .. attribute:: on_wulff list for all input_miller, True", "get_angle import numpy as np import scipy as sp from", "Undefined facets will use default color site. Note: If you", "r_range * 1.1]) ax.set_zlim([-r_range * 1.1, r_range * 1.1]) #", "x[-1]) for x in miller_list]) self.e_surf_list = tuple(e_surf_list) self.lattice =", "+ str(-x) + '}' else: str_format += str(x) str_format +=", "(bool): default is False alpha (float): chosen from 0 to", "from the conventional unit cell, and (hkil) for hexagonal lattices.", "from lattice .. attribute:: miller_list list of input miller index,", "convex self.dual_cv_simp = dual_cv_simp self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp = wulff_cv_simp", "facets functions for wulff shape calculation: |normal| = 1, e_surf", "index self.m_ind_orig = m_ind_orig self.miller = miller self.points = []", "alpha, off_color, custom_colors={}): \"\"\" assign colors according to the surface", "direction[1], direction[-1]]) wulff_pt_list = self.wulff_pt_list ax = mpl3.Axes3D(fig, azim=azim, elev=elev)", "bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # display surface energies ax1", "with given conventional unit cell. surface energy (Jm^2) is the", "self.total_surface_energy / self.surface_area @property def area_fraction_dict(self): \"\"\" Returns: (dict): {hkl:", "pt def get_plot(self, color_set='PuBu', grid_off=True, axis_off=True, show_area=False, alpha=1, off_color='red', direction=None,", "= self.weighted_surface_energy area_frac_dict = self.area_fraction_dict miller_energy_dict = self.miller_energy_dict for hkl", "wulff, off_wulff = 0. .. attribute:: miller_area ($hkl$): area for", "self.facets: edges = [] pt = self.get_line_in_facet(facet) lines = []", "{hkl: self.miller_area_dict[hkl] / self.surface_area for hkl in self.miller_area_dict.keys()} @property def", "= \"$J/m^2$\" if units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface Energies (%s)' %", "Default color for facets not present on the Wulff shape.", "= self._get_simpx_plane() miller_area = [] for m, in_mill_fig in enumerate(self.input_miller_fig):", "in_mill_fig + ' : ' + str(round(self.color_area[m], 4))) self.miller_area =", "miller_area_dict(self): \"\"\" Returns {hkl: area_hkl on wulff} \"\"\" return dict(zip(self.miller_list,", "shadow=False) else: ax.legend(color_proxy_on_wulff, miller_on_wulff, loc='upper center', bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True,", "= self.get_line_in_facet(facet) lines = [] for i, p in enumerate(pt):", "as plt import mpl_toolkits.mplot3d as mpl3 color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff,", "hkl_tuple_to_str(hkl): \"\"\" Prepare for display on plots \"(hkl)\" for surfaces", "in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig + ' : ' + str(round(self.color_area[m],", "sp from scipy.spatial import ConvexHull import logging import warnings __author__", "\"\"\" Returns the number of edges in the convex hull.", "elev = get_angle(cart, v) return azim, elev @property def volume(self):", "Variation from weighted surface energy The ideal sphere is 0.", "as mpl import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as mpl3", "elev = self._get_azimuth_elev([direction[0], direction[1], direction[-1]]) wulff_pt_list = self.wulff_pt_list ax =", "return azim, elev @property def volume(self): \"\"\" Volume of the", "self.wulff_cv_simp = wulff_cv_simp self.wulff_convex = wulff_convex self.on_wulff, self.color_area = self._get_simpx_plane()", "of the simplices is on one plane for plane in", "len(self.wulff_convex.vertices) @property def tot_edges(self): \"\"\" Returns the number of edges", "get cross point from the simplices of the dual convex", "input_miller, True is on wulff. .. attribute:: color_area list for", "1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: # if there is", "[WulffFacet] \"\"\" all_hkl = [] color_ind = self.color_ind planes =", "of miller index and surface energies, with given conventional unit", "normal_pt self.dual_pt = dual_pt self.index = index self.m_ind_orig = m_ind_orig", "from self: normal_e_m to get the plane functions dual_simp: (i,", "l[1] == prev: l.reverse() break # make sure the lines", "0.15, 0.05, 0.65] bar_on (bool): default is False legend_on (bool):", "the Wulff shape. Returns: (float) sum(surface_energy_hkl * area_hkl) \"\"\" tot_surface_energy", "'Copyright 2013, The Materials Virtual Lab' __version__ = '0.1' __maintainer__", "self.m_ind_orig = m_ind_orig self.miller = miller self.points = [] self.outer_lines", "attribute:: structure Structure object, input conventional unit cell (with H", "on_wulff facets. return: (color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\" import", "a list of coords for 3 points, Compute the area", "= m_ind_orig self.miller = miller self.points = [] self.outer_lines =", "in range(3)] center = np.sum(pts, 0) / 3.0 # check", "in_mill_fig in enumerate(self.input_miller_fig): miller_area.append( in_mill_fig + ' : ' +", "condition dual_pts = [x.dual_pt for x in self.facets] dual_convex =", "volume of the wulff shape,the weighted surface energy, the anisotropy", "color_plane = color_ind[divmod(i, len(color_ind))[1]] planes.append(WulffFacet(normal, energy, normal_pt, dual_pt, color_plane, i,", "def miller_area_dict(self): \"\"\" Returns {hkl: area_hkl on wulff} \"\"\" return", "if any([se < 0 for se in e_surf_list]): warnings.warn(\"Unphysical (negative)", "and consistent display for all directions r_range = max([np.linalg.norm(x) for", "Total surface energy of the Wulff shape. Returns: (float) sum(surface_energy_hkl", "color_set: default is 'PuBu' grid_off (bool): default is True axis_off", "False legend_on (bool): default is True aspect_ratio: default is (8,", "4) * (self.volume / np.pi)) ** (1 / 3) @property", "def anisotropy(self): \"\"\" Returns: (float) Coefficient of Variation from weighted", "get_tri_area(pts): \"\"\" Given a list of coords for 3 points,", "\"\"\" if any([se < 0 for se in e_surf_list]): warnings.warn(\"Unphysical", "index. The lattice is from the conventional unit cell, and", "tot_edges(self): \"\"\" Returns the number of edges in the convex", "* area_hkl) \"\"\" tot_surface_energy = 0 for hkl in self.miller_energy_dict.keys():", "from the dual convex hull i, j, k: plane index(same", "plane.outer_lines.count(line) != 2] return on_wulff, surface_area def _get_colors(self, color_set, alpha,", "tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set ranges of x, y, z #", ".. attribute:: miller_area ($hkl$): area for all input_miller \"\"\" def", "pt = self.get_line_in_facet(facet) lines = [] for i, p in", "tri.set_color(plane_color) tri.set_edgecolor(\"#808080\") ax.add_collection3d(tri) # set ranges of x, y, z", "list of coords for 3 points, Compute the area of", "same order with input_miller .. attribute:: lattice Lattice object, the", "attribute:: hkl_list modify hkill to hkl, in the same order", "show_area: ax.legend(color_proxy, self.miller_area, loc='upper left', bbox_to_anchor=(0, 1), fancybox=True, shadow=False) else:", "in e_surf_on_wulff] if len(e_surf_on_wulff) > 1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list))", ".. attribute:: miller_list list of input miller index, for hcp", "Get the Wulff shape plot. Args: color_set: default is 'PuBu'", "self.normal = normal self.e_surf = e_surf self.normal_pt = normal_pt self.dual_pt", "from 0 to 1 (float), default is 1 off_color: Default", "Team. # Distributed under the terms of the MIT License.", "the following: <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. (2016). Surface", "\"\"\" Returns the sorted pts in a facet used to", "is the color. Undefined facets will use default color site.", "indices and their corresponding surface energies, and the total area", "import get_angle import numpy as np import scipy as sp", "k, l] or (h, k, l) \"\"\" str_format = '($'", "get all the data for wulff construction # get all", "= [] self.outer_lines = [] class WulffShape: \"\"\" Generate Wulff", "break lines.append(tuple(sorted(tuple([tuple(pt[i * 2]), tuple(pt[i * 2 + 1])])))) for", "Add colorbar if bar_on: cmap = plt.get_cmap(color_set) cmap.set_over('0.25') cmap.set_under('0.75') bounds", "lattice .. attribute:: miller_list list of input miller index, for", "is on wulff. .. attribute:: color_area list for all input_miller,", "according to the surface energies of on_wulff facets. return: (color_list,", "<NAME>' __copyright__ = 'Copyright 2013, The Materials Virtual Lab' __version__", "2. label with color 3. get wulff_area and other properties", "e_surf from self: normal_e_m to get the plane functions dual_simp:", "enumerate(lines): if p not in all_edges: edges.append(p) all_edges.extend(edges) return len(all_edges)", "3. consider the dual condition dual_pts = [x.dual_pt for x", "facets not present on the Wulff shape. direction: default is", "= '($' for x in hkl: if x < 0:", "= dual_cv_simp self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp = wulff_cv_simp self.wulff_convex =", "and the color_list for on_wulff plane_color = color_list[plane.index] pt =", "bar on. Return: (matplotlib.pyplot) \"\"\" import matplotlib as mpl import", "is only one hkl on wulff, choose the color of", "norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # display surface energies ax1 =", "plane. \"\"\" def __init__(self, normal, e_surf, normal_pt, dual_pt, index, m_ind_orig,", "self.wulff_pt_list ax = mpl3.Axes3D(fig, azim=azim, elev=elev) for plane in self.facets:", "shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Add colorbar if bar_on: cmap", "tuple(pt[i * 2 + 1])])))) for i, p in enumerate(lines):", "grid_off (bool): default is True axis_off (bool): default is Ture", "+= '\\\\overline{' + str(-x) + '}' else: str_format += str(x)", "wulff simplices 2. label with color 3. get wulff_area and", "custom_colors=custom_colors) if not direction: # If direction is not specified,", "str_format def get_tri_area(pts): \"\"\" Given a list of coords for", "length of normal. Wulff shape is the convex hull. Based", "move to the next simplices break for plane in self.facets:", "all_edges = [] for facet in self.facets: edges = []", "all input_miller, True is on wulff. .. attribute:: color_area list", "+= str(x) str_format += '$)' return str_format def get_tri_area(pts): \"\"\"", "miller_on_wulff = [] e_surf_on_wulff = [(i, e_surf) for i, e_surf", "planes def _get_cross_pt_dual_simp(self, dual_simp): \"\"\" |normal| = 1, e_surf is", "and surface energies, with given conventional unit cell. surface energy", "= [self.facets[dual_simp[i]].normal for i in range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf for", "color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff_list) \"\"\" import matplotlib as mpl import matplotlib.pyplot", "Total surface area of Wulff shape. \"\"\" return sum(self.miller_area_dict.values()) @property", "index and value is the color. Undefined facets will use", "1, e_surf is plane's distance to (0, 0, 0), plane", "specified, use the miller indices of # maximum area. direction", "# if there is only one hkl on wulff, choose", "weighted surface energy, the anisotropy and shape_factor can also be", "Returns the sorted pts in a facet used to draw", "from scipy.spatial import ConvexHull import logging import warnings __author__ =", "in wulff_pt_list]) ax.set_xlim([-r_range * 1.1, r_range * 1.1]) ax.set_ylim([-r_range *", "0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf", "are connected one by one. # find the way covering", "of the dual convex hull wulff_pt_list = [self._get_cross_pt_dual_simp(dual_simp) for dual_simp", "> 1: cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list), vmax=max(e_surf_on_wulff_list)) else: # if there", "hcp e_surf_list ([float]): list of corresponding surface energies symprec (float):", "convex hull. Useful for identifying catalytically active sites. \"\"\" return", "sp.linalg.norm(normal) normal_pt = [x * energy for x in normal]", "[] for facet in self.facets: edges = [] pt =", "\"\"\" Args: miller_index: viewing direction Returns: azim, elev for plotting", "of [h, k, l] or (h, k, l) \"\"\" str_format", "the corresponding Miller index and value is the color. Undefined", "to set your own colors, it probably won't make any", "simpx in self.wulff_cv_simp: pts = [self.wulff_pt_list[simpx[i]] for i in range(3)]", "def tot_corner_sites(self): \"\"\" Returns the number of vertices in the", "the plane, move to the next simplices break for plane", "logger.debug(len(self.facets)) # 3. consider the dual condition dual_pts = [x.dual_pt", "for recp_operation, default is 1e-5. \"\"\" if any([se < 0", "as sp from scipy.spatial import ConvexHull import logging import warnings", "surface energy detected.\") self.color_ind = list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x) for", "spacing='proportional', orientation='vertical') units = \"$J/m^2$\" if units_in_JPERM2 else r\"$eV/\\AA^2$\" cbar.set_label('Surface", "key is the corresponding Miller index and value is the", "container for each Wulff plane. \"\"\" def __init__(self, normal, e_surf,", "show_area (bool): default is False alpha (float): chosen from 0", "return self.wulff_convex.volume @property def miller_area_dict(self): \"\"\" Returns {hkl: area_hkl on", "any([se < 0 for se in e_surf_list]): warnings.warn(\"Unphysical (negative) surface", "(negative) surface energy detected.\") self.color_ind = list(range(len(miller_list))) self.input_miller_fig = [hkl_tuple_to_str(x)", "Wulff shape from a lattice, a list of indices and", "in normal_e_m) \"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal for i in range(3)]", "in l: l = lines.pop(i) if l[1] == prev: l.reverse()", "* len(self.miller_list) surface_area = [0.0] * len(self.miller_list) for simpx in", "dual_cv_simp self.wulff_pt_list = wulff_pt_list self.wulff_cv_simp = wulff_cv_simp self.wulff_convex = wulff_convex", "for x in op.operate(hkl)]) if miller not in all_hkl: all_hkl.append(miller)", "mpl3 color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors( color_set, alpha,", "**kwargs): r\"\"\" Show the Wulff plot. Args: *args: Passed to", "ndim)) # list of [i, j, k] , ndim =", "self.lattice = lattice self.symprec = symprec # 2. get all", "color_set, alpha, off_color, custom_colors=custom_colors) if not direction: # If direction", "e in e_surf_on_wulff] bounds.append(1.2 * bounds[-1]) norm = mpl.colors.BoundaryNorm(bounds, cmap.N)", "\"\"\" assign colors according to the surface energies of on_wulff", "empty if len(plane.points) < 1: # empty, plane is not", "True is on wulff. .. attribute:: color_area list for all", "self._get_simpx_plane() miller_area = [] for m, in_mill_fig in enumerate(self.input_miller_fig): miller_area.append(", "= [] recp = self.structure.lattice.reciprocal_lattice_crystallographic recp_symmops = self.lattice.get_recp_symmetry_operation(self.symprec) for i,", "x in e_surf_on_wulff]) color_proxy = [plt.Rectangle((2, 2), 1, 1, fc=x,", "area_hkl)/ sum(area_hkl) \"\"\" return self.total_surface_energy / self.surface_area @property def area_fraction_dict(self):", "ints, shape (nfacet, ndim)) # list of [i, j, k]", "order in normal_e_m) \"\"\" matrix_surfs = [self.facets[dual_simp[i]].normal for i in", "of Materials. (<NAME>, 2005), p.461 Returns: (float) Shape factor. \"\"\"", "in range(3)] matrix_e = [self.facets[dual_simp[i]].e_surf for i in range(3)] cross_pt", "+ bounds + [10], extend='both', ticks=bounds[:-1], spacing='proportional', orientation='vertical') units =", "in miller_list]) self.e_surf_list = tuple(e_surf_list) self.lattice = lattice self.symprec =", "1])])))) for i, p in enumerate(lines): if p not in", "for on_wulff plane_color = color_list[plane.index] pt = self.get_line_in_facet(plane) # plot", "for i, p in enumerate(pt): if i == len(pt) /", "the next simplices break for plane in self.facets: plane.outer_lines.sort() plane.outer_lines", "else: for i, l in enumerate(lines): if prev in l:", "off_wulff = 0. .. attribute:: miller_area ($hkl$): area for all", "for i, (hkl, energy) in enumerate(zip(self.hkl_list, self.e_surf_list)): for op in", "matplotlib.pyplot as plt import mpl_toolkits.mplot3d as mpl3 color_list, color_proxy, color_proxy_on_wulff,", "for x in miller_list] # store input data self.structure =", "< 1: # empty, plane is not on_wulff. continue #", "color_proxy_on_wulff.append( plt.Rectangle((2, 2), 1, 1, fc=color_list[i], alpha=alpha)) miller_on_wulff.append(self.input_miller_fig[i]) scalar_map.set_array([x[1] for", "wulff} \"\"\" return dict(zip(self.miller_list, self.color_area)) @property def miller_energy_dict(self): \"\"\" Returns", "Returns {hkl: surface energy_hkl} \"\"\" return dict(zip(self.miller_list, self.e_surf_list)) @property def", "input_miller \"\"\" def __init__(self, lattice, miller_list, e_surf_list, symprec=1e-5): \"\"\" Args:", "for facet in self.facets: edges = [] pt = self.get_line_in_facet(facet)", "object of the conventional unit cell miller_list ([(hkl), ...]: list", "\"\"\" Returns: (dict): {hkl: area_hkl/total area on wulff} \"\"\" return", "area_hkl on wulff} \"\"\" return dict(zip(self.miller_list, self.color_area)) @property def miller_energy_dict(self):", ": ' + str(round(self.color_area[m], 4))) self.miller_area = miller_area def _get_all_miller_e(self):", "surface energies, in the same order with input_miller .. attribute::", "median cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1, vmax=max(e_surf_on_wulff_list) + 0.1) scalar_map", "0.05, 0.65] bar_on (bool): default is False legend_on (bool): default", "attribute:: miller_list list of input miller index, for hcp in", "loc='upper center', bbox_to_anchor=(0.5, 1), ncol=3, fancybox=True, shadow=False) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z')", "in the form of [h, k, l] or (h, k,", "== (0, 0, 0, 1): return 0, 90 else: cart", "self._get_all_miller_e() logger.debug(len(self.facets)) # 3. consider the dual condition dual_pts =", "(0, 0, 0, 1): return 0, 90 else: cart =", "\"\"\" str_format = '($' for x in hkl: if x", "2013, The Materials Virtual Lab' __version__ = '0.1' __maintainer__ =", "self._get_colors( color_set, alpha, off_color, custom_colors=custom_colors) if not direction: # If", "wulff_pt_list]) ax.set_xlim([-r_range * 1.1, r_range * 1.1]) ax.set_ylim([-r_range * 1.1,", "return tot_surface_energy @property def tot_corner_sites(self): \"\"\" Returns the number of", "0]]) self.miller_list = tuple([tuple(x) for x in miller_list]) self.hkl_list =" ]
[ "= min_count self.include_UNK = include_UNK self.include_PAD = include_PAD self.frozen =", "i2s(self, i): assert self.frozen if 0 <= i < self.voc_size:", "__reduce__(self): return Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i,", "-1 self.UNK_s = \"<UNK>\" self.PAD_i = -2 self.PAD_s = \"<PAD>\"", "= dict() def iter_item(self): return enumerate(self._i2s) def get_s2i(self, s, default:", "self._s2i, self._i2s, self.frequency) def __setstate__(self, state): self.min_count = state[0] self.include_UNK", "i self.voc_size = len(self._i2s) self.frozen = True def __reduce__(self): return", "[] self.frequency = dict() def iter_item(self): return enumerate(self._i2s) def get_s2i(self,", "return self.s2i(s) def s2i(self, s): i = self.get_s2i(s, -1) if", "if count >= self.min_count: self._i2s.append(s) for i, s in enumerate(self._i2s):", "self._s2i.get(s, -1) if i >= 0: return i elif self.include_UNK:", "self.s2i(s) def s2i(self, s): i = self.get_s2i(s, -1) if i", "0: return i else: raise Exception(f\"out of vocabulary entry {s}\")", "= i self.voc_size = len(self._i2s) self.frozen = True def __reduce__(self):", "self.include_PAD = include_PAD self.frozen = False self.UNK_i = -1 self.UNK_s", "def __reduce__(self): return Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen,", "<= i < self.voc_size: return self._i2s[i] else: raise Exception(f\"not entry", "self.frozen if 0 <= i < self.voc_size: return self._i2s[i] else:", "in sorted(self.frequency.items(), key=lambda x: -x[1]): if count >= self.min_count: self._i2s.append(s)", "return i else: raise Exception(f\"out of vocabulary entry {s}\") def", "if self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i =", "def get_s2i(self, s, default: int): assert self.frozen i = self._s2i.get(s,", "-2 self.PAD_s = \"<PAD>\" self.voc_size = 0 self._s2i = dict()", "self._i2s = [] self.frequency = dict() def iter_item(self): return enumerate(self._i2s)", "state[6] self.voc_size = state[7] self._s2i = state[8] self._i2s = state[9]", "def i2s(self, i): assert self.frozen if 0 <= i <", "def iter_item(self): return enumerate(self._i2s) def get_s2i(self, s, default: int): assert", "include_PAD: bool): self.min_count = min_count self.include_UNK = include_UNK self.include_PAD =", "dict() def iter_item(self): return enumerate(self._i2s) def get_s2i(self, s, default: int):", "False self.UNK_i = -1 self.UNK_s = \"<UNK>\" self.PAD_i = -2", "i >= 0: return i elif self.include_UNK: return self.UNK_i else:", "for s, count in sorted(self.frequency.items(), key=lambda x: -x[1]): if count", "= \"<UNK>\" self.PAD_i = -2 self.PAD_s = \"<PAD>\" self.voc_size =", "self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for s, count", "self.PAD_i = -2 self.PAD_s = \"<PAD>\" self.voc_size = 0 self._s2i", "self._i2s.append(s) for i, s in enumerate(self._i2s): self._s2i[s] = i self.voc_size", "self.include_UNK = include_UNK self.include_PAD = include_PAD self.frozen = False self.UNK_i", "s, count in sorted(self.frequency.items(), key=lambda x: -x[1]): if count >=", "state[3] self.UNK_s = state[4] self.PAD_i = state[5] self.PAD_s = state[6]", "x: -x[1]): if count >= self.min_count: self._i2s.append(s) for i, s", "return Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s,", "__setstate__(self, state): self.min_count = state[0] self.include_UNK = state[1] self.frozen =", "self._s2i[s] = i self.voc_size = len(self._i2s) self.frozen = True def", "add_to_counts(self, s): assert not self.frozen self.frequency[s] = self.frequency.get(s, 0)+1 def", "0)+1 def freeze(self): assert not self.frozen if self.include_UNK: self.UNK_i =", "assert not self.frozen self.frequency[s] = self.frequency.get(s, 0)+1 def freeze(self): assert", "{i} for a vocabulary of size {self.voc_size}\") def add_to_counts(self, s):", "i = self.get_s2i(s, -1) if i >= 0: return i", "self.min_count: self._i2s.append(s) for i, s in enumerate(self._i2s): self._s2i[s] = i", "state[1] self.frozen = state[2] self.UNK_i = state[3] self.UNK_s = state[4]", "self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency) def __setstate__(self, state): self.min_count", "= state[0] self.include_UNK = state[1] self.frozen = state[2] self.UNK_i =", "self.UNK_s = \"<UNK>\" self.PAD_i = -2 self.PAD_s = \"<PAD>\" self.voc_size", "i = self._s2i.get(s, -1) if i >= 0: return i", "self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i = len(self._i2s)", "of vocabulary entry {s}\") def contains(self, s): return self.get_s2i(s, -1)", "get_s2i(self, s, default: int): assert self.frozen i = self._s2i.get(s, -1)", "= self.frequency.get(s, 0)+1 def freeze(self): assert not self.frozen if self.include_UNK:", "self._s2i = dict() self._i2s = [] self.frequency = dict() def", "def contains(self, s): return self.get_s2i(s, -1) != -1 def i2s(self,", "else: raise Exception(f\"out of vocabulary entry {s}\") def contains(self, s):", "self.frozen if self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i", "self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for s, count in sorted(self.frequency.items(),", "{self.voc_size}\") def add_to_counts(self, s): assert not self.frozen self.frequency[s] = self.frequency.get(s,", "def __setstate__(self, state): self.min_count = state[0] self.include_UNK = state[1] self.frozen", "self.frozen = True def __reduce__(self): return Any2Int, (2, self.include_UNK, self.include_PAD),", "dict() self._i2s = [] self.frequency = dict() def iter_item(self): return", "len(self._i2s) self._i2s.append(self.PAD_s) for s, count in sorted(self.frequency.items(), key=lambda x: -x[1]):", "else: return default def __getitem__(self, s): return self.s2i(s) def s2i(self,", "min_count self.include_UNK = include_UNK self.include_PAD = include_PAD self.frozen = False", "default def __getitem__(self, s): return self.s2i(s) def s2i(self, s): i", "raise Exception(f\"out of vocabulary entry {s}\") def contains(self, s): return", "= state[1] self.frozen = state[2] self.UNK_i = state[3] self.UNK_s =", "= state[4] self.PAD_i = state[5] self.PAD_s = state[6] self.voc_size =", "i): assert self.frozen if 0 <= i < self.voc_size: return", "for a vocabulary of size {self.voc_size}\") def add_to_counts(self, s): assert", "return self.get_s2i(s, -1) != -1 def i2s(self, i): assert self.frozen", "not self.frozen self.frequency[s] = self.frequency.get(s, 0)+1 def freeze(self): assert not", "count in sorted(self.frequency.items(), key=lambda x: -x[1]): if count >= self.min_count:", "assert not self.frozen if self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if", "state[4] self.PAD_i = state[5] self.PAD_s = state[6] self.voc_size = state[7]", "Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i,", "iter_item(self): return enumerate(self._i2s) def get_s2i(self, s, default: int): assert self.frozen", "a vocabulary of size {self.voc_size}\") def add_to_counts(self, s): assert not", "not self.frozen if self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD:", "self.voc_size = state[7] self._s2i = state[8] self._i2s = state[9] self.frequency", "-1) if i >= 0: return i elif self.include_UNK: return", "bool, include_PAD: bool): self.min_count = min_count self.include_UNK = include_UNK self.include_PAD", "count >= self.min_count: self._i2s.append(s) for i, s in enumerate(self._i2s): self._s2i[s]", "Any2Int: def __init__(self, min_count: int, include_UNK: bool, include_PAD: bool): self.min_count", "state[2] self.UNK_i = state[3] self.UNK_s = state[4] self.PAD_i = state[5]", "position {i} for a vocabulary of size {self.voc_size}\") def add_to_counts(self,", "__init__(self, min_count: int, include_UNK: bool, include_PAD: bool): self.min_count = min_count", "= len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for", "s in enumerate(self._i2s): self._s2i[s] = i self.voc_size = len(self._i2s) self.frozen", ">= 0: return i elif self.include_UNK: return self.UNK_i else: return", "= len(self._i2s) self._i2s.append(self.PAD_s) for s, count in sorted(self.frequency.items(), key=lambda x:", "self.UNK_i else: return default def __getitem__(self, s): return self.s2i(s) def", "entry {s}\") def contains(self, s): return self.get_s2i(s, -1) != -1", "freeze(self): assert not self.frozen if self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s)", "= dict() self._i2s = [] self.frequency = dict() def iter_item(self):", "self.get_s2i(s, -1) if i >= 0: return i else: raise", "< self.voc_size: return self._i2s[i] else: raise Exception(f\"not entry at position", "self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency)", "{s}\") def contains(self, s): return self.get_s2i(s, -1) != -1 def", "-x[1]): if count >= self.min_count: self._i2s.append(s) for i, s in", "state[7] self._s2i = state[8] self._i2s = state[9] self.frequency = state[10]", "enumerate(self._i2s): self._s2i[s] = i self.voc_size = len(self._i2s) self.frozen = True", "s): i = self.get_s2i(s, -1) if i >= 0: return", "= -2 self.PAD_s = \"<PAD>\" self.voc_size = 0 self._s2i =", "\"<UNK>\" self.PAD_i = -2 self.PAD_s = \"<PAD>\" self.voc_size = 0", "self.voc_size = 0 self._s2i = dict() self._i2s = [] self.frequency", "= \"<PAD>\" self.voc_size = 0 self._s2i = dict() self._i2s =", "i else: raise Exception(f\"out of vocabulary entry {s}\") def contains(self,", "-1 def i2s(self, i): assert self.frozen if 0 <= i", "i elif self.include_UNK: return self.UNK_i else: return default def __getitem__(self,", "self._i2s.append(self.PAD_s) for s, count in sorted(self.frequency.items(), key=lambda x: -x[1]): if", "sorted(self.frequency.items(), key=lambda x: -x[1]): if count >= self.min_count: self._i2s.append(s) for", ">= self.min_count: self._i2s.append(s) for i, s in enumerate(self._i2s): self._s2i[s] =", "self.PAD_s = state[6] self.voc_size = state[7] self._s2i = state[8] self._i2s", "self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency) def __setstate__(self, state):", "include_UNK self.include_PAD = include_PAD self.frozen = False self.UNK_i = -1", "state): self.min_count = state[0] self.include_UNK = state[1] self.frozen = state[2]", "for i, s in enumerate(self._i2s): self._s2i[s] = i self.voc_size =", "int, include_UNK: bool, include_PAD: bool): self.min_count = min_count self.include_UNK =", "= include_UNK self.include_PAD = include_PAD self.frozen = False self.UNK_i =", "s, default: int): assert self.frozen i = self._s2i.get(s, -1) if", "min_count: int, include_UNK: bool, include_PAD: bool): self.min_count = min_count self.include_UNK", "in enumerate(self._i2s): self._s2i[s] = i self.voc_size = len(self._i2s) self.frozen =", "self.frozen = False self.UNK_i = -1 self.UNK_s = \"<UNK>\" self.PAD_i", "def __getitem__(self, s): return self.s2i(s) def s2i(self, s): i =", "True def __reduce__(self): return Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK,", "s): return self.get_s2i(s, -1) != -1 def i2s(self, i): assert", "if self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for s, count in", "self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i,", "\"<PAD>\" self.voc_size = 0 self._s2i = dict() self._i2s = []", "vocabulary of size {self.voc_size}\") def add_to_counts(self, s): assert not self.frozen", "self.voc_size: return self._i2s[i] else: raise Exception(f\"not entry at position {i}", "of size {self.voc_size}\") def add_to_counts(self, s): assert not self.frozen self.frequency[s]", "self.voc_size, self._s2i, self._i2s, self.frequency) def __setstate__(self, state): self.min_count = state[0]", "(2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s,", "= state[6] self.voc_size = state[7] self._s2i = state[8] self._i2s =", "len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for s,", "raise Exception(f\"not entry at position {i} for a vocabulary of", "return enumerate(self._i2s) def get_s2i(self, s, default: int): assert self.frozen i", "self._i2s, self.frequency) def __setstate__(self, state): self.min_count = state[0] self.include_UNK =", "self.frozen i = self._s2i.get(s, -1) if i >= 0: return", "def s2i(self, s): i = self.get_s2i(s, -1) if i >=", ">= 0: return i else: raise Exception(f\"out of vocabulary entry", "def __init__(self, min_count: int, include_UNK: bool, include_PAD: bool): self.min_count =", "len(self._i2s) self.frozen = True def __reduce__(self): return Any2Int, (2, self.include_UNK,", "= True def __reduce__(self): return Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count,", "bool): self.min_count = min_count self.include_UNK = include_UNK self.include_PAD = include_PAD", "if i >= 0: return i elif self.include_UNK: return self.UNK_i", "s2i(self, s): i = self.get_s2i(s, -1) if i >= 0:", "self.frequency.get(s, 0)+1 def freeze(self): assert not self.frozen if self.include_UNK: self.UNK_i", "= state[2] self.UNK_i = state[3] self.UNK_s = state[4] self.PAD_i =", "self.frozen self.frequency[s] = self.frequency.get(s, 0)+1 def freeze(self): assert not self.frozen", "0 self._s2i = dict() self._i2s = [] self.frequency = dict()", "= include_PAD self.frozen = False self.UNK_i = -1 self.UNK_s =", "i >= 0: return i else: raise Exception(f\"out of vocabulary", "if 0 <= i < self.voc_size: return self._i2s[i] else: raise", "= [] self.frequency = dict() def iter_item(self): return enumerate(self._i2s) def", "default: int): assert self.frozen i = self._s2i.get(s, -1) if i", "self._i2s[i] else: raise Exception(f\"not entry at position {i} for a", "self.frequency[s] = self.frequency.get(s, 0)+1 def freeze(self): assert not self.frozen if", "include_UNK: bool, include_PAD: bool): self.min_count = min_count self.include_UNK = include_UNK", "i < self.voc_size: return self._i2s[i] else: raise Exception(f\"not entry at", "self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s)", "else: raise Exception(f\"not entry at position {i} for a vocabulary", "= state[5] self.PAD_s = state[6] self.voc_size = state[7] self._s2i =", "return default def __getitem__(self, s): return self.s2i(s) def s2i(self, s):", "enumerate(self._i2s) def get_s2i(self, s, default: int): assert self.frozen i =", "self.min_count = state[0] self.include_UNK = state[1] self.frozen = state[2] self.UNK_i", "s): assert not self.frozen self.frequency[s] = self.frequency.get(s, 0)+1 def freeze(self):", "self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for s, count in sorted(self.frequency.items(), key=lambda", "!= -1 def i2s(self, i): assert self.frozen if 0 <=", "= state[3] self.UNK_s = state[4] self.PAD_i = state[5] self.PAD_s =", "self.get_s2i(s, -1) != -1 def i2s(self, i): assert self.frozen if", "self.PAD_s = \"<PAD>\" self.voc_size = 0 self._s2i = dict() self._i2s", "size {self.voc_size}\") def add_to_counts(self, s): assert not self.frozen self.frequency[s] =", "at position {i} for a vocabulary of size {self.voc_size}\") def", "def add_to_counts(self, s): assert not self.frozen self.frequency[s] = self.frequency.get(s, 0)+1", "s): return self.s2i(s) def s2i(self, s): i = self.get_s2i(s, -1)", "__getitem__(self, s): return self.s2i(s) def s2i(self, s): i = self.get_s2i(s,", "self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency) def __setstate__(self, state): self.min_count =", "def freeze(self): assert not self.frozen if self.include_UNK: self.UNK_i = len(self._i2s)", "0: return i elif self.include_UNK: return self.UNK_i else: return default", "return self.UNK_i else: return default def __getitem__(self, s): return self.s2i(s)", "assert self.frozen if 0 <= i < self.voc_size: return self._i2s[i]", "= False self.UNK_i = -1 self.UNK_s = \"<UNK>\" self.PAD_i =", "i, s in enumerate(self._i2s): self._s2i[s] = i self.voc_size = len(self._i2s)", "entry at position {i} for a vocabulary of size {self.voc_size}\")", "-1) != -1 def i2s(self, i): assert self.frozen if 0", "return self._i2s[i] else: raise Exception(f\"not entry at position {i} for", "self.voc_size = len(self._i2s) self.frozen = True def __reduce__(self): return Any2Int,", "= self._s2i.get(s, -1) if i >= 0: return i elif", "include_PAD self.frozen = False self.UNK_i = -1 self.UNK_s = \"<UNK>\"", "Exception(f\"out of vocabulary entry {s}\") def contains(self, s): return self.get_s2i(s,", "contains(self, s): return self.get_s2i(s, -1) != -1 def i2s(self, i):", "state[0] self.include_UNK = state[1] self.frozen = state[2] self.UNK_i = state[3]", "self.UNK_i = state[3] self.UNK_s = state[4] self.PAD_i = state[5] self.PAD_s", "self.UNK_s = state[4] self.PAD_i = state[5] self.PAD_s = state[6] self.voc_size", "self.include_UNK = state[1] self.frozen = state[2] self.UNK_i = state[3] self.UNK_s", "self.PAD_i = state[5] self.PAD_s = state[6] self.voc_size = state[7] self._s2i", "return i elif self.include_UNK: return self.UNK_i else: return default def", "assert self.frozen i = self._s2i.get(s, -1) if i >= 0:", "= -1 self.UNK_s = \"<UNK>\" self.PAD_i = -2 self.PAD_s =", "self.include_UNK: return self.UNK_i else: return default def __getitem__(self, s): return", "self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency) def __setstate__(self,", "self.frequency) def __setstate__(self, state): self.min_count = state[0] self.include_UNK = state[1]", "state[5] self.PAD_s = state[6] self.voc_size = state[7] self._s2i = state[8]", "self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency) def", "-1) if i >= 0: return i else: raise Exception(f\"out", "(self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s,", "self.frozen = state[2] self.UNK_i = state[3] self.UNK_s = state[4] self.PAD_i", "= self.get_s2i(s, -1) if i >= 0: return i else:", "vocabulary entry {s}\") def contains(self, s): return self.get_s2i(s, -1) !=", "if i >= 0: return i else: raise Exception(f\"out of", "= len(self._i2s) self.frozen = True def __reduce__(self): return Any2Int, (2,", "= state[7] self._s2i = state[8] self._i2s = state[9] self.frequency =", "class Any2Int: def __init__(self, min_count: int, include_UNK: bool, include_PAD: bool):", "= 0 self._s2i = dict() self._i2s = [] self.frequency =", "elif self.include_UNK: return self.UNK_i else: return default def __getitem__(self, s):", "self.min_count = min_count self.include_UNK = include_UNK self.include_PAD = include_PAD self.frozen", "key=lambda x: -x[1]): if count >= self.min_count: self._i2s.append(s) for i,", "Exception(f\"not entry at position {i} for a vocabulary of size", "int): assert self.frozen i = self._s2i.get(s, -1) if i >=", "0 <= i < self.voc_size: return self._i2s[i] else: raise Exception(f\"not", "self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size,", "self.UNK_i = -1 self.UNK_s = \"<UNK>\" self.PAD_i = -2 self.PAD_s", "self.frequency = dict() def iter_item(self): return enumerate(self._i2s) def get_s2i(self, s," ]
[ "in j: name=j['name'] if not j['name']: name = randint(1000,9000) tmp", "msg.append(list) m.close() if adj: value=float(value)+(adj) msg.append(\"ADJ: %d\" % value) for", "Sensor %s added ok\" %rom) else: print (\"[ nettemp ][", "randint(50,600) map_x = randint(50,600) data = [rom, type, device, ip,", "v1, v2, v3 in list: if (value>=float(min)) and (value<=float(max)): if(value==v1)", "def create_sensor(rom, data, data2, map_settings): m = mysql.connection.cursor() rom1 =", "sql=\"DELETE FROM sensors WHERE id=? AND rom=%s\" m.execute(sql, data) m.connection.commit()", "ok\" %rom) else: print (\"[ nettemp ][ sensor ] Sensor", "app from flask import Flask, request, jsonify, g import sqlite3", "insert ok\" %rom) return True else: print (\"[ nettemp ][", "def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[ nettemp ][", "name='def'\" c.execute(sql) if c.fetchone()[0]==1: data = [value] sql = \"INSERT", "= None if 'device' in j: device=j['device'] ip = None", "flask_jwt_extended import jwt_required import datetime from flask_mysqldb import MySQL mysql", "VALUES (%s, %s, %s, %s, %s, %s)\" m.execute(map, map_settings) m.connection.commit()", "randint(1000,9000) if 'name' in j: name=j['name'] if not j['name']: name", "%s, %s, %s, %s, %s)\" m.execute(map, map_settings) m.connection.commit() m.close() print", "stat_min is null OR stat_min='0.0') AND rom=%s\" m.execute(sql, data) sql", "count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun = m.fetchone()", "[rom, type, device, ip, gpio, i2c, usb, name] data2 =", "j: tmp=j['tmp'] value = None if 'value' in j: value=j['value']", "value=float(value) else: msg.append(\"filter 1 back to previous %f\" % tmp)", "OR stat_max is null OR stat_max='0.0') AND rom=%s\" m.execute(sql, data)", "= \"SELECT min, max, value1, value2, value3 FROM types WHERE", "= m.fetchone() if coun[0]==0: sql = \"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name)", "new_db(rom): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor()", "= [rom] sql=\"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1)", "= getattr(g, '_database', None) if db is not None: db.close()", "= rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor() sql =", "with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() print (\"Database %s", "FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun = m.fetchone() if", "= \"UPDATE sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data", "j['name']: name = randint(1000,9000) tmp = None if 'tmp' in", "if 'group' in j: group=j['group'] map_id = randint(1000,9000) map_y =", "for adj, tmp in sensor: tmp=float(tmp) adj=float(adj) msg=[] sql =", "null OR stat_max='0.0') AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() print", "else: sql = \"UPDATE sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE", "type=%s\" m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN VALUE: %f\" % value) msg.append(list)", "rom=%s\" m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql", "count() FROM sqlite_master WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1:", "data) conn.commit() conn.close() print (\"[ nettemp ][ sensor ] Database", "value) for min, max, v1, v2, v3 in list: if", "sql = \"SELECT adj, tmp FROM sensors WHERE rom=%s\" m.execute(sql,", "if adj: value=float(value)+(adj) msg.append(\"ADJ: %d\" % value) for min, max,", "db.commit() print (\"Database %s created\" %rom) return False def insert_db(rom,value):", "= sqlite3.connect(rom) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g,", "(\"[ nettemp ][ sensor ] Sensor %s updated\" %rom) return", "jwt_required import datetime from flask_mysqldb import MySQL mysql = MySQL()", "ip, gpio, i2c, usb, name] data2 = [group, map_id, rom]", "os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[ nettemp ][ sensor ] Database %s", "= \"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun", "nettemp ][ sensor ] Sensor %s not exist\" %rom) return", "delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[ nettemp ][ sensor", "not exist\" %rom) return False def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom):", "db.close() def check_value(value, type, rom): adj='' tm='' value=float(value) m =", "= request.get_json() for j in data: rom = None if", "%s, %s, %s)\" m.execute(map, map_settings) m.connection.commit() m.close() print (\"[ nettemp", "map_y = randint(50,600) map_x = randint(50,600) data = [rom, type,", "sql = \"UPDATE sensors SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE", "usb=j['usb'] name = randint(1000,9000) if 'name' in j: name=j['name'] if", "i2c = None if 'i2c' in j: i2c=j['i2c'] usb =", "for j in data: rom = None if 'rom' in", "name = randint(1000,9000) if 'name' in j: name=j['name'] if not", "False def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[ nettemp", "= randint(1000,9000) if 'name' in j: name=j['name'] if not j['name']:", "@app.route('/sensor', methods=['POST']) @jwt_required def url_sensor(): sensor() return '', 200 @app.route('/local',", "INTO def (value) VALUES (?)\" c.execute(sql, data) conn.commit() conn.close() print", "= mysql.connection.cursor() rom1 = [rom] sql=\"SELECT count(*) FROM sensors WHERE", "mode='r') as f: db.cursor().executescript(f.read()) db.commit() print (\"Database %s created\" %rom)", "data) m.connection.commit() m.close() print (\"[ nettemp ][ sensor ] Sensor", "= get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() print", "Database %s insert ok\" %rom) return True else: print (\"[", "None if 'tmp' in j: tmp=j['tmp'] value = None if", "%f\" % tmp) value=tmp msg.append(\"VALUE OUT: %f\" % value) print(msg)", "import sqlite3 import os import json from random import randint", "coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql = \"UPDATE sensors", "nettemp ][ sensor ] Sensor %s removed ok\" %rom) def", "random import randint from flask_jwt_extended import jwt_required import datetime from", "= \"SELECT adj, tmp FROM sensors WHERE rom=%s\" m.execute(sql, [rom])", "sensor ] Database %s not exist\" %rom) return False def", "sqlite3.connect(rom) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database',", "id=? AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() delete_db(rom) print (\"[", "= None if 'usb' in j: usb=j['usb'] name = randint(1000,9000)", "value=check_value(value, type, rom) if insert_db(rom, value) == False: new_db(rom) insert_db(rom,value)", "already exist\" %rom) return None def sensor(): data = request.get_json()", "map_id = randint(1000,9000) map_y = randint(50,600) map_x = randint(50,600) data", "max, v1, v2, v3 in list: if (value>=float(min)) and (value<=float(max)):", "db is None: db = g._database = sqlite3.connect(rom) return db", "get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() print (\"Database", "charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on',", "][ sensor ] Sensor %s removed ok\" %rom) def create_sensor(rom,", "(value) VALUES (?)\" c.execute(sql, data) conn.commit() conn.close() print (\"[ nettemp", "%s, %s)\" m.execute(sql, data) sql2 = \"UPDATE sensors SET alarm='off',", "in j: ip = j['ip'] gpio = None if 'gpio'", "not exist\" %rom) return False def update_sensor_tmp(rom,value): m = mysql.connection.cursor()", "device, ip, gpio, i2c, usb, name] data2 = [group, map_id,", "insert_db(rom,value) if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required", "sensor: tmp=float(tmp) adj=float(adj) msg=[] sql = \"SELECT min, max, value1,", "not exist\" %rom) return False def delete_sensor(id,rom): data = [id,", "msg.append(\"IN VALUE: %f\" % value) msg.append(list) m.close() if adj: value=float(value)+(adj)", "1 back to previous %f\" % tmp) value=tmp msg.append(\"VALUE OUT:", "[value] sql = \"INSERT OR IGNORE INTO def (value) VALUES", "] Database %s not exist\" %rom) return False def update_sensor_tmp(rom,value):", "%rom) return None def sensor(): data = request.get_json() for j", "value=tmp msg.append(\"VALUE OUT: %f\" % value) print(msg) return value def", "gpio = None if 'gpio' in j: gpio=j['gpio'] i2c =", "return True else: print (\"[ nettemp ][ sensor ] Sensor", "min, max, v1, v2, v3 in list: if (value>=float(min)) and", "nettemp ][ sensor ] Sensor %s already exist\" %rom) return", "data = [rom, type, device, ip, gpio, i2c, usb, name]", "return True else: with app.app_context(): db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql',", "(stat_max<%s OR stat_max is null OR stat_max='0.0') AND rom=%s\" m.execute(sql,", "%rom) return True else: print (\"[ nettemp ][ sensor ]", "= None if 'gpio' in j: gpio=j['gpio'] i2c = None", "(value>=float(min)) and (value<=float(max)): if(value==v1) or (value==v2) or (value==v3): msg.append(\"filter 2", "if 'usb' in j: usb=j['usb'] name = randint(1000,9000) if 'name'", "return False def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[", "INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s, %s, %s, %s,", "%s exists\" %rom) return True else: with app.app_context(): db =", "in j: gpio=j['gpio'] i2c = None if 'i2c' in j:", "200 @app.route('/local', methods=['POST']) def url_localhost(): if request.remote_addr == '127.0.0.1': sensor()", "data = [value] sql = \"INSERT OR IGNORE INTO def", "sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max is null", "sql = \"SELECT min, max, value1, value2, value3 FROM types", "v3 in list: if (value>=float(min)) and (value<=float(max)): if(value==v1) or (value==v2)", "rom=%s\" m.execute(sql, data) m.connection.commit() m.close() print (\"[ nettemp ][ sensor", "g._database = sqlite3.connect(rom) return db @app.teardown_appcontext def close_connection(exception): db =", "map_settings = [type, map_y, map_x, 'on', map_id, 'on'] value=check_value(value, type,", "map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s\" m.execute(sql2, data2) map = \"INSERT", "stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max is null OR stat_max='0.0')", "app.app_context(): db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read())", "False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor',", "= \"UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max", "ok\" %rom) def create_sensor(rom, data, data2, map_settings): m = mysql.connection.cursor()", "FROM sensors WHERE rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall() for adj, tmp", "stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max is null OR stat_max='0.0') AND", "alarm='off', adj='0', charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0',", "to previous %f\" % tmp) value=tmp msg.append(\"VALUE OUT: %f\" %", "tmp FROM sensors WHERE rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall() for adj,", "added ok\" %rom) else: print (\"[ nettemp ][ sensor ]", "in j: rom=j['rom'] type = None if 'type' in j:", "ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5',", "FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1: if", "def sensor(): data = request.get_json() for j in data: rom", "int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql = \"UPDATE sensors SET tmp=%s, tmp_5ago=%s, nodata='',", "map_id, 'on'] value=check_value(value, type, rom) if insert_db(rom, value) == False:", "= \"UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min", "coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql = \"UPDATE sensors SET tmp=%s,", "ip = None if 'ip' in j: ip = j['ip']", "value2, value3 FROM types WHERE type=%s\" m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN", "name=j['name'] if not j['name']: name = randint(1000,9000) tmp = None", "stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s\" m.execute(sql2,", "tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,rom] m.execute(sql, data)", "%s already exist\" %rom) return None def sensor(): data =", "type = None if 'type' in j: type=j['type'] device =", "%f\" % tmp) value=tmp else: value=float(value) else: msg.append(\"filter 1 back", "if 'device' in j: device=j['device'] ip = None if 'ip'", "'device' in j: device=j['device'] ip = None if 'ip' in", "app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() print (\"Database %s created\"", "%f\" % value) print(msg) return value def new_db(rom): rom =", "FROM sqlite_master WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: print", "map = \"INSERT INTO maps (type, pos_x, pos_y, map_on, map_id,", "WHERE rom=%s\" m.execute(sql2, data2) map = \"INSERT INTO maps (type,", "None if 'device' in j: device=j['device'] ip = None if", "@app.route('/local', methods=['POST']) def url_localhost(): if request.remote_addr == '127.0.0.1': sensor() return", "None if 'type' in j: type=j['type'] device = None if", "% tmp) value=tmp msg.append(\"VALUE OUT: %f\" % value) print(msg) return", "Database %s not exist\" %rom) return False def update_sensor_tmp(rom,value): m", "= j['ip'] gpio = None if 'gpio' in j: gpio=j['gpio']", "is null OR stat_min='0.0') AND rom=%s\" m.execute(sql, data) sql =", "[type, map_y, map_x, 'on', map_id, 'on'] value=check_value(value, type, rom) if", "Sensor %s not exist\" %rom) return False def delete_db(rom): rom=rom+'.sql'", "MySQL() def get_db(rom): db = getattr(g, '_database', None) if db", "import randint from flask_jwt_extended import jwt_required import datetime from flask_mysqldb", "rom=%s\" m.execute(sql, data) m.connection.commit() m.close() delete_db(rom) print (\"[ nettemp ][", "<gh_stars>10-100 from app import app from flask import Flask, request,", "WHERE rom=%s\" data = [value,rom] m.execute(sql, data) # stat min", "rom=j['rom'] type = None if 'type' in j: type=j['type'] device", "= \"SELECT count() FROM sqlite_master WHERE type='table' AND name='def'\" c.execute(sql)", "True else: with app.app_context(): db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r')", "from app import app from flask import Flask, request, jsonify,", "'usb' in j: usb=j['usb'] name = randint(1000,9000) if 'name' in", "sqlite3.connect(app.romdir+rom) c = conn.cursor() sql = \"SELECT count() FROM sqlite_master", "sql = \"SELECT count() FROM sqlite_master WHERE type='table' AND name='def'\"", "'gpio' in j: gpio=j['gpio'] i2c = None if 'i2c' in", "insert_db(rom, value) == False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) == False:", "conn = sqlite3.connect(app.romdir+rom) c = conn.cursor() sql = \"SELECT count()", "data = [value,tmp_5ago,rom] else: sql = \"UPDATE sensors SET tmp=%s,", "types WHERE type=%s\" m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN VALUE: %f\" %", "sql = \"UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR", "= \"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s, %s,", "%s, %s)\" m.execute(map, map_settings) m.connection.commit() m.close() print (\"[ nettemp ][", "%s, %s, %s, %s, %s, %s, %s)\" m.execute(sql, data) sql2", "%s, %s, %s, %s)\" m.execute(map, map_settings) m.connection.commit() m.close() print (\"[", "INTO maps (type, pos_x, pos_y, map_on, map_id, display_name) VALUES (%s,", "print (\"[ nettemp ][ sensor ] Sensor %s added ok\"", "adj=float(adj) msg=[] sql = \"SELECT min, max, value1, value2, value3", "m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN VALUE: %f\" % value) msg.append(list) m.close()", "sql = \"UPDATE sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\"", "nettemp ][ sensor ] Sensor %s added ok\" %rom) else:", "f: db.cursor().executescript(f.read()) db.commit() print (\"Database %s created\" %rom) return False", "db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()", "if db is not None: db.close() def check_value(value, type, rom):", "datetime from flask_mysqldb import MySQL mysql = MySQL() def get_db(rom):", "device = None if 'device' in j: device=j['device'] ip =", "'on', map_id, 'on'] value=check_value(value, type, rom) if insert_db(rom, value) ==", "%s, %s, %s, %s)\" m.execute(sql, data) sql2 = \"UPDATE sensors", "sql=\"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun=m.fetchone() if", "if 'tmp' in j: tmp=j['tmp'] value = None if 'value'", "import app from flask import Flask, request, jsonify, g import", "nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,rom] m.execute(sql, data) #", "m.connection.commit() m.close() print (\"[ nettemp ][ sensor ] Sensor %s", "return value def new_db(rom): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom)", "%rom) return False def update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1 =", "tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,tmp_5ago,rom] else: sql", "map_on, map_id, display_name) VALUES (%s, %s, %s, %s, %s, %s)\"", "tmp = None if 'tmp' in j: tmp=j['tmp'] value =", "create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def url_sensor(): sensor() return '',", "msg.append(\"VALUE OUT: %f\" % value) print(msg) return value def new_db(rom):", "data = [value,rom] m.execute(sql, data) # stat min max data", "tmp) value=tmp else: value=float(value) else: msg.append(\"filter 1 back to previous", "rom1) coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql = \"UPDATE", "maps (type, pos_x, pos_y, map_on, map_id, display_name) VALUES (%s, %s,", "return False def insert_db(rom,value): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom)", "tmp) value=tmp msg.append(\"VALUE OUT: %f\" % value) print(msg) return value", "rom] sql = \"UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s", "created\" %rom) return False def insert_db(rom,value): rom = rom+'.sql' conn", "% tmp) value=tmp else: value=float(value) else: msg.append(\"filter 1 back to", "if os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[ nettemp ][ sensor ] Database", "check_value(value, type, rom): adj='' tm='' value=float(value) m = mysql.connection.cursor() sql", "] Sensor %s not exist\" %rom) return False def delete_db(rom):", "value3 FROM types WHERE type=%s\" m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN VALUE:", "map_settings) m.connection.commit() m.close() print (\"[ nettemp ][ sensor ] Sensor", "group=j['group'] map_id = randint(1000,9000) map_y = randint(50,600) map_x = randint(50,600)", "i2c, usb, name] data2 = [group, map_id, rom] map_settings =", "%rom) return True else: with app.app_context(): db = get_db(app.romdir+rom) with", "][ sensor ] Database %s insert ok\" %rom) return True", "%s, %s, %s)\" m.execute(sql, data) sql2 = \"UPDATE sensors SET", "(\"[ nettemp ][ sensor ] Sensor %s removed ok\" %rom)", "][ sensor ] Sensor %s already exist\" %rom) return None", "else: print (\"[ nettemp ][ sensor ] Database %s not", "OR stat_max='0.0') AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() print (\"[", "\"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s, %s, %s,", "] Sensor %s already exist\" %rom) return None def sensor():", "m.execute(sql, data) sql = \"UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE", "update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def url_sensor():", "== False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def url_sensor(): sensor()", "ok\" %rom) return True else: print (\"[ nettemp ][ sensor", "\"UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max is", "if 'name' in j: name=j['name'] if not j['name']: name =", "sensor(): data = request.get_json() for j in data: rom =", "tmp in sensor: tmp=float(tmp) adj=float(adj) msg=[] sql = \"SELECT min,", "%s not exist\" %rom) return False def delete_db(rom): rom=rom+'.sql' if", "in j: type=j['type'] device = None if 'device' in j:", "%d\" % value) for min, max, v1, v2, v3 in", "[value, value, rom] sql = \"UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP()", "True else: print (\"[ nettemp ][ sensor ] Sensor %s", "SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,tmp_5ago,rom]", "from flask import Flask, request, jsonify, g import sqlite3 import", "type, device, ip, gpio, i2c, usb, name] data2 = [group,", "Sensor %s updated\" %rom) return True else: print (\"[ nettemp", "if request.remote_addr == '127.0.0.1': sensor() return 'Local' else: return '',", "(value<=float(max)): if(value==v1) or (value==v2) or (value==v3): msg.append(\"filter 2 back to", "sqlite_master WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: data =", "%s, %s, %s, %s, %s)\" m.execute(sql, data) sql2 = \"UPDATE", "def url_sensor(): sensor() return '', 200 @app.route('/local', methods=['POST']) def url_localhost():", "type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: data = [value] sql", "False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def url_sensor(): sensor() return", "\"UPDATE sensors SET alarm='off', adj='0', charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0',", "not j['name']: name = randint(1000,9000) tmp = None if 'tmp'", "url_localhost(): if request.remote_addr == '127.0.0.1': sensor() return 'Local' else: return", "data: rom = None if 'rom' in j: rom=j['rom'] type", "updated\" %rom) return True else: print (\"[ nettemp ][ sensor", "randint(1000,9000) tmp = None if 'tmp' in j: tmp=j['tmp'] value", "else: print (\"[ nettemp ][ sensor ] Sensor %s not", "tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,tmp_5ago,rom] else:", "%s not exist\" %rom) return False def update_sensor_tmp(rom,value): m =", "json from random import randint from flask_jwt_extended import jwt_required import", "value=float(value) m = mysql.connection.cursor() sql = \"SELECT adj, tmp FROM", "rom) if insert_db(rom, value) == False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value)", "WHERE rom=%s\" data = [value,tmp_5ago,rom] else: sql = \"UPDATE sensors", "randint(1000,9000) map_y = randint(50,600) map_x = randint(50,600) data = [rom,", "%s created\" %rom) return False def insert_db(rom,value): rom = rom+'.sql'", "m.execute(map, map_settings) m.connection.commit() m.close() print (\"[ nettemp ][ sensor ]", "sensors SET alarm='off', adj='0', charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off',", "print (\"Database %s created\" %rom) return False def insert_db(rom,value): rom", "rom=%s\" data = [value,tmp_5ago,rom] else: sql = \"UPDATE sensors SET", "msg.append(\"ADJ: %d\" % value) for min, max, v1, v2, v3", "update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1 = [rom] sql=\"SELECT count(*) FROM", "tmp_5ago=value sql = \"UPDATE sensors SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP()", "if insert_db(rom, value) == False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) ==", "] Database %s deleted\" %rom) return True else: print (\"[", "'rom' in j: rom=j['rom'] type = None if 'type' in", "%rom) return False def insert_db(rom,value): rom = rom+'.sql' conn =", "deleted\" %rom) return True else: print (\"[ nettemp ][ sensor", "in j: device=j['device'] ip = None if 'ip' in j:", "WHERE (stat_min>%s OR stat_min is null OR stat_min='0.0') AND rom=%s\"", "if not j['name']: name = randint(1000,9000) tmp = None if", "group = type if 'group' in j: group=j['group'] map_id =", "@jwt_required def url_sensor(): sensor() return '', 200 @app.route('/local', methods=['POST']) def", "def url_localhost(): if request.remote_addr == '127.0.0.1': sensor() return 'Local' else:", "previous %f\" % tmp) value=tmp else: value=float(value) else: msg.append(\"filter 1", "in list: if (value>=float(min)) and (value<=float(max)): if(value==v1) or (value==v2) or", "sensor ] Sensor %s updated\" %rom) return True else: print", "= \"INSERT INTO maps (type, pos_x, pos_y, map_on, map_id, display_name)", "request.remote_addr == '127.0.0.1': sensor() return 'Local' else: return '', 404", "None if 'gpio' in j: gpio=j['gpio'] i2c = None if", "tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE", "%s)\" m.execute(sql, data) sql2 = \"UPDATE sensors SET alarm='off', adj='0',", "is null OR stat_max='0.0') AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close()", "j: type=j['type'] device = None if 'device' in j: device=j['device']", "value=tmp else: value=float(value) else: msg.append(\"filter 1 back to previous %f\"", "app import app from flask import Flask, request, jsonify, g", "sql = \"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s,", "sql2 = \"UPDATE sensors SET alarm='off', adj='0', charts='on', status='on', ch_group=%s,", "False def update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1 = [rom] sql=\"SELECT", "def delete_sensor(id,rom): data = [id, rom] m = mysql.connection.cursor() sql=\"DELETE", "db = getattr(g, '_database', None) if db is not None:", "value) msg.append(list) m.close() if adj: value=float(value)+(adj) msg.append(\"ADJ: %d\" % value)", "for min, max, v1, v2, v3 in list: if (value>=float(min))", "AND rom=%s\" m.execute(sql, data) sql = \"UPDATE sensors SET stat_max=%s,", "= \"UPDATE sensors SET alarm='off', adj='0', charts='on', status='on', ch_group=%s, tmp_min='0',", "sensor ] Sensor %s added ok\" %rom) else: print (\"[", "update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def url_sensor(): sensor() return '', 200", "import datetime from flask_mysqldb import MySQL mysql = MySQL() def", "removed ok\" %rom) def create_sensor(rom, data, data2, map_settings): m =", "pos_x, pos_y, map_on, map_id, display_name) VALUES (%s, %s, %s, %s,", "'value' in j: value=j['value'] group = type if 'group' in", "m.connection.commit() m.close() delete_db(rom) print (\"[ nettemp ][ sensor ] Sensor", "print (\"[ nettemp ][ sensor ] Sensor %s removed ok\"", "print(msg) return value def new_db(rom): rom = rom+'.sql' conn =", "exists\" %rom) return True else: with app.app_context(): db = get_db(app.romdir+rom)", "= [type, map_y, map_x, 'on', map_id, 'on'] value=check_value(value, type, rom)", "mysql.connection.cursor() rom1 = [rom] sql = \"SELECT count(*) FROM sensors", "VALUE: %f\" % value) msg.append(list) m.close() if adj: value=float(value)+(adj) msg.append(\"ADJ:", "max, value1, value2, value3 FROM types WHERE type=%s\" m.execute(sql, [type])", "list: if (value>=float(min)) and (value<=float(max)): if(value==v1) or (value==v2) or (value==v3):", "OUT: %f\" % value) print(msg) return value def new_db(rom): rom", "nettemp ][ sensor ] Database %s insert ok\" %rom) return", "print (\"[ nettemp ][ sensor ] Database %s not exist\"", "[value,tmp_5ago,rom] else: sql = \"UPDATE sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP()", "gpio=j['gpio'] i2c = None if 'i2c' in j: i2c=j['i2c'] usb", "in j: tmp=j['tmp'] value = None if 'value' in j:", "%rom) else: print (\"[ nettemp ][ sensor ] Sensor %s", "\"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun =", "\"UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min is", "os import json from random import randint from flask_jwt_extended import", "sql = \"INSERT OR IGNORE INTO def (value) VALUES (?)\"", "c.execute(sql, data) conn.commit() conn.close() print (\"[ nettemp ][ sensor ]", "in j: value=j['value'] group = type if 'group' in j:", "(\"[ nettemp ][ sensor ] Database %s deleted\" %rom) return", "map_settings): m = mysql.connection.cursor() rom1 = [rom] sql = \"SELECT", "coun = m.fetchone() if coun[0]==0: sql = \"INSERT INTO sensors", "Database %s not exist\" %rom) return False def delete_sensor(id,rom): data", "flask_mysqldb import MySQL mysql = MySQL() def get_db(rom): db =", "import MySQL mysql = MySQL() def get_db(rom): db = getattr(g,", "] Sensor %s added ok\" %rom) else: print (\"[ nettemp", "in j: group=j['group'] map_id = randint(1000,9000) map_y = randint(50,600) map_x", "close_connection(exception): db = getattr(g, '_database', None) if db is not", "None: db = g._database = sqlite3.connect(rom) return db @app.teardown_appcontext def", "request, jsonify, g import sqlite3 import os import json from", "= type if 'group' in j: group=j['group'] map_id = randint(1000,9000)", "= mysql.connection.cursor() sql=\"DELETE FROM sensors WHERE id=? AND rom=%s\" m.execute(sql,", "%s)\" m.execute(map, map_settings) m.connection.commit() m.close() print (\"[ nettemp ][ sensor", "url_sensor(): sensor() return '', 200 @app.route('/local', methods=['POST']) def url_localhost(): if", "= randint(50,600) map_x = randint(50,600) data = [rom, type, device,", "'tmp' in j: tmp=j['tmp'] value = None if 'value' in", "stat_min='0.0') AND rom=%s\" m.execute(sql, data) sql = \"UPDATE sensors SET", "[id, rom] m = mysql.connection.cursor() sql=\"DELETE FROM sensors WHERE id=?", "request.get_json() for j in data: rom = None if 'rom'", "methods=['POST']) @jwt_required def url_sensor(): sensor() return '', 200 @app.route('/local', methods=['POST'])", "sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s, %s, %s, %s, %s,", "%rom) return False def delete_sensor(id,rom): data = [id, rom] m", "def check_value(value, type, rom): adj='' tm='' value=float(value) m = mysql.connection.cursor()", "tm='' value=float(value) m = mysql.connection.cursor() sql = \"SELECT adj, tmp", "None if 'ip' in j: ip = j['ip'] gpio =", "m.execute(sql, rom1) coun = m.fetchone() if coun[0]==0: sql = \"INSERT", "ip = j['ip'] gpio = None if 'gpio' in j:", "if 'gpio' in j: gpio=j['gpio'] i2c = None if 'i2c'", "sensor ] Database %s insert ok\" %rom) return True else:", "2 back to previous %f\" % tmp) value=tmp else: value=float(value)", "if 'value' in j: value=j['value'] group = type if 'group'", "db is not None: db.close() def check_value(value, type, rom): adj=''", "time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,rom] m.execute(sql, data) # stat", "mysql.connection.cursor() sql = \"SELECT adj, tmp FROM sensors WHERE rom=%s\"", "Flask, request, jsonify, g import sqlite3 import os import json", "tmp=j['tmp'] value = None if 'value' in j: value=j['value'] group", "def update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1 = [rom] sql=\"SELECT count(*)", "j: name=j['name'] if not j['name']: name = randint(1000,9000) tmp =", "return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None)", "sensors WHERE rom=%s\" m.execute(sql, rom1) coun = m.fetchone() if coun[0]==0:", "%s insert ok\" %rom) return True else: print (\"[ nettemp", "max data = [value, value, rom] sql = \"UPDATE sensors", "data, data2, map_settings): m = mysql.connection.cursor() rom1 = [rom] sql", "False def delete_sensor(id,rom): data = [id, rom] m = mysql.connection.cursor()", "if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql = \"UPDATE sensors SET tmp=%s, tmp_5ago=%s,", "= randint(1000,9000) tmp = None if 'tmp' in j: tmp=j['tmp']", "and (value<=float(max)): if(value==v1) or (value==v2) or (value==v3): msg.append(\"filter 2 back", "OR stat_min is null OR stat_min='0.0') AND rom=%s\" m.execute(sql, data)", "MySQL mysql = MySQL() def get_db(rom): db = getattr(g, '_database',", "value=float(value)+(adj) msg.append(\"ADJ: %d\" % value) for min, max, v1, v2,", "WHERE id=? AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() delete_db(rom) print", "import json from random import randint from flask_jwt_extended import jwt_required", "data = [id, rom] m = mysql.connection.cursor() sql=\"DELETE FROM sensors", "(rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"", "Sensor %s removed ok\" %rom) def create_sensor(rom, data, data2, map_settings):", "fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s\" m.execute(sql2, data2) map =", "WHERE rom=%s\" m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value", "None def sensor(): data = request.get_json() for j in data:", "j: rom=j['rom'] type = None if 'type' in j: type=j['type']", "= None if 'i2c' in j: i2c=j['i2c'] usb = None", "AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() print (\"[ nettemp ][", "[rom]) sensor=m.fetchall() for adj, tmp in sensor: tmp=float(tmp) adj=float(adj) msg=[]", "m.execute(sql2, data2) map = \"INSERT INTO maps (type, pos_x, pos_y,", "sensors WHERE id=? AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() delete_db(rom)", "= [value, value, rom] sql = \"UPDATE sensors SET stat_min=%s,", "(value==v2) or (value==v3): msg.append(\"filter 2 back to previous %f\" %", "'name' in j: name=j['name'] if not j['name']: name = randint(1000,9000)", "= getattr(g, '_database', None) if db is None: db =", "tmp=float(tmp) adj=float(adj) msg=[] sql = \"SELECT min, max, value1, value2,", "is None: db = g._database = sqlite3.connect(rom) return db @app.teardown_appcontext", "m = mysql.connection.cursor() rom1 = [rom] sql=\"SELECT count(*) FROM sensors", "adj: value=float(value)+(adj) msg.append(\"ADJ: %d\" % value) for min, max, v1,", "sensors WHERE rom=%s\" m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0:", "m = mysql.connection.cursor() sql = \"SELECT adj, tmp FROM sensors", "msg=[] sql = \"SELECT min, max, value1, value2, value3 FROM", "IGNORE INTO def (value) VALUES (?)\" c.execute(sql, data) conn.commit() conn.close()", "= conn.cursor() sql = \"SELECT count() FROM sqlite_master WHERE type='table'", "AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() delete_db(rom) print (\"[ nettemp", "min max data = [value, value, rom] sql = \"UPDATE", "= mysql.connection.cursor() sql = \"SELECT adj, tmp FROM sensors WHERE", "if 'rom' in j: rom=j['rom'] type = None if 'type'", "WHERE rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall() for adj, tmp in sensor:", "adj, tmp FROM sensors WHERE rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall() for", "map_y, map_x, 'on', map_id, 'on'] value=check_value(value, type, rom) if insert_db(rom,", "else: print (\"[ nettemp ][ sensor ] Sensor %s already", "# stat min max data = [value, value, rom] sql", "= None if 'rom' in j: rom=j['rom'] type = None", "value) == False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings)", "g import sqlite3 import os import json from random import", "(\"[ nettemp ][ sensor ] Database %s insert ok\" %rom)", "data) # stat min max data = [value, value, rom]", "OR stat_min='0.0') AND rom=%s\" m.execute(sql, data) sql = \"UPDATE sensors", "gpio, i2c, usb, name] data2 = [group, map_id, rom] map_settings", "if coun[0]==0: sql = \"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s,", "value = None if 'value' in j: value=j['value'] group =", "nettemp ][ sensor ] Sensor %s updated\" %rom) return True", "if 'type' in j: type=j['type'] device = None if 'device'", "= \"UPDATE sensors SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\"", "rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print (\"[ nettemp ][ sensor ]", "FROM types WHERE type=%s\" m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN VALUE: %f\"", "display_name) VALUES (%s, %s, %s, %s, %s, %s)\" m.execute(map, map_settings)", "data2 = [group, map_id, rom] map_settings = [type, map_y, map_x,", "(\"Database %s exists\" %rom) return True else: with app.app_context(): db", "(stat_min>%s OR stat_min is null OR stat_min='0.0') AND rom=%s\" m.execute(sql,", "m = mysql.connection.cursor() sql=\"DELETE FROM sensors WHERE id=? AND rom=%s\"", "%s updated\" %rom) return True else: print (\"[ nettemp ][", "type=j['type'] device = None if 'device' in j: device=j['device'] ip", "stat_max is null OR stat_max='0.0') AND rom=%s\" m.execute(sql, data) m.connection.commit()", "rom=%s\" data = [value,rom] m.execute(sql, data) # stat min max", "name = randint(1000,9000) tmp = None if 'tmp' in j:", "= \"INSERT OR IGNORE INTO def (value) VALUES (?)\" c.execute(sql,", "(\"[ nettemp ][ sensor ] Sensor %s not exist\" %rom)", "c.execute(sql) if c.fetchone()[0]==1: print (\"Database %s exists\" %rom) return True", "(\"Database %s created\" %rom) return False def insert_db(rom,value): rom =", "c.execute(sql) if c.fetchone()[0]==1: data = [value] sql = \"INSERT OR", "as f: db.cursor().executescript(f.read()) db.commit() print (\"Database %s created\" %rom) return", "msg.append(\"filter 2 back to previous %f\" % tmp) value=tmp else:", "print (\"[ nettemp ][ sensor ] Database %s deleted\" %rom)", "m.close() print (\"[ nettemp ][ sensor ] Sensor %s updated\"", "SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max is null OR", "return False def update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1 = [rom]", "= MySQL() def get_db(rom): db = getattr(g, '_database', None) if", "][ sensor ] Sensor %s updated\" %rom) return True else:", "print (\"Database %s exists\" %rom) return True else: with app.app_context():", "\"UPDATE sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data =", "import jwt_required import datetime from flask_mysqldb import MySQL mysql =", "%rom) def create_sensor(rom, data, data2, map_settings): m = mysql.connection.cursor() rom1", "methods=['POST']) def url_localhost(): if request.remote_addr == '127.0.0.1': sensor() return 'Local'", "= g._database = sqlite3.connect(rom) return db @app.teardown_appcontext def close_connection(exception): db", "'ip' in j: ip = j['ip'] gpio = None if", "] Sensor %s removed ok\" %rom) def create_sensor(rom, data, data2,", "True else: print (\"[ nettemp ][ sensor ] Database %s", "sqlite_master WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: print (\"Database", "None: db.close() def check_value(value, type, rom): adj='' tm='' value=float(value) m", "value) print(msg) return value def new_db(rom): rom = rom+'.sql' conn", "jsonify, g import sqlite3 import os import json from random", "conn.close() print (\"[ nettemp ][ sensor ] Database %s insert", "randint(50,600) data = [rom, type, device, ip, gpio, i2c, usb,", "= [value] sql = \"INSERT OR IGNORE INTO def (value)", "== False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value)", "db = getattr(g, '_database', None) if db is None: db", "def new_db(rom): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c =", "c.fetchone()[0]==1: print (\"Database %s exists\" %rom) return True else: with", "email_delay='10' WHERE rom=%s\" m.execute(sql2, data2) map = \"INSERT INTO maps", "j: gpio=j['gpio'] i2c = None if 'i2c' in j: i2c=j['i2c']", "@app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db", "null OR stat_min='0.0') AND rom=%s\" m.execute(sql, data) sql = \"UPDATE", "(%s, %s, %s, %s, %s, %s)\" m.execute(map, map_settings) m.connection.commit() m.close()", "rom] m = mysql.connection.cursor() sql=\"DELETE FROM sensors WHERE id=? AND", "def (value) VALUES (?)\" c.execute(sql, data) conn.commit() conn.close() print (\"[", "'type' in j: type=j['type'] device = None if 'device' in", "sql = \"UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR", "randint from flask_jwt_extended import jwt_required import datetime from flask_mysqldb import", "= [value,tmp_5ago,rom] else: sql = \"UPDATE sensors SET tmp=%s, nodata='',", "data) sql = \"UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s", "Database %s deleted\" %rom) return True else: print (\"[ nettemp", "= randint(1000,9000) map_y = randint(50,600) map_x = randint(50,600) data =", "WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: data = [value]", "%f\" % value) msg.append(list) m.close() if adj: value=float(value)+(adj) msg.append(\"ADJ: %d\"", "(\"[ nettemp ][ sensor ] Sensor %s already exist\" %rom)", "= sqlite3.connect(app.romdir+rom) c = conn.cursor() sql = \"SELECT count() FROM", "SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min is null OR", "minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s\"", "list=m.fetchall() msg.append(\"IN VALUE: %f\" % value) msg.append(list) m.close() if adj:", "if c.fetchone()[0]==1: print (\"Database %s exists\" %rom) return True else:", "else: value=float(value) else: msg.append(\"filter 1 back to previous %f\" %", "None if 'i2c' in j: i2c=j['i2c'] usb = None if", "m.execute(sql, data) sql2 = \"UPDATE sensors SET alarm='off', adj='0', charts='on',", "] Database %s insert ok\" %rom) return True else: print", "[rom] sql=\"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun=m.fetchone()", "stat min max data = [value, value, rom] sql =", "map_x = randint(50,600) data = [rom, type, device, ip, gpio,", "adj, tmp in sensor: tmp=float(tmp) adj=float(adj) msg=[] sql = \"SELECT", "\"INSERT INTO maps (type, pos_x, pos_y, map_on, map_id, display_name) VALUES", "m.execute(sql, data) m.connection.commit() m.close() delete_db(rom) print (\"[ nettemp ][ sensor", "stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s\" m.execute(sql2, data2)", "sensor ] Sensor %s already exist\" %rom) return None def", "%s, %s, %s, %s, %s, %s)\" m.execute(sql, data) sql2 =", "% value) for min, max, v1, v2, v3 in list:", "def insert_db(rom,value): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c =", "os.remove(rom) print (\"[ nettemp ][ sensor ] Database %s deleted\"", "[rom] sql = \"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql,", "= [group, map_id, rom] map_settings = [type, map_y, map_x, 'on',", "delete_db(rom) print (\"[ nettemp ][ sensor ] Sensor %s removed", "rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor() sql = \"SELECT", "j: value=j['value'] group = type if 'group' in j: group=j['group']", "usb, name] data2 = [group, map_id, rom] map_settings = [type,", "(?)\" c.execute(sql, data) conn.commit() conn.close() print (\"[ nettemp ][ sensor", "[group, map_id, rom] map_settings = [type, map_y, map_x, 'on', map_id,", "(\"[ nettemp ][ sensor ] Database %s not exist\" %rom)", "data) sql2 = \"UPDATE sensors SET alarm='off', adj='0', charts='on', status='on',", "mysql.connection.cursor() rom1 = [rom] sql=\"SELECT count(*) FROM sensors WHERE rom=%s\"", "sensors SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data =", "stat_max='0.0') AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close() print (\"[ nettemp", "sql = \"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1)", "if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql = \"UPDATE sensors SET", "data2) map = \"INSERT INTO maps (type, pos_x, pos_y, map_on,", "][ sensor ] Sensor %s not exist\" %rom) return False", "if(value==v1) or (value==v2) or (value==v3): msg.append(\"filter 2 back to previous", "WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: print (\"Database %s", "time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,tmp_5ago,rom] else: sql = \"UPDATE", "rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor() sql", "m.fetchone() if coun[0]==0: sql = \"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES", "db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if", "map_x, 'on', map_id, 'on'] value=check_value(value, type, rom) if insert_db(rom, value)", "sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,rom]", "m = mysql.connection.cursor() rom1 = [rom] sql = \"SELECT count(*)", "%rom) return False def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print", "j in data: rom = None if 'rom' in j:", "\"UPDATE sensors SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data", "j: ip = j['ip'] gpio = None if 'gpio' in", "def close_connection(exception): db = getattr(g, '_database', None) if db is", "if 'ip' in j: ip = j['ip'] gpio = None", "][ sensor ] Sensor %s added ok\" %rom) else: print", "type, rom): adj='' tm='' value=float(value) m = mysql.connection.cursor() sql =", "m.execute(sql, data) m.connection.commit() m.close() print (\"[ nettemp ][ sensor ]", "name='def'\" c.execute(sql) if c.fetchone()[0]==1: print (\"Database %s exists\" %rom) return", "nettemp ][ sensor ] Database %s deleted\" %rom) return True", "c.fetchone()[0]==1: data = [value] sql = \"INSERT OR IGNORE INTO", "VALUES (?)\" c.execute(sql, data) conn.commit() conn.close() print (\"[ nettemp ][", "[type]) list=m.fetchall() msg.append(\"IN VALUE: %f\" % value) msg.append(list) m.close() if", "print (\"[ nettemp ][ sensor ] Sensor %s not exist\"", "SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,rom] m.execute(sql,", "in data: rom = None if 'rom' in j: rom=j['rom']", "][ sensor ] Database %s not exist\" %rom) return False", "if 'i2c' in j: i2c=j['i2c'] usb = None if 'usb'", "previous %f\" % tmp) value=tmp msg.append(\"VALUE OUT: %f\" % value)", "or (value==v2) or (value==v3): msg.append(\"filter 2 back to previous %f\"", "return None def sensor(): data = request.get_json() for j in", "= randint(50,600) data = [rom, type, device, ip, gpio, i2c,", "'i2c' in j: i2c=j['i2c'] usb = None if 'usb' in", "AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: print (\"Database %s exists\" %rom)", "is not None: db.close() def check_value(value, type, rom): adj='' tm=''", "rom=%s\" m.execute(sql, rom1) coun = m.fetchone() if coun[0]==0: sql =", "else: msg.append(\"filter 1 back to previous %f\" % tmp) value=tmp", "print (\"[ nettemp ][ sensor ] Sensor %s already exist\"", "(type, pos_x, pos_y, map_on, map_id, display_name) VALUES (%s, %s, %s,", "None if 'value' in j: value=j['value'] group = type if", "WHERE type=%s\" m.execute(sql, [type]) list=m.fetchall() msg.append(\"IN VALUE: %f\" % value)", "exist\" %rom) return None def sensor(): data = request.get_json() for", "exist\" %rom) return False def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom)", "%s added ok\" %rom) else: print (\"[ nettemp ][ sensor", "None if 'rom' in j: rom=j['rom'] type = None if", "= [rom, type, device, ip, gpio, i2c, usb, name] data2", "name] data2 = [group, map_id, rom] map_settings = [type, map_y,", "j['ip'] gpio = None if 'gpio' in j: gpio=j['gpio'] i2c", "(%s, %s, %s, %s, %s, %s, %s, %s)\" m.execute(sql, data)", "WHERE rom=%s\" m.execute(sql, rom1) coun = m.fetchone() if coun[0]==0: sql", "map_id, display_name) VALUES (%s, %s, %s, %s, %s, %s)\" m.execute(map,", "insert_db(rom,value): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor()", "m.close() print (\"[ nettemp ][ sensor ] Sensor %s added", "delete_sensor(id,rom): data = [id, rom] m = mysql.connection.cursor() sql=\"DELETE FROM", "print (\"[ nettemp ][ sensor ] Database %s insert ok\"", "= [value,rom] m.execute(sql, data) # stat min max data =", "sensor ] Database %s deleted\" %rom) return True else: print", "rom=%s\" m.execute(sql, data) sql = \"UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP()", "'group' in j: group=j['group'] map_id = randint(1000,9000) map_y = randint(50,600)", "map_id, rom] map_settings = [type, map_y, map_x, 'on', map_id, 'on']", "type, rom) if insert_db(rom, value) == False: new_db(rom) insert_db(rom,value) if", "msg.append(\"filter 1 back to previous %f\" % tmp) value=tmp msg.append(\"VALUE", "= mysql.connection.cursor() rom1 = [rom] sql = \"SELECT count(*) FROM", "getattr(g, '_database', None) if db is None: db = g._database", "def get_db(rom): db = getattr(g, '_database', None) if db is", "sensor ] Sensor %s not exist\" %rom) return False def", "Sensor %s already exist\" %rom) return None def sensor(): data", "status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s,", "m.execute(sql, data) # stat min max data = [value, value,", "nodata_time='5', email_delay='10' WHERE rom=%s\" m.execute(sql2, data2) map = \"INSERT INTO", "\"SELECT min, max, value1, value2, value3 FROM types WHERE type=%s\"", "value def new_db(rom): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c", "data2, map_settings): m = mysql.connection.cursor() rom1 = [rom] sql =", "rom1) coun = m.fetchone() if coun[0]==0: sql = \"INSERT INTO", "%s deleted\" %rom) return True else: print (\"[ nettemp ][", "c = conn.cursor() sql = \"SELECT count() FROM sqlite_master WHERE", "None) if db is None: db = g._database = sqlite3.connect(rom)", "from flask_mysqldb import MySQL mysql = MySQL() def get_db(rom): db", "m.close() delete_db(rom) print (\"[ nettemp ][ sensor ] Sensor %s", "stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min is null OR stat_min='0.0') AND", "j: group=j['group'] map_id = randint(1000,9000) map_y = randint(50,600) map_x =", "j: usb=j['usb'] name = randint(1000,9000) if 'name' in j: name=j['name']", "= None if 'ip' in j: ip = j['ip'] gpio", "\"INSERT OR IGNORE INTO def (value) VALUES (?)\" c.execute(sql, data)", "from random import randint from flask_jwt_extended import jwt_required import datetime", "min, max, value1, value2, value3 FROM types WHERE type=%s\" m.execute(sql,", "m.close() if adj: value=float(value)+(adj) msg.append(\"ADJ: %d\" % value) for min,", "value=j['value'] group = type if 'group' in j: group=j['group'] map_id", "get_db(rom): db = getattr(g, '_database', None) if db is None:", "\"SELECT adj, tmp FROM sensors WHERE rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall()", "adj='' tm='' value=float(value) m = mysql.connection.cursor() sql = \"SELECT adj,", "v2, v3 in list: if (value>=float(min)) and (value<=float(max)): if(value==v1) or", "sensors WHERE rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall() for adj, tmp in", "value1, value2, value3 FROM types WHERE type=%s\" m.execute(sql, [type]) list=m.fetchall()", "exist\" %rom) return False def update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1", "device=j['device'] ip = None if 'ip' in j: ip =", "return True else: print (\"[ nettemp ][ sensor ] Database", "SET alarm='off', adj='0', charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0',", "i2c=j['i2c'] usb = None if 'usb' in j: usb=j['usb'] name", "sensor() return '', 200 @app.route('/local', methods=['POST']) def url_localhost(): if request.remote_addr", "data = [value, value, rom] sql = \"UPDATE sensors SET", "pos_y, map_on, map_id, display_name) VALUES (%s, %s, %s, %s, %s,", "tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10'", "data = request.get_json() for j in data: rom = None", "AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: data = [value] sql =", "conn.commit() conn.close() print (\"[ nettemp ][ sensor ] Database %s", "sqlite3 import os import json from random import randint from", "rom1 = [rom] sql=\"SELECT count(*) FROM sensors WHERE rom=%s\" m.execute(sql,", "type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: print (\"Database %s exists\"", "][ sensor ] Database %s deleted\" %rom) return True else:", "% value) print(msg) return value def new_db(rom): rom = rom+'.sql'", "or (value==v3): msg.append(\"filter 2 back to previous %f\" % tmp)", "rom=%s\" m.execute(sql, [rom]) sensor=m.fetchall() for adj, tmp in sensor: tmp=float(tmp)", "m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime(\"%M\"))%5==0: tmp_5ago=value sql =", "mysql = MySQL() def get_db(rom): db = getattr(g, '_database', None)", "None if 'usb' in j: usb=j['usb'] name = randint(1000,9000) if", "rom] map_settings = [type, map_y, map_x, 'on', map_id, 'on'] value=check_value(value,", "WHERE (stat_max<%s OR stat_max is null OR stat_max='0.0') AND rom=%s\"", "None) if db is not None: db.close() def check_value(value, type,", "j: device=j['device'] ip = None if 'ip' in j: ip", "% value) msg.append(list) m.close() if adj: value=float(value)+(adj) msg.append(\"ADJ: %d\" %", "else: with app.app_context(): db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as", "in j: i2c=j['i2c'] usb = None if 'usb' in j:", "print (\"[ nettemp ][ sensor ] Sensor %s updated\" %rom)", "sensor=m.fetchall() for adj, tmp in sensor: tmp=float(tmp) adj=float(adj) msg=[] sql", "db = g._database = sqlite3.connect(rom) return db @app.teardown_appcontext def close_connection(exception):", "sensor ] Sensor %s removed ok\" %rom) def create_sensor(rom, data,", "%s removed ok\" %rom) def create_sensor(rom, data, data2, map_settings): m", "if db is None: db = g._database = sqlite3.connect(rom) return", "rom): adj='' tm='' value=float(value) m = mysql.connection.cursor() sql = \"SELECT", "\"SELECT count() FROM sqlite_master WHERE type='table' AND name='def'\" c.execute(sql) if", "= [rom] sql = \"SELECT count(*) FROM sensors WHERE rom=%s\"", "back to previous %f\" % tmp) value=tmp else: value=float(value) else:", "rom=%s\" m.execute(sql2, data2) map = \"INSERT INTO maps (type, pos_x,", "'on'] value=check_value(value, type, rom) if insert_db(rom, value) == False: new_db(rom)", "(value==v3): msg.append(\"filter 2 back to previous %f\" % tmp) value=tmp", "db.cursor().executescript(f.read()) db.commit() print (\"Database %s created\" %rom) return False def", "m.execute(sql, [rom]) sensor=m.fetchall() for adj, tmp in sensor: tmp=float(tmp) adj=float(adj)", "import Flask, request, jsonify, g import sqlite3 import os import", "with app.app_context(): db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f:", "adj='0', charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0',", "in j: usb=j['usb'] name = randint(1000,9000) if 'name' in j:", "'_database', None) if db is not None: db.close() def check_value(value,", "%s not exist\" %rom) return False def delete_sensor(id,rom): data =", "not None: db.close() def check_value(value, type, rom): adj='' tm='' value=float(value)", "tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s\" m.execute(sql2, data2) map", "back to previous %f\" % tmp) value=tmp msg.append(\"VALUE OUT: %f\"", "return '', 200 @app.route('/local', methods=['POST']) def url_localhost(): if request.remote_addr ==", "if (value>=float(min)) and (value<=float(max)): if(value==v1) or (value==v2) or (value==v3): msg.append(\"filter", "] Database %s not exist\" %rom) return False def delete_sensor(id,rom):", "OR IGNORE INTO def (value) VALUES (?)\" c.execute(sql, data) conn.commit()", "return False def delete_sensor(id,rom): data = [id, rom] m =", "j: i2c=j['i2c'] usb = None if 'usb' in j: usb=j['usb']", "flask import Flask, request, jsonify, g import sqlite3 import os", "rom = None if 'rom' in j: rom=j['rom'] type =", "[value,rom] m.execute(sql, data) # stat min max data = [value,", "] Sensor %s updated\" %rom) return True else: print (\"[", "to previous %f\" % tmp) value=tmp else: value=float(value) else: msg.append(\"filter", "FROM sqlite_master WHERE type='table' AND name='def'\" c.execute(sql) if c.fetchone()[0]==1: data", "getattr(g, '_database', None) if db is not None: db.close() def", "nettemp ][ sensor ] Database %s not exist\" %rom) return", "create_sensor(rom, data, data2, map_settings): m = mysql.connection.cursor() rom1 = [rom]", "'_database', None) if db is None: db = g._database =", "nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s\" data = [value,tmp_5ago,rom] else: sql =", "coun[0]==0: sql = \"INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s,", "= None if 'tmp' in j: tmp=j['tmp'] value = None", "= None if 'type' in j: type=j['type'] device = None", "= None if 'value' in j: value=j['value'] group = type", "mysql.connection.cursor() sql=\"DELETE FROM sensors WHERE id=? AND rom=%s\" m.execute(sql, data)", "sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min is null", "in sensor: tmp=float(tmp) adj=float(adj) msg=[] sql = \"SELECT min, max,", "value, rom] sql = \"UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE", "False def insert_db(rom,value): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c", "count(*) FROM sensors WHERE rom=%s\" m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1:", "exist\" %rom) return False def delete_sensor(id,rom): data = [id, rom]", "if c.fetchone()[0]==1: data = [value] sql = \"INSERT OR IGNORE", "import os import json from random import randint from flask_jwt_extended", "stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min is null OR stat_min='0.0')", "FROM sensors WHERE id=? AND rom=%s\" m.execute(sql, data) m.connection.commit() m.close()", "= [id, rom] m = mysql.connection.cursor() sql=\"DELETE FROM sensors WHERE", "'', 200 @app.route('/local', methods=['POST']) def url_localhost(): if request.remote_addr == '127.0.0.1':", "data) m.connection.commit() m.close() delete_db(rom) print (\"[ nettemp ][ sensor ]", "usb = None if 'usb' in j: usb=j['usb'] name =", "if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def", "rom1 = [rom] sql = \"SELECT count(*) FROM sensors WHERE", "new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST'])", "conn.cursor() sql = \"SELECT count() FROM sqlite_master WHERE type='table' AND", "from flask_jwt_extended import jwt_required import datetime from flask_mysqldb import MySQL", "type if 'group' in j: group=j['group'] map_id = randint(1000,9000) map_y", "(\"[ nettemp ][ sensor ] Sensor %s added ok\" %rom)", "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\" m.execute(sql," ]
[ "isinstance(result, Failure) assert type(result.value) == TypeError assert repr(result.value) == \"TypeError('can", "import as_either, Failure, Success @as_either(TypeError) def add_one(x): return x +", "Failure) assert type(result.value) == TypeError assert repr(result.value) == \"TypeError('can only", "Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure) assert type(result.value) == TypeError assert repr(result.value)", "def times_five(x): return x * 5 def test_success_executes_bindings(): result =", "result = Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure) assert type(result.value) == TypeError", "assert repr(result.value) == \"TypeError('can only concatenate str (not \\\"int\\\") to", "result = Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success) assert result.value == 10", "@as_either(TypeError) def add_one(x): return x + 1 @as_either() def times_five(x):", "def test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success) assert result.value", "@as_either() def times_five(x): return x * 5 def test_success_executes_bindings(): result", "* 5 def test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success)", "assert type(result.value) == TypeError assert repr(result.value) == \"TypeError('can only concatenate", "assert isinstance(result, Failure) assert type(result.value) == TypeError assert repr(result.value) ==", "+ 1 @as_either() def times_five(x): return x * 5 def", "isinstance(result, Success) assert result.value == 10 def test_a_failure_stops_the_execution_of_later_bindings(): result =", "type(result.value) == TypeError assert repr(result.value) == \"TypeError('can only concatenate str", "as_either, Failure, Success @as_either(TypeError) def add_one(x): return x + 1", "test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success) assert result.value ==", "Success @as_either(TypeError) def add_one(x): return x + 1 @as_either() def", "= Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure) assert type(result.value) == TypeError assert", "x * 5 def test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five) assert isinstance(result,", "Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success) assert result.value == 10 def test_a_failure_stops_the_execution_of_later_bindings():", "TypeError assert repr(result.value) == \"TypeError('can only concatenate str (not \\\"int\\\")", "test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure) assert type(result.value) ==", "Success) assert result.value == 10 def test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five)", "return x + 1 @as_either() def times_five(x): return x *", "repr(result.value) == \"TypeError('can only concatenate str (not \\\"int\\\") to str')\"", "from python_on_rails.either import as_either, Failure, Success @as_either(TypeError) def add_one(x): return", "== 10 def test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure)", "add_one(x): return x + 1 @as_either() def times_five(x): return x", "Failure, Success @as_either(TypeError) def add_one(x): return x + 1 @as_either()", "times_five(x): return x * 5 def test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five)", "def add_one(x): return x + 1 @as_either() def times_five(x): return", "5 def test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success) assert", "assert result.value == 10 def test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five) assert", "return x * 5 def test_success_executes_bindings(): result = Success(1).bind(add_one).bind(times_five) assert", "10 def test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure) assert", "python_on_rails.either import as_either, Failure, Success @as_either(TypeError) def add_one(x): return x", "1 @as_either() def times_five(x): return x * 5 def test_success_executes_bindings():", "== TypeError assert repr(result.value) == \"TypeError('can only concatenate str (not", "result.value == 10 def test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result,", "assert isinstance(result, Success) assert result.value == 10 def test_a_failure_stops_the_execution_of_later_bindings(): result", "x + 1 @as_either() def times_five(x): return x * 5", "def test_a_failure_stops_the_execution_of_later_bindings(): result = Success(\"NaN\").bind(add_one).bind(times_five) assert isinstance(result, Failure) assert type(result.value)", "= Success(1).bind(add_one).bind(times_five) assert isinstance(result, Success) assert result.value == 10 def" ]
[ "models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100)", "= models.CharField(max_length=100) stationLocation = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date =", "stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.customerName", "def __str__(self): return self.itemName # Payments class Payments(models.Model): customerPhone =", "date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.stationName # Customers class", "import models # Create your models here. # Station class", "models.CharField(max_length=100) dateExpected = models.CharField(max_length=100) def __str__(self): return self.itemName # Payments", "# Station class Stations(models.Model): stationName = models.CharField(max_length=100) stationLocation = models.CharField(max_length=100)", "Items(models.Model): itemName = models.CharField(max_length=100) itemType = models.CharField(max_length=100) Quantity = models.CharField(max_length=100)", "self.stationName # Customers class Customers(models.Model): customerName = models.CharField(max_length=100) customerPhone =", "class Items(models.Model): itemName = models.CharField(max_length=100) itemType = models.CharField(max_length=100) Quantity =", "customerStartLoc = models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date", "from django.db import models # Create your models here. #", "= models.CharField(max_length=100) customerPhone = models.CharField(max_length=100) customerId = models.CharField(max_length=100) customerStartLoc =", "# Customers class Customers(models.Model): customerName = models.CharField(max_length=100) customerPhone = models.CharField(max_length=100)", "dateExpected = models.CharField(max_length=100) def __str__(self): return self.itemName # Payments class", "models.CharField(max_length=100) Quantity = models.CharField(max_length=100) originStation = models.CharField(max_length=100) originCounty = models.CharField(max_length=100)", "Create your models here. # Station class Stations(models.Model): stationName =", "Station class Stations(models.Model): stationName = models.CharField(max_length=100) stationLocation = models.CharField(max_length=100) stationStaffId", "code = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.customerPhone", "originCounty = models.CharField(max_length=100) receiverName = models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100) destinationAddress", "= models.CharField(max_length=100) def __str__(self): return self.itemName # Payments class Payments(models.Model):", "return self.customerName # Items class Items(models.Model): itemName = models.CharField(max_length=100) itemType", "= models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self):", "= models.EmailField(max_length=100) code = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str__(self):", "originStation = models.CharField(max_length=100) originCounty = models.CharField(max_length=100) receiverName = models.CharField(max_length=100) receiverPhone", "customerPhone = models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100) code", "Payments(models.Model): customerPhone = models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100)", "stationName = models.CharField(max_length=100) stationLocation = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date", "stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.stationName", "Payments class Payments(models.Model): customerPhone = models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100) paymentMeans", "models.CharField(max_length=100) customerPhone = models.CharField(max_length=100) customerId = models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100)", "self.itemName # Payments class Payments(models.Model): customerPhone = models.CharField(max_length=100) paymentAmount =", "models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100) code = models.CharField(max_length=100)", "= models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.customerName #", "your models here. # Station class Stations(models.Model): stationName = models.CharField(max_length=100)", "stationLocation = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def", "= models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100) dateSend= models.CharField(max_length=100)", "class Stations(models.Model): stationName = models.CharField(max_length=100) stationLocation = models.CharField(max_length=100) stationStaffId =", "models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected = models.CharField(max_length=100) def __str__(self): return self.itemName", "models.DateTimeField(auto_now_add=True) def __str_(self): return self.customerName # Items class Items(models.Model): itemName", "models.CharField(max_length=100) def __str__(self): return self.itemName # Payments class Payments(models.Model): customerPhone", "customerId = models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100) stationStaffId", "= models.DateTimeField(auto_now_add=True) def __str_(self): return self.stationName # Customers class Customers(models.Model):", "customerDestinationLoc = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def", "def __str_(self): return self.customerName # Items class Items(models.Model): itemName =", "= models.CharField(max_length=100) customerId = models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100) customerDestinationLoc =", "Quantity = models.CharField(max_length=100) originStation = models.CharField(max_length=100) originCounty = models.CharField(max_length=100) receiverName", "models.CharField(max_length=100) originStation = models.CharField(max_length=100) originCounty = models.CharField(max_length=100) receiverName = models.CharField(max_length=100)", "Customers(models.Model): customerName = models.CharField(max_length=100) customerPhone = models.CharField(max_length=100) customerId = models.CharField(max_length=100)", "class Payments(models.Model): customerPhone = models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100) paymentMeans =", "= models.CharField(max_length=100) itemType = models.CharField(max_length=100) Quantity = models.CharField(max_length=100) originStation =", "models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.customerName # Items", "self.customerName # Items class Items(models.Model): itemName = models.CharField(max_length=100) itemType =", "Customers class Customers(models.Model): customerName = models.CharField(max_length=100) customerPhone = models.CharField(max_length=100) customerId", "Items class Items(models.Model): itemName = models.CharField(max_length=100) itemType = models.CharField(max_length=100) Quantity", "models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.stationName # Customers", "__str_(self): return self.stationName # Customers class Customers(models.Model): customerName = models.CharField(max_length=100)", "= models.CharField(max_length=100) Quantity = models.CharField(max_length=100) originStation = models.CharField(max_length=100) originCounty =", "class Customers(models.Model): customerName = models.CharField(max_length=100) customerPhone = models.CharField(max_length=100) customerId =", "models.CharField(max_length=100) itemType = models.CharField(max_length=100) Quantity = models.CharField(max_length=100) originStation = models.CharField(max_length=100)", "= models.CharField(max_length=100) originCounty = models.CharField(max_length=100) receiverName = models.CharField(max_length=100) receiverPhone =", "models here. # Station class Stations(models.Model): stationName = models.CharField(max_length=100) stationLocation", "receiverPhone = models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100) dateSend=", "= models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date =", "customerPhone = models.CharField(max_length=100) customerId = models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100) customerDestinationLoc", "paymentAmount = models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100) code = models.CharField(max_length=100) date", "= models.CharField(max_length=100) originStation = models.CharField(max_length=100) originCounty = models.CharField(max_length=100) receiverName =", "# Items class Items(models.Model): itemName = models.CharField(max_length=100) itemType = models.CharField(max_length=100)", "itemType = models.CharField(max_length=100) Quantity = models.CharField(max_length=100) originStation = models.CharField(max_length=100) originCounty", "destinationCounty = models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected = models.CharField(max_length=100) def __str__(self):", "models.CharField(max_length=100) stationLocation = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True)", "models.CharField(max_length=100) customerId = models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100)", "models # Create your models here. # Station class Stations(models.Model):", "= models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected = models.CharField(max_length=100)", "dateSend= models.CharField(max_length=100) dateExpected = models.CharField(max_length=100) def __str__(self): return self.itemName #", "= models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.stationName #", "models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected = models.CharField(max_length=100) def", "= models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected = models.CharField(max_length=100) def __str__(self): return", "= models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100) code = models.CharField(max_length=100) date =", "models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True)", "# Payments class Payments(models.Model): customerPhone = models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100)", "django.db import models # Create your models here. # Station", "Stations(models.Model): stationName = models.CharField(max_length=100) stationLocation = models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100)", "models.CharField(max_length=100) originCounty = models.CharField(max_length=100) receiverName = models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100)", "destinationAddress = models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected =", "date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.customerName # Items class", "paymentMeans = models.EmailField(max_length=100) code = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def", "# Create your models here. # Station class Stations(models.Model): stationName", "models.CharField(max_length=100) stationStaffId = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str_(self): return", "models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100)", "here. # Station class Stations(models.Model): stationName = models.CharField(max_length=100) stationLocation =", "= models.CharField(max_length=100) customerStartLoc = models.CharField(max_length=100) customerDestinationLoc = models.CharField(max_length=100) stationStaffId =", "itemName = models.CharField(max_length=100) itemType = models.CharField(max_length=100) Quantity = models.CharField(max_length=100) originStation", "= models.CharField(max_length=100) paymentAmount = models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100) code =", "= models.CharField(max_length=100) receiverName = models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100) destinationAddress =", "= models.DateTimeField(auto_now_add=True) def __str_(self): return self.customerName # Items class Items(models.Model):", "customerName = models.CharField(max_length=100) customerPhone = models.CharField(max_length=100) customerId = models.CharField(max_length=100) customerStartLoc", "models.EmailField(max_length=100) code = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) def __str__(self): return", "__str_(self): return self.customerName # Items class Items(models.Model): itemName = models.CharField(max_length=100)", "models.DateTimeField(auto_now_add=True) def __str_(self): return self.stationName # Customers class Customers(models.Model): customerName", "receiverName = models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100) destinationCounty", "__str__(self): return self.itemName # Payments class Payments(models.Model): customerPhone = models.CharField(max_length=100)", "= models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100) destinationCounty =", "return self.itemName # Payments class Payments(models.Model): customerPhone = models.CharField(max_length=100) paymentAmount", "models.CharField(max_length=100) receiverName = models.CharField(max_length=100) receiverPhone = models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100)", "models.CharField(max_length=100) paymentMeans = models.EmailField(max_length=100) code = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True)", "models.CharField(max_length=100) destinationAddress = models.CharField(max_length=100) destinationCounty = models.CharField(max_length=100) dateSend= models.CharField(max_length=100) dateExpected", "def __str_(self): return self.stationName # Customers class Customers(models.Model): customerName =", "return self.stationName # Customers class Customers(models.Model): customerName = models.CharField(max_length=100) customerPhone" ]
[ "that have spaces in their names, since bazel # cannot", "properties to pass on. \"\"\" # Ignore some patterns by", "test runner. # # This is reusing the LLVM Lit", "\"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data = [\":\" + local_test_files] + data", "are upstreamed. # TODO(b/136126535): remove this custom rule. \"\"\"Lit runner", "Run tests individually such that errors can be attributed to", "name = name, srcs = test_file, size = size, deps", "not currently supported and specifying a default driver will abort", "_default_size, size_override = {}, data = [], per_test_extra_data = {},", "(for tests and inputs). test_file_exts: [str], extensions for files that", "data = [], size = _default_size, tags = _default_tags, driver", "= \"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\" _default_tags = [] # These", "features = features, exec_properties = exec_properties, ) def lit_test( name,", "size, tags, driver, features, exec_properties): \"\"\"Runs lit on all tests", "\"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") # Default values used by the test", "the interim until the new build # rules are upstreamed.", "TODO(b/136126535): remove this custom rule. \"\"\"Lit runner globbing test \"\"\"", "= [], exec_properties = {}): \"\"\"Runs test files under lit.", "{str: str}, tags to add to specific tests. driver: str,", "\"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") # Default values", "files. _ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", # Exclude input", "test. tags: [str], tags to attach to the test. driver:", "the test, including extension. data: [str], the data input to", "their inputs) under this directory. Args: exclude: [str], paths to", "of the test, including extension. data: [str], the data input", "\"*.mlir\", ]), ) tf_cc_test( name = name, srcs = test_file,", "for targets not in \"size_override\". size_override: {str: str}, sizes to", "tests that are included in the `data` parameter, regardless of", "(and their inputs) under this directory. Args: exclude: [str], paths", "errors can be attributed to a specific # failure. for", "tests. features: [str], list of extra features to enable. exec_properties:", "driver = _default_driver, features = [], exec_properties = {}): \"\"\"Runs", "exist in the directory searched. Args: name: str, the name", "with such \"targets\" in the srcs list. \"**/* *\", \"**/*", "it can find in `data` under tensorflow/compiler/mlir. Note that, due", "= [\":\" + local_test_files] + data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\",", "to the test. per_test_extra_data: {str: [str]}, extra data to attach", "to a specific # failure. for i in range(len(tests)): curr_test", "new build # rules are upstreamed. # TODO(b/136126535): remove this", "runner. _default_test_file_exts = [\"mlir\", \".pbtxt\", \".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size", "of extra features to enable. exec_properties: a dictionary of properties", "[str], the data input to the test. size: str, the", "additional tags to attach to the test. tags_override: {str: str},", "file. default_tags: [str], additional tags to attach to the test.", "the LLVM test runner. # # This is reusing the", "test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\")", "glob_op_tests( exclude = [], test_file_exts = _default_test_file_exts, default_size = _default_size,", "the srcs list. \"**/* *\", \"**/* */**\", ] def _run_lit_test(name,", "# test input data files. _ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\", \"**/README.txt\",", ") def glob_op_tests( exclude = [], test_file_exts = _default_test_file_exts, default_size", "to attach to the test. tags_override: {str: str}, tags to", "name of the test. data: [str], labels that should be", "driver, features, exec_properties): \"\"\"Runs lit on all tests it can", "tests = native.glob( [\"*.\" + ext for ext in test_file_exts],", "data to the test. per_test_extra_data: {str: [str]}, extra data to", "with updated parameters. lit_test( name = curr_test, data = data", "_default_size = \"small\" _default_tags = [] # These are patterns", "native.glob([ \"data/\" + name_without_suffix + \"*.mlir\", ]), ) tf_cc_test( name", "by default for tests and input data. exclude = _ALWAYS_EXCLUDE", "tags = _default_tags, driver = _default_driver, features = [], exec_properties", "= _default_test_file_exts, default_size = _default_size, size_override = {}, data =", "\"small\" _default_tags = [] # These are patterns which we", "tags to attach to the test. tags_override: {str: str}, tags", "\"\"\" _run_lit_test(name + \".test\", [name], data, size, tags, driver, features,", "for tests and input data. exclude = _ALWAYS_EXCLUDE + exclude", "in the directory searched. Args: name: str, the name of", "have spaces in their names, since bazel # cannot cope", "str, label of the driver shell script. Note: use of", "abort the tests. features: [str], list of extra features to", "`data` under tensorflow/compiler/mlir. Note that, due to Bazel's hermetic builds,", "\"//tensorflow/core:testlib\", ], data = [\":\" + local_test_files] + data +", "globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\",", "test size for targets not in \"size_override\". size_override: {str: str},", "= native.glob( [\"*.\" + ext for ext in test_file_exts], exclude", "features to enable. exec_properties: a dictionary of properties to pass", "name = curr_test, data = data + per_test_extra_data.get(curr_test, []), size", "driver: str, label of the driver shell script. Note: use", "extra features to enable. \"\"\" _run_lit_test(name + \".test\", [name], data,", "data = [], per_test_extra_data = {}, default_tags = _default_tags, tags_override", "test input data files. _ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\",", "per_test_extra_data = {}, default_tags = _default_tags, tags_override = {}, driver", "files under lit. Args: name: str, the name of the", "features: [str], list of extra features to enable. \"\"\" name_without_suffix", "tests. driver: str, label of the driver shell script. Note:", "on all tests it can find in `data` under tensorflow/compiler/mlir.", "to attach to the test. driver: str, label of the", "cope with such \"targets\" in the srcs list. \"**/* *\",", "size = size, deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\",", "]), ) tf_cc_test( name = name, srcs = test_file, size", "\"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], ) def glob_op_tests( exclude = [],", "of extra features to enable. \"\"\" _run_lit_test(name + \".test\", [name],", "[str]}, extra data to attach to a given file. default_tags:", "script. Note: use of a custom driver is not currently", "[str], list of extra features to enable. \"\"\" _run_lit_test(name +", "input data files. _ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", #", "= \"small\" _default_tags = [] # These are patterns which", "this directory. Args: exclude: [str], paths to exclude (for tests", "def _run_lit_test(name, test_file, data, size, tags, driver, features, exec_properties): \"\"\"Runs", "the size of the test. tags: [str], tags to attach", "lit on all tests it can find in `data` under", "[\"mlir\", \".pbtxt\", \".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\" _default_tags", "# Instantiate this test with updated parameters. lit_test( name =", "Ignore some patterns by default for tests and input data.", "to the test. driver: str, label of the driver shell", "for ext in test_file_exts], exclude = exclude, ) # Run", "+ tags_override.get(curr_test, []), driver = driver, features = features, exec_properties", "name + \".test_files\" filegroup( name = local_test_files, srcs = native.glob([", "name, srcs = test_file, size = size, deps = [", "enable. \"\"\" _run_lit_test(name + \".test\", [name], data, size, tags, driver,", "test_file[0].split('.')[0] local_test_files = name + \".test_files\" filegroup( name = local_test_files,", "to enable. \"\"\" name_without_suffix = test_file[0].split('.')[0] local_test_files = name +", "data: [str], additional input data to the test. per_test_extra_data: {str:", "load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") # Default values used", "] def _run_lit_test(name, test_file, data, size, tags, driver, features, exec_properties):", "searched. Args: name: str, the name of the test, including", "[str], additional tags to attach to the test. tags_override: {str:", "{str: str}, sizes to use for specific tests. data: [str],", "the tests. features: [str], list of extra features to enable.", "custom rule. \"\"\"Lit runner globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\",", "Args: name: str, the name of the test. data: [str],", "= test_file[0].split('.')[0] local_test_files = name + \".test_files\" filegroup( name =", "deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data =", "that are included in the `data` parameter, regardless of what", "def glob_op_tests( exclude = [], test_file_exts = _default_test_file_exts, default_size =", "that are tests. default_size: str, the test size for targets", "of the test. tags: [str], tags to attach to the", "\"\"\"Creates all plausible Lit tests (and their inputs) under this", "features, exec_properties = exec_properties, ) def lit_test( name, data =", "a specific # failure. for i in range(len(tests)): curr_test =", "should never match, for tests, subdirectories, or # test input", "test_file_exts = _default_test_file_exts, default_size = _default_size, size_override = {}, data", "given file. default_tags: [str], additional tags to attach to the", "tests. default_size: str, the test size for targets not in", "to the test. tags_override: {str: str}, tags to add to", "# failure. for i in range(len(tests)): curr_test = tests[i] #", "[ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", # Exclude input files that have", "a given file. default_tags: [str], additional tags to attach to", "plausible Lit tests (and their inputs) under this directory. Args:", "definitions for Lit, the LLVM test runner. # # This", "in the srcs list. \"**/* *\", \"**/* */**\", ] def", "\".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\" _default_tags = []", "Exclude input files that have spaces in their names, since", "\"targets\" in the srcs list. \"**/* *\", \"**/* */**\", ]", "dictionary of properties to pass on. \"\"\" # Ignore some", "= tests[i] # Instantiate this test with updated parameters. lit_test(", "\"//tensorflow/compiler/mlir:tf-opt\", ], ) def glob_op_tests( exclude = [], test_file_exts =", "= [], test_file_exts = _default_test_file_exts, default_size = _default_size, size_override =", "# Exclude input files that have spaces in their names,", "\"\"\"Runs lit on all tests it can find in `data`", "the test runner. _default_test_file_exts = [\"mlir\", \".pbtxt\", \".td\"] _default_driver =", "= _default_tags, tags_override = {}, driver = _default_driver, features =", "under lit. Args: name: str, the name of the test.", "bazel # cannot cope with such \"targets\" in the srcs", "the name of the test, including extension. data: [str], the", "= [ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", # Exclude input files that", "attributed to a specific # failure. for i in range(len(tests)):", "_default_tags = [] # These are patterns which we should", "tests. features: [str], list of extra features to enable. \"\"\"", "all tests it can find in `data` under tensorflow/compiler/mlir. Note", "test. tags_override: {str: str}, tags to add to specific tests.", "\"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", # Exclude input files that have spaces", "= local_test_files, srcs = native.glob([ \"data/\" + name_without_suffix + \"*.mlir\",", "{}, driver = _default_driver, features = [], exec_properties = {}):", "tags_override.get(curr_test, []), driver = driver, features = features, exec_properties =", "_run_lit_test(name, test_file, data, size, tags, driver, features, exec_properties): \"\"\"Runs lit", "range(len(tests)): curr_test = tests[i] # Instantiate this test with updated", "lit. Args: name: str, the name of the test. data:", "cannot cope with such \"targets\" in the srcs list. \"**/*", "[str], extensions for files that are tests. default_size: str, the", "the driver shell script. Note: use of a custom driver", "for specific tests. data: [str], additional input data to the", "test runner in the interim until the new build #", "Lit test runner in the interim until the new build", "driver, features = features, exec_properties = exec_properties, ) def lit_test(", "filegroup( name = local_test_files, srcs = native.glob([ \"data/\" + name_without_suffix", "size = _default_size, tags = _default_tags, driver = _default_driver, features", "\"\"\"Lit runner globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\",", "= exclude, ) # Run tests individually such that errors", "size_override.get(curr_test, default_size), tags = default_tags + tags_override.get(curr_test, []), driver =", "exec_properties = exec_properties, ) def lit_test( name, data = [],", "def lit_test( name, data = [], size = _default_size, tags", "lit only sees the tests that are included in the", "tf_cc_test( name = name, srcs = test_file, size = size,", "to specific tests. driver: str, label of the driver shell", "to pass on. \"\"\" # Ignore some patterns by default", "under tensorflow/compiler/mlir. Note that, due to Bazel's hermetic builds, lit", "{}, data = [], per_test_extra_data = {}, default_tags = _default_tags,", "to enable. \"\"\" _run_lit_test(name + \".test\", [name], data, size, tags,", "are patterns which we should never match, for tests, subdirectories,", "extensions for files that are tests. default_size: str, the test", "= data + per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test, default_size), tags", "= curr_test, data = data + per_test_extra_data.get(curr_test, []), size =", "extra features to enable. \"\"\" name_without_suffix = test_file[0].split('.')[0] local_test_files =", "data inputs. size: str, the size of the test. tags:", "Default values used by the test runner. _default_test_file_exts = [\"mlir\",", "of extra features to enable. \"\"\" name_without_suffix = test_file[0].split('.')[0] local_test_files", "], data = [\":\" + local_test_files] + data + [", "attach to the test. driver: str, label of the driver", "\"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], ) def glob_op_tests( exclude = [], test_file_exts", "by the test runner. _default_test_file_exts = [\"mlir\", \".pbtxt\", \".td\"] _default_driver", "features: [str], list of extra features to enable. exec_properties: a", "native.glob( [\"*.\" + ext for ext in test_file_exts], exclude =", "= name + \".test_files\" filegroup( name = local_test_files, srcs =", "test. size: str, the size of the test. tags: [str],", "data. exclude = _ALWAYS_EXCLUDE + exclude tests = native.glob( [\"*.\"", ") def lit_test( name, data = [], size = _default_size,", "name: str, the name of the test, including extension. data:", "other tests might exist in the directory searched. Args: name:", "data to attach to a given file. default_tags: [str], additional", "[\":\" + local_test_files] + data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\",", "[]), size = size_override.get(curr_test, default_size), tags = default_tags + tags_override.get(curr_test,", "tests and inputs). test_file_exts: [str], extensions for files that are", "a custom driver is not currently supported and specifying a", "driver will abort the tests. features: [str], list of extra", "[str], tags to attach to the test. driver: str, label", "that should be provided as data inputs. size: str, the", "tags = default_tags + tags_override.get(curr_test, []), driver = driver, features", "the directory searched. Args: name: str, the name of the", "size_override = {}, data = [], per_test_extra_data = {}, default_tags", "Note that, due to Bazel's hermetic builds, lit only sees", "in test_file_exts], exclude = exclude, ) # Run tests individually", "+ \"*.mlir\", ]), ) tf_cc_test( name = name, srcs =", "can be attributed to a specific # failure. for i", "attach to the test. tags_override: {str: str}, tags to add", "tests it can find in `data` under tensorflow/compiler/mlir. Note that,", "= _default_tags, driver = _default_driver, features = [], exec_properties =", "tests. data: [str], additional input data to the test. per_test_extra_data:", "for Lit, the LLVM test runner. # # This is", "this test with updated parameters. lit_test( name = curr_test, data", "\"**/README.txt\", \"**/lit.local.cfg\", # Exclude input files that have spaces in", "enable. \"\"\" name_without_suffix = test_file[0].split('.')[0] local_test_files = name + \".test_files\"", "under this directory. Args: exclude: [str], paths to exclude (for", "data = [\":\" + local_test_files] + data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\",", "for files that are tests. default_size: str, the test size", "remove this custom rule. \"\"\"Lit runner globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\",", "= _default_driver, features = [], exec_properties = {}): \"\"\"Creates all", ") tf_cc_test( name = name, srcs = test_file, size =", "default_size = _default_size, size_override = {}, data = [], per_test_extra_data", "directory searched. Args: name: str, the name of the test,", "exclude, ) # Run tests individually such that errors can", "exec_properties, ) def lit_test( name, data = [], size =", "[ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], ) def glob_op_tests( exclude =", "[str], labels that should be provided as data inputs. size:", "= _default_size, size_override = {}, data = [], per_test_extra_data =", "curr_test, data = data + per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test,", "= [], size = _default_size, tags = _default_tags, driver =", "add to specific tests. driver: str, label of the driver", "of a custom driver is not currently supported and specifying", "Args: exclude: [str], paths to exclude (for tests and inputs).", "upstreamed. # TODO(b/136126535): remove this custom rule. \"\"\"Lit runner globbing", "size of the test. tags: [str], tags to attach to", "not in \"size_override\". size_override: {str: str}, sizes to use for", "interim until the new build # rules are upstreamed. #", "tags to attach to the test. driver: str, label of", "\"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\" _default_tags = [] # These are", "str, the test size for targets not in \"size_override\". size_override:", "_default_driver, features = [], exec_properties = {}): \"\"\"Creates all plausible", "such that errors can be attributed to a specific #", "specific tests. driver: str, label of the driver shell script.", "is reusing the LLVM Lit test runner in the interim", "parameters. lit_test( name = curr_test, data = data + per_test_extra_data.get(curr_test,", "srcs = native.glob([ \"data/\" + name_without_suffix + \"*.mlir\", ]), )", "# Test definitions for Lit, the LLVM test runner. #", "\"**/* *\", \"**/* */**\", ] def _run_lit_test(name, test_file, data, size,", "default driver will abort the tests. features: [str], list of", "specific # failure. for i in range(len(tests)): curr_test = tests[i]", "the LLVM Lit test runner in the interim until the", "# Ignore some patterns by default for tests and input", "size = size_override.get(curr_test, default_size), tags = default_tags + tags_override.get(curr_test, []),", "\"**/* */**\", ] def _run_lit_test(name, test_file, data, size, tags, driver,", "features, exec_properties): \"\"\"Runs lit on all tests it can find", "for tests, subdirectories, or # test input data files. _ALWAYS_EXCLUDE", "\"\"\" # Ignore some patterns by default for tests and", "+ [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], ) def glob_op_tests( exclude", "= {}, data = [], per_test_extra_data = {}, default_tags =", "a default driver will abort the tests. features: [str], list", "= {}): \"\"\"Runs test files under lit. Args: name: str,", "reusing the LLVM Lit test runner in the interim until", "inputs). test_file_exts: [str], extensions for files that are tests. default_size:", "are included in the `data` parameter, regardless of what other", "str}, sizes to use for specific tests. data: [str], additional", "\".pbtxt\", \".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\" _default_tags =", "specific tests. data: [str], additional input data to the test.", "size: str, the size of the test. tags: [str], tags", "= size, deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ],", "data files. _ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", # Exclude", "inputs. size: str, the size of the test. tags: [str],", "load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") # Default values used by the", "data + per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test, default_size), tags =", "use of a custom driver is not currently supported and", "\"\"\"Runs test files under lit. Args: name: str, the name", "the data input to the test. size: str, the size", "\"data/\" + name_without_suffix + \"*.mlir\", ]), ) tf_cc_test( name =", "exec_properties = {}): \"\"\"Runs test files under lit. Args: name:", "{str: [str]}, extra data to attach to a given file.", "= native.glob([ \"data/\" + name_without_suffix + \"*.mlir\", ]), ) tf_cc_test(", "exclude: [str], paths to exclude (for tests and inputs). test_file_exts:", "might exist in the directory searched. Args: name: str, the", "the test. per_test_extra_data: {str: [str]}, extra data to attach to", "features to enable. \"\"\" name_without_suffix = test_file[0].split('.')[0] local_test_files = name", "driver is not currently supported and specifying a default driver", "data, size, tags, driver, features, exec_properties): \"\"\"Runs lit on all", "name: str, the name of the test. data: [str], labels", "[str], paths to exclude (for tests and inputs). test_file_exts: [str],", "_default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\" _default_tags = [] #", "we should never match, for tests, subdirectories, or # test", "the test. tags: [str], tags to attach to the test.", "list of extra features to enable. exec_properties: a dictionary of", "# Default values used by the test runner. _default_test_file_exts =", "per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test, default_size), tags = default_tags +", "the test. data: [str], labels that should be provided as", "find in `data` under tensorflow/compiler/mlir. Note that, due to Bazel's", "be attributed to a specific # failure. for i in", "exclude = exclude, ) # Run tests individually such that", "a dictionary of properties to pass on. \"\"\" # Ignore", "name_without_suffix + \"*.mlir\", ]), ) tf_cc_test( name = name, srcs", ") # Run tests individually such that errors can be", "to enable. exec_properties: a dictionary of properties to pass on.", "targets not in \"size_override\". size_override: {str: str}, sizes to use", "test files under lit. Args: name: str, the name of", "regardless of what other tests might exist in the directory", "labels that should be provided as data inputs. size: str,", "_ALWAYS_EXCLUDE + exclude tests = native.glob( [\"*.\" + ext for", "= exec_properties, ) def lit_test( name, data = [], size", "Args: name: str, the name of the test, including extension.", "should be provided as data inputs. size: str, the size", "values used by the test runner. _default_test_file_exts = [\"mlir\", \".pbtxt\",", "_ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\", \"**/README.txt\", \"**/lit.local.cfg\", # Exclude input files", "to exclude (for tests and inputs). test_file_exts: [str], extensions for", "of properties to pass on. \"\"\" # Ignore some patterns", "the tests that are included in the `data` parameter, regardless", "{}): \"\"\"Creates all plausible Lit tests (and their inputs) under", "lit_test( name, data = [], size = _default_size, tags =", "Note: use of a custom driver is not currently supported", "of what other tests might exist in the directory searched.", "patterns which we should never match, for tests, subdirectories, or", "= name, srcs = test_file, size = size, deps =", "_default_size, tags = _default_tags, driver = _default_driver, features = [],", "included in the `data` parameter, regardless of what other tests", "srcs = test_file, size = size, deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\",", "extra data to attach to a given file. default_tags: [str],", "in the interim until the new build # rules are", "local_test_files = name + \".test_files\" filegroup( name = local_test_files, srcs", "the test. tags_override: {str: str}, tags to add to specific", "extension. data: [str], the data input to the test. size:", "in \"size_override\". size_override: {str: str}, sizes to use for specific", "enable. exec_properties: a dictionary of properties to pass on. \"\"\"", "= size_override.get(curr_test, default_size), tags = default_tags + tags_override.get(curr_test, []), driver", "to Bazel's hermetic builds, lit only sees the tests that", "rules are upstreamed. # TODO(b/136126535): remove this custom rule. \"\"\"Lit", "default_tags + tags_override.get(curr_test, []), driver = driver, features = features,", "These are patterns which we should never match, for tests,", "exec_properties = {}): \"\"\"Creates all plausible Lit tests (and their", "and specifying a default driver will abort the tests. features:", "tests[i] # Instantiate this test with updated parameters. lit_test( name", "and input data. exclude = _ALWAYS_EXCLUDE + exclude tests =", "tests might exist in the directory searched. Args: name: str,", "= features, exec_properties = exec_properties, ) def lit_test( name, data", "ext for ext in test_file_exts], exclude = exclude, ) #", "lit_test( name = curr_test, data = data + per_test_extra_data.get(curr_test, []),", "[], exec_properties = {}): \"\"\"Runs test files under lit. Args:", "be provided as data inputs. size: str, the size of", "# These are patterns which we should never match, for", "\"tf_native_cc_binary\", \"tf_copts\") # Default values used by the test runner.", "= _default_driver, features = [], exec_properties = {}): \"\"\"Runs test", "= [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data = [\":\"", "pass on. \"\"\" # Ignore some patterns by default for", "[], size = _default_size, tags = _default_tags, driver = _default_driver,", "shell script. Note: use of a custom driver is not", "[] # These are patterns which we should never match,", "# This is reusing the LLVM Lit test runner in", "default for tests and input data. exclude = _ALWAYS_EXCLUDE +", "list. \"**/* *\", \"**/* */**\", ] def _run_lit_test(name, test_file, data,", "\"\"\" name_without_suffix = test_file[0].split('.')[0] local_test_files = name + \".test_files\" filegroup(", "[str], additional input data to the test. per_test_extra_data: {str: [str]},", "# Run tests individually such that errors can be attributed", "and inputs). test_file_exts: [str], extensions for files that are tests.", "some patterns by default for tests and input data. exclude", "extra features to enable. exec_properties: a dictionary of properties to", "= {}): \"\"\"Creates all plausible Lit tests (and their inputs)", "including extension. data: [str], the data input to the test.", "to attach to a given file. default_tags: [str], additional tags", "input data. exclude = _ALWAYS_EXCLUDE + exclude tests = native.glob(", "build # rules are upstreamed. # TODO(b/136126535): remove this custom", "tags, driver, features, exec_properties): \"\"\"Runs lit on all tests it", "], ) def glob_op_tests( exclude = [], test_file_exts = _default_test_file_exts,", "[], test_file_exts = _default_test_file_exts, default_size = _default_size, size_override = {},", "\"tf_copts\") # Default values used by the test runner. _default_test_file_exts", "default_size: str, the test size for targets not in \"size_override\".", "Lit tests (and their inputs) under this directory. Args: exclude:", "# cannot cope with such \"targets\" in the srcs list.", "supported and specifying a default driver will abort the tests.", "= _ALWAYS_EXCLUDE + exclude tests = native.glob( [\"*.\" + ext", "runner globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\",", "input files that have spaces in their names, since bazel", "data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], ) def glob_op_tests(", "that errors can be attributed to a specific # failure.", "spaces in their names, since bazel # cannot cope with", "that, due to Bazel's hermetic builds, lit only sees the", "never match, for tests, subdirectories, or # test input data", "str, the name of the test, including extension. data: [str],", "Lit, the LLVM test runner. # # This is reusing", "test. per_test_extra_data: {str: [str]}, extra data to attach to a", "\"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data = [\":\" + local_test_files]", "files that have spaces in their names, since bazel #", "_default_test_file_exts, default_size = _default_size, size_override = {}, data = [],", "the test. driver: str, label of the driver shell script.", "test_file, data, size, tags, driver, features, exec_properties): \"\"\"Runs lit on", "# rules are upstreamed. # TODO(b/136126535): remove this custom rule.", "data = data + per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test, default_size),", "size_override: {str: str}, sizes to use for specific tests. data:", "This is reusing the LLVM Lit test runner in the", "features = [], exec_properties = {}): \"\"\"Runs test files under", "= driver, features = features, exec_properties = exec_properties, ) def", "exclude = [], test_file_exts = _default_test_file_exts, default_size = _default_size, size_override", "test with updated parameters. lit_test( name = curr_test, data =", "list of extra features to enable. \"\"\" _run_lit_test(name + \".test\",", "for i in range(len(tests)): curr_test = tests[i] # Instantiate this", "\"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") # Default values used by", "[ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data = [\":\" +", "local_test_files] + data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], )", "input to the test. size: str, the size of the", "exclude (for tests and inputs). test_file_exts: [str], extensions for files", "*\", \"**/* */**\", ] def _run_lit_test(name, test_file, data, size, tags,", "features: [str], list of extra features to enable. \"\"\" _run_lit_test(name", "default_tags = _default_tags, tags_override = {}, driver = _default_driver, features", "\"size_override\". size_override: {str: str}, sizes to use for specific tests.", "the test. size: str, the size of the test. tags:", "+ exclude tests = native.glob( [\"*.\" + ext for ext", "test, including extension. data: [str], the data input to the", "ext in test_file_exts], exclude = exclude, ) # Run tests", "+ \".test_files\" filegroup( name = local_test_files, srcs = native.glob([ \"data/\"", "of the driver shell script. Note: use of a custom", "exec_properties: a dictionary of properties to pass on. \"\"\" #", "what other tests might exist in the directory searched. Args:", "Instantiate this test with updated parameters. lit_test( name = curr_test,", "files that are tests. default_size: str, the test size for", "\"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data = [\":\" + local_test_files] +", "names, since bazel # cannot cope with such \"targets\" in", "sizes to use for specific tests. data: [str], additional input", "will abort the tests. features: [str], list of extra features", "name, data = [], size = _default_size, tags = _default_tags,", "size, deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\", \"//tensorflow/core:testlib\", ], data", "srcs list. \"**/* *\", \"**/* */**\", ] def _run_lit_test(name, test_file,", "tags to add to specific tests. driver: str, label of", "attach to a given file. default_tags: [str], additional tags to", "name of the test, including extension. data: [str], the data", "test_file, size = size, deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\", \"//tensorflow/core:test_main\",", "features to enable. \"\"\" _run_lit_test(name + \".test\", [name], data, size,", "Bazel's hermetic builds, lit only sees the tests that are", "features = [], exec_properties = {}): \"\"\"Creates all plausible Lit", "test_file_exts], exclude = exclude, ) # Run tests individually such", "\"**/lit.local.cfg\", # Exclude input files that have spaces in their", "provided as data inputs. size: str, the size of the", "paths to exclude (for tests and inputs). test_file_exts: [str], extensions", "curr_test = tests[i] # Instantiate this test with updated parameters.", "test. driver: str, label of the driver shell script. Note:", "to add to specific tests. driver: str, label of the", "+ data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ], ) def", "such \"targets\" in the srcs list. \"**/* *\", \"**/* */**\",", "are tests. default_size: str, the test size for targets not", "= [], exec_properties = {}): \"\"\"Creates all plausible Lit tests", "LLVM Lit test runner in the interim until the new", "to use for specific tests. data: [str], additional input data", "data: [str], the data input to the test. size: str,", "Test definitions for Lit, the LLVM test runner. # #", "str, the name of the test. data: [str], labels that", "input data to the test. per_test_extra_data: {str: [str]}, extra data", "label of the driver shell script. Note: use of a", "local_test_files, srcs = native.glob([ \"data/\" + name_without_suffix + \"*.mlir\", ]),", "currently supported and specifying a default driver will abort the", "per_test_extra_data: {str: [str]}, extra data to attach to a given", "to a given file. default_tags: [str], additional tags to attach", "\".test_files\" filegroup( name = local_test_files, srcs = native.glob([ \"data/\" +", "all plausible Lit tests (and their inputs) under this directory.", "the `data` parameter, regardless of what other tests might exist", "parameter, regardless of what other tests might exist in the", "tags_override: {str: str}, tags to add to specific tests. driver:", "data: [str], labels that should be provided as data inputs.", "on. \"\"\" # Ignore some patterns by default for tests", "+ name_without_suffix + \"*.mlir\", ]), ) tf_cc_test( name = name,", "[str], list of extra features to enable. \"\"\" name_without_suffix =", "rule. \"\"\"Lit runner globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\")", "failure. for i in range(len(tests)): curr_test = tests[i] # Instantiate", "the new build # rules are upstreamed. # TODO(b/136126535): remove", "[], per_test_extra_data = {}, default_tags = _default_tags, tags_override = {},", "only sees the tests that are included in the `data`", "of the test. data: [str], labels that should be provided", "in range(len(tests)): curr_test = tests[i] # Instantiate this test with", "_default_test_file_exts = [\"mlir\", \".pbtxt\", \".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size =", "patterns by default for tests and input data. exclude =", "list of extra features to enable. \"\"\" name_without_suffix = test_file[0].split('.')[0]", "updated parameters. lit_test( name = curr_test, data = data +", "[str], list of extra features to enable. exec_properties: a dictionary", "this custom rule. \"\"\"Lit runner globbing test \"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\")", "data input to the test. size: str, the size of", "= [], per_test_extra_data = {}, default_tags = _default_tags, tags_override =", "_default_driver, features = [], exec_properties = {}): \"\"\"Runs test files", "+ ext for ext in test_file_exts], exclude = exclude, )", "\"\"\" load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") #", "is not currently supported and specifying a default driver will", "= [] # These are patterns which we should never", "custom driver is not currently supported and specifying a default", "the name of the test. data: [str], labels that should", "due to Bazel's hermetic builds, lit only sees the tests", "*/**\", ] def _run_lit_test(name, test_file, data, size, tags, driver, features,", "[]), driver = driver, features = features, exec_properties = exec_properties,", "[], exec_properties = {}): \"\"\"Creates all plausible Lit tests (and", "directory. Args: exclude: [str], paths to exclude (for tests and", "tags_override = {}, driver = _default_driver, features = [], exec_properties", "specifying a default driver will abort the tests. features: [str],", "str}, tags to add to specific tests. driver: str, label", "inputs) under this directory. Args: exclude: [str], paths to exclude", "driver = _default_driver, features = [], exec_properties = {}): \"\"\"Creates", "tensorflow/compiler/mlir. Note that, due to Bazel's hermetic builds, lit only", "sees the tests that are included in the `data` parameter,", "exec_properties): \"\"\"Runs lit on all tests it can find in", "= {}, driver = _default_driver, features = [], exec_properties =", "additional input data to the test. per_test_extra_data: {str: [str]}, extra", "test_file_exts: [str], extensions for files that are tests. default_size: str,", "since bazel # cannot cope with such \"targets\" in the", "size for targets not in \"size_override\". size_override: {str: str}, sizes", "individually such that errors can be attributed to a specific", "`data` parameter, regardless of what other tests might exist in", "or # test input data files. _ALWAYS_EXCLUDE = [ \"**/LICENSE.txt\",", "+ per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test, default_size), tags = default_tags", "load(\"//tensorflow:tensorflow.bzl\", \"filegroup\") load(\"@bazel_skylib//lib:paths.bzl\", \"paths\") load(\"//tensorflow:tensorflow.bzl\", \"tf_cc_test\", \"tf_native_cc_binary\", \"tf_copts\") # Default", "= _default_size, tags = _default_tags, driver = _default_driver, features =", "default_size), tags = default_tags + tags_override.get(curr_test, []), driver = driver,", "driver shell script. Note: use of a custom driver is", "in `data` under tensorflow/compiler/mlir. Note that, due to Bazel's hermetic", "tests individually such that errors can be attributed to a", "used by the test runner. _default_test_file_exts = [\"mlir\", \".pbtxt\", \".td\"]", "in the `data` parameter, regardless of what other tests might", "_run_lit_test(name + \".test\", [name], data, size, tags, driver, features, exec_properties)", "runner in the interim until the new build # rules", "name_without_suffix = test_file[0].split('.')[0] local_test_files = name + \".test_files\" filegroup( name", "exclude = _ALWAYS_EXCLUDE + exclude tests = native.glob( [\"*.\" +", "the test size for targets not in \"size_override\". size_override: {str:", "tests and input data. exclude = _ALWAYS_EXCLUDE + exclude tests", "subdirectories, or # test input data files. _ALWAYS_EXCLUDE = [", "their names, since bazel # cannot cope with such \"targets\"", "driver = driver, features = features, exec_properties = exec_properties, )", "match, for tests, subdirectories, or # test input data files.", "which we should never match, for tests, subdirectories, or #", "LLVM test runner. # # This is reusing the LLVM", "exclude tests = native.glob( [\"*.\" + ext for ext in", "= default_tags + tags_override.get(curr_test, []), driver = driver, features =", "+ local_test_files] + data + [ \"//tensorflow/compiler/mlir/disc:disc_compiler_main\", \"//tensorflow/compiler/mlir:tf-mlir-translate\", \"//tensorflow/compiler/mlir:tf-opt\", ],", "name = local_test_files, srcs = native.glob([ \"data/\" + name_without_suffix +", "{}): \"\"\"Runs test files under lit. Args: name: str, the", "[\"*.\" + ext for ext in test_file_exts], exclude = exclude,", "until the new build # rules are upstreamed. # TODO(b/136126535):", "tags: [str], tags to attach to the test. driver: str,", "= {}, default_tags = _default_tags, tags_override = {}, driver =", "= test_file, size = size, deps = [ \"//tensorflow/compiler/mlir/disc/tests:mlir_feature_test\", \"//tensorflow/core:test\",", "_default_tags, driver = _default_driver, features = [], exec_properties = {}):", "i in range(len(tests)): curr_test = tests[i] # Instantiate this test", "test. data: [str], labels that should be provided as data", "{}, default_tags = _default_tags, tags_override = {}, driver = _default_driver,", "use for specific tests. data: [str], additional input data to", "test runner. _default_test_file_exts = [\"mlir\", \".pbtxt\", \".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\"", "builds, lit only sees the tests that are included in", "= [\"mlir\", \".pbtxt\", \".td\"] _default_driver = \"@llvm-project//mlir:run_lit.sh\" _default_size = \"small\"", "default_tags: [str], additional tags to attach to the test. tags_override:", "to the test. size: str, the size of the test.", "tests, subdirectories, or # test input data files. _ALWAYS_EXCLUDE =", "in their names, since bazel # cannot cope with such", "# # This is reusing the LLVM Lit test runner", "# TODO(b/136126535): remove this custom rule. \"\"\"Lit runner globbing test", "str, the size of the test. tags: [str], tags to", "hermetic builds, lit only sees the tests that are included", "tests (and their inputs) under this directory. Args: exclude: [str],", "as data inputs. size: str, the size of the test.", "runner. # # This is reusing the LLVM Lit test", "can find in `data` under tensorflow/compiler/mlir. Note that, due to", "_default_tags, tags_override = {}, driver = _default_driver, features = []," ]
[ "#if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR == 4", "of messager_libname) \"\"\" if not real_libs: real_libs = [message_libname] context.Message(\"Checking", "element, the value of messager_libname) \"\"\" if not real_libs: real_libs", "else: context.env['LIBS'] = libsave return ret libuuid_source = ''' #include", "<stdint.h> int main() { uint16_t b16 = 0x00FF; uint32_t b32", "byteswap_source = ''' #include <byteswap.h> #include <stdint.h> int main() {", "show in the message output from scons real_libs -- list", "if not real_libs: real_libs = [message_libname] context.Message(\"Checking for %s...\" %", "libsave is None: del(context.env['LIBS']) else: context.env['LIBS'] = libsave return ret", "arguments: source -- source to try to compile source_type --", "int main() { uint16_t b16 = 0x00FF; uint32_t b32 =", "security_context_t ctx; getpeercon(0, &ctx); return 0; } ''' def CheckSeLinux(context):", "\"\"\" Check that source can be successfully compiled and linked", "#error \"\" #endif #endif #else #error \"\" #endif ''' def", "source_type -- type of source file, (probably should be \".c\")", "are functions to add to the configure context. \"\"\" def", "context.Result( ret ) if libsave is None: del(context.env['LIBS']) else: context.env['LIBS']", "\"\" #endif #endif #else #error \"\" #endif ''' def CheckBDB(context):", "= ''' #include <selinux/selinux.h> int main() { security_context_t ctx; getpeercon(0,", "library name to show in the message output from scons", "in the message output from scons real_libs -- list of", "source -- source to try to compile source_type -- type", "-- source to try to compile source_type -- type of", "context.Message(\"Checking for byteswap.h...\") ret = context.TryCompile(byteswap_source, '.c') context.Result( ret )", "and linked against real_libs. Keyword arguments: source -- source to", "context. \"\"\" def __checkCanLink(context, source, source_type, message_libname, real_libs=[]): \"\"\" Check", "main() { uint16_t b16 = 0x00FF; uint32_t b32 = 0x0011EEFF;", "to link against (defaults to a list with one element,", "&& DB_VERSION_MINOR >= 3 #else #error \"\" #endif #endif #else", "#else #error \"\" #endif ''' def CheckBDB(context): context.Message(\"Checking for BDB", "BDB >= 4.3...\") ret = context.TryCompile(bdb_source, '.c') context.Result(ret) return ret", "main() { security_context_t ctx; getpeercon(0, &ctx); return 0; } '''", "to show in the message output from scons real_libs --", "0; } ''' def CheckLibUUID(context): return __checkCanLink(context, libuuid_source, \".c\", \"libuuid\",", "CheckLibUUID(context): return __checkCanLink(context, libuuid_source, \".c\", \"libuuid\", [\"uuid\"]) selinux_source = '''", "should be \".c\") message_libname -- library name to show in", "of actual libraries to link against (defaults to a list", "a list with one element, the value of messager_libname) \"\"\"", "b16 = 0x00FF; uint32_t b32 = 0x0011EEFF; uint64_t b64 =", "getpeercon(0, &ctx); return 0; } ''' def CheckSeLinux(context): return __checkCanLink(context,", "''' #include <uuid/uuid.h> int main() { uuid_t uu; char uuid_str[37];", "libsave return ret libuuid_source = ''' #include <uuid/uuid.h> int main()", "Check that source can be successfully compiled and linked against", "ret bdb_source = ''' #include <db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR", "DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3 #else", "#error \"\" #endif ''' def CheckBDB(context): context.Message(\"Checking for BDB >=", "return 0; } ''' def CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp',", "source, source_type, message_libname, real_libs=[]): \"\"\" Check that source can be", "0x00FF; uint32_t b32 = 0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16);", "char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0; } ''' def", "= ''' #include <uuid/uuid.h> int main() { uuid_t uu; char", "compile source_type -- type of source file, (probably should be", "= 0x00FF; uint32_t b32 = 0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF;", "= context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type) context.Result( ret )", "&ctx); return 0; } ''' def CheckSeLinux(context): return __checkCanLink(context, selinux_source,", "can be successfully compiled and linked against real_libs. Keyword arguments:", "of source file, (probably should be \".c\") message_libname -- library", "real_libs -- list of actual libraries to link against (defaults", "(defaults to a list with one element, the value of", "These are functions to add to the configure context. \"\"\"", "uuid_unparse(uu, uuid_str); return 0; } ''' def CheckLibUUID(context): return __checkCanLink(context,", "def __checkCanLink(context, source, source_type, message_libname, real_libs=[]): \"\"\" Check that source", "#include <selinux/selinux.h> int main() { security_context_t ctx; getpeercon(0, &ctx); return", "#else #error \"\" #endif #endif #else #error \"\" #endif '''", "bswap_32(b32); bswap_64(b64); return 0; } ''' def CheckByteswap(context): context.Message(\"Checking for", "linked against real_libs. Keyword arguments: source -- source to try", "type of source file, (probably should be \".c\") message_libname --", "ret ) return ret bdb_source = ''' #include <db.h> #if", "for byteswap.h...\") ret = context.TryCompile(byteswap_source, '.c') context.Result( ret ) return", "#include <byteswap.h> #include <stdint.h> int main() { uint16_t b16 =", "add to the configure context. \"\"\" def __checkCanLink(context, source, source_type,", "file, (probably should be \".c\") message_libname -- library name to", "uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0; }", "#if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3 #else #error \"\" #endif", "against real_libs. Keyword arguments: source -- source to try to", "if libsave is None: del(context.env['LIBS']) else: context.env['LIBS'] = libsave return", "context.env['LIBS'] = libsave return ret libuuid_source = ''' #include <uuid/uuid.h>", "def CheckLibUUID(context): return __checkCanLink(context, libuuid_source, \".c\", \"libuuid\", [\"uuid\"]) selinux_source =", "return __checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source = ''' #include", "\"\"\" def __checkCanLink(context, source, source_type, message_libname, real_libs=[]): \"\"\" Check that", "source_type) context.Result( ret ) if libsave is None: del(context.env['LIBS']) else:", "} ''' def CheckByteswap(context): context.Message(\"Checking for byteswap.h...\") ret = context.TryCompile(byteswap_source,", "try to compile source_type -- type of source file, (probably", "to the configure context. \"\"\" def __checkCanLink(context, source, source_type, message_libname,", "#include <stdint.h> int main() { uint16_t b16 = 0x00FF; uint32_t", "ret = context.TryCompile(byteswap_source, '.c') context.Result( ret ) return ret bdb_source", "ret ) if libsave is None: del(context.env['LIBS']) else: context.env['LIBS'] =", "against (defaults to a list with one element, the value", ") if libsave is None: del(context.env['LIBS']) else: context.env['LIBS'] = libsave", "context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type) context.Result( ret ) if", "''' def CheckByteswap(context): context.Message(\"Checking for byteswap.h...\") ret = context.TryCompile(byteswap_source, '.c')", "\".c\", \"libuuid\", [\"uuid\"]) selinux_source = ''' #include <selinux/selinux.h> int main()", "0; } ''' def CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp', 'selinux',", "<db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR ==", "uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0; } ''' def CheckLibUUID(context):", "== 4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3 #else #error", "{ uuid_t uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0;", "{ security_context_t ctx; getpeercon(0, &ctx); return 0; } ''' def", "#endif #endif #else #error \"\" #endif ''' def CheckBDB(context): context.Message(\"Checking", "int main() { uuid_t uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str);", "to a list with one element, the value of messager_libname)", "\"\"\" if not real_libs: real_libs = [message_libname] context.Message(\"Checking for %s...\"", "functions to add to the configure context. \"\"\" def __checkCanLink(context,", "name to show in the message output from scons real_libs", "''' #include <db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4 #if", "that source can be successfully compiled and linked against real_libs.", "actual libraries to link against (defaults to a list with", "uint32_t b32 = 0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32);", "bdb_source = ''' #include <db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >=", "''' #include <selinux/selinux.h> int main() { security_context_t ctx; getpeercon(0, &ctx);", "bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0; } ''' def CheckByteswap(context): context.Message(\"Checking", "return __checkCanLink(context, libuuid_source, \".c\", \"libuuid\", [\"uuid\"]) selinux_source = ''' #include", "&& DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR)", "'.c') context.Result( ret ) return ret bdb_source = ''' #include", "bswap_64(b64); return 0; } ''' def CheckByteswap(context): context.Message(\"Checking for byteswap.h...\")", "\"libuuid\", [\"uuid\"]) selinux_source = ''' #include <selinux/selinux.h> int main() {", "''' def CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source", "0; } ''' def CheckByteswap(context): context.Message(\"Checking for byteswap.h...\") ret =", "real_libs. Keyword arguments: source -- source to try to compile", "message output from scons real_libs -- list of actual libraries", "DB_VERSION_MINOR >= 3 #else #error \"\" #endif #endif #else #error", "[message_libname] context.Message(\"Checking for %s...\" % message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs)", "''' #include <byteswap.h> #include <stdint.h> int main() { uint16_t b16", "to compile source_type -- type of source file, (probably should", "real_libs=[]): \"\"\" Check that source can be successfully compiled and", "del(context.env['LIBS']) else: context.env['LIBS'] = libsave return ret libuuid_source = '''", "ctx; getpeercon(0, &ctx); return 0; } ''' def CheckSeLinux(context): return", "#include <db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR", "= libsave return ret libuuid_source = ''' #include <uuid/uuid.h> int", "4 #if DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >=", "= 0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return", "''' def CheckLibUUID(context): return __checkCanLink(context, libuuid_source, \".c\", \"libuuid\", [\"uuid\"]) selinux_source", "libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type) context.Result( ret", "= context.TryLink(source, source_type) context.Result( ret ) if libsave is None:", "the message output from scons real_libs -- list of actual", "configure context. \"\"\" def __checkCanLink(context, source, source_type, message_libname, real_libs=[]): \"\"\"", "ret libuuid_source = ''' #include <uuid/uuid.h> int main() { uuid_t", "''' def CheckBDB(context): context.Message(\"Checking for BDB >= 4.3...\") ret =", "compiled and linked against real_libs. Keyword arguments: source -- source", "#endif #else #error \"\" #endif ''' def CheckBDB(context): context.Message(\"Checking for", "#endif ''' def CheckBDB(context): context.Message(\"Checking for BDB >= 4.3...\") ret", "message_libname -- library name to show in the message output", ">= 3 #else #error \"\" #endif #endif #else #error \"\"", "uint16_t b16 = 0x00FF; uint32_t b32 = 0x0011EEFF; uint64_t b64", "def CheckBDB(context): context.Message(\"Checking for BDB >= 4.3...\") ret = context.TryCompile(bdb_source,", "libraries to link against (defaults to a list with one", "['selinux']) byteswap_source = ''' #include <byteswap.h> #include <stdint.h> int main()", "uuid_str); return 0; } ''' def CheckLibUUID(context): return __checkCanLink(context, libuuid_source,", "selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source = ''' #include <byteswap.h> #include", "% message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type)", "-- list of actual libraries to link against (defaults to", "__checkCanLink(context, libuuid_source, \".c\", \"libuuid\", [\"uuid\"]) selinux_source = ''' #include <selinux/selinux.h>", "message_libname, real_libs=[]): \"\"\" Check that source can be successfully compiled", "context.TryLink(source, source_type) context.Result( ret ) if libsave is None: del(context.env['LIBS'])", "<byteswap.h> #include <stdint.h> int main() { uint16_t b16 = 0x00FF;", "defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR == 4 #if", "source_type, message_libname, real_libs=[]): \"\"\" Check that source can be successfully", "= ''' #include <db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4", "ret = context.TryLink(source, source_type) context.Result( ret ) if libsave is", "4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3 #else #error \"\"", "\"\"\" These are functions to add to the configure context.", "list of actual libraries to link against (defaults to a", "'selinux', ['selinux']) byteswap_source = ''' #include <byteswap.h> #include <stdint.h> int", "be \".c\") message_libname -- library name to show in the", "source to try to compile source_type -- type of source", "is None: del(context.env['LIBS']) else: context.env['LIBS'] = libsave return ret libuuid_source", "for BDB >= 4.3...\") ret = context.TryCompile(bdb_source, '.c') context.Result(ret) return", "#include <uuid/uuid.h> int main() { uuid_t uu; char uuid_str[37]; uuid_generate(uu);", "= context.TryCompile(byteswap_source, '.c') context.Result( ret ) return ret bdb_source =", "link against (defaults to a list with one element, the", "uuid_t uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0; }", "} ''' def CheckLibUUID(context): return __checkCanLink(context, libuuid_source, \".c\", \"libuuid\", [\"uuid\"])", "[\"uuid\"]) selinux_source = ''' #include <selinux/selinux.h> int main() { security_context_t", "successfully compiled and linked against real_libs. Keyword arguments: source --", "return 0; } ''' def CheckLibUUID(context): return __checkCanLink(context, libuuid_source, \".c\",", "= [message_libname] context.Message(\"Checking for %s...\" % message_libname) libsave = context.env.get('LIBS')", "None: del(context.env['LIBS']) else: context.env['LIBS'] = libsave return ret libuuid_source =", ">= 4 #if DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR", "CheckBDB(context): context.Message(\"Checking for BDB >= 4.3...\") ret = context.TryCompile(bdb_source, '.c')", "source can be successfully compiled and linked against real_libs. Keyword", "byteswap.h...\") ret = context.TryCompile(byteswap_source, '.c') context.Result( ret ) return ret", "\"\" #endif ''' def CheckBDB(context): context.Message(\"Checking for BDB >= 4.3...\")", "= 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0; } ''' def", "scons real_libs -- list of actual libraries to link against", "to try to compile source_type -- type of source file,", "context.TryCompile(byteswap_source, '.c') context.Result( ret ) return ret bdb_source = '''", "to add to the configure context. \"\"\" def __checkCanLink(context, source,", "int main() { security_context_t ctx; getpeercon(0, &ctx); return 0; }", "\".c\") message_libname -- library name to show in the message", "with one element, the value of messager_libname) \"\"\" if not", "main() { uuid_t uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return", "real_libs: real_libs = [message_libname] context.Message(\"Checking for %s...\" % message_libname) libsave", "} ''' def CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux'])", "return 0; } ''' def CheckByteswap(context): context.Message(\"Checking for byteswap.h...\") ret", ") return ret bdb_source = ''' #include <db.h> #if defined(DB_VERSION_MAJOR)", "__checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source = ''' #include <byteswap.h>", "list with one element, the value of messager_libname) \"\"\" if", "CheckByteswap(context): context.Message(\"Checking for byteswap.h...\") ret = context.TryCompile(byteswap_source, '.c') context.Result( ret", "b32 = 0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64);", "the configure context. \"\"\" def __checkCanLink(context, source, source_type, message_libname, real_libs=[]):", "def CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source =", "Keyword arguments: source -- source to try to compile source_type", "output from scons real_libs -- list of actual libraries to", "context.Message(\"Checking for BDB >= 4.3...\") ret = context.TryCompile(bdb_source, '.c') context.Result(ret)", "not real_libs: real_libs = [message_libname] context.Message(\"Checking for %s...\" % message_libname)", "= ''' #include <byteswap.h> #include <stdint.h> int main() { uint16_t", "DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR) &&", "selinux_source = ''' #include <selinux/selinux.h> int main() { security_context_t ctx;", "uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0; } '''", "-- type of source file, (probably should be \".c\") message_libname", "(probably should be \".c\") message_libname -- library name to show", "0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0; } ''' def CheckByteswap(context):", "'.cpp', 'selinux', ['selinux']) byteswap_source = ''' #include <byteswap.h> #include <stdint.h>", "libuuid_source, \".c\", \"libuuid\", [\"uuid\"]) selinux_source = ''' #include <selinux/selinux.h> int", "uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0; } ''' def CheckLibUUID(context): return", "source file, (probably should be \".c\") message_libname -- library name", "message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type) context.Result(", "context.Message(\"Checking for %s...\" % message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret", "return ret libuuid_source = ''' #include <uuid/uuid.h> int main() {", "for %s...\" % message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret =", "def CheckByteswap(context): context.Message(\"Checking for byteswap.h...\") ret = context.TryCompile(byteswap_source, '.c') context.Result(", "#if DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3", "3 #else #error \"\" #endif #endif #else #error \"\" #endif", "<uuid/uuid.h> int main() { uuid_t uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu,", "value of messager_libname) \"\"\" if not real_libs: real_libs = [message_libname]", "libuuid_source = ''' #include <uuid/uuid.h> int main() { uuid_t uu;", "0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0;", "-- library name to show in the message output from", "{ uint16_t b16 = 0x00FF; uint32_t b32 = 0x0011EEFF; uint64_t", "return ret bdb_source = ''' #include <db.h> #if defined(DB_VERSION_MAJOR) &&", "b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0; } '''", "CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source = '''", "context.Result( ret ) return ret bdb_source = ''' #include <db.h>", "from scons real_libs -- list of actual libraries to link", "be successfully compiled and linked against real_libs. Keyword arguments: source", "messager_libname) \"\"\" if not real_libs: real_libs = [message_libname] context.Message(\"Checking for", "one element, the value of messager_libname) \"\"\" if not real_libs:", "<selinux/selinux.h> int main() { security_context_t ctx; getpeercon(0, &ctx); return 0;", "context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type) context.Result( ret ) if libsave", "defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3 #else #error \"\" #endif #endif", "real_libs = [message_libname] context.Message(\"Checking for %s...\" % message_libname) libsave =", "the value of messager_libname) \"\"\" if not real_libs: real_libs =", "__checkCanLink(context, source, source_type, message_libname, real_libs=[]): \"\"\" Check that source can", "%s...\" % message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source," ]
[ "0 weight_value_tuples = [] all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight in", "sure restore ops are run logger.info(\"Loaded {:,} parameters in the", "symbolic weights in a PyTorch model \"\"\" try: import tensorflow", "+= (pt_weight.shape, array.shape) raise e # logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name))", "- pytorch model weight name - transpose: boolean indicating weither", "2.0 (the \"License\"); # you may not use this file", "attribute names conversions: - '$1___$2' is replaced by $2 (can", "os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights from {}\".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location=\"cpu\")", "start_prefix_to_remove = \"\" if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()):", "try: assert list(pt_weight.shape) == list(array.shape) except AssertionError as e: e.args", "len(array.shape): array = numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape): array =", "load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None,", "allow_missing_keys=False): \"\"\" Load pytorch checkpoints in a TF 2.0 model", "associated numpy array in pytorch model state dict if name", "new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters()) # Make sure we", "name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find associated", "new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make sure we are able", "remove this and update the AWS weights files instead #", "{:,} parameters in the TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers", "2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers not loaded from PyTorch model:", "training=False) # Make sure model is built # Adapt state", "s in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix + \".\" # Build", "start_prefix_to_remove = tf_model.base_model_prefix + \".\" symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights", "tf_model(tf_inputs, training=False) # Make sure restore ops are run logger.info(\"Loaded", "loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated numpy array", "PyTorch - TF 2.0 general utilities.\"\"\" import logging import os", "vs PyTorch) - '_._' is replaced by a new level", "able to load PyTorch base models as well as derived", "Variables tf_weights_map = {} for tf_weight in tf_weights: pt_name, transpose", "needed tf_name = \".\".join(tf_name) if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, \"\",", "for tf_weight in tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove", "from {}\".format(tf_checkpoint_path)) # Instantiate and load the associated TF 2.0", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "models as well as derived models (with heads) # TF", "array = numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape): array = numpy.expand_dims(array,", "= loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated numpy array in pytorch", "and https://www.tensorflow.org/install/ for installation instructions.\" ) raise if tf_inputs is", "the beggining tf_model_class = getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config) if", "# device ids tf_name = re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name )", "\" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise new_pt_params_dict", "PyTorch weights from {}\".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint", "Remove empty levels at the end tf_name = tf_name.split(\"/\") #", ") raise if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if", "= re.sub(r\"//+\", \"/\", tf_name) # Remove empty levels at the", "array.size # logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples)", "+= array.size # logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name)", "= key.replace(\"beta\", \"bias\") if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key", "start_prefix_to_remove=start_prefix_to_remove ) # Find associated numpy array in pytorch model", "TF2.0 vs PyTorch) - '_._' is replaced by a new", "permissions and # limitations under the License. \"\"\" PyTorch -", "Make sure model is built # Adapt state dict -", "import logging import os import re import numpy logger =", "# ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch", "len(missing_keys) > 0: logger.info( \"Weights of {} not initialized from", "buffers not loaded from TF 2.0 model: {}\".format(all_tf_weights)) return pt_model", "2018 The Google AI Language Team Authors and The HuggingFace", "current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix + \".\" # Build a map", "pytorch model \"\"\" weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys)", "and update the AWS weights files instead # Convert old", "> len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape) ==", "\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise new_pt_params_dict =", "# Remove empty levels at the end tf_name = tf_name.split(\"/\")", "\" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise if", "instead # Convert old format to new format if needed", "tf_name or \"out_projs\" in tf_name) # Convert standard TF2.0 names", "duplicate or remove layers in TF2.0 vs PyTorch) - '_._'", "use this file except in compliance with the License. #", "if name not in pt_state_dict: if allow_missing_keys: continue raise AttributeError(\"{}", "len(symbolic_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape):", "F401 import torch # noqa: F401 except ImportError: logger.error( \"Loading", "reserved. # # Licensed under the Apache License, Version 2.0", "to easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import", "\"_._\", \"/\" ) # '_._' is replaced by a level", "def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in", "tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples = [] all_pytorch_weights", "is built # Adapt state dict - TODO remove this", "\"beta\" in key: new_key = key.replace(\"beta\", \"bias\") if new_key: old_keys.append(key)", "end tf_name = tf_name.split(\"/\") # Convert from TF2.0 '/' separators", "TF2.0 scopes -> PyTorch attribute names conversions: - '$1___$2' is", "tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\" Load", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "instructions.\" ) raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights from", "in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix + \".\" # Build a", "team. # Copyright (c) 2018, <NAME>. All rights reserved. #", "used to convert TF2.0 lists in PyTorch nn.ModulesList) return tuple", "License. # You may obtain a copy of the License", "AttributeError(\"{} not found in TF 2.0 model\".format(pt_weight_name)) array, transpose =", "don't start_prefix_to_remove = \"\" if not any(s.startswith(pt_model.base_model_prefix) for s in", "= tf_model_class(pt_model.config) if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if", "# coding=utf-8 # Copyright 2018 The Google AI Language Team", "weights files instead # Convert old format to new format", "# Build a map from potential PyTorch weight names to", "The HuggingFace Inc. team. # Copyright (c) 2018, <NAME>. All", "under the License is distributed on an \"AS IS\" BASIS,", "model: {}\".format(all_pytorch_weights)) return tf_model ##################### # TF 2.0 => PyTorch", "\"kernel\" or \"emb_projs\" in tf_name or \"out_projs\" in tf_name) #", "License for the specific language governing permissions and # limitations", "r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name ) # '$1___$2' is replaced by $2", "this and update the AWS weights files instead # Convert", "model is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def", "##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints", "None: tf_inputs = tf_model.dummy_inputs if tf_inputs is not None: tf_model(tf_inputs,", "array = pt_state_dict[name].numpy() if transpose: array = numpy.transpose(array) if len(symbolic_weight.shape)", "def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch state_dict in", "weight ()not duplicated in TF 2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr:", "if needed from a PyTorch state_dict old_keys = [] new_keys", "# PyTorch => TF 2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path,", "by a level separation (can be used to convert TF2.0", "'$1___$2' is replaced by $2 (can be used to duplicate", "pt_weight_name, pt_weight in current_pt_params_dict.items(): # Handle PyTorch shared weight ()not", "HuggingFace Inc. team. # Copyright (c) 2018, <NAME>. All rights", "PyTorch attribute names conversions: - '$1___$2' is replaced by $2", "# Adapt state dict - TODO remove this and update", "logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs", "Find associated numpy array in pytorch model state dict if", "# ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load TF", "parameters\".format(sum(t.numel() for t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs,", "\"Loading a PyTorch model in TensorFlow, requires both PyTorch and", "at the beggining tf_model_class = getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config)", "lists in PyTorch nn.ModulesList) tf_name = re.sub(r\"//+\", \"/\", tf_name) #", "logger.info(\"Loading PyTorch weights from {}\".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch", "e # logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()]", "F401 except ImportError: logger.error( \"Loading a PyTorch model in TensorFlow,", "F401 import tensorflow as tf # noqa: F401 from tensorflow.python.keras", "PyTorch state_dict old_keys = [] new_keys = [] for key", "raise AttributeError(\"{} not found in PyTorch model\".format(name)) array = pt_state_dict[name].numpy()", "buffers not loaded from PyTorch model: {}\".format(all_pytorch_weights)) return tf_model #####################", "from a PyTorch state_dict old_keys = [] new_keys = []", "weither TF2.0 and PyTorch weights matrices are transposed with regards", "used in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights or buffers not", "e: e.args += (pt_weight.shape, array.shape) raise e # logger.warning(\"Initialize PyTorch", "K.batch_set_value(weight_value_tuples) if tf_inputs is not None: tf_model(tf_inputs, training=False) # Make", "import backend as K except ImportError: logger.error( \"Loading a PyTorch", "if len(unexpected_keys) > 0: logger.info( \"Weights from TF 2.0 model", "tf_weights_map = {} for tf_weight in tf_weights: pt_name, transpose =", ") raise import transformers logger.info(\"Loading TensorFlow weights from {}\".format(tf_checkpoint_path)) #", "\".\" # Build a map from potential PyTorch weight names", "transpose the weights transpose = bool(tf_name[-1] == \"kernel\" or \"emb_projs\"", "in compliance with the License. # You may obtain a", "weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is not None: tf_model(tf_inputs,", "array = numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape) == list(array.shape) except", "\"embeddings\" or tf_name[-1] == \"gamma\": tf_name[-1] = \"weight\" if tf_name[-1]", "with: - pytorch model weight name - transpose: boolean indicating", "software # distributed under the License is distributed on an", "return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\" Load", "+ tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples = [] all_pytorch_weights =", "\" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise import", "= symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) #", "load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in a", "= numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape) == list(array.shape) except AssertionError", "torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt", "from potential PyTorch weight names to TF 2.0 Variables tf_weights_map", "= tf_name[1:] # Remove level zero # When should we", "in tf_name) # Convert standard TF2.0 names in PyTorch names", "load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\" Load TF", "# limitations under the License. \"\"\" PyTorch - TF 2.0", "2.0 model not used in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights", "\"\"\" weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model,", "tensorflow.python.keras import backend as K except ImportError: logger.error( \"Loading a", "zero # When should we transpose the weights transpose =", "ids tf_name = re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name ) # '$1___$2'", "separators tf_name = tf_name[1:] # Remove level zero # When", "PyTorch names if tf_name[-1] == \"kernel\" or tf_name[-1] == \"embeddings\"", "is replaced by a new level separation (can be used", "pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix + \".\" symbolic_weights = tf_model.trainable_weights +", "\"emb_projs\" in tf_name or \"out_projs\" in tf_name) # Convert standard", "built # Adapt state dict - TODO remove this and", "TF2.0 '/' separators to PyTorch '.' separators tf_name = tf_name[1:]", "= \"\" if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()): start_prefix_to_remove", "checkpoint contains {:,} parameters\".format(sum(t.numel() for t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model(", "not found in TF 2.0 model\".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name]", "= pt_state_dict.pop(old_key) # Make sure we are able to load", "model\".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name] if transpose: array = numpy.transpose(array)", "PyTorch '.' separators tf_name = tf_name[1:] # Remove level zero", "array, transpose = tf_weights_map[pt_weight_name] if transpose: array = numpy.transpose(array) if", "loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated numpy array in pytorch model", "Remove level zero # When should we transpose the weights", "tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys()))", "a PyTorch model \"\"\" try: import tensorflow as tf #", "in TF 2.0 model\".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name] if transpose:", "TF 2.0 model tf_model_class_name = \"TF\" + pt_model.__class__.__name__ # Add", "Make sure restore ops are run logger.info(\"Loaded {:,} parameters in", "tf_name.split(\"/\") # Convert from TF2.0 '/' separators to PyTorch '.'", "level zero # When should we transpose the weights transpose", "or tf_name[-1] == \"embeddings\" or tf_name[-1] == \"gamma\": tf_name[-1] =", "zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make sure we are", "transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt = []", "to duplicate or remove layers in TF2.0 vs PyTorch) tf_name", "\"out_projs\" in tf_name) # Convert standard TF2.0 names in PyTorch", "scopes -> PyTorch attribute names conversions: - '$1___$2' is replaced", "\"\"\" try: import torch # noqa: F401 import tensorflow as", "by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\"", "PyTorch nn.ModulesList) return tuple with: - pytorch model weight name", "\"bias\" # Remove prefix if needed tf_name = \".\".join(tf_name) if", "checkpoints in a TF 2.0 model \"\"\" try: import tensorflow", "2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue #", "new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated numpy array in", "checkpoint in a PyTorch model We use HDF5 to easily", "raise if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if tf_inputs", "from TF 2.0 model not used in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys)", "pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in a TF", "$2 (can be used to duplicate or remove layers in", "list(pt_weight.shape) == list(array.shape) except AssertionError as e: e.args += (pt_weight.shape,", "general utilities.\"\"\" import logging import os import re import numpy", "import os import re import numpy logger = logging.getLogger(__name__) def", "- '$1___$2' is replaced by $2 (can be used to", "pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model,", "- TODO remove this and update the AWS weights files", "state dict if pt_weight_name not in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name)", "- transpose: boolean indicating weither TF2.0 and PyTorch weights matrices", "pytorch state_dict in a TF 2.0 model. \"\"\" try: import", "tensorflow as tf # noqa: F401 from tensorflow.python.keras import backend", "AWS weights files instead # Convert old format to new", "# TF 2.0 => PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path,", "list(array.shape) except AssertionError as e: e.args += (pt_weight.shape, array.shape) raise", "not used in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights or buffers", "to load PyTorch base models as well as derived models", "to PyTorch '.' separators tf_name = tf_name[1:] # Remove level", "Instantiate and load the associated TF 2.0 model tf_model_class_name =", "duplicated in TF 2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] =", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert a TF 2.0 model variable", "always have a prefix, some of PyTorch models (base ones)", "TF2.0 names in PyTorch names if tf_name[-1] == \"kernel\" or", "all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights: sw_name = symbolic_weight.name", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "tf_name[-1] == \"kernel\" or tf_name[-1] == \"embeddings\" or tf_name[-1] ==", "tf_name = tf_name.split(\"/\") # Convert from TF2.0 '/' separators to", "models always have a prefix, some of PyTorch models (base", "\"\" if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()): start_prefix_to_remove =", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "AI Language Team Authors and The HuggingFace Inc. team. #", "for the specific language governing permissions and # limitations under", "\"beta\": tf_name[-1] = \"bias\" # Remove prefix if needed tf_name", "2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load", "for key in pt_state_dict.keys(): new_key = None if \"gamma\" in", "well as derived models (with heads) # TF models always", "to in writing, software # distributed under the License is", "array = numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape): array = numpy.squeeze(array)", "re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name ) # '$1___$2' is replaced by", "models (with heads) # TF models always have a prefix,", "and # limitations under the License. \"\"\" PyTorch - TF", "[] all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights: sw_name =", "Build a map from potential PyTorch weight names to TF", "PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to", "tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] =", "# See the License for the specific language governing permissions", "= pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt if len(missing_keys) > 0:", "initialized from TF 2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys)", "missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt if len(missing_keys)", "tf_name[1:] # Remove level zero # When should we transpose", "tf_name = re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name ) # '$1___$2' is", "= \"weight\" if tf_name[-1] == \"beta\": tf_name[-1] = \"bias\" #", "new_key = key.replace(\"beta\", \"bias\") if new_key: old_keys.append(key) new_keys.append(new_key) for old_key,", "convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find associated numpy array in", "or agreed to in writing, software # distributed under the", "tf_inputs is not None: tf_model(tf_inputs, training=False) # Make sure restore", "name not in pt_state_dict: if allow_missing_keys: continue raise AttributeError(\"{} not", "prefix, some of PyTorch models (base ones) don't start_prefix_to_remove =", "required by applicable law or agreed to in writing, software", "= numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "boolean indicating weither TF2.0 and PyTorch weights matrices are transposed", "or \"out_projs\" in tf_name) # Convert standard TF2.0 names in", "# When should we transpose the weights transpose = bool(tf_name[-1]", "with the License. # You may obtain a copy of", "used to convert TF2.0 lists in PyTorch nn.ModulesList) tf_name =", "tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch state_dict in a TF 2.0", "loaded from PyTorch model: {}\".format(all_pytorch_weights)) return tf_model ##################### # TF", "if transpose: array = numpy.transpose(array) if len(pt_weight.shape) < len(array.shape): array", "(c) 2018, <NAME>. All rights reserved. # # Licensed under", "PyTorch shared weight ()not duplicated in TF 2.0 if pt_weight.data_ptr()", "torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False)", "a pytorch model \"\"\" weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights,", "pytorch checkpoints in a TF 2.0 model \"\"\" pt_state_dict =", "indicating weither TF2.0 and PyTorch weights matrices are transposed with", "allow_missing_keys=False): \"\"\" Load TF2.0 symbolic weights in a PyTorch model", "\"\"\" Convert a TF 2.0 model variable name in a", "torch # noqa: F401 except ImportError: logger.error( \"Loading a PyTorch", "TF 2.0 model. \"\"\" try: import torch # noqa: F401", "model in TensorFlow, requires both PyTorch and TensorFlow to be", "training=False) # Make sure model is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return", "tf_inputs is not None: tf_model(tf_inputs, training=False) # Make sure model", "numpy logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert a", "TF 2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\"", "PyTorch model: {}\".format(all_pytorch_weights)) return tf_model ##################### # TF 2.0 =>", "=> TF 2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False):", "= tf_name.replace(\":0\", \"\") # device ids tf_name = re.sub( r\"/[^/]*___([^/]*)/\",", "= 0 weight_value_tuples = [] all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight", "and https://www.tensorflow.org/install/ for installation instructions.\" ) raise import transformers logger.info(\"Loading", "if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if tf_inputs is", "transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import tensorflow as tf", "Add \"TF\" at the beggining tf_model_class = getattr(transformers, tf_model_class_name) tf_model", "(tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt =", "(with heads) # TF models always have a prefix, some", "# Copyright (c) 2018, <NAME>. All rights reserved. # #", "compliance with the License. # You may obtain a copy", "tf_name[-1] == \"beta\": tf_name[-1] = \"bias\" # Remove prefix if", "agreed to in writing, software # distributed under the License", "files instead # Convert old format to new format if", "TensorFlow weights from {}\".format(tf_checkpoint_path)) # Instantiate and load the associated", "in PyTorch nn.ModulesList) tf_name = re.sub(r\"//+\", \"/\", tf_name) # Remove", "= getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config) if tf_inputs is None:", "TODO remove this and update the AWS weights files instead", "remove layers in TF2.0 vs PyTorch) - '_._' is replaced", "distributed under the License is distributed on an \"AS IS\"", "\"Weights of {} not initialized from TF 2.0 model: {}\".format(pt_model.__class__.__name__,", "all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is not None: tf_model(tf_inputs, training=False) #", "if tf_name[-1] == \"kernel\" or tf_name[-1] == \"embeddings\" or tf_name[-1]", "if pt_weight_name not in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise", "see \" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise", ") # '_._' is replaced by a level separation (can", "= tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples = []", "nn.ModulesList) tf_name = re.sub(r\"//+\", \"/\", tf_name) # Remove empty levels", "allow_missing_keys=False): \"\"\" Load pytorch state_dict in a TF 2.0 model.", "map from potential PyTorch weight names to TF 2.0 Variables", "def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\" Load TF 2.0 model in", "we are able to load PyTorch base models as well", "()not duplicated in TF 2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name]", "the weights transpose = bool(tf_name[-1] == \"kernel\" or \"emb_projs\" in", "dict if pt_weight_name not in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue", "ImportError: logger.error( \"Loading a TensorFlow model in PyTorch, requires both", "a PyTorch state_dict old_keys = [] new_keys = [] for", "express or implied. # See the License for the specific", "transpose: array = numpy.transpose(array) if len(pt_weight.shape) < len(array.shape): array =", "except in compliance with the License. # You may obtain", "numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try:", "tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load TF 2.0 HDF5 checkpoint in", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "in TF2.0 vs PyTorch) tf_name = tf_name.replace( \"_._\", \"/\" )", "not use this file except in compliance with the License.", "numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(symbolic_weight.shape)", "the associated TF 2.0 model tf_model_class_name = \"TF\" + pt_model.__class__.__name__", "2.0 model in a pytorch model \"\"\" weights = tf_model.weights", "run logger.info(\"Loaded {:,} parameters in the TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights", "current_pt_params_dict = dict(pt_model.named_parameters()) # Make sure we are able to", "nn.ModulesList) return tuple with: - pytorch model weight name -", "prefix if needed tf_name = \".\".join(tf_name) if start_prefix_to_remove: tf_name =", "layers in TF2.0 vs PyTorch) tf_name = tf_name.replace( \"_._\", \"/\"", ") # Find associated numpy array in pytorch model state", "Convert standard TF2.0 names in PyTorch names if tf_name[-1] ==", "writing, software # distributed under the License is distributed on", "weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights,", "if transpose: array = numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape): array", "ImportError: logger.error( \"Loading a PyTorch model in TensorFlow, requires both", "= [] all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights: sw_name", "torch # noqa: F401 except ImportError: logger.error( \"Loading a TensorFlow", "weights matrices are transposed with regards to each other \"\"\"", "you may not use this file except in compliance with", "convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert a TF 2.0 model variable name", "transpose = bool(tf_name[-1] == \"kernel\" or \"emb_projs\" in tf_name or", "level separation (can be used to convert TF2.0 lists in", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "e tf_loaded_numel += array.size # logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight,", "PyTorch, requires both PyTorch and TensorFlow to be installed. Please", "names to TF 2.0 Variables tf_weights_map = {} for tf_weight", "instructions.\" ) raise new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters()) #", "# Copyright 2018 The Google AI Language Team Authors and", "contains {:,} parameters\".format(sum(t.numel() for t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model,", "logger.info(\"Loaded {:,} parameters in the TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or", "2.0 model. \"\"\" try: import torch # noqa: F401 import", "for installation instructions.\" ) raise if tf_inputs is None: tf_inputs", "symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples =", "= tf_name.replace( \"_._\", \"/\" ) # '_._' is replaced by", "{}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights or buffers not loaded from TF", "sure model is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys)", "model tf_model_class_name = \"TF\" + pt_model.__class__.__name__ # Add \"TF\" at", "weight_value_tuples = [] all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights:", "with regards to each other \"\"\" tf_name = tf_name.replace(\":0\", \"\")", "conversions: - '$1___$2' is replaced by $2 (can be used", "pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch state_dict in a TF", "PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load", "raise AttributeError(\"{} not found in TF 2.0 model\".format(pt_weight_name)) array, transpose", "load the associated TF 2.0 model tf_model_class_name = \"TF\" +", "variable name in a pytorch model weight name. Conventions for", "used to duplicate or remove layers in TF2.0 vs PyTorch)", "pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\"", "Remove prefix if needed tf_name = \".\".join(tf_name) if start_prefix_to_remove: tf_name", "\"kernel\" or tf_name[-1] == \"embeddings\" or tf_name[-1] == \"gamma\": tf_name[-1]", "symbolic_weight in symbolic_weights: sw_name = symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name(", "array in pytorch model state dict if name not in", "except ImportError: logger.error( \"Loading a TensorFlow model in PyTorch, requires", "Handle PyTorch shared weight ()not duplicated in TF 2.0 if", "start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, \"\", 1) return tf_name, transpose #####################", "CONDITIONS OF ANY KIND, either express or implied. # See", "model. \"\"\" try: import torch # noqa: F401 import tensorflow", "if tf_inputs is not None: tf_model(tf_inputs, training=False) # Make sure", "The Google AI Language Team Authors and The HuggingFace Inc.", "Convert a TF 2.0 model variable name in a pytorch", "state_dict old_keys = [] new_keys = [] for key in", "is replaced by $2 (can be used to duplicate or", "\"/\", tf_name) # Remove empty levels at the end tf_name", "a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow", "= pt_state_dict[name].numpy() if transpose: array = numpy.transpose(array) if len(symbolic_weight.shape) <", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "matrices are transposed with regards to each other \"\"\" tf_name", "\"\"\" tf_name = tf_name.replace(\":0\", \"\") # device ids tf_name =", "TF2.0 lists in PyTorch nn.ModulesList) tf_name = re.sub(r\"//+\", \"/\", tf_name)", "in pytorch model state dict if name not in pt_state_dict:", "\"\"\" Load TF 2.0 model in a pytorch model \"\"\"", ") raise new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters()) # Make", "all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt = [] for", "# noqa: F401 from tensorflow.python.keras import backend as K except", "as e: e.args += (pt_weight.shape, array.shape) raise e # logger.warning(\"Initialize", "sure we are able to load PyTorch base models as", "a pytorch model weight name. Conventions for TF2.0 scopes ->", "https://www.tensorflow.org/install/ for installation instructions.\" ) raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading", "training=False) # Make sure restore ops are run logger.info(\"Loaded {:,}", "start_prefix_to_remove = pt_model.base_model_prefix + \".\" # Build a map from", "= \".\".join(tf_name) if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, \"\", 1) return", "dict if name not in pt_state_dict: if allow_missing_keys: continue raise", "array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is not None: tf_model(tf_inputs, training=False)", "logger.error( \"Loading a PyTorch model in TensorFlow, requires both PyTorch", "as K except ImportError: logger.error( \"Loading a PyTorch model in", "load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch state_dict in a", "checkpoints in a TF 2.0 model \"\"\" pt_state_dict = pt_model.state_dict()", "2.0 model tf_model_class_name = \"TF\" + pt_model.__class__.__name__ # Add \"TF\"", "pytorch model weight name - transpose: boolean indicating weither TF2.0", "allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch", "not in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{} not", "noqa: F401 from tensorflow.python.keras import backend as K except ImportError:", "tf_name) # Convert standard TF2.0 names in PyTorch names if", "and load the associated TF 2.0 model tf_model_class_name = \"TF\"", "the end tf_name = tf_name.split(\"/\") # Convert from TF2.0 '/'", "logger.info(\"Weights or buffers not loaded from PyTorch model: {}\".format(all_pytorch_weights)) return", "{:,} parameters\".format(sum(t.numel() for t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict,", "= pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def", "len(array.shape): array = numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape): array =", "allow_missing_keys=False): \"\"\" Load TF 2.0 HDF5 checkpoint in a PyTorch", "logger.info( \"Weights from TF 2.0 model not used in {}:", "be used to convert TF2.0 lists in PyTorch nn.ModulesList) tf_name", "PyTorch nn.ModulesList) tf_name = re.sub(r\"//+\", \"/\", tf_name) # Remove empty", "bool(tf_name[-1] == \"kernel\" or \"emb_projs\" in tf_name or \"out_projs\" in", "a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow", "= tf_model.base_model_prefix + \".\" symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel", "Load TF 2.0 HDF5 checkpoint in a PyTorch model We", "# Instantiate and load the associated TF 2.0 model tf_model_class_name", "state dict if name not in pt_state_dict: if allow_missing_keys: continue", "pt_weight in current_pt_params_dict.items(): # Handle PyTorch shared weight ()not duplicated", "and TensorFlow to be installed. Please see \" \"https://pytorch.org/ and", "instructions.\" ) raise import transformers logger.info(\"Loading TensorFlow weights from {}\".format(tf_checkpoint_path))", "model\".format(name)) array = pt_state_dict[name].numpy() if transpose: array = numpy.transpose(array) if", "tf_loaded_numel += array.size # logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array))", "TF 2.0 HDF5 checkpoint in a PyTorch model We use", "empty levels at the end tf_name = tf_name.split(\"/\") # Convert", "assert list(pt_weight.shape) == list(array.shape) except AssertionError as e: e.args +=", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= \"\" if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()): start_prefix_to_remove", "TF2.0 vs PyTorch) tf_name = tf_name.replace( \"_._\", \"/\" ) #", "# Find associated numpy array in pytorch model state dict", "\"\" if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()): start_prefix_to_remove =", "pytorch model weight name. Conventions for TF2.0 scopes -> PyTorch", "the License is distributed on an \"AS IS\" BASIS, #", "remove layers in TF2.0 vs PyTorch) tf_name = tf_name.replace( \"_._\",", "in TensorFlow, requires both PyTorch and TensorFlow to be installed.", "{}\".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys) > 0: logger.info( \"Weights from", "for installation instructions.\" ) raise new_pt_params_dict = {} current_pt_params_dict =", "# Remove level zero # When should we transpose the", "= dict(pt_model.named_parameters()) # Make sure we are able to load", "continue raise AttributeError(\"{} not found in TF 2.0 model\".format(pt_weight_name)) array,", "start_prefix_to_remove=\"\"): \"\"\" Convert a TF 2.0 model variable name in", ") logger.info(\"Weights or buffers not loaded from TF 2.0 model:", "+= (symbolic_weight.shape, array.shape) raise e tf_loaded_numel += array.size # logger.warning(\"Initialize", "=> PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\"", "if \"beta\" in key: new_key = key.replace(\"beta\", \"bias\") if new_key:", "language governing permissions and # limitations under the License. \"\"\"", "import re import numpy logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"):", "weight names to TF 2.0 Variables tf_weights_map = {} for", "= None if \"gamma\" in key: new_key = key.replace(\"gamma\", \"weight\")", "= tf_weights_map[pt_weight_name] if transpose: array = numpy.transpose(array) if len(pt_weight.shape) <", "# Make sure restore ops are run logger.info(\"Loaded {:,} parameters", "load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None,", "2.0 => PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False):", "tf_model.dummy_inputs if tf_inputs is not None: tf_model(tf_inputs, training=False) # Make", "model in PyTorch, requires both PyTorch and TensorFlow to be", "from TF2.0 '/' separators to PyTorch '.' separators tf_name =", "tf_model_class_name = \"TF\" + pt_model.__class__.__name__ # Add \"TF\" at the", "numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape) == list(array.shape) except AssertionError as", "the AWS weights files instead # Convert old format to", "(can be used to convert TF2.0 lists in PyTorch nn.ModulesList)", "logger.info(\"PyTorch checkpoint contains {:,} parameters\".format(sum(t.numel() for t in pt_state_dict.values()))) return", "tf_name.replace(\":0\", \"\") # device ids tf_name = re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\",", "\"\", 1) return tf_name, transpose ##################### # PyTorch => TF", "ops are run logger.info(\"Loaded {:,} parameters in the TF 2.0", "law or agreed to in writing, software # distributed under", "if \"gamma\" in key: new_key = key.replace(\"gamma\", \"weight\") if \"beta\"", "tf_loaded_numel = 0 weight_value_tuples = [] all_pytorch_weights = set(list(pt_state_dict.keys())) for", "TF models always have a prefix, some of PyTorch models", "Load TF2.0 symbolic weights in a PyTorch model \"\"\" try:", "shared weight ()not duplicated in TF 2.0 if pt_weight.data_ptr() in", "= torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict,", "in key: new_key = key.replace(\"beta\", \"bias\") if new_key: old_keys.append(key) new_keys.append(new_key)", "(base ones) don't start_prefix_to_remove = \"\" if not any(s.startswith(tf_model.base_model_prefix) for", "each other \"\"\" tf_name = tf_name.replace(\":0\", \"\") # device ids", "\"\"\" Load pytorch checkpoints in a TF 2.0 model \"\"\"", "len(unexpected_keys) > 0: logger.info( \"Weights from TF 2.0 model not", "== \"kernel\" or tf_name[-1] == \"embeddings\" or tf_name[-1] == \"gamma\":", "tf_name, transpose ##################### # PyTorch => TF 2.0 # #####################", "tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in a TF 2.0", "\"Weights from TF 2.0 model not used in {}: {}\".format(pt_model.__class__.__name__,", "as derived models (with heads) # TF models always have", "load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load TF 2.0 HDF5 checkpoint", "'.' separators tf_name = tf_name[1:] # Remove level zero #", "tf # noqa: F401 from tensorflow.python.keras import backend as K", "s in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix + \".\" symbolic_weights =", "transposed with regards to each other \"\"\" tf_name = tf_name.replace(\":0\",", "tensorflow as tf # noqa: F401 import torch # noqa:", "return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict,", "PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name)", "installation instructions.\" ) raise new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters())", "new_key in zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make sure", "# noqa: F401 except ImportError: logger.error( \"Loading a PyTorch model", "array = numpy.transpose(array) if len(pt_weight.shape) < len(array.shape): array = numpy.squeeze(array)", "in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights or buffers not loaded", "tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False):", "if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix", "TF 2.0 model \"\"\" try: import tensorflow as tf #", "names in PyTorch names if tf_name[-1] == \"kernel\" or tf_name[-1]", "set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights: sw_name = symbolic_weight.name name, transpose", "\"\"\" Load pytorch state_dict in a TF 2.0 model. \"\"\"", "= os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights from {}\".format(pt_path)) pt_state_dict = torch.load(pt_path,", "try: import torch # noqa: F401 import tensorflow as tf", "try: assert list(symbolic_weight.shape) == list(array.shape) except AssertionError as e: e.args", "Make sure model is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model,", "names conversions: - '$1___$2' is replaced by $2 (can be", "pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated", "may obtain a copy of the License at # #", "tf_name = tf_name.replace(start_prefix_to_remove, \"\", 1) return tf_name, transpose ##################### #", "# noqa: F401 import torch # noqa: F401 except ImportError:", "<NAME>. All rights reserved. # # Licensed under the Apache", "are transposed with regards to each other \"\"\" tf_name =", "of PyTorch models (base ones) don't start_prefix_to_remove = \"\" if", "tf_name[-1] == \"gamma\": tf_name[-1] = \"weight\" if tf_name[-1] == \"beta\":", "= convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find associated numpy array", "PyTorch model \"\"\" try: import tensorflow as tf # noqa:", "https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import tensorflow as tf # noqa: F401", "model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers not loaded from PyTorch model: {}\".format(all_pytorch_weights))", "# Make sure we are able to load PyTorch base", "model state dict if pt_weight_name not in tf_weights_map: if allow_missing_keys:", "len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape) == list(array.shape)", "missing_keys += missing_keys_pt if len(missing_keys) > 0: logger.info( \"Weights of", "> 0: logger.info( \"Weights of {} not initialized from TF", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# '_._' is replaced by a level separation (can be", "return tf_model ##################### # TF 2.0 => PyTorch # #####################", "= \"bias\" # Remove prefix if needed tf_name = \".\".join(tf_name)", "needed from a PyTorch state_dict old_keys = [] new_keys =", "list(symbolic_weight.shape) == list(array.shape) except AssertionError as e: e.args += (symbolic_weight.shape,", "model is built # Adapt state dict - TODO remove", "weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys,", "= [] new_keys = [] for key in pt_state_dict.keys(): new_key", "model weight name - transpose: boolean indicating weither TF2.0 and", "a level separation (can be used to convert TF2.0 lists", "as tf # noqa: F401 from tensorflow.python.keras import backend as", "device ids tf_name = re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name ) #", "may not use this file except in compliance with the", "tf_model = tf_model_class(pt_model.config) if tf_inputs is None: tf_inputs = tf_model.dummy_inputs", "return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\" Load", "tf_name[-1] = \"bias\" # Remove prefix if needed tf_name =", "[] new_keys = [] for key in pt_state_dict.keys(): new_key =", "start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr", "= (tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt", ") tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr =", "+= missing_keys_pt if len(missing_keys) > 0: logger.info( \"Weights of {}", "import tensorflow as tf # noqa: F401 import torch #", "# Handle PyTorch shared weight ()not duplicated in TF 2.0", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "name - transpose: boolean indicating weither TF2.0 and PyTorch weights", "numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape) == list(array.shape) except AssertionError as", "if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find", "this file except in compliance with the License. # You", "(symbolic_weight.shape, array.shape) raise e tf_loaded_numel += array.size # logger.warning(\"Initialize TF", "load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\" Load TF 2.0 model in a", "missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{} not found in TF 2.0 model\".format(pt_weight_name))", "tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{} not found in", "pt_weight_name not in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{}", "tf_model(tf_inputs, training=False) # Make sure model is built # Adapt", "TF 2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys) > 0:", "- TF 2.0 general utilities.\"\"\" import logging import os import", "model We use HDF5 to easily do transfer learning (see", "None: tf_model(tf_inputs, training=False) # Make sure model is built tf_model.load_weights(tf_checkpoint_path,", "= torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys +=", "TF 2.0 model \"\"\" pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model,", "in a PyTorch model We use HDF5 to easily do", "in a TF 2.0 model \"\"\" pt_state_dict = pt_model.state_dict() return", "{}\".format(all_pytorch_weights)) return tf_model ##################### # TF 2.0 => PyTorch #", ") def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch state_dict", "from {}\".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains {:,}", "TensorFlow, requires both PyTorch and TensorFlow to be installed. Please", "key.replace(\"beta\", \"bias\") if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "as tf # noqa: F401 import torch # noqa: F401", "raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights from {}\".format(pt_path)) pt_state_dict", "coding=utf-8 # Copyright 2018 The Google AI Language Team Authors", "# # Licensed under the Apache License, Version 2.0 (the", "elif len(symbolic_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert", "tf # noqa: F401 import torch # noqa: F401 except", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "\"\") # device ids tf_name = re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name", "array.shape) raise e # logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] =", "in a TF 2.0 model. \"\"\" try: import torch #", "learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import tensorflow as tf #", "model not used in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights or", "\"weight\") if \"beta\" in key: new_key = key.replace(\"beta\", \"bias\") if", "load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in a", "2.0 model variable name in a pytorch model weight name.", "to duplicate or remove layers in TF2.0 vs PyTorch) -", "import numpy logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert", "model \"\"\" try: import tensorflow as tf # noqa: F401", "##################### # TF 2.0 => PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model,", "PyTorch => TF 2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "\"\"\" PyTorch - TF 2.0 general utilities.\"\"\" import logging import", "beggining tf_model_class = getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config) if tf_inputs", "HDF5 to easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try:", "= tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False):", "a new level separation (can be used to convert TF2.0", "for symbolic_weight in symbolic_weights: sw_name = symbolic_weight.name name, transpose =", "2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys) > 0: logger.info(", "TF 2.0 model not used in {}: {}\".format(pt_model.__class__.__name__, unexpected_keys) )", "{}: {}\".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info(\"Weights or buffers not loaded from", "load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\" Load TF2.0", "\"\"\" pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys", "= logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert a TF 2.0", "def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in", "by $2 (can be used to duplicate or remove layers", "pt_state_dict.keys(): new_key = None if \"gamma\" in key: new_key =", "for s in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix + \".\" #", "= tf_name.split(\"/\") # Convert from TF2.0 '/' separators to PyTorch", "# Convert standard TF2.0 names in PyTorch names if tf_name[-1]", "rights reserved. # # Licensed under the Apache License, Version", "pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make sure we are able to", "pt_state_dict: if allow_missing_keys: continue raise AttributeError(\"{} not found in PyTorch", "from PyTorch model: {}\".format(all_pytorch_weights)) return tf_model ##################### # TF 2.0", "len(pt_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape):", "0: logger.info( \"Weights from TF 2.0 model not used in", "or \"emb_projs\" in tf_name or \"out_projs\" in tf_name) # Convert", "= {} for tf_weight in tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name(", "import torch # noqa: F401 except ImportError: logger.error( \"Loading a", "or buffers not loaded from TF 2.0 model: {}\".format(all_tf_weights)) return", "\"\"\" try: import tensorflow as tf # noqa: F401 import", "not None: tf_model(tf_inputs, training=False) # Make sure restore ops are", "for pt_weight_name, pt_weight in current_pt_params_dict.items(): # Handle PyTorch shared weight", "for old_key, new_key in zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) #", "TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to", "a TF 2.0 model \"\"\" try: import tensorflow as tf", "torch # noqa: F401 import tensorflow as tf # noqa:", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "len(symbolic_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape)", "set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt = [] for pt_weight_name, pt_weight", "PyTorch and TensorFlow to be installed. Please see \" \"https://pytorch.org/", "{}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys", "restore ops are run logger.info(\"Loaded {:,} parameters in the TF", "not loaded from PyTorch model: {}\".format(all_pytorch_weights)) return tf_model ##################### #", "TF 2.0 model variable name in a pytorch model weight", "##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load TF 2.0", "= numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape) == list(array.shape) except AssertionError", "or implied. # See the License for the specific language", "in TF 2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()]", "if allow_missing_keys: continue raise AttributeError(\"{} not found in PyTorch model\".format(name))", "2.0 model\".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name] if transpose: array =", "logger.info(\"Weights or buffers not loaded from TF 2.0 model: {}\".format(all_tf_weights))", "tf_name.replace(start_prefix_to_remove, \"\", 1) return tf_name, transpose ##################### # PyTorch =>", "load PyTorch base models as well as derived models (with", "use HDF5 to easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\"", "== \"embeddings\" or tf_name[-1] == \"gamma\": tf_name[-1] = \"weight\" if", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "tf_weights, allow_missing_keys=False): \"\"\" Load TF2.0 symbolic weights in a PyTorch", "pytorch checkpoints in a TF 2.0 model \"\"\" try: import", "weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is not", "and PyTorch weights matrices are transposed with regards to each", "are run logger.info(\"Loaded {:,} parameters in the TF 2.0 model.\".format(tf_loaded_numel))", "+ pt_model.__class__.__name__ # Add \"TF\" at the beggining tf_model_class =", "and The HuggingFace Inc. team. # Copyright (c) 2018, <NAME>.", "tf_name = re.sub(r\"//+\", \"/\", tf_name) # Remove empty levels at", "License. \"\"\" PyTorch - TF 2.0 general utilities.\"\"\" import logging", "== \"beta\": tf_name[-1] = \"bias\" # Remove prefix if needed", "Load pytorch state_dict in a TF 2.0 model. \"\"\" try:", "noqa: F401 except ImportError: logger.error( \"Loading a PyTorch model in", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "format to new format if needed from a PyTorch state_dict", "= \"TF\" + pt_model.__class__.__name__ # Add \"TF\" at the beggining", "pytorch model state dict if name not in pt_state_dict: if", "def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\" Load TF2.0 symbolic weights in", "some of PyTorch models (base ones) don't start_prefix_to_remove = \"\"", "models (base ones) don't start_prefix_to_remove = \"\" if not any(s.startswith(pt_model.base_model_prefix)", "replaced by a level separation (can be used to convert", "a prefix, some of PyTorch models (base ones) don't start_prefix_to_remove", "ones) don't start_prefix_to_remove = \"\" if not any(s.startswith(tf_model.base_model_prefix) for s", "Inc. team. # Copyright (c) 2018, <NAME>. All rights reserved.", "continue raise AttributeError(\"{} not found in PyTorch model\".format(name)) array =", "if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, \"\", 1) return tf_name, transpose", "Adapt state dict - TODO remove this and update the", "a TF 2.0 model variable name in a pytorch model", "easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import tensorflow", "convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights =", "TF 2.0 model in a pytorch model \"\"\" weights =", "tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\" Load TF 2.0", "in PyTorch names if tf_name[-1] == \"kernel\" or tf_name[-1] ==", "return tuple with: - pytorch model weight name - transpose:", "# Make sure model is built # Adapt state dict", "for s in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix + \".\" symbolic_weights", "new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys =", "regards to each other \"\"\" tf_name = tf_name.replace(\":0\", \"\") #", "(the \"License\"); # you may not use this file except", "tf_name = tf_name.replace(\":0\", \"\") # device ids tf_name = re.sub(", "transpose ##################### # PyTorch => TF 2.0 # ##################### def", "None if \"gamma\" in key: new_key = key.replace(\"gamma\", \"weight\") if", "tf_model, allow_missing_keys=False): \"\"\" Load TF 2.0 model in a pytorch", "missing_keys) ) if len(unexpected_keys) > 0: logger.info( \"Weights from TF", "# you may not use this file except in compliance", "tf_inputs is None: tf_inputs = tf_model.dummy_inputs if tf_inputs is not", "separation (can be used to convert TF2.0 lists in PyTorch", "e.args += (symbolic_weight.shape, array.shape) raise e tf_loaded_numel += array.size #", "'_._' is replaced by a level separation (can be used", "re.sub(r\"//+\", \"/\", tf_name) # Remove empty levels at the end", "weights from {}\".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains", "(see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import tensorflow as tf # noqa:", "= set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt = [] for pt_weight_name,", "transpose = tf_weights_map[pt_weight_name] if transpose: array = numpy.transpose(array) if len(pt_weight.shape)", "numpy.transpose(array) if len(pt_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(pt_weight.shape)", "transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find associated numpy", "(pt_weight.shape, array.shape) raise e # logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name]", "axis=0) try: assert list(pt_weight.shape) == list(array.shape) except AssertionError as e:", "= numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0)", "2.0 Variables tf_weights_map = {} for tf_weight in tf_weights: pt_name,", "torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains {:,} parameters\".format(sum(t.numel() for t in", "instructions.\" ) raise if tf_inputs is None: tf_inputs = tf_model.dummy_inputs", "tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples = [] all_pytorch_weights = set(list(pt_state_dict.keys()))", "current_pt_params_dict.items(): # Handle PyTorch shared weight ()not duplicated in TF", "len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape) == list(array.shape)", "pytorch model state dict if pt_weight_name not in tf_weights_map: if", "numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try:", "tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {}", "raise e tf_loaded_numel += array.size # logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name))", "to convert TF2.0 lists in PyTorch nn.ModulesList) return tuple with:", "tf_name ) # '$1___$2' is replaced by $2 (can be", "potential PyTorch weight names to TF 2.0 Variables tf_weights_map =", "or buffers not loaded from PyTorch model: {}\".format(all_pytorch_weights)) return tf_model", "= [] for pt_weight_name, pt_weight in current_pt_params_dict.items(): # Handle PyTorch", "getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config) if tf_inputs is None: tf_inputs", "# # Unless required by applicable law or agreed to", "When should we transpose the weights transpose = bool(tf_name[-1] ==", "tf_model ##################### # TF 2.0 => PyTorch # ##################### def", "should we transpose the weights transpose = bool(tf_name[-1] == \"kernel\"", "installation instructions.\" ) raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights", "{}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is not None:", "tf_model.base_model_prefix + \".\" symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel =", "\"\"\" Load TF2.0 symbolic weights in a PyTorch model \"\"\"", "\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise import transformers", "a TF 2.0 model \"\"\" pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model(", "sw_name = symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove )", "+ \".\" # Build a map from potential PyTorch weight", "TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers not loaded from PyTorch", "other \"\"\" tf_name = tf_name.replace(\":0\", \"\") # device ids tf_name", "PyTorch) tf_name = tf_name.replace( \"_._\", \"/\" ) # '_._' is", "not in pt_state_dict: if allow_missing_keys: continue raise AttributeError(\"{} not found", "# logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] =", "logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert a TF", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "model variable name in a pytorch model weight name. Conventions", "allow_missing_keys: continue raise AttributeError(\"{} not found in PyTorch model\".format(name)) array", "F401 except ImportError: logger.error( \"Loading a TensorFlow model in PyTorch,", "model \"\"\" pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs,", "utilities.\"\"\" import logging import os import re import numpy logger", "key: new_key = key.replace(\"gamma\", \"weight\") if \"beta\" in key: new_key", "\".\" symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples", "TF 2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue", "missing_keys_pt if len(missing_keys) > 0: logger.info( \"Weights of {} not", "Version 2.0 (the \"License\"); # you may not use this", "have a prefix, some of PyTorch models (base ones) don't", "model state dict if name not in pt_state_dict: if allow_missing_keys:", "< len(array.shape): array = numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape): array", "the License. \"\"\" PyTorch - TF 2.0 general utilities.\"\"\" import", "weights from {}\".format(tf_checkpoint_path)) # Instantiate and load the associated TF", "+ \".\" symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel = 0", "state_dict in a TF 2.0 model. \"\"\" try: import torch", "= numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0)", ") def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints", "transpose: array = numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape): array =", "new_key = None if \"gamma\" in key: new_key = key.replace(\"gamma\",", "model \"\"\" weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def", "{} current_pt_params_dict = dict(pt_model.named_parameters()) # Make sure we are able", "= pt_model.base_model_prefix + \".\" # Build a map from potential", "2.0 model \"\"\" pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict,", "sure model is built # Adapt state dict - TODO", "pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\"", "built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model,", "both PyTorch and TensorFlow to be installed. Please see \"", "model: {}\".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys) > 0: logger.info( \"Weights", "derived models (with heads) # TF models always have a", "len(pt_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape)", "implied. # See the License for the specific language governing", "installation instructions.\" ) raise import transformers logger.info(\"Loading TensorFlow weights from", "not None: tf_model(tf_inputs, training=False) # Make sure model is built", "under the Apache License, Version 2.0 (the \"License\"); # you", "models (base ones) don't start_prefix_to_remove = \"\" if not any(s.startswith(tf_model.base_model_prefix)", "strict=False) missing_keys += missing_keys_pt if len(missing_keys) > 0: logger.info( \"Weights", "os import re import numpy logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name,", "in zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make sure we", "allow_missing_keys=False): \"\"\" Load TF 2.0 model in a pytorch model", "tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False):", "weight name - transpose: boolean indicating weither TF2.0 and PyTorch", "Copyright 2018 The Google AI Language Team Authors and The", "new_key = key.replace(\"gamma\", \"weight\") if \"beta\" in key: new_key =", "raise new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters()) # Make sure", "Load TF 2.0 model in a pytorch model \"\"\" weights", "don't start_prefix_to_remove = \"\" if not any(s.startswith(tf_model.base_model_prefix) for s in", "array in pytorch model state dict if pt_weight_name not in", "All rights reserved. # # Licensed under the Apache License,", "logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\" Convert a TF 2.0 model", "pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(),", "> 0: logger.info( \"Weights from TF 2.0 model not used", "by applicable law or agreed to in writing, software #", "to be installed. Please see \" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for", "Language Team Authors and The HuggingFace Inc. team. # Copyright", "key: new_key = key.replace(\"beta\", \"bias\") if new_key: old_keys.append(key) new_keys.append(new_key) for", "tf_model_class = getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config) if tf_inputs is", "missing_keys_pt = [] for pt_weight_name, pt_weight in current_pt_params_dict.items(): # Handle", "duplicate or remove layers in TF2.0 vs PyTorch) tf_name =", "layers in TF2.0 vs PyTorch) - '_._' is replaced by", "== \"gamma\": tf_name[-1] = \"weight\" if tf_name[-1] == \"beta\": tf_name[-1]", "t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys )", "ones) don't start_prefix_to_remove = \"\" if not any(s.startswith(pt_model.base_model_prefix) for s", "or remove layers in TF2.0 vs PyTorch) tf_name = tf_name.replace(", "tf_weights_map[pt_weight_name] if transpose: array = numpy.transpose(array) if len(pt_weight.shape) < len(array.shape):", "# Add \"TF\" at the beggining tf_model_class = getattr(transformers, tf_model_class_name)", "is replaced by a level separation (can be used to", "https://www.tensorflow.org/install/ for installation instructions.\" ) raise import transformers logger.info(\"Loading TensorFlow", ") raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights from {}\".format(pt_path))", "[] for pt_weight_name, pt_weight in current_pt_params_dict.items(): # Handle PyTorch shared", "Load pytorch checkpoints in a TF 2.0 model \"\"\" try:", "Copyright (c) 2018, <NAME>. All rights reserved. # # Licensed", "old format to new format if needed from a PyTorch", "[] for key in pt_state_dict.keys(): new_key = None if \"gamma\"", "2018, <NAME>. All rights reserved. # # Licensed under the", "tuple with: - pytorch model weight name - transpose: boolean", "to convert TF2.0 lists in PyTorch nn.ModulesList) tf_name = re.sub(r\"//+\",", "convert TF2.0 lists in PyTorch nn.ModulesList) return tuple with: -", "# Remove prefix if needed tf_name = \".\".join(tf_name) if start_prefix_to_remove:", "update the AWS weights files instead # Convert old format", "TensorFlow to be installed. Please see \" \"https://pytorch.org/ and https://www.tensorflow.org/install/", "in PyTorch, requires both PyTorch and TensorFlow to be installed.", "of {} not initialized from TF 2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys)", "found in TF 2.0 model\".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name] if", "if len(missing_keys) > 0: logger.info( \"Weights of {} not initialized", "1) return tf_name, transpose ##################### # PyTorch => TF 2.0", "are able to load PyTorch base models as well as", "tf_inputs=None, allow_missing_keys=False): \"\"\" Load TF 2.0 HDF5 checkpoint in a", "= set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights: sw_name = symbolic_weight.name name,", "not initialized from TF 2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys) ) if", "in a PyTorch model \"\"\" try: import tensorflow as tf", "unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt if len(missing_keys) >", "tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\"", "tf_model_class_name) tf_model = tf_model_class(pt_model.config) if tf_inputs is None: tf_inputs =", "associated numpy array in pytorch model state dict if pt_weight_name", "old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): pt_state_dict[new_key] =", "elif len(pt_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert", "{}\".format(tf_checkpoint_path)) # Instantiate and load the associated TF 2.0 model", "for TF2.0 scopes -> PyTorch attribute names conversions: - '$1___$2'", "= tf_name.replace(start_prefix_to_remove, \"\", 1) return tf_name, transpose ##################### # PyTorch", "\"TF\" + pt_model.__class__.__name__ # Add \"TF\" at the beggining tf_model_class", "axis=0) try: assert list(symbolic_weight.shape) == list(array.shape) except AssertionError as e:", "= convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights", "# noqa: F401 import tensorflow as tf # noqa: F401", "be used to convert TF2.0 lists in PyTorch nn.ModulesList) return", "heads) # TF models always have a prefix, some of", "in tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name]", "Please see \" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" )", "# '$1___$2' is replaced by $2 (can be used to", "be installed. Please see \" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "separators to PyTorch '.' separators tf_name = tf_name[1:] # Remove", "to new format if needed from a PyTorch state_dict old_keys", "'_._' is replaced by a new level separation (can be", "dict(pt_model.named_parameters()) # Make sure we are able to load PyTorch", "= {} missing_keys_pt = [] for pt_weight_name, pt_weight in current_pt_params_dict.items():", "Unless required by applicable law or agreed to in writing,", "levels at the end tf_name = tf_name.split(\"/\") # Convert from", "we transpose the weights transpose = bool(tf_name[-1] == \"kernel\" or", "at the end tf_name = tf_name.split(\"/\") # Convert from TF2.0", "\"Loading a TensorFlow model in PyTorch, requires both PyTorch and", "if len(pt_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(pt_weight.shape) >", "{} not initialized from TF 2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys) )", "new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): pt_state_dict[new_key]", "noqa: F401 except ImportError: logger.error( \"Loading a TensorFlow model in", "the specific language governing permissions and # limitations under the", "transformers logger.info(\"Loading TensorFlow weights from {}\".format(tf_checkpoint_path)) # Instantiate and load", "not found in PyTorch model\".format(name)) array = pt_state_dict[name].numpy() if transpose:", "PyTorch model\".format(name)) array = pt_state_dict[name].numpy() if transpose: array = numpy.transpose(array)", "tf_weight in tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove )", "Team Authors and The HuggingFace Inc. team. # Copyright (c)", "\"gamma\": tf_name[-1] = \"weight\" if tf_name[-1] == \"beta\": tf_name[-1] =", "applicable law or agreed to in writing, software # distributed", "allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{} not found in TF 2.0", "in PyTorch model\".format(name)) array = pt_state_dict[name].numpy() if transpose: array =", "vs PyTorch) tf_name = tf_name.replace( \"_._\", \"/\" ) # '_._'", "governing permissions and # limitations under the License. \"\"\" PyTorch", "tf_name[-1] == \"embeddings\" or tf_name[-1] == \"gamma\": tf_name[-1] = \"weight\"", "allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): \"\"\" Load TF 2.0 model", "= key.replace(\"gamma\", \"weight\") if \"beta\" in key: new_key = key.replace(\"beta\",", "from tensorflow.python.keras import backend as K except ImportError: logger.error( \"Loading", ") if len(unexpected_keys) > 0: logger.info( \"Weights from TF 2.0", "in the TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers not loaded", "as e: e.args += (symbolic_weight.shape, array.shape) raise e tf_loaded_numel +=", "base models as well as derived models (with heads) #", "except AssertionError as e: e.args += (pt_weight.shape, array.shape) raise e", "lists in PyTorch nn.ModulesList) return tuple with: - pytorch model", "symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find", "load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\" Load TF2.0 symbolic weights in a", "TF2.0 lists in PyTorch nn.ModulesList) return tuple with: - pytorch", "# TF models always have a prefix, some of PyTorch", "PyTorch weight names to TF 2.0 Variables tf_weights_map = {}", "if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys):", "is None: tf_inputs = tf_model.dummy_inputs if tf_inputs is not None:", "in writing, software # distributed under the License is distributed", "pt_state_dict[name].numpy() if transpose: array = numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape):", "tf_name = tf_name.replace( \"_._\", \"/\" ) # '_._' is replaced", "in pt_state_dict: if allow_missing_keys: continue raise AttributeError(\"{} not found in", "in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix + \".\" symbolic_weights = tf_model.trainable_weights", "= re.sub( r\"/[^/]*___([^/]*)/\", r\"/\\1/\", tf_name ) # '$1___$2' is replaced", "in pt_state_dict.keys(): new_key = None if \"gamma\" in key: new_key", "TF 2.0 Variables tf_weights_map = {} for tf_weight in tf_weights:", "standard TF2.0 names in PyTorch names if tf_name[-1] == \"kernel\"", "new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key)", "logger.info( \"Weights of {} not initialized from TF 2.0 model:", "in a TF 2.0 model \"\"\" try: import tensorflow as", "e: e.args += (symbolic_weight.shape, array.shape) raise e tf_loaded_numel += array.size", "from TF 2.0 model: {}\".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys) >", "pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys )", "< len(array.shape): array = numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape): array", "tf_name = \".\".join(tf_name) if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, \"\", 1)", "in tf_name or \"out_projs\" in tf_name) # Convert standard TF2.0", "= torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains {:,} parameters\".format(sum(t.numel() for t", "a TF 2.0 model. \"\"\" try: import torch # noqa:", "import tensorflow as tf # noqa: F401 from tensorflow.python.keras import", "if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix", "transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(), transpose)", "name in a pytorch model weight name. Conventions for TF2.0", "weights in a PyTorch model \"\"\" try: import tensorflow as", "(base ones) don't start_prefix_to_remove = \"\" if not any(s.startswith(pt_model.base_model_prefix) for", "if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{} not found in TF", "== list(array.shape) except AssertionError as e: e.args += (symbolic_weight.shape, array.shape)", "pt_model.__class__.__name__ # Add \"TF\" at the beggining tf_model_class = getattr(transformers,", "2.0 general utilities.\"\"\" import logging import os import re import", "PyTorch) - '_._' is replaced by a new level separation", "new level separation (can be used to convert TF2.0 lists", "is not None: tf_model(tf_inputs, training=False) # Make sure model is", "limitations under the License. \"\"\" PyTorch - TF 2.0 general", "allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\" Load TF2.0 symbolic weights", "tf_model(tf_inputs, training=False) # Make sure model is built tf_model.load_weights(tf_checkpoint_path, by_name=True)", "all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt if", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch", "License, Version 2.0 (the \"License\"); # you may not use", "array = numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape): array = numpy.expand_dims(array,", "map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains {:,} parameters\".format(sum(t.numel() for t in pt_state_dict.values())))", "# You may obtain a copy of the License at", "be used to duplicate or remove layers in TF2.0 vs", "for installation instructions.\" ) raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch", "\"gamma\" in key: new_key = key.replace(\"gamma\", \"weight\") if \"beta\" in", "PyTorch models (base ones) don't start_prefix_to_remove = \"\" if not", "array.shape) raise e tf_loaded_numel += array.size # logger.warning(\"Initialize TF weight", "model in a pytorch model \"\"\" weights = tf_model.weights return", "TF2.0 and PyTorch weights matrices are transposed with regards to", "weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): \"\"\" Load TF2.0 symbolic", "##################### # PyTorch => TF 2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model,", "2.0 model \"\"\" try: import tensorflow as tf # noqa:", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "except AssertionError as e: e.args += (symbolic_weight.shape, array.shape) raise e", "for installation instructions.\" ) raise import transformers logger.info(\"Loading TensorFlow weights", "name. Conventions for TF2.0 scopes -> PyTorch attribute names conversions:", "dict - TODO remove this and update the AWS weights", "state dict - TODO remove this and update the AWS", "{} missing_keys_pt = [] for pt_weight_name, pt_weight in current_pt_params_dict.items(): #", "AssertionError as e: e.args += (symbolic_weight.shape, array.shape) raise e tf_loaded_numel", "{} for tf_weight in tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name,", "in TF2.0 vs PyTorch) - '_._' is replaced by a", "import transformers logger.info(\"Loading TensorFlow weights from {}\".format(tf_checkpoint_path)) # Instantiate and", "names if tf_name[-1] == \"kernel\" or tf_name[-1] == \"embeddings\" or", "list(array.shape) except AssertionError as e: e.args += (symbolic_weight.shape, array.shape) raise", "a map from potential PyTorch weight names to TF 2.0", "HDF5 checkpoint in a PyTorch model We use HDF5 to", "TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is", "any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix + \".\"", "TF 2.0 general utilities.\"\"\" import logging import os import re", "installed. Please see \" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\"", "tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\" Load", "\".\".join(tf_name) if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, \"\", 1) return tf_name,", "pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(\"Loading PyTorch weights from {}\".format(pt_path)) pt_state_dict =", "tf_name) # Remove empty levels at the end tf_name =", "PyTorch base models as well as derived models (with heads)", "numpy array in pytorch model state dict if name not", "is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model,", "in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def", "the License for the specific language governing permissions and #", "AttributeError(\"{} not found in PyTorch model\".format(name)) array = pt_state_dict[name].numpy() if", "pt_state_dict.pop(old_key) # Make sure we are able to load PyTorch", "tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False):", "Apache License, Version 2.0 (the \"License\"); # you may not", "loaded_pt_weights_data_ptr = {} missing_keys_pt = [] for pt_weight_name, pt_weight in", "F401 from tensorflow.python.keras import backend as K except ImportError: logger.error(", "either express or implied. # See the License for the", "new format if needed from a PyTorch state_dict old_keys =", "if len(symbolic_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(symbolic_weight.shape) >", "'/' separators to PyTorch '.' separators tf_name = tf_name[1:] #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "model weight name. Conventions for TF2.0 scopes -> PyTorch attribute", "pt_model, tf_inputs=None, allow_missing_keys=False): \"\"\" Load pytorch checkpoints in a TF", "symbolic_weights: sw_name = symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove", "https://www.tensorflow.org/install/ for installation instructions.\" ) raise if tf_inputs is None:", "= bool(tf_name[-1] == \"kernel\" or \"emb_projs\" in tf_name or \"out_projs\"", "= tf_model.dummy_inputs if tf_inputs is not None: tf_model(tf_inputs, training=False) #", "parameters in the TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers not", "in a pytorch model weight name. Conventions for TF2.0 scopes", "replaced by $2 (can be used to duplicate or remove", "TF2.0 symbolic weights in a PyTorch model \"\"\" try: import", "old_key, new_key in zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make", "in PyTorch nn.ModulesList) return tuple with: - pytorch model weight", "# Convert old format to new format if needed from", "format if needed from a PyTorch state_dict old_keys = []", "TF 2.0 model\".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name] if transpose: array", "0: logger.info( \"Weights of {} not initialized from TF 2.0", "in key: new_key = key.replace(\"gamma\", \"weight\") if \"beta\" in key:", "\"/\" ) # '_._' is replaced by a level separation", "e.args += (pt_weight.shape, array.shape) raise e # logger.warning(\"Initialize PyTorch weight", "weight name. Conventions for TF2.0 scopes -> PyTorch attribute names", "as well as derived models (with heads) # TF models", "= numpy.transpose(array) if len(pt_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif", "pt_model.base_model_prefix + \".\" # Build a map from potential PyTorch", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "under the License. \"\"\" PyTorch - TF 2.0 general utilities.\"\"\"", "to each other \"\"\" tf_name = tf_name.replace(\":0\", \"\") # device", "numpy array in pytorch model state dict if pt_weight_name not", "try: import tensorflow as tf # noqa: F401 import torch", "{}\".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains {:,} parameters\".format(sum(t.numel()", "logger.info(\"Loading TensorFlow weights from {}\".format(tf_checkpoint_path)) # Instantiate and load the", "> len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape) ==", "unexpected_keys) ) logger.info(\"Weights or buffers not loaded from TF 2.0", "in current_pt_params_dict.items(): # Handle PyTorch shared weight ()not duplicated in", "None: tf_model(tf_inputs, training=False) # Make sure model is built #", "K except ImportError: logger.error( \"Loading a PyTorch model in TensorFlow,", "AssertionError as e: e.args += (pt_weight.shape, array.shape) raise e #", "Conventions for TF2.0 scopes -> PyTorch attribute names conversions: -", "tf_name = tf_name[1:] # Remove level zero # When should", "found in PyTorch model\".format(name)) array = pt_state_dict[name].numpy() if transpose: array", "2.0 HDF5 checkpoint in a PyTorch model We use HDF5", "Google AI Language Team Authors and The HuggingFace Inc. team.", "logger.error( \"Loading a TensorFlow model in PyTorch, requires both PyTorch", "raise import transformers logger.info(\"Loading TensorFlow weights from {}\".format(tf_checkpoint_path)) # Instantiate", "and https://www.tensorflow.org/install/ for installation instructions.\" ) raise pt_path = os.path.abspath(pytorch_checkpoint_path)", "pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model,", "(can be used to duplicate or remove layers in TF2.0", "Convert old format to new format if needed from a", "assert list(symbolic_weight.shape) == list(array.shape) except AssertionError as e: e.args +=", "Convert from TF2.0 '/' separators to PyTorch '.' separators tf_name", "noqa: F401 import torch # noqa: F401 except ImportError: logger.error(", "None: tf_model(tf_inputs, training=False) # Make sure restore ops are run", "if needed tf_name = \".\".join(tf_name) if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove,", "or tf_name[-1] == \"gamma\": tf_name[-1] = \"weight\" if tf_name[-1] ==", "start_prefix_to_remove = \"\" if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()):", "tf_name[-1] = \"weight\" if tf_name[-1] == \"beta\": tf_name[-1] = \"bias\"", "= [] for key in pt_state_dict.keys(): new_key = None if", "except ImportError: logger.error( \"Loading a PyTorch model in TensorFlow, requires", "\"License\"); # you may not use this file except in", "TF 2.0 => PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None,", "\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise if tf_inputs", "def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): \"\"\" Load TF 2.0 HDF5", "== \"kernel\" or \"emb_projs\" in tf_name or \"out_projs\" in tf_name)", "old_keys = [] new_keys = [] for key in pt_state_dict.keys():", "\"\"\" Load TF 2.0 HDF5 checkpoint in a PyTorch model", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "= {} current_pt_params_dict = dict(pt_model.named_parameters()) # Make sure we are", "return tf_name, transpose ##################### # PyTorch => TF 2.0 #", "# logger.warning(\"Initialize TF weight {}\".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if", "backend as K except ImportError: logger.error( \"Loading a PyTorch model", "sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find associated numpy array in pytorch", "r\"/\\1/\", tf_name ) # '$1___$2' is replaced by $2 (can", "continue # Find associated numpy array in pytorch model state", "# Convert from TF2.0 '/' separators to PyTorch '.' separators", "installation instructions.\" ) raise if tf_inputs is None: tf_inputs =", "# distributed under the License is distributed on an \"AS", "if tf_name[-1] == \"beta\": tf_name[-1] = \"bias\" # Remove prefix", "noqa: F401 import tensorflow as tf # noqa: F401 from", "\"weight\" if tf_name[-1] == \"beta\": tf_name[-1] = \"bias\" # Remove", "key in pt_state_dict.keys(): new_key = None if \"gamma\" in key:", "logging import os import re import numpy logger = logging.getLogger(__name__)", "\"bias\") if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys,", "# Unless required by applicable law or agreed to in", "import torch # noqa: F401 import tensorflow as tf #", "and https://www.tensorflow.org/install/ for installation instructions.\" ) raise new_pt_params_dict = {}", "not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix +", "Load pytorch checkpoints in a TF 2.0 model \"\"\" pt_state_dict", "pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt if len(missing_keys) > 0: logger.info(", "in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError(\"{} not found", "tf_name.replace( \"_._\", \"/\" ) # '_._' is replaced by a", "pt_state_dict = torch.load(pt_path, map_location=\"cpu\") logger.info(\"PyTorch checkpoint contains {:,} parameters\".format(sum(t.numel() for", "any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix + \".\"", "transpose: boolean indicating weither TF2.0 and PyTorch weights matrices are", "is not None: tf_model(tf_inputs, training=False) # Make sure restore ops", "associated TF 2.0 model tf_model_class_name = \"TF\" + pt_model.__class__.__name__ #", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "by a new level separation (can be used to convert", "new_keys = [] for key in pt_state_dict.keys(): new_key = None", "array = numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape) == list(array.shape) except", "Authors and The HuggingFace Inc. team. # Copyright (c) 2018,", ") # '$1___$2' is replaced by $2 (can be used", "- '_._' is replaced by a new level separation (can", "return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model,", "re import numpy logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=\"\"): \"\"\"", "loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys", "convert TF2.0 lists in PyTorch nn.ModulesList) tf_name = re.sub(r\"//+\", \"/\",", "tf_model_class(pt_model.config) if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if tf_inputs", "in symbolic_weights: sw_name = symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name,", "We use HDF5 to easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).", "not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix +", "the TF 2.0 model.\".format(tf_loaded_numel)) logger.info(\"Weights or buffers not loaded from", "a PyTorch model We use HDF5 to easily do transfer", "replaced by a new level separation (can be used to", "You may obtain a copy of the License at #", "https://www.tensorflow.org/install/ for installation instructions.\" ) raise new_pt_params_dict = {} current_pt_params_dict", "in pytorch model state dict if pt_weight_name not in tf_weights_map:", "-> PyTorch attribute names conversions: - '$1___$2' is replaced by", "Make sure we are able to load PyTorch base models", "PyTorch model We use HDF5 to easily do transfer learning", "to TF 2.0 Variables tf_weights_map = {} for tf_weight in", "# Make sure model is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model,", "weights transpose = bool(tf_name[-1] == \"kernel\" or \"emb_projs\" in tf_name", "== list(array.shape) except AssertionError as e: e.args += (pt_weight.shape, array.shape)", "raise e # logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array)", "in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated numpy", "\"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise pt_path =", "key.replace(\"gamma\", \"weight\") if \"beta\" in key: new_key = key.replace(\"beta\", \"bias\")", "the Apache License, Version 2.0 (the \"License\"); # you may", "tf_inputs = tf_model.dummy_inputs if tf_inputs is not None: tf_model(tf_inputs, training=False)", "requires both PyTorch and TensorFlow to be installed. Please see", "for t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys", "do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). \"\"\" try: import tensorflow as", "or remove layers in TF2.0 vs PyTorch) - '_._' is", "logger.warning(\"Initialize PyTorch weight {}\".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array)", "in a pytorch model \"\"\" weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model,", "\" \"https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions.\" ) raise pt_path", "PyTorch weights matrices are transposed with regards to each other", "\"TF\" at the beggining tf_model_class = getattr(transformers, tf_model_class_name) tf_model =", "# noqa: F401 except ImportError: logger.error( \"Loading a TensorFlow model" ]
[ "local backend\", strict=True) def run_with_cxx_compile(): @decorator def wrapper(func, *args, **kwargs):", "*args, **kwargs): return return wrapper def assert_evals_to(e, v): res =", "'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets(): return (create_all_values_table(),", "Env import hail as hl from hail.backend.local_backend import LocalBackend _initialized", "= flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return func(*args,", "quiet=True) else: Env.hc() # force initialization _initialized = True def", "list): return [convert_struct_to_dict(elt) for elt in x] elif isinstance(x, tuple):", "+ k: s[k] for k in s}) def create_all_values_table(): all_values", "assert (start - end) < max_duration print(f'took {end - start:.3f}')", "import default_timer as timer import unittest import pytest from decorator", "def create_all_values_table(): all_values = create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_'))", "def lower_only(): @decorator def wrapper(func, *args, **kwargs): flags = hl._get_flags()", "expecteds) def lower_only(): @decorator def wrapper(func, *args, **kwargs): flags =", "= pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't yet work on local", "as timer import unittest import pytest from decorator import decorator", "x._fields.items()} elif isinstance(x, list): return [convert_struct_to_dict(elt) for elt in x]", ".annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend():", "def run_with_cxx_compile(): @decorator def wrapper(func, *args, **kwargs): return return wrapper", "2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_'))", "convert_struct_to_dict(v) for k, v in x._fields.items()} elif isinstance(x, list): return", "_dataset is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f,", "return {k: convert_struct_to_dict(v) for k, v in x.items()} else: return", "x def create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5),", "work on local backend\", strict=True) def run_with_cxx_compile(): @decorator def wrapper(func,", "zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator def wrapper(func, *args, **kwargs):", "fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't yet work on", "{k: convert_struct_to_dict(v) for k, v in x._fields.items()} elif isinstance(x, list):", "x _dataset = None def get_dataset(): global _dataset if _dataset", "LocalBackend _initialized = False def startTestHailContext(): global _initialized if not", "= zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator def wrapper(func, *args,", "pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't yet work on local backend\",", "timeit import default_timer as timer import unittest import pytest from", "b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5,", "1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'),", "10).reshape((2, 5)), ) def prefix_struct(s, prefix): return hl.struct(**{prefix + k:", "def convert_struct_to_dict(x): if isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v) for k,", "expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds)", "hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def prefix_struct(s, prefix):", "if not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name ==", "in x] elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for elt in", "elt in x]) elif isinstance(x, dict): return {k: convert_struct_to_dict(v) for", "lower_only='1') try: return func(*args, **kwargs) finally: hl._set_flags(lower=prev_lower, lower_only=prev_lower_only) return wrapper", "mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2,", "elif isinstance(x, dict): return {k: convert_struct_to_dict(v) for k, v in", "< max_duration print(f'took {end - start:.3f}') return x def create_all_values():", "from decorator import decorator from hail.utils.java import Env import hail", "def doctest_resource(filename): return os.path.join(_doctest_dir, filename) def schema_eq(x, y): x_fds =", "end = timer() assert (start - end) < max_duration print(f'took", "import SparkBackend @decorator def wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend):", "ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1,", "== y_fds def convert_struct_to_dict(x): if isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v)", "create_all_values_table(): all_values = create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values)", "t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)),", "os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't yet work on local backend\", strict=True)", "(hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values =", "raise ValueError(f' actual: {res}\\n expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds", "== 'local', reason=\"doesn't yet work on local backend\", strict=True) def", "h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0,", "# force initialization _initialized = True def stopTestHailContext(): pass _test_dir", "def wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs)", "hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc() # force initialization _initialized =", "v): res = hl.eval(e) if res != v: raise ValueError(f'", "(hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values,", "global _dataset if _dataset is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return", "_dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f, max_duration): start =", "y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr),", "import hail as hl from hail.backend.local_backend import LocalBackend _initialized =", "prefix): return hl.struct(**{prefix + k: s[k] for k in s})", "= False def startTestHailContext(): global _initialized if not _initialized: backend_name", "hl.Struct): return {k: convert_struct_to_dict(v) for k, v in x._fields.items()} elif", "k: s[k] for k in s}) def create_all_values_table(): all_values =", "hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]),", "hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')),", "'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32,", "False def startTestHailContext(): global _initialized if not _initialized: backend_name =", "os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return os.path.join(_test_dir,", "else: raise unittest.SkipTest('requires Spark') return wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND')", "elif isinstance(x, list): return [convert_struct_to_dict(elt) for elt in x] elif", "= hl._get_flags() prev_lower = flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1')", "0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999),", "yet work on local backend\", strict=True) def run_with_cxx_compile(): @decorator def", "*args, **kwargs): flags = hl._get_flags() prev_lower = flags.get('lower') prev_lower_only =", "{end - start:.3f}') return x def create_all_values(): return hl.struct( f32=hl.float32(3.14),", "hail.utils.java import Env import hail as hl from hail.backend.local_backend import", "= hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f, max_duration): start = timer()", "create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend", "flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return func(*args, **kwargs) finally: hl._set_flags(lower=prev_lower, lower_only=prev_lower_only)", "from hail.backend.local_backend import LocalBackend _initialized = False def startTestHailContext(): global", "*args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs) else: raise", "= dict(x) y_fds = dict(y) return x_fds == y_fds def", "return os.path.join(_doctest_dir, filename) def schema_eq(x, y): x_fds = dict(x) y_fds", "'../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return os.path.join(_test_dir, filename)", "x_fds == y_fds def convert_struct_to_dict(x): if isinstance(x, hl.Struct): return {k:", "max_duration print(f'took {end - start:.3f}') return x def create_all_values(): return", "md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1',", "k in s}) def create_all_values_table(): all_values = create_all_values() return (hl.utils.range_table(5,", "create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values,", "- start:.3f}') return x def create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9),", "hl from hail.backend.local_backend import LocalBackend _initialized = False def startTestHailContext():", "**kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs) else: raise unittest.SkipTest('requires", "unittest.SkipTest('requires Spark') return wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local',", "_initialized = True def stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources')", "import Env import hail as hl from hail.backend.local_backend import LocalBackend", "create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend @decorator def wrapper(func,", "import unittest import pytest from decorator import decorator from hail.utils.java", "min_block_size=0, quiet=True) else: Env.hc() # force initialization _initialized = True", "2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), )", "- end) < max_duration print(f'took {end - start:.3f}') return x", "[convert_struct_to_dict(elt) for elt in x] elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt)", "if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs) else: raise unittest.SkipTest('requires Spark')", "def assert_evals_to(e, v): res = hl.eval(e) if res != v:", "hl._get_flags() prev_lower = flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try:", "mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def prefix_struct(s, prefix): return", "resource(filename): return os.path.join(_test_dir, filename) def doctest_resource(filename): return os.path.join(_doctest_dir, filename) def", "mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)),", "return func(*args, **kwargs) else: raise unittest.SkipTest('requires Spark') return wrapper fails_local_backend", "hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True),", "_test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename):", "_dataset if _dataset is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset", "if res != v: raise ValueError(f' actual: {res}\\n expected: {v}')", "import os from timeit import default_timer as timer import unittest", "return tuple([convert_struct_to_dict(elt) for elt in x]) elif isinstance(x, dict): return", "from hail.utils.java import Env import hail as hl from hail.backend.local_backend", "1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0,", "_dataset = None def get_dataset(): global _dataset if _dataset is", "is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f, max_duration):", "def get_dataset(): global _dataset if _dataset is None: _dataset =", "start:.3f}') return x def create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64),", "else: Env.hc() # force initialization _initialized = True def stopTestHailContext():", "!= v: raise ValueError(f' actual: {res}\\n expected: {v}') def assert_all_eval_to(*expr_and_expected):", "os from timeit import default_timer as timer import unittest import", "x] elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for elt in x])", "backend_name == 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc() # force", "= f() end = timer() assert (start - end) <", "**kwargs): return return wrapper def assert_evals_to(e, v): res = hl.eval(e)", "default_timer as timer import unittest import pytest from decorator import", ".annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def", "startTestHailContext(): global _initialized if not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark')", "for k, v in x.items()} else: return x _dataset =", "if backend_name == 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc() #", "f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']),", "= timer() assert (start - end) < max_duration print(f'took {end", "{k: convert_struct_to_dict(v) for k, v in x.items()} else: return x", "return x def create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32),", "assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator def wrapper(func, *args, **kwargs): flags", "'hail/docs/data') def resource(filename): return os.path.join(_test_dir, filename) def doctest_resource(filename): return os.path.join(_doctest_dir,", "def create_all_values_matrix_table(): all_values = create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values,", "from timeit import default_timer as timer import unittest import pytest", "'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978,", ".cache()) def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend", "y_fds def convert_struct_to_dict(x): if isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v) for", "return wrapper def assert_evals_to(e, v): res = hl.eval(e) if res", "return return wrapper def assert_evals_to(e, v): res = hl.eval(e) if", "'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall),", "wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs) else:", "return _dataset def assert_time(f, max_duration): start = timer() x =", "hail as hl from hail.backend.local_backend import LocalBackend _initialized = False", "start = timer() x = f() end = timer() assert", "os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return os.path.join(_test_dir, filename) def doctest_resource(filename): return", "in x.items()} else: return x _dataset = None def get_dataset():", "@decorator def wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args,", "filename) def doctest_resource(filename): return os.path.join(_doctest_dir, filename) def schema_eq(x, y): x_fds", "on local backend\", strict=True) def run_with_cxx_compile(): @decorator def wrapper(func, *args,", "as hl from hail.backend.local_backend import LocalBackend _initialized = False def", "pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def", "isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v) for k, v in x._fields.items()}", "999), hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo',", "astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']):", "return x _dataset = None def get_dataset(): global _dataset if", "'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets():", "raise unittest.SkipTest('requires Spark') return wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') ==", "decorator import decorator from hail.utils.java import Env import hail as", "os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name == 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else:", "= dict(y) return x_fds == y_fds def convert_struct_to_dict(x): if isinstance(x,", "== 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc() # force initialization", "return wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't yet", "elt in x] elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for elt", "in s}) def create_all_values_table(): all_values = create_all_values() return (hl.utils.range_table(5, n_partitions=3)", "def wrapper(func, *args, **kwargs): flags = hl._get_flags() prev_lower = flags.get('lower')", "i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)),", "return {k: convert_struct_to_dict(v) for k, v in x._fields.items()} elif isinstance(x,", "def resource(filename): return os.path.join(_test_dir, filename) def doctest_resource(filename): return os.path.join(_doctest_dir, filename)", "prefix_struct(s, prefix): return hl.struct(**{prefix + k: s[k] for k in", "k, v in x._fields.items()} elif isinstance(x, list): return [convert_struct_to_dict(elt) for", "'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc() # force initialization _initialized", "i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2,", "get_dataset(): global _dataset if _dataset is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache()", "@decorator def wrapper(func, *args, **kwargs): return return wrapper def assert_evals_to(e,", "end) < max_duration print(f'took {end - start:.3f}') return x def", "v in x.items()} else: return x _dataset = None def", "initialization _initialized = True def stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR',", "d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22',", "return [convert_struct_to_dict(elt) for elt in x] elif isinstance(x, tuple): return", "hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval(", "hl._set_flags(lower='1', lower_only='1') try: return func(*args, **kwargs) finally: hl._set_flags(lower=prev_lower, lower_only=prev_lower_only) return", "(create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend @decorator def", "return os.path.join(_test_dir, filename) def doctest_resource(filename): return os.path.join(_doctest_dir, filename) def schema_eq(x,", "s}) def create_all_values_table(): all_values = create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values,", "wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't yet work", "= create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_'))", "if isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v) for k, v in", "convert_struct_to_dict(v) for k, v in x.items()} else: return x _dataset", "nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def prefix_struct(s, prefix): return hl.struct(**{prefix +", "hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)),", "_initialized if not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name", "'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}),", "assert_evals_to(e, v): res = hl.eval(e) if res != v: raise", "(start - end) < max_duration print(f'took {end - start:.3f}') return", "decorator from hail.utils.java import Env import hail as hl from", "unittest import pytest from decorator import decorator from hail.utils.java import", ") def prefix_struct(s, prefix): return hl.struct(**{prefix + k: s[k] for", "flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return func(*args, **kwargs)", "= hl.eval(e) if res != v: raise ValueError(f' actual: {res}\\n", ".annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table())", "hl.eval(e) if res != v: raise ValueError(f' actual: {res}\\n expected:", "x]) elif isinstance(x, dict): return {k: convert_struct_to_dict(v) for k, v", "'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1',", "= os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return", "<gh_stars>0 import os from timeit import default_timer as timer import", "filename) def schema_eq(x, y): x_fds = dict(x) y_fds = dict(y)", "tuple([convert_struct_to_dict(elt) for elt in x]) elif isinstance(x, dict): return {k:", "y): x_fds = dict(x) y_fds = dict(y) return x_fds ==", "def create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32,", "backend\", strict=True) def run_with_cxx_compile(): @decorator def wrapper(func, *args, **kwargs): return", "for k in s}) def create_all_values_table(): all_values = create_all_values() return", "n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values = create_all_values()", "hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar',", "**kwargs): flags = hl._get_flags() prev_lower = flags.get('lower') prev_lower_only = flags.get('lower_only')", "assert_time(f, max_duration): start = timer() x = f() end =", "Spark') return wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason=\"doesn't", "_initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name == 'spark': hl.init(master='local[1]',", "expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator def wrapper(func,", "None def get_dataset(): global _dataset if _dataset is None: _dataset", "prev_lower = flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return", "Env.hc() # force initialization _initialized = True def stopTestHailContext(): pass", "backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name == 'spark': hl.init(master='local[1]', min_block_size=0,", "def skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend @decorator def wrapper(func, *args,", "c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)),", "import decorator from hail.utils.java import Env import hail as hl", ".annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets(): return", "return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values", "force initialization _initialized = True def stopTestHailContext(): pass _test_dir =", "'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def", "dict): return {k: convert_struct_to_dict(v) for k, v in x.items()} else:", "isinstance(x, list): return [convert_struct_to_dict(elt) for elt in x] elif isinstance(x,", "= os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name == 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True)", ".annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values = create_all_values() return (hl.utils.range_matrix_table(3, 2,", "from hail.backend.spark_backend import SparkBackend @decorator def wrapper(func, *args, **kwargs): if", "SparkBackend @decorator def wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return", "def wrapper(func, *args, **kwargs): return return wrapper def assert_evals_to(e, v):", "all_values = create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values,", "def schema_eq(x, y): x_fds = dict(x) y_fds = dict(y) return", "if _dataset is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def", "os.path.join(_test_dir, filename) def doctest_resource(filename): return os.path.join(_doctest_dir, filename) def schema_eq(x, y):", "y_fds = dict(y) return x_fds == y_fds def convert_struct_to_dict(x): if", "def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend import", "v in x._fields.items()} elif isinstance(x, list): return [convert_struct_to_dict(elt) for elt", "for k, v in x._fields.items()} elif isinstance(x, list): return [convert_struct_to_dict(elt)", "return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend @decorator", "import pytest from decorator import decorator from hail.utils.java import Env", "hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f, max_duration): start = timer() x", "= None def get_dataset(): global _dataset if _dataset is None:", "def prefix_struct(s, prefix): return hl.struct(**{prefix + k: s[k] for k", "'entry_')) .cache()) def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from", "{res}\\n expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs),", "hl.struct(**{prefix + k: s[k] for k in s}) def create_all_values_table():", "return hl.struct(**{prefix + k: s[k] for k in s}) def", "wrapper(func, *args, **kwargs): return return wrapper def assert_evals_to(e, v): res", "ValueError(f' actual: {res}\\n expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds =", "**kwargs) else: raise unittest.SkipTest('requires Spark') return wrapper fails_local_backend = pytest.mark.xfail(", "def assert_time(f, max_duration): start = timer() x = f() end", "x_fds = dict(x) y_fds = dict(y) return x_fds == y_fds", "isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs) else: raise unittest.SkipTest('requires Spark') return", "= create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def", "run_with_cxx_compile(): @decorator def wrapper(func, *args, **kwargs): return return wrapper def", "def assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only():", "import LocalBackend _initialized = False def startTestHailContext(): global _initialized if", "create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table():", "{v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def", "in x]) elif isinstance(x, dict): return {k: convert_struct_to_dict(v) for k,", "convert_struct_to_dict(x): if isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v) for k, v", "'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values = create_all_values() return (hl.utils.range_matrix_table(3,", "actual: {res}\\n expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected)", "return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo',", "hail.backend.local_backend import LocalBackend _initialized = False def startTestHailContext(): global _initialized", "dict(y) return x_fds == y_fds def convert_struct_to_dict(x): if isinstance(x, hl.Struct):", "dict(x) y_fds = dict(y) return x_fds == y_fds def convert_struct_to_dict(x):", "f() end = timer() assert (start - end) < max_duration", "prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return func(*args, **kwargs) finally:", "x.items()} else: return x _dataset = None def get_dataset(): global", "@decorator def wrapper(func, *args, **kwargs): flags = hl._get_flags() prev_lower =", "k, v in x.items()} else: return x _dataset = None", "flags = hl._get_flags() prev_lower = flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1',", "isinstance(x, dict): return {k: convert_struct_to_dict(v) for k, v in x.items()}", "lower_only(): @decorator def wrapper(func, *args, **kwargs): flags = hl._get_flags() prev_lower", "x = f() end = timer() assert (start - end)", "hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def prefix_struct(s, prefix): return hl.struct(**{prefix", "= flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return func(*args, **kwargs) finally: hl._set_flags(lower=prev_lower,", "all_values = create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache())", "0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'),", "not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name == 'spark':", "'spark') if backend_name == 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc()", "for elt in x] elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for", "skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend @decorator def wrapper(func, *args, **kwargs):", "def stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR',", "None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f, max_duration): start", "exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator def", "'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def prefix_struct(s,", "wrapper(func, *args, **kwargs): flags = hl._get_flags() prev_lower = flags.get('lower') prev_lower_only", "= True def stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir", ".cache()) def create_all_values_matrix_table(): all_values = create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2)", "_doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return os.path.join(_test_dir, filename) def", "phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def", "_dataset def assert_time(f, max_duration): start = timer() x = f()", "aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']):", "s[k] for k in s}) def create_all_values_table(): all_values = create_all_values()", "in x._fields.items()} elif isinstance(x, list): return [convert_struct_to_dict(elt) for elt in", "create_all_values_matrix_table(): all_values = create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_'))", "= os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return os.path.join(_test_dir, filename) def doctest_resource(filename):", "for elt in x]) elif isinstance(x, dict): return {k: convert_struct_to_dict(v)", "isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for elt in x]) elif isinstance(x,", "schema_eq(x, y): x_fds = dict(x) y_fds = dict(y) return x_fds", "n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache())", "func(*args, **kwargs) else: raise unittest.SkipTest('requires Spark') return wrapper fails_local_backend =", "max_duration): start = timer() x = f() end = timer()", "m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a',", "assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator", ".annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values = create_all_values() return", "print(f'took {end - start:.3f}') return x def create_all_values(): return hl.struct(", "create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)),", "return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_'))", "def startTestHailContext(): global _initialized if not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND',", "'local', reason=\"doesn't yet work on local backend\", strict=True) def run_with_cxx_compile():", "timer() x = f() end = timer() assert (start -", "elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for elt in x]) elif", "v: raise ValueError(f' actual: {res}\\n expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs,", "5)), ) def prefix_struct(s, prefix): return hl.struct(**{prefix + k: s[k]", "wrapper def assert_evals_to(e, v): res = hl.eval(e) if res !=", "strict=True) def run_with_cxx_compile(): @decorator def wrapper(func, *args, **kwargs): return return", "return x_fds == y_fds def convert_struct_to_dict(x): if isinstance(x, hl.Struct): return", "res != v: raise ValueError(f' actual: {res}\\n expected: {v}') def", "True def stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir =", "os.path.join(_doctest_dir, filename) def schema_eq(x, y): x_fds = dict(x) y_fds =", "global _initialized if not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if", "hail.backend.spark_backend import SparkBackend @decorator def wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(),", "doctest_resource(filename): return os.path.join(_doctest_dir, filename) def schema_eq(x, y): x_fds = dict(x)", "33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0, 1),", "timer import unittest import pytest from decorator import decorator from", "else: return x _dataset = None def get_dataset(): global _dataset", "_initialized = False def startTestHailContext(): global _initialized if not _initialized:", "reason=\"doesn't yet work on local backend\", strict=True) def run_with_cxx_compile(): @decorator", "tuple): return tuple([convert_struct_to_dict(elt) for elt in x]) elif isinstance(x, dict):", "res = hl.eval(e) if res != v: raise ValueError(f' actual:", "SparkBackend): return func(*args, **kwargs) else: raise unittest.SkipTest('requires Spark') return wrapper", "= timer() x = f() end = timer() assert (start", "pytest from decorator import decorator from hail.utils.java import Env import", "stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data')", "timer() assert (start - end) < max_duration print(f'took {end -", "mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x'," ]
[ "shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L] self.label_scores = tf.matmul(context_encoded,", "<NAME> \"\"\" import time import tensorflow as tf import numpy", "= tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable( name=\"label_weights\",", "class LabelingModel(Model): \"\"\"Unsupervised Clustering using Discrete-State VAE\"\"\" def __init__(self, batch_size,", "as np from entity_linker.models.base import Model class LabelingModel(Model): \"\"\"Unsupervised Clustering", "# [B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss", "self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses)", "self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name, device_gpu): with", "import numpy as np from entity_linker.models.base import Model class LabelingModel(Model):", "shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded = tf.concat( 1, [context_encoded,", "d: # [B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\")", "[B, L] self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ###", "tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name, device_gpu):", "else: context_encoded = tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights =", "with tf.variable_scope(scope_name) as s, tf.device(device) as d: if mention_embed ==", "stddev=1.0/(100.0))) # [B, L] self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs =", "np from entity_linker.models.base import Model class LabelingModel(Model): \"\"\"Unsupervised Clustering using", "def loss_graph(self, true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name) as s, tf.device(device_gpu)", "logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses", "tf.device(device_gpu) as d: # [B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores,", "word_embed_dim, context_encoded, mention_embed, scope_name, device): self.batch_size = batch_size self.num_labels =", "[B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss =", "tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\") self.entity_labeling_loss = tf.reduce_sum(", "(C) 2020 <NAME> \"\"\" import time import tensorflow as tf", "word_embed_dim with tf.variable_scope(scope_name) as s, tf.device(device) as d: if mention_embed", "Discrete-State VAE\"\"\" def __init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded,", "tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L] self.label_scores", "self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name)", "device_gpu): with tf.variable_scope(scope_name) as s, tf.device(device_gpu) as d: # [B,", "num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name, device): self.batch_size =", "#true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs =", "\"\"\" Modifications copyright (C) 2020 <NAME> \"\"\" import time import", "tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM ENTITIES", "Modifications copyright (C) 2020 <NAME> \"\"\" import time import tensorflow", "= tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings,", "tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size)", "numpy as np from entity_linker.models.base import Model class LabelingModel(Model): \"\"\"Unsupervised", "s, tf.device(device) as d: if mention_embed == None: self.label_weights =", "L] self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT", "TYPES FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings,", "stddev=1.0/(100.0))) else: context_encoded = tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights", "self.batch_size = batch_size self.num_labels = num_labels self.word_embed_dim = word_embed_dim with", "self.num_labels = num_labels self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name) as s,", "= word_embed_dim with tf.variable_scope(scope_name) as s, tf.device(device) as d: if", "tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded = tf.concat(", "self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded", "scope_name, device): self.batch_size = batch_size self.num_labels = num_labels self.word_embed_dim =", "true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name) as s, tf.device(device_gpu) as d:", "targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses =", "tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim,", "tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5)", "### PREDICT TYPES FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores", "None: self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else:", "batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name, device): self.batch_size", "= tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name) as", "def __init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name,", "\"\"\"Unsupervised Clustering using Discrete-State VAE\"\"\" def __init__(self, batch_size, num_labels, context_encoded_dim,", "self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT TYPES", "name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits(", "from entity_linker.models.base import Model class LabelingModel(Model): \"\"\"Unsupervised Clustering using Discrete-State", "= tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores)", "if mention_embed == None: self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels],", "mention_embed == None: self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0,", "as tf import numpy as np from entity_linker.models.base import Model", "name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded = tf.concat( 1,", "tf.device(device) as d: if mention_embed == None: self.label_weights = tf.get_variable(", "self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM ENTITIES #true_entity_embeddings =", "import tensorflow as tf import numpy as np from entity_linker.models.base", "context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name, device): self.batch_size = batch_size", "__init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name, device):", "self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores,", "self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids,", "keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self,", "tf.variable_scope(scope_name) as s, tf.device(device_gpu) as d: # [B, L] self.cross_entropy_losses", "= tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids,", "tf.variable_scope(scope_name) as s, tf.device(device) as d: if mention_embed == None:", "self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B,", "self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM ENTITIES #true_entity_embeddings", "# [B, L] self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores)", "num_labels self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name) as s, tf.device(device) as", "/ tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\") self.entity_labeling_loss =", "context_encoded, mention_embed, scope_name, device): self.batch_size = batch_size self.num_labels = num_labels", "mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0)))", "tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def", "batch_size self.num_labels = num_labels self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name) as", "Clustering using Discrete-State VAE\"\"\" def __init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings,", "as s, tf.device(device) as d: if mention_embed == None: self.label_weights", "= tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded =", "s, tf.device(device_gpu) as d: # [B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits(", "= tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\") self.entity_labeling_loss = tf.reduce_sum( self.enlabel_cross_entropy_losses) /", "copyright (C) 2020 <NAME> \"\"\" import time import tensorflow as", "import time import tensorflow as tf import numpy as np", "2020 <NAME> \"\"\" import time import tensorflow as tf import", "name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L] self.label_scores =", "as d: if mention_embed == None: self.label_weights = tf.get_variable( name=\"label_weights\",", "as s, tf.device(device_gpu) as d: # [B, L] self.cross_entropy_losses =", "= batch_size self.num_labels = num_labels self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name)", "VAE\"\"\" def __init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed,", "ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs", "= tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L]", "true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name, device): self.batch_size = batch_size self.num_labels", "initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded = tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr')", "import Model class LabelingModel(Model): \"\"\"Unsupervised Clustering using Discrete-State VAE\"\"\" def", "FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights)", "time import tensorflow as tf import numpy as np from", "tf import numpy as np from entity_linker.models.base import Model class", "entity_linker.models.base import Model class LabelingModel(Model): \"\"\"Unsupervised Clustering using Discrete-State VAE\"\"\"", "tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\") self.entity_labeling_loss = tf.reduce_sum( self.enlabel_cross_entropy_losses) / tf.to_float(self.batch_size)", "== None: self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0)))", "num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L] self.label_scores = tf.matmul(context_encoded, self.label_weights)", "<filename>src/entity_linker/models/figer_model/labeling_model.py \"\"\" Modifications copyright (C) 2020 <NAME> \"\"\" import time", "L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum(", "with tf.variable_scope(scope_name) as s, tf.device(device_gpu) as d: # [B, L]", "self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\") self.entity_labeling_loss = tf.reduce_sum( self.enlabel_cross_entropy_losses)", "initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L] self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs", "\"\"\" import time import tensorflow as tf import numpy as", "= tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name,", "num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded = tf.concat( 1, [context_encoded, mention_embed],", "LabelingModel(Model): \"\"\"Unsupervised Clustering using Discrete-State VAE\"\"\" def __init__(self, batch_size, num_labels,", "as d: # [B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids,", "using Discrete-State VAE\"\"\" def __init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim,", "PREDICT TYPES FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores =", "1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels],", "mention_embed, scope_name, device): self.batch_size = batch_size self.num_labels = num_labels self.word_embed_dim", "self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\") self.entity_labeling_loss", "tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name) as s,", "= tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name=\"labeling_loss\") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) /", "scope_name, device_gpu): with tf.variable_scope(scope_name) as s, tf.device(device_gpu) as d: #", "loss_graph(self, true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name) as s, tf.device(device_gpu) as", "device): self.batch_size = batch_size self.num_labels = num_labels self.word_embed_dim = word_embed_dim", "[context_encoded, mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0,", "tensorflow as tf import numpy as np from entity_linker.models.base import", "context_encoded = tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable(", "= num_labels self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name) as s, tf.device(device)", "d: if mention_embed == None: self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim,", "tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name=\"entity_labeling_loss\")", "Model class LabelingModel(Model): \"\"\"Unsupervised Clustering using Discrete-State VAE\"\"\" def __init__(self,", "name='con_ment_repr') self.label_weights = tf.get_variable( name=\"label_weights\", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) #", "self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name) as s, tf.device(device) as d:", "= tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM" ]
[ "2: print \"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1) mol = pmd.load_file(sys.argv[1]) crds", "as np from scipy.spatial import distance if len(sys.argv) < 2:", "np from scipy.spatial import distance if len(sys.argv) < 2: print", "len(sys.argv) < 2: print \"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1) mol =", "as pmd import numpy as np from scipy.spatial import distance", "<gh_stars>1-10 #!/usr/bin/env python import sys import parmed as pmd import", "import parmed as pmd import numpy as np from scipy.spatial", "print \"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1) mol = pmd.load_file(sys.argv[1]) crds =", "numpy as np from scipy.spatial import distance if len(sys.argv) <", "from scipy.spatial import distance if len(sys.argv) < 2: print \"Usage:", "pmd import numpy as np from scipy.spatial import distance if", "exit(1) mol = pmd.load_file(sys.argv[1]) crds = mol.coordinates dist = distance.cdist(crds,", "molecular_diameter.py <mymolecule.mol2>\" exit(1) mol = pmd.load_file(sys.argv[1]) crds = mol.coordinates dist", "pmd.load_file(sys.argv[1]) crds = mol.coordinates dist = distance.cdist(crds, crds, 'euclidean') print", "python import sys import parmed as pmd import numpy as", "distance if len(sys.argv) < 2: print \"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1)", "sys import parmed as pmd import numpy as np from", "\"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1) mol = pmd.load_file(sys.argv[1]) crds = mol.coordinates", "= mol.coordinates dist = distance.cdist(crds, crds, 'euclidean') print np.max(dist) exit(0)", "import numpy as np from scipy.spatial import distance if len(sys.argv)", "parmed as pmd import numpy as np from scipy.spatial import", "mol = pmd.load_file(sys.argv[1]) crds = mol.coordinates dist = distance.cdist(crds, crds,", "#!/usr/bin/env python import sys import parmed as pmd import numpy", "<mymolecule.mol2>\" exit(1) mol = pmd.load_file(sys.argv[1]) crds = mol.coordinates dist =", "= pmd.load_file(sys.argv[1]) crds = mol.coordinates dist = distance.cdist(crds, crds, 'euclidean')", "crds = mol.coordinates dist = distance.cdist(crds, crds, 'euclidean') print np.max(dist)", "< 2: print \"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1) mol = pmd.load_file(sys.argv[1])", "import sys import parmed as pmd import numpy as np", "if len(sys.argv) < 2: print \"Usage: molecular_diameter.py <mymolecule.mol2>\" exit(1) mol", "scipy.spatial import distance if len(sys.argv) < 2: print \"Usage: molecular_diameter.py", "import distance if len(sys.argv) < 2: print \"Usage: molecular_diameter.py <mymolecule.mol2>\"" ]
[ "# # Evaluate the model # result, model_outputs, wrong_predictions =", "ClassificationModel prefix = \"data/\" train_df = pd.read_csv(prefix + \"train.csv\", header=None)", "\"roberta-base\" elif model_type == \"distilbert\": model_name = \"distilbert-base-cased\" elif model_type", "\"bert\": model_name = \"bert-base-cased\" elif model_type == \"roberta\": model_name =", "{\"text\": train_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": train_df[0]} ) print(train_df.head()) eval_df", "== \"distilbert\": model_name = \"distilbert-base-cased\" elif model_type == \"distilroberta\": model_type", "== \"electra-small\": model_type = \"electra\" model_name = \"google/electra-small-discriminator\" elif model_type", "\"early_stopping_metric\": \"mcc\", # \"n_gpu\": 2, # \"manual_seed\": 4, # \"use_multiprocessing\":", "elif model_type == \"xlnet\": model_name = \"xlnet-base-cased\" train_args = {", "= \"xlnet-base-cased\" train_args = { \"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"use_cached_eval_features\":", "{\"name\": model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\": False, # \"use_early_stopping\": True, #", "model_name = \"google/electra-base-discriminator\" elif model_type == \"electra-small\": model_type = \"electra\"", "= \"google/electra-base-discriminator\" elif model_type == \"electra-small\": model_type = \"electra\" model_name", "\"n_gpu\": 2, # \"manual_seed\": 4, # \"use_multiprocessing\": False, \"train_batch_size\": 128,", "\"xlnet-base-cased\" train_args = { \"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"use_cached_eval_features\": True,", "print(train_df.head()) eval_df = pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\":", "import sys import pandas as pd from simpletransformers.classification import ClassificationModel", "2, # \"manual_seed\": 4, # \"use_multiprocessing\": False, \"train_batch_size\": 128, \"eval_batch_size\":", "eval_df = pd.read_csv(prefix + \"test.csv\", header=None) eval_df.head() train_df[0] = (train_df[0]", "prefix = \"data/\" train_df = pd.read_csv(prefix + \"train.csv\", header=None) train_df.head()", "{\"text\": eval_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": eval_df[0]} ) print(eval_df.head()) model_type", "\"eval_batch_size\": 64, # \"config\": { # \"output_hidden_states\": True # }", "\"manual_seed\": 4, # \"use_multiprocessing\": False, \"train_batch_size\": 128, \"eval_batch_size\": 64, #", "Create a ClassificationModel model = ClassificationModel(model_type, model_name, args=train_args) # Train", "True # } } if model_type == \"xlnet\": train_args[\"train_batch_size\"] =", "model_type == \"xlnet\": model_name = \"xlnet-base-cased\" train_args = { \"reprocess_input_data\":", "f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\": 128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\":", "= \"distilbert-base-cased\" elif model_type == \"distilroberta\": model_type = \"roberta\" model_name", "elif model_type == \"roberta\": model_name = \"roberta-base\" elif model_type ==", "\"wandb_project\": \"Classification Model Comparison\", \"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\":", "elif model_type == \"distilbert\": model_name = \"distilbert-base-cased\" elif model_type ==", "False, \"save_eval_checkpoints\": False, # \"use_early_stopping\": True, # \"early_stopping_metric\": \"mcc\", #", "\"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification Model Comparison\", \"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\":", "\"electra-small\": model_type = \"electra\" model_name = \"google/electra-small-discriminator\" elif model_type ==", "model_type == \"distilroberta\": model_type = \"roberta\" model_name = \"distilroberta-base\" elif", "model_name = \"xlnet-base-cased\" train_args = { \"reprocess_input_data\": True, \"overwrite_output_dir\": True,", "model_name = \"distilroberta-base\" elif model_type == \"electra-base\": model_type = \"electra\"", "\"config\": { # \"output_hidden_states\": True # } } if model_type", "model_type == \"bert\": model_name = \"bert-base-cased\" elif model_type == \"roberta\":", "pandas as pd from simpletransformers.classification import ClassificationModel prefix = \"data/\"", "\"bert-base-cased\" elif model_type == \"roberta\": model_name = \"roberta-base\" elif model_type", "# \"manual_seed\": 4, # \"use_multiprocessing\": False, \"train_batch_size\": 128, \"eval_batch_size\": 64,", "= \"distilroberta-base\" elif model_type == \"electra-base\": model_type = \"electra\" model_name", "# \"early_stopping_metric\": \"mcc\", # \"n_gpu\": 2, # \"manual_seed\": 4, #", "\"electra-base\": model_type = \"electra\" model_name = \"google/electra-base-discriminator\" elif model_type ==", "model_name, args=train_args) # Train the model model.train_model(train_df, eval_df=eval_df) # #", "pd.read_csv(prefix + \"test.csv\", header=None) eval_df.head() train_df[0] = (train_df[0] == 2).astype(int)", "2).astype(int) train_df = pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\":", "simpletransformers.classification import ClassificationModel prefix = \"data/\" train_df = pd.read_csv(prefix +", "elif model_type == \"electra-base\": model_type = \"electra\" model_name = \"google/electra-base-discriminator\"", "\"distilbert\": model_name = \"distilbert-base-cased\" elif model_type == \"distilroberta\": model_type =", "model_type == \"electra-small\": model_type = \"electra\" model_name = \"google/electra-small-discriminator\" elif", "= \"roberta\" model_name = \"distilroberta-base\" elif model_type == \"electra-base\": model_type", "\"google/electra-base-discriminator\" elif model_type == \"electra-small\": model_type = \"electra\" model_name =", "eval_df[0] = (eval_df[0] == 2).astype(int) train_df = pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\",", "\" \", regex=True), \"labels\": eval_df[0]} ) print(eval_df.head()) model_type = sys.argv[1]", "pd.read_csv(prefix + \"train.csv\", header=None) train_df.head() eval_df = pd.read_csv(prefix + \"test.csv\",", "# \"config\": { # \"output_hidden_states\": True # } } if", "train_df[0] = (train_df[0] == 2).astype(int) eval_df[0] = (eval_df[0] == 2).astype(int)", "model_type = \"roberta\" model_name = \"distilroberta-base\" elif model_type == \"electra-base\":", "import pandas as pd from simpletransformers.classification import ClassificationModel prefix =", "ClassificationModel(model_type, model_name, args=train_args) # Train the model model.train_model(train_df, eval_df=eval_df) #", "+ \"train.csv\", header=None) train_df.head() eval_df = pd.read_csv(prefix + \"test.csv\", header=None)", "== \"electra-base\": model_type = \"electra\" model_name = \"google/electra-base-discriminator\" elif model_type", "elif model_type == \"electra-small\": model_type = \"electra\" model_name = \"google/electra-small-discriminator\"", "== \"xlnet\": model_name = \"xlnet-base-cased\" train_args = { \"reprocess_input_data\": True,", "eval_df.head() train_df[0] = (train_df[0] == 2).astype(int) eval_df[0] = (eval_df[0] ==", "== 2).astype(int) train_df = pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \" \", regex=True),", "+ \"test.csv\", header=None) eval_df.head() train_df[0] = (train_df[0] == 2).astype(int) eval_df[0]", "# \"output_hidden_states\": True # } } if model_type == \"xlnet\":", "eval_df=eval_df) # # # Evaluate the model # result, model_outputs,", "= \"bert-base-cased\" elif model_type == \"roberta\": model_name = \"roberta-base\" elif", "\"distilroberta-base\" elif model_type == \"electra-base\": model_type = \"electra\" model_name =", "\"train_batch_size\": 128, \"eval_batch_size\": 64, # \"config\": { # \"output_hidden_states\": True", "\"output_hidden_states\": True # } } if model_type == \"xlnet\": train_args[\"train_batch_size\"]", "\"mcc\", # \"n_gpu\": 2, # \"manual_seed\": 4, # \"use_multiprocessing\": False,", "= (train_df[0] == 2).astype(int) eval_df[0] = (eval_df[0] == 2).astype(int) train_df", "header=None) train_df.head() eval_df = pd.read_csv(prefix + \"test.csv\", header=None) eval_df.head() train_df[0]", "\"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification Model Comparison\", \"wandb_kwargs\": {\"name\":", "3, \"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification Model Comparison\", \"wandb_kwargs\": {\"name\": model_name},", "train_args[\"gradient_accumulation_steps\"] = 2 # Create a ClassificationModel model = ClassificationModel(model_type,", "= 64 train_args[\"gradient_accumulation_steps\"] = 2 # Create a ClassificationModel model", "train_args = { \"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"use_cached_eval_features\": True, \"output_dir\":", "128, \"eval_batch_size\": 64, # \"config\": { # \"output_hidden_states\": True #", "= 2 # Create a ClassificationModel model = ClassificationModel(model_type, model_name,", "\"Classification Model Comparison\", \"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\": False,", "model_type == \"electra-base\": model_type = \"electra\" model_name = \"google/electra-base-discriminator\" elif", "64, # \"config\": { # \"output_hidden_states\": True # } }", "f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\": 128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000, \"wandb_project\":", "args=train_args) # Train the model model.train_model(train_df, eval_df=eval_df) # # #", "\"test.csv\", header=None) eval_df.head() train_df[0] = (train_df[0] == 2).astype(int) eval_df[0] =", "== \"xlnet\": train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"] = 2 # Create", "\"train.csv\", header=None) train_df.head() eval_df = pd.read_csv(prefix + \"test.csv\", header=None) eval_df.head()", "eval_df[0]} ) print(eval_df.head()) model_type = sys.argv[1] if model_type == \"bert\":", "Model Comparison\", \"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\": False, #", "<reponame>liorshk/simpletransformers<gh_stars>1000+ import sys import pandas as pd from simpletransformers.classification import", "train_df = pd.read_csv(prefix + \"train.csv\", header=None) train_df.head() eval_df = pd.read_csv(prefix", "train_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": train_df[0]} ) print(train_df.head()) eval_df =", "\"save_model_every_epoch\": False, \"save_eval_checkpoints\": False, # \"use_early_stopping\": True, # \"early_stopping_metric\": \"mcc\",", ") print(train_df.head()) eval_df = pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \" \", regex=True),", "= \"electra\" model_name = \"google/electra-small-discriminator\" elif model_type == \"xlnet\": model_name", "if model_type == \"bert\": model_name = \"bert-base-cased\" elif model_type ==", "\", regex=True), \"labels\": eval_df[0]} ) print(eval_df.head()) model_type = sys.argv[1] if", "= pd.read_csv(prefix + \"train.csv\", header=None) train_df.head() eval_df = pd.read_csv(prefix +", "= \"google/electra-small-discriminator\" elif model_type == \"xlnet\": model_name = \"xlnet-base-cased\" train_args", "\", regex=True), \"labels\": train_df[0]} ) print(train_df.head()) eval_df = pd.DataFrame( {\"text\":", "model model.train_model(train_df, eval_df=eval_df) # # # Evaluate the model #", "4, # \"use_multiprocessing\": False, \"train_batch_size\": 128, \"eval_batch_size\": 64, # \"config\":", "model_type == \"xlnet\": train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"] = 2 #", "model = ClassificationModel(model_type, model_name, args=train_args) # Train the model model.train_model(train_df,", "{ # \"output_hidden_states\": True # } } if model_type ==", "\"data/\" train_df = pd.read_csv(prefix + \"train.csv\", header=None) train_df.head() eval_df =", "header=None) eval_df.head() train_df[0] = (train_df[0] == 2).astype(int) eval_df[0] = (eval_df[0]", "model_type == \"distilbert\": model_name = \"distilbert-base-cased\" elif model_type == \"distilroberta\":", "True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\": 128, \"num_train_epochs\":", "\"max_seq_length\": 128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification Model Comparison\",", "regex=True), \"labels\": eval_df[0]} ) print(eval_df.head()) model_type = sys.argv[1] if model_type", "model_name = \"distilbert-base-cased\" elif model_type == \"distilroberta\": model_type = \"roberta\"", "import ClassificationModel prefix = \"data/\" train_df = pd.read_csv(prefix + \"train.csv\",", "model_type = sys.argv[1] if model_type == \"bert\": model_name = \"bert-base-cased\"", "model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\": False, # \"use_early_stopping\": True, # \"early_stopping_metric\":", "\"save_eval_checkpoints\": False, # \"use_early_stopping\": True, # \"early_stopping_metric\": \"mcc\", # \"n_gpu\":", "# \"use_multiprocessing\": False, \"train_batch_size\": 128, \"eval_batch_size\": 64, # \"config\": {", "# # # Evaluate the model # result, model_outputs, wrong_predictions", "the model model.train_model(train_df, eval_df=eval_df) # # # Evaluate the model", "= (eval_df[0] == 2).astype(int) train_df = pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \"", "= sys.argv[1] if model_type == \"bert\": model_name = \"bert-base-cased\" elif", "== 2).astype(int) eval_df[0] = (eval_df[0] == 2).astype(int) train_df = pd.DataFrame(", "ClassificationModel model = ClassificationModel(model_type, model_name, args=train_args) # Train the model", "elif model_type == \"distilroberta\": model_type = \"roberta\" model_name = \"distilroberta-base\"", ") print(eval_df.head()) model_type = sys.argv[1] if model_type == \"bert\": model_name", "model_type = \"electra\" model_name = \"google/electra-small-discriminator\" elif model_type == \"xlnet\":", "128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification Model Comparison\", \"wandb_kwargs\":", "\"electra\" model_name = \"google/electra-base-discriminator\" elif model_type == \"electra-small\": model_type =", "= pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": train_df[0]} )", "\"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\": 128,", "(train_df[0] == 2).astype(int) eval_df[0] = (eval_df[0] == 2).astype(int) train_df =", "\"labels\": eval_df[0]} ) print(eval_df.head()) model_type = sys.argv[1] if model_type ==", "# } } if model_type == \"xlnet\": train_args[\"train_batch_size\"] = 64", "\"use_early_stopping\": True, # \"early_stopping_metric\": \"mcc\", # \"n_gpu\": 2, # \"manual_seed\":", "Train the model model.train_model(train_df, eval_df=eval_df) # # # Evaluate the", "== \"bert\": model_name = \"bert-base-cased\" elif model_type == \"roberta\": model_name", "model_name = \"roberta-base\" elif model_type == \"distilbert\": model_name = \"distilbert-base-cased\"", "model_name = \"google/electra-small-discriminator\" elif model_type == \"xlnet\": model_name = \"xlnet-base-cased\"", "True, \"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\":", "pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": train_df[0]} ) print(train_df.head())", "if model_type == \"xlnet\": train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"] = 2", "== \"distilroberta\": model_type = \"roberta\" model_name = \"distilroberta-base\" elif model_type", "\"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\",", "== \"roberta\": model_name = \"roberta-base\" elif model_type == \"distilbert\": model_name", "print(eval_df.head()) model_type = sys.argv[1] if model_type == \"bert\": model_name =", "2 # Create a ClassificationModel model = ClassificationModel(model_type, model_name, args=train_args)", "= \"data/\" train_df = pd.read_csv(prefix + \"train.csv\", header=None) train_df.head() eval_df", "\"roberta\": model_name = \"roberta-base\" elif model_type == \"distilbert\": model_name =", "regex=True), \"labels\": train_df[0]} ) print(train_df.head()) eval_df = pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\",", "\"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\": 128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000,", "64 train_args[\"gradient_accumulation_steps\"] = 2 # Create a ClassificationModel model =", "} if model_type == \"xlnet\": train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"] =", "Comparison\", \"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\": False, # \"use_early_stopping\":", "# Train the model model.train_model(train_df, eval_df=eval_df) # # # Evaluate", "= \"electra\" model_name = \"google/electra-base-discriminator\" elif model_type == \"electra-small\": model_type", "model.train_model(train_df, eval_df=eval_df) # # # Evaluate the model # result,", "\"xlnet\": model_name = \"xlnet-base-cased\" train_args = { \"reprocess_input_data\": True, \"overwrite_output_dir\":", "\"xlnet\": train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"] = 2 # Create a", "eval_df = pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": eval_df[0]}", "a ClassificationModel model = ClassificationModel(model_type, model_name, args=train_args) # Train the", "\"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\": False, \"save_eval_checkpoints\": False, # \"use_early_stopping\": True,", "# \"n_gpu\": 2, # \"manual_seed\": 4, # \"use_multiprocessing\": False, \"train_batch_size\":", "True, \"max_seq_length\": 128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification Model", "(eval_df[0] == 2).astype(int) train_df = pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \" \",", "\"roberta\" model_name = \"distilroberta-base\" elif model_type == \"electra-base\": model_type =", "sys import pandas as pd from simpletransformers.classification import ClassificationModel prefix", "2).astype(int) eval_df[0] = (eval_df[0] == 2).astype(int) train_df = pd.DataFrame( {\"text\":", "\" \", regex=True), \"labels\": train_df[0]} ) print(train_df.head()) eval_df = pd.DataFrame(", "sys.argv[1] if model_type == \"bert\": model_name = \"bert-base-cased\" elif model_type", "\"distilbert-base-cased\" elif model_type == \"distilroberta\": model_type = \"roberta\" model_name =", "} } if model_type == \"xlnet\": train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"]", "False, \"train_batch_size\": 128, \"eval_batch_size\": 64, # \"config\": { # \"output_hidden_states\":", "train_df[0]} ) print(train_df.head()) eval_df = pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \" \",", "model_name = \"bert-base-cased\" elif model_type == \"roberta\": model_name = \"roberta-base\"", "= { \"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\",", "model_type = \"electra\" model_name = \"google/electra-base-discriminator\" elif model_type == \"electra-small\":", "\"overwrite_output_dir\": True, \"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True,", "= pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": eval_df[0]} )", "= ClassificationModel(model_type, model_name, args=train_args) # Train the model model.train_model(train_df, eval_df=eval_df)", "= \"roberta-base\" elif model_type == \"distilbert\": model_name = \"distilbert-base-cased\" elif", "train_df = pd.DataFrame( {\"text\": train_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": train_df[0]}", "\"use_multiprocessing\": False, \"train_batch_size\": 128, \"eval_batch_size\": 64, # \"config\": { #", "pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": eval_df[0]} ) print(eval_df.head())", "# Create a ClassificationModel model = ClassificationModel(model_type, model_name, args=train_args) #", "as pd from simpletransformers.classification import ClassificationModel prefix = \"data/\" train_df", "\"labels\": train_df[0]} ) print(train_df.head()) eval_df = pd.DataFrame( {\"text\": eval_df[1].replace(r\"\\n\", \"", "{ \"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\":", "True, \"overwrite_output_dir\": True, \"use_cached_eval_features\": True, \"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\":", "\"output_dir\": f\"outputs/{model_type}\", \"best_model_dir\": f\"outputs/{model_type}/best_model\", \"evaluate_during_training\": True, \"max_seq_length\": 128, \"num_train_epochs\": 3,", "\"distilroberta\": model_type = \"roberta\" model_name = \"distilroberta-base\" elif model_type ==", "model_type == \"roberta\": model_name = \"roberta-base\" elif model_type == \"distilbert\":", "from simpletransformers.classification import ClassificationModel prefix = \"data/\" train_df = pd.read_csv(prefix", "pd from simpletransformers.classification import ClassificationModel prefix = \"data/\" train_df =", "eval_df[1].replace(r\"\\n\", \" \", regex=True), \"labels\": eval_df[0]} ) print(eval_df.head()) model_type =", "train_df.head() eval_df = pd.read_csv(prefix + \"test.csv\", header=None) eval_df.head() train_df[0] =", "= pd.read_csv(prefix + \"test.csv\", header=None) eval_df.head() train_df[0] = (train_df[0] ==", "1000, \"wandb_project\": \"Classification Model Comparison\", \"wandb_kwargs\": {\"name\": model_name}, \"save_model_every_epoch\": False,", "# \"use_early_stopping\": True, # \"early_stopping_metric\": \"mcc\", # \"n_gpu\": 2, #", "train_args[\"train_batch_size\"] = 64 train_args[\"gradient_accumulation_steps\"] = 2 # Create a ClassificationModel", "\"evaluate_during_training\": True, \"max_seq_length\": 128, \"num_train_epochs\": 3, \"evaluate_during_training_steps\": 1000, \"wandb_project\": \"Classification", "True, # \"early_stopping_metric\": \"mcc\", # \"n_gpu\": 2, # \"manual_seed\": 4,", "# Evaluate the model # result, model_outputs, wrong_predictions = model.eval_model(eval_df)", "\"google/electra-small-discriminator\" elif model_type == \"xlnet\": model_name = \"xlnet-base-cased\" train_args =", "\"electra\" model_name = \"google/electra-small-discriminator\" elif model_type == \"xlnet\": model_name =", "False, # \"use_early_stopping\": True, # \"early_stopping_metric\": \"mcc\", # \"n_gpu\": 2," ]
[ "as file: for line in file.readlines(): line = line.split(delimiter) v1", "with open(path) as file: for line in file.readlines(): line =", "graph.add_edge(v1, v2, weight=w) return graph def load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph", "graph.add_node(v1) graph.add_node(v2) w = float(line[2]) p = float(line[3]) if (self_loop", "as file: for line in file.readlines(): w = 1.0 line", "if not os.path.isfile(path): print(\"Error: file \" + path + \"", "graph.add_node(v2) w = float(line[2]) p = float(line[3]) if (self_loop and", "p = float(line[3]) if (self_loop and v1 == v2) or", "v1 == v2) or (v1 != v2): graph.add_edge(v1, v2, weight=w)", "weighted=False, delimiter='\\t', self_loop=False): graph = nx.Graph() if not os.path.isfile(path): print(\"Error:", "file.readlines(): w = 1.0 line = line.split(delimiter) v1 = int(line[0])", "v1 == v2) or (v1 != v2): graph.add_edge(v1, v2, weight=w,", "for line in file.readlines(): w = 1.0 line = line.split(delimiter)", "!= v2): graph.add_edge(v1, v2, weight=w) return graph def load_graph_uncertain(path, delimiter='\\t',", "self_loop=False): graph = nx.Graph() if not os.path.isfile(path): print(\"Error: file \"", "weight=w) return graph def load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph = nx.Graph()", "exit(-1) with open(path) as file: for line in file.readlines(): line", "== v2) or (v1 != v2): graph.add_edge(v1, v2, weight=w, prob=p)", "1.0 line = line.split(delimiter) v1 = int(line[0]) v2 = int(line[1])", "graph.add_node(v2) if weighted: w = float(line[2]) if (self_loop and v1", "w = float(line[2]) p = float(line[3]) if (self_loop and v1", "not found!\") exit(-1) with open(path) as file: for line in", "nx import os.path def load_graph(path, weighted=False, delimiter='\\t', self_loop=False): graph =", "= int(line[1]) graph.add_node(v1) graph.add_node(v2) w = float(line[2]) p = float(line[3])", "= int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) if weighted: w", "v2): graph.add_edge(v1, v2, weight=w) return graph def load_graph_uncertain(path, delimiter='\\t', self_loop=False):", "exit(-1) with open(path) as file: for line in file.readlines(): w", "\" + path + \" not found!\") exit(-1) with open(path)", "for line in file.readlines(): line = line.split(delimiter) v1 = int(line[0])", "= float(line[2]) if (self_loop and v1 == v2) or (v1", "open(path) as file: for line in file.readlines(): w = 1.0", "v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) if weighted: w = float(line[2])", "file: for line in file.readlines(): w = 1.0 line =", "int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) w = float(line[2]) p", "load_graph(path, weighted=False, delimiter='\\t', self_loop=False): graph = nx.Graph() if not os.path.isfile(path):", "v2) or (v1 != v2): graph.add_edge(v1, v2, weight=w, prob=p) return", "as nx import os.path def load_graph(path, weighted=False, delimiter='\\t', self_loop=False): graph", "os.path.isfile(path): print(\"Error: file \" + path + \" not found!\")", "and v1 == v2) or (v1 != v2): graph.add_edge(v1, v2,", "v2) or (v1 != v2): graph.add_edge(v1, v2, weight=w) return graph", "float(line[2]) p = float(line[3]) if (self_loop and v1 == v2)", "v1 = int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) if weighted:", "= float(line[2]) p = float(line[3]) if (self_loop and v1 ==", "\" not found!\") exit(-1) with open(path) as file: for line", "or (v1 != v2): graph.add_edge(v1, v2, weight=w) return graph def", "int(line[1]) graph.add_node(v1) graph.add_node(v2) if weighted: w = float(line[2]) if (self_loop", "= 1.0 line = line.split(delimiter) v1 = int(line[0]) v2 =", "== v2) or (v1 != v2): graph.add_edge(v1, v2, weight=w) return", "with open(path) as file: for line in file.readlines(): w =", "or (v1 != v2): graph.add_edge(v1, v2, weight=w, prob=p) return graph", "graph def load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph = nx.Graph() if not", "import os.path def load_graph(path, weighted=False, delimiter='\\t', self_loop=False): graph = nx.Graph()", "(v1 != v2): graph.add_edge(v1, v2, weight=w) return graph def load_graph_uncertain(path,", "v2, weight=w) return graph def load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph =", "if (self_loop and v1 == v2) or (v1 != v2):", "= nx.Graph() if not os.path.isfile(path): print(\"Error: file \" + path", "int(line[1]) graph.add_node(v1) graph.add_node(v2) w = float(line[2]) p = float(line[3]) if", "graph = nx.Graph() if not os.path.isfile(path): print(\"Error: file \" +", "import networkx as nx import os.path def load_graph(path, weighted=False, delimiter='\\t',", "found!\") exit(-1) with open(path) as file: for line in file.readlines():", "v1 = int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) w =", "v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) w = float(line[2]) p =", "load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph = nx.Graph() if not os.path.isfile(path): print(\"Error:", "<reponame>mahdi-zafarmand/SNA import networkx as nx import os.path def load_graph(path, weighted=False,", "file \" + path + \" not found!\") exit(-1) with", "file: for line in file.readlines(): line = line.split(delimiter) v1 =", "not os.path.isfile(path): print(\"Error: file \" + path + \" not", "line in file.readlines(): w = 1.0 line = line.split(delimiter) v1", "delimiter='\\t', self_loop=False): graph = nx.Graph() if not os.path.isfile(path): print(\"Error: file", "w = 1.0 line = line.split(delimiter) v1 = int(line[0]) v2", "line.split(delimiter) v1 = int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) if", "path + \" not found!\") exit(-1) with open(path) as file:", "= line.split(delimiter) v1 = int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2)", "= float(line[3]) if (self_loop and v1 == v2) or (v1", "float(line[2]) if (self_loop and v1 == v2) or (v1 !=", "line = line.split(delimiter) v1 = int(line[0]) v2 = int(line[1]) graph.add_node(v1)", "line in file.readlines(): line = line.split(delimiter) v1 = int(line[0]) v2", "networkx as nx import os.path def load_graph(path, weighted=False, delimiter='\\t', self_loop=False):", "def load_graph(path, weighted=False, delimiter='\\t', self_loop=False): graph = nx.Graph() if not", "+ path + \" not found!\") exit(-1) with open(path) as", "line.split(delimiter) v1 = int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) w", "os.path def load_graph(path, weighted=False, delimiter='\\t', self_loop=False): graph = nx.Graph() if", "if weighted: w = float(line[2]) if (self_loop and v1 ==", "float(line[3]) if (self_loop and v1 == v2) or (v1 !=", "+ \" not found!\") exit(-1) with open(path) as file: for", "in file.readlines(): w = 1.0 line = line.split(delimiter) v1 =", "= int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) w = float(line[2])", "graph.add_node(v1) graph.add_node(v2) if weighted: w = float(line[2]) if (self_loop and", "in file.readlines(): line = line.split(delimiter) v1 = int(line[0]) v2 =", "weighted: w = float(line[2]) if (self_loop and v1 == v2)", "print(\"Error: file \" + path + \" not found!\") exit(-1)", "int(line[0]) v2 = int(line[1]) graph.add_node(v1) graph.add_node(v2) if weighted: w =", "= int(line[1]) graph.add_node(v1) graph.add_node(v2) if weighted: w = float(line[2]) if", "return graph def load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph = nx.Graph() if", "nx.Graph() if not os.path.isfile(path): print(\"Error: file \" + path +", "w = float(line[2]) if (self_loop and v1 == v2) or", "def load_graph_uncertain(path, delimiter='\\t', self_loop=False): graph = nx.Graph() if not os.path.isfile(path):", "open(path) as file: for line in file.readlines(): line = line.split(delimiter)", "file.readlines(): line = line.split(delimiter) v1 = int(line[0]) v2 = int(line[1])", "(self_loop and v1 == v2) or (v1 != v2): graph.add_edge(v1," ]
[ "file previously generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature", ") # Basic fields date = models.DateField( blank=True, editable=False, null=True,", "signature_id - Signature ID - Every time a key is", "sign something it will generate a unique signature ID. No", "Meta: verbose_name = _('Document version detached signature') verbose_name_plural = _('Document", "# Not signed logger.debug( 'detached signature verification error; %s', exception", "exception: # Not signed logger.debug( 'embedded signature verification error; %s',", "models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date signed') ) key_id = models.CharField(", "**kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\" Fields: * key_id -", "import reverse from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy", "self.document_version.open(raw=raw) as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object ) except", "locate a key in the key servers: http://pgp.mit.edu * signature_id", "signature verification error; %s', exception ) else: self.signature_file.seek(0) self.date =", "to sign the document.'), max_length=40, verbose_name=_('Key ID') ) # With", "signature') verbose_name_plural = _('Document version detached signatures') def __str__(self): return", "django.db import models from django.urls import reverse from django.utils.encoding import", "return self.signature_id or '{} - {}'.format(self.date, self.key_id) def get_absolute_url(self): return", "embedded signature') if self.pk: raw = True else: raw =", "ID. The Key ID is also used to locate a", "signature') if self.pk: raw = True else: raw = False", "signature_file = models.FileField( blank=True, help_text=_( 'Signature file previously generated.' ),", "same Key ID. The Key ID is also used to", "self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class", "# With proper key signature_id = models.CharField( blank=True, editable=False, null=True,", "from mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models import Key from mayan.apps.documents.models", "detached signatures') def __str__(self): return '{}-{}'.format(self.document_version, _('signature')) def delete(self, *args,", "signed') ) key_id = models.CharField( help_text=_('ID of the key that", "is also used to locate a key in the key", "version embedded signature') verbose_name_plural = _('Document version embedded signatures') def", "With proper key signature_id = models.CharField( blank=True, editable=False, null=True, max_length=64,", "for embedded signature') if self.pk: raw = True else: raw", "related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') ) # Basic fields date =", "self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file =", "if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def save(self, *args, **kwargs):", "verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs)", "django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ from", "objects = InheritanceManager() class Meta: ordering = ('pk',) verbose_name =", "Fields: * key_id - Key Identifier - This is what", "'signature_file') class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class Meta: verbose_name =", "file') ) objects = DetachedSignatureManager() class Meta: verbose_name = _('Document", "DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True, help_text=_( 'Signature file previously generated.'", "get_signature_type_display(self): if self.is_detached: return _('Detached') else: return _('Embedded') @property def", "key is used to sign something it will generate a", "Not signed logger.debug( 'embedded signature verification error; %s', exception )", "exception ) else: self.signature_file.seek(0) self.date = verify_result.date self.key_id = verify_result.key_id", "Not two keys in the world have the same Key", "except VerificationError as exception: # Not signed logger.debug( 'embedded signature", "super(DetachedSignature, self).delete(*args, **kwargs) def save(self, *args, **kwargs): with self.document_version.open() as", "class SignatureBaseModel(models.Model): \"\"\" Fields: * key_id - Key Identifier -", "django.urls import reverse from django.utils.encoding import force_text from django.utils.translation import", "= verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint =", "*args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def save(self,", "from django.urls import reverse from django.utils.encoding import force_text from django.utils.translation", "servers: http://pgp.mit.edu * signature_id - Signature ID - Every time", "VerificationError from mayan.apps.django_gpg.models import Key from mayan.apps.documents.models import DocumentVersion from", "'embedded signature verification error; %s', exception ) else: self.date =", "'{}-{}'.format(self.document_version, _('signature')) def delete(self, *args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature,", "= EmbeddedSignatureManager() class Meta: verbose_name = _('Document version embedded signature')", "null=True, max_length=40, verbose_name=_('Public key fingerprint') ) objects = InheritanceManager() class", "file_object: try: verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except VerificationError", "def save(self, *args, **kwargs): logger.debug(msg='checking for embedded signature') if self.pk:", "reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def get_key_id(self): if self.public_key_fingerprint: return", "models.CharField( help_text=_('ID of the key that will be used to", "signature_id = models.CharField( blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature ID') )", "version signature') verbose_name_plural = _('Document version signatures') def __str__(self): return", "ID is also used to locate a key in the", "except VerificationError as exception: # Not signed logger.debug( 'detached signature", "This is what identifies uniquely a key. Not two keys", "to locate a key in the key servers: http://pgp.mit.edu *", "that will be used to sign the document.'), max_length=40, verbose_name=_('Key", "= models.CharField( blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public key fingerprint') )", "verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file", "'Signature file previously generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to,", "key. \"\"\" document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document", "**kwargs) def save(self, *args, **kwargs): with self.document_version.open() as file_object: try:", "identifies uniquely a key. Not two keys in the world", "= verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file = models.FileField(", "_('Document version embedded signature') verbose_name_plural = _('Document version embedded signatures')", "\"\"\" document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version')", "if self.is_detached: return _('Detached') else: return _('Embedded') @property def is_detached(self):", "raw = False with self.document_version.open(raw=raw) as file_object: try: verify_result =", "save(self, *args, **kwargs): with self.document_version.open() as file_object: try: verify_result =", "http://pgp.mit.edu * signature_id - Signature ID - Every time a", "self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return self.key_id def get_signature_type_display(self): if self.is_detached:", "verbose_name = _('Document version detached signature') verbose_name_plural = _('Document version", "null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file') ) objects =", "uuid from django.db import models from django.urls import reverse from", "= verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint return super(DetachedSignature,", "verbose_name=_('Public key fingerprint') ) objects = InheritanceManager() class Meta: ordering", "else: return _('Embedded') @property def is_detached(self): return hasattr(self, 'signature_file') @property", "verbose_name = _('Document version embedded signature') verbose_name_plural = _('Document version", "embedded signatures') def save(self, *args, **kwargs): logger.debug(msg='checking for embedded signature')", "import force_text from django.utils.translation import ugettext_lazy as _ from model_utils.managers", "save(self, *args, **kwargs): logger.debug(msg='checking for embedded signature') if self.pk: raw", "= verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel):", "return _('Embedded') @property def is_detached(self): return hasattr(self, 'signature_file') @property def", "the same Key ID. The Key ID is also used", "= _('Document version signatures') def __str__(self): return self.signature_id or '{}", "), upload_to=upload_to, verbose_name=_('Signature file') ) objects = DetachedSignatureManager() class Meta:", "= DetachedSignatureManager() class Meta: verbose_name = _('Document version detached signature')", "as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except", "date = models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date signed') ) key_id", "key in the key servers: http://pgp.mit.edu * signature_id - Signature", "signature') verbose_name_plural = _('Document version signatures') def __str__(self): return self.signature_id", "version embedded signatures') def save(self, *args, **kwargs): logger.debug(msg='checking for embedded", "return '{}-{}'.format(self.document_version, _('signature')) def delete(self, *args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name)", "SignatureBaseModel(models.Model): \"\"\" Fields: * key_id - Key Identifier - This", "def is_embedded(self): return not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects =", "from django.utils.translation import ugettext_lazy as _ from model_utils.managers import InheritanceManager", "import VerificationError from mayan.apps.django_gpg.models import Key from mayan.apps.documents.models import DocumentVersion", "= models.CharField( help_text=_('ID of the key that will be used", "InheritanceManager() class Meta: ordering = ('pk',) verbose_name = _('Document version", "key. Not two keys in the world have the same", ") except VerificationError as exception: # Not signed logger.debug( 'embedded", ") objects = DetachedSignatureManager() class Meta: verbose_name = _('Document version", "document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') )", "with self.document_version.open(raw=raw) as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object )", "logger.debug( 'embedded signature verification error; %s', exception ) else: self.date", "DetachedSignatureManager() class Meta: verbose_name = _('Document version detached signature') verbose_name_plural", "def is_detached(self): return hasattr(self, 'signature_file') @property def is_embedded(self): return not", "= _('Document version embedded signature') verbose_name_plural = _('Document version embedded", "def get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return self.key_id def", "get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return self.key_id def get_signature_type_display(self):", "model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models import", "force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\" Fields: * key_id - Key Identifier", "= _('Document version detached signature') verbose_name_plural = _('Document version detached", "DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4())", "%s', exception ) else: self.date = verify_result.date self.key_id = verify_result.key_id", "**kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def save(self, *args,", "Key Identifier - This is what identifies uniquely a key.", "- This is what identifies uniquely a key. Not two", "even when using the same key. \"\"\" document_version = models.ForeignKey(", "'signature_file') @property def is_embedded(self): return not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel):", "the world have the same Key ID. The Key ID", "logger = logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model):", "The Key ID is also used to locate a key", "* signature_id - Signature ID - Every time a key", "verbose_name=_('Key ID') ) # With proper key signature_id = models.CharField(", "try: verify_result = Key.objects.verify_file( file_object=file_object ) except VerificationError as exception:", "self.key_id) def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def", "is_detached(self): return hasattr(self, 'signature_file') @property def is_embedded(self): return not hasattr(self,", "blank=True, editable=False, null=True, verbose_name=_('Date signed') ) key_id = models.CharField( help_text=_('ID", "as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object ) except VerificationError", ") except VerificationError as exception: # Not signed logger.debug( 'detached", "signature') verbose_name_plural = _('Document version embedded signatures') def save(self, *args,", "= logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\"", "self.pk: raw = True else: raw = False with self.document_version.open(raw=raw)", "as exception: # Not signed logger.debug( 'detached signature verification error;", "try: verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except VerificationError as", "self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def save(self, *args, **kwargs): with", "_ from model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError from", "= _('Document version signature') verbose_name_plural = _('Document version signatures') def", "blank=True, help_text=_( 'Signature file previously generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE", "version') ) # Basic fields date = models.DateField( blank=True, editable=False,", "is used to sign something it will generate a unique", "the same key. \"\"\" document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures',", "class Meta: verbose_name = _('Document version detached signature') verbose_name_plural =", "_('Document version signatures') def __str__(self): return self.signature_id or '{} -", "else: self.signature_file.seek(0) self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id =", "Every time a key is used to sign something it", "), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file') ) objects", "a unique signature ID. No two signature IDs are the", "verbose_name_plural = _('Document version signatures') def __str__(self): return self.signature_id or", "key fingerprint') ) objects = InheritanceManager() class Meta: ordering =", ".literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager, EmbeddedSignatureManager logger =", "hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class Meta: verbose_name", "**kwargs) class DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True, help_text=_( 'Signature file", "DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from", "ID') ) public_key_fingerprint = models.CharField( blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public", "to sign something it will generate a unique signature ID.", "self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint", "return self.key_id def get_signature_type_display(self): if self.is_detached: return _('Detached') else: return", "* key_id - Key Identifier - This is what identifies", "will generate a unique signature ID. No two signature IDs", "what identifies uniquely a key. Not two keys in the", "verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint return super(DetachedSignature, self).save(*args,", "def save(self, *args, **kwargs): with self.document_version.open() as file_object: try: verify_result", "document.'), max_length=40, verbose_name=_('Key ID') ) # With proper key signature_id", "__str__(self): return '{}-{}'.format(self.document_version, _('signature')) def delete(self, *args, **kwargs): if self.signature_file.name:", "logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\" Fields:", "VerificationError as exception: # Not signed logger.debug( 'embedded signature verification", "blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint = models.CharField(", "a key in the key servers: http://pgp.mit.edu * signature_id -", "('pk',) verbose_name = _('Document version signature') verbose_name_plural = _('Document version", "key signature_id = models.CharField( blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature ID')", "\"\"\" Fields: * key_id - Key Identifier - This is", "class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class Meta: verbose_name = _('Document", "editable=False, null=True, max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint = models.CharField( blank=True,", "def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def get_key_id(self):", "editable=False, null=True, verbose_name=_('Date signed') ) key_id = models.CharField( help_text=_('ID of", "name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file') ) objects = DetachedSignatureManager() class", "self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint return", "key servers: http://pgp.mit.edu * signature_id - Signature ID - Every", ") else: self.signature_file.seek(0) self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id", "used to sign the document.'), max_length=40, verbose_name=_('Key ID') ) #", "a key is used to sign something it will generate", "viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:]", "help_text=_('ID of the key that will be used to sign", "unique signature ID. No two signature IDs are the same,", "as _ from model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError", ") objects = InheritanceManager() class Meta: ordering = ('pk',) verbose_name", "exception ) else: self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id", "Identifier - This is what identifies uniquely a key. Not", "delete(self, *args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def", "= models.CharField( blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint", "self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint return super(DetachedSignature, self).save(*args, **kwargs)", "Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except VerificationError as exception: # Not", "when using the same key. \"\"\" document_version = models.ForeignKey( editable=False,", "verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint", "self.public_key_fingerprint[-16:] else: return self.key_id def get_signature_type_display(self): if self.is_detached: return _('Detached')", "IDs are the same, even when using the same key.", "signature IDs are the same, even when using the same", ") public_key_fingerprint = models.CharField( blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public key", "= verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args,", "ugettext_lazy as _ from model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions import", "return self.public_key_fingerprint[-16:] else: return self.key_id def get_signature_type_display(self): if self.is_detached: return", "return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\" Fields: * key_id - Key", "on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') ) # Basic fields date", "return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def get_key_id(self): if self.public_key_fingerprint:", "No two signature IDs are the same, even when using", "or '{} - {}'.format(self.date, self.key_id) def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details',", "import models from django.urls import reverse from django.utils.encoding import force_text", "verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except VerificationError as exception:", "key_id = models.CharField( help_text=_('ID of the key that will be", "signatures') def __str__(self): return self.signature_id or '{} - {}'.format(self.date, self.key_id)", "return not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class", "self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True, help_text=_( 'Signature", "world have the same Key ID. The Key ID is", "to=DocumentVersion, verbose_name=_('Document version') ) # Basic fields date = models.DateField(", "from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _", "max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint = models.CharField( blank=True, editable=False, null=True,", "mayan.apps.storage.classes import DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import", "also used to locate a key in the key servers:", ".managers import DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def upload_to(*args, **kwargs):", "= models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date signed') ) key_id =", "kwargs={'signature_id': self.pk} ) def get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else:", "import logging import uuid from django.db import models from django.urls", "two keys in the world have the same Key ID.", "else: self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id", "using the same key. \"\"\" document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE,", "help_text=_( 'Signature file previously generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ),", "two signature IDs are the same, even when using the", "is_embedded(self): return not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager()", "verbose_name=_('Date signed') ) key_id = models.CharField( help_text=_('ID of the key", "detached signature') verbose_name_plural = _('Document version detached signatures') def __str__(self):", "ID - Every time a key is used to sign", "*args, **kwargs): with self.document_version.open() as file_object: try: verify_result = Key.objects.verify_file(", ") else: self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id =", "have the same Key ID. The Key ID is also", "max_length=40, verbose_name=_('Public key fingerprint') ) objects = InheritanceManager() class Meta:", "verbose_name = _('Document version signature') verbose_name_plural = _('Document version signatures')", "if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return self.key_id def get_signature_type_display(self): if", "import DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE", "ID. No two signature IDs are the same, even when", "editable=False, null=True, max_length=40, verbose_name=_('Public key fingerprint') ) objects = InheritanceManager()", "verbose_name_plural = _('Document version embedded signatures') def save(self, *args, **kwargs):", "# Not signed logger.debug( 'embedded signature verification error; %s', exception", "the key servers: http://pgp.mit.edu * signature_id - Signature ID -", "models.CharField( blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint =", "= models.FileField( blank=True, help_text=_( 'Signature file previously generated.' ), null=True,", "= ('pk',) verbose_name = _('Document version signature') verbose_name_plural = _('Document", "VerificationError as exception: # Not signed logger.debug( 'detached signature verification", "uniquely a key. Not two keys in the world have", "is what identifies uniquely a key. Not two keys in", "**kwargs): with self.document_version.open() as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object,", "as exception: # Not signed logger.debug( 'embedded signature verification error;", "Basic fields date = models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date signed')", "embedded signature') verbose_name_plural = _('Document version embedded signatures') def save(self,", "time a key is used to sign something it will", "@property def is_embedded(self): return not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects", "objects = DetachedSignatureManager() class Meta: verbose_name = _('Document version detached", "same, even when using the same key. \"\"\" document_version =", "the document.'), max_length=40, verbose_name=_('Key ID') ) # With proper key", "generate a unique signature ID. No two signature IDs are", "previously generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file')", "upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\" Fields: * key_id", "it will generate a unique signature ID. No two signature", "False with self.document_version.open(raw=raw) as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object", "logging import uuid from django.db import models from django.urls import", "verify_result = Key.objects.verify_file( file_object=file_object ) except VerificationError as exception: #", ") key_id = models.CharField( help_text=_('ID of the key that will", "class Meta: ordering = ('pk',) verbose_name = _('Document version signature')", "get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def get_key_id(self): if", "verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True,", "EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class Meta: verbose_name = _('Document version", "STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def", "verification error; %s', exception ) else: self.signature_file.seek(0) self.date = verify_result.date", "verbose_name=_('Signature ID') ) public_key_fingerprint = models.CharField( blank=True, editable=False, null=True, max_length=40,", "def get_signature_type_display(self): if self.is_detached: return _('Detached') else: return _('Embedded') @property", "Meta: ordering = ('pk',) verbose_name = _('Document version signature') verbose_name_plural", "= _('Document version embedded signatures') def save(self, *args, **kwargs): logger.debug(msg='checking", "file_object=file_object, signature_file=self.signature_file ) except VerificationError as exception: # Not signed", "self.pk} ) def get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return", "**kwargs): logger.debug(msg='checking for embedded signature') if self.pk: raw = True", "True else: raw = False with self.document_version.open(raw=raw) as file_object: try:", "class DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True, help_text=_( 'Signature file previously", "key that will be used to sign the document.'), max_length=40,", "sign the document.'), max_length=40, verbose_name=_('Key ID') ) # With proper", ") # With proper key signature_id = models.CharField( blank=True, editable=False,", "version signatures') def __str__(self): return self.signature_id or '{} - {}'.format(self.date,", "generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file') )", "def __str__(self): return '{}-{}'.format(self.document_version, _('signature')) def delete(self, *args, **kwargs): if", "be used to sign the document.'), max_length=40, verbose_name=_('Key ID') )", "def __str__(self): return self.signature_id or '{} - {}'.format(self.date, self.key_id) def", "from model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models", "blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public key fingerprint') ) objects =", "- Every time a key is used to sign something", "signature_file=self.signature_file ) except VerificationError as exception: # Not signed logger.debug(", "Meta: verbose_name = _('Document version embedded signature') verbose_name_plural = _('Document", "version detached signature') verbose_name_plural = _('Document version detached signatures') def", "keys in the world have the same Key ID. The", "storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file') ) objects = DetachedSignatureManager()", "force_text from django.utils.translation import ugettext_lazy as _ from model_utils.managers import", "not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class Meta:", "null=True, max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint = models.CharField( blank=True, editable=False,", "of the key that will be used to sign the", "EmbeddedSignatureManager() class Meta: verbose_name = _('Document version embedded signature') verbose_name_plural", "InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models import Key from", "signatures') def __str__(self): return '{}-{}'.format(self.document_version, _('signature')) def delete(self, *args, **kwargs):", "same key. \"\"\" document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion,", "return _('Detached') else: return _('Embedded') @property def is_detached(self): return hasattr(self,", "from django.db import models from django.urls import reverse from django.utils.encoding", "@property def is_detached(self): return hasattr(self, 'signature_file') @property def is_embedded(self): return", "from mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy from .literals", "import DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager,", "Key from mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy from", "ID') ) # With proper key signature_id = models.CharField( blank=True,", "used to sign something it will generate a unique signature", "Key ID is also used to locate a key in", "# Basic fields date = models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date", "self.signature_id or '{} - {}'.format(self.date, self.key_id) def get_absolute_url(self): return reverse(", "{}'.format(self.date, self.key_id) def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} )", "signed logger.debug( 'detached signature verification error; %s', exception ) else:", "something it will generate a unique signature ID. No two", "verbose_name_plural = _('Document version detached signatures') def __str__(self): return '{}-{}'.format(self.document_version,", "Key ID. The Key ID is also used to locate", "- {}'.format(self.date, self.key_id) def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk}", "error; %s', exception ) else: self.signature_file.seek(0) self.date = verify_result.date self.key_id", "import InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models import Key", "Not signed logger.debug( 'detached signature verification error; %s', exception )", "def delete(self, *args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs)", "signatures') def save(self, *args, **kwargs): logger.debug(msg='checking for embedded signature') if", "= InheritanceManager() class Meta: ordering = ('pk',) verbose_name = _('Document", "from mayan.apps.storage.classes import DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers", "fingerprint') ) objects = InheritanceManager() class Meta: ordering = ('pk',)", "key_id - Key Identifier - This is what identifies uniquely", "EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class", "file_object=file_object ) except VerificationError as exception: # Not signed logger.debug(", "version detached signatures') def __str__(self): return '{}-{}'.format(self.document_version, _('signature')) def delete(self,", "_('signature')) def delete(self, *args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args,", "_('Document version detached signatures') def __str__(self): return '{}-{}'.format(self.document_version, _('signature')) def", "_('Embedded') @property def is_detached(self): return hasattr(self, 'signature_file') @property def is_embedded(self):", "Signature ID - Every time a key is used to", "= Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except VerificationError as exception: #", "'detached signature verification error; %s', exception ) else: self.signature_file.seek(0) self.date", "exception: # Not signed logger.debug( 'detached signature verification error; %s',", "logger.debug( 'detached signature verification error; %s', exception ) else: self.signature_file.seek(0)", "- Signature ID - Every time a key is used", "= _('Document version detached signatures') def __str__(self): return '{}-{}'.format(self.document_version, _('signature'))", "signed logger.debug( 'embedded signature verification error; %s', exception ) else:", "models from django.urls import reverse from django.utils.encoding import force_text from", "else: raw = False with self.document_version.open(raw=raw) as file_object: try: verify_result", "self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def save(self, *args, **kwargs): with self.document_version.open()", "- Key Identifier - This is what identifies uniquely a", "with self.document_version.open() as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file", "objects = EmbeddedSignatureManager() class Meta: verbose_name = _('Document version embedded", "null=True, verbose_name=_('Date signed') ) key_id = models.CharField( help_text=_('ID of the", "self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature,", "_('Document version embedded signatures') def save(self, *args, **kwargs): logger.debug(msg='checking for", "signature verification error; %s', exception ) else: self.date = verify_result.date", "_('Document version signature') verbose_name_plural = _('Document version signatures') def __str__(self):", "editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') ) # Basic fields", "fields date = models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date signed') )", "self.key_id def get_signature_type_display(self): if self.is_detached: return _('Detached') else: return _('Embedded')", "*args, **kwargs): logger.debug(msg='checking for embedded signature') if self.pk: raw =", "the same, even when using the same key. \"\"\" document_version", "hasattr(self, 'signature_file') @property def is_embedded(self): return not hasattr(self, 'signature_file') class", "import uuid from django.db import models from django.urls import reverse", "import Key from mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy", "models.CharField( blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public key fingerprint') ) objects", "are the same, even when using the same key. \"\"\"", "Key.objects.verify_file( file_object=file_object ) except VerificationError as exception: # Not signed", "the key that will be used to sign the document.'),", "= Key.objects.verify_file( file_object=file_object ) except VerificationError as exception: # Not", "raw = True else: raw = False with self.document_version.open(raw=raw) as", "import ugettext_lazy as _ from model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions", "will be used to sign the document.'), max_length=40, verbose_name=_('Key ID')", "file_object: try: verify_result = Key.objects.verify_file( file_object=file_object ) except VerificationError as", "max_length=40, verbose_name=_('Key ID') ) # With proper key signature_id =", "self).delete(*args, **kwargs) def save(self, *args, **kwargs): with self.document_version.open() as file_object:", "from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager, EmbeddedSignatureManager logger", "return hasattr(self, 'signature_file') @property def is_embedded(self): return not hasattr(self, 'signature_file')", "verbose_name=_('Signature file') ) objects = DetachedSignatureManager() class Meta: verbose_name =", "mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models import Key from mayan.apps.documents.models import", "self.signature_file.seek(0) self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id", "verbose_name=_('Document version') ) # Basic fields date = models.DateField( blank=True,", "= False with self.document_version.open(raw=raw) as file_object: try: verify_result = Key.objects.verify_file(", "a key. Not two keys in the world have the", "def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): \"\"\" Fields: *", "from mayan.apps.django_gpg.models import Key from mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes", "upload_to=upload_to, verbose_name=_('Signature file') ) objects = DetachedSignatureManager() class Meta: verbose_name", "signature ID. No two signature IDs are the same, even", "in the key servers: http://pgp.mit.edu * signature_id - Signature ID", "super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True, help_text=_(", "public_key_fingerprint = models.CharField( blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public key fingerprint')", "import DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return", "= True else: raw = False with self.document_version.open(raw=raw) as file_object:", "models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') ) # Basic", "'{} - {}'.format(self.date, self.key_id) def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id':", "self.is_detached: return _('Detached') else: return _('Embedded') @property def is_detached(self): return", "mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy from .literals import", "proper key signature_id = models.CharField( blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature", "__str__(self): return self.signature_id or '{} - {}'.format(self.date, self.key_id) def get_absolute_url(self):", "verification error; %s', exception ) else: self.date = verify_result.date self.key_id", "in the world have the same Key ID. The Key", "reverse from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as", "mayan.apps.django_gpg.models import Key from mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes import", "django.utils.translation import ugettext_lazy as _ from model_utils.managers import InheritanceManager from", "self.document_version.open() as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file )", "if self.pk: raw = True else: raw = False with", "logger.debug(msg='checking for embedded signature') if self.pk: raw = True else:", "else: return self.key_id def get_signature_type_display(self): if self.is_detached: return _('Detached') else:", ") def get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return self.key_id", "%s', exception ) else: self.signature_file.seek(0) self.date = verify_result.date self.key_id =", "import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__)", "DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager, EmbeddedSignatureManager", "error; %s', exception ) else: self.date = verify_result.date self.key_id =", "ordering = ('pk',) verbose_name = _('Document version signature') verbose_name_plural =", "models.FileField( blank=True, help_text=_( 'Signature file previously generated.' ), null=True, storage=DefinedStorageLazy(", "_('Document version detached signature') verbose_name_plural = _('Document version detached signatures')", "class Meta: verbose_name = _('Document version embedded signature') verbose_name_plural =", "from .managers import DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def upload_to(*args,", "_('Detached') else: return _('Embedded') @property def is_detached(self): return hasattr(self, 'signature_file')", "used to locate a key in the key servers: http://pgp.mit.edu", "= models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') ) #" ]
[ "> 2: universe_config_file = argv[2] parser = ConfigParser() parser.read(universe_config_file) with", "# Write all properties from reports config replacing as #", "reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line)", "perform replacement on # this line if needed. synced_line =", "universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property, universe_config) replaced_property = replacement_property break", "f.readlines() replaced_properties = set([]) with open(reports_config_file, \"w\") as f: #", "line if needed. synced_line = reports_line replaced_property = None for", "2: universe_config_file = argv[2] parser = ConfigParser() parser.read(universe_config_file) with open(reports_config_file,", "replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line", "REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property,", "as # needed. for reports_config_line in reports_config_lines: (line, replaced_property) =", "any properties appear in universe config and not in #", "def get_universe_line(property_name, universe_config): return \"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION, property_name)) if", "in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and \\ not (replacement_property in", "Write all properties from reports config replacing as # needed.", "for replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and \\ not", "\"r\") as f: reports_config_lines = f.readlines() replaced_properties = set([]) with", "the relevant properites from galaxy.ini # into reports.ini reports_config_file =", "reports.ini reports_config_file = \"config/reports.ini\" if len(argv) > 1: reports_config_file =", "get_universe_line(property_name, universe_config): return \"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION, property_name)) if __name__", "config and not in # reports write these as well.", "reports_config_line in reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line, parser) if replaced_property:", "\"database_connection\", \"new_file_path\"] MAIN_SECTION = \"app:main\" def sync(): # Add or", "# reports write these as well. for replacement_property in REPLACE_PROPERTIES:", "replaced_property: replaced_properties.add(replaced_property) f.write(line) # If any properties appear in universe", "= argv[1] universe_config_file = \"config/galaxy.ini\" if len(argv) > 2: universe_config_file", "\"w\") as f: # Write all properties from reports config", "= f.readlines() replaced_properties = set([]) with open(reports_config_file, \"w\") as f:", "\"config/reports.ini\" if len(argv) > 1: reports_config_file = argv[1] universe_config_file =", "= argv[2] parser = ConfigParser() parser.read(universe_config_file) with open(reports_config_file, \"r\") as", "return (synced_line, replaced_property) def get_universe_line(property_name, universe_config): return \"%s=%s\\n\" % (property_name,", "# into reports.ini reports_config_file = \"config/reports.ini\" if len(argv) > 1:", "def sync(): # Add or replace the relevant properites from", "universe_config): # Cycle through properties to replace and perform replacement", "for replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION, replacement_property):", "def get_synced_line(reports_line, universe_config): # Cycle through properties to replace and", "or replace the relevant properites from galaxy.ini # into reports.ini", "replacement_property break return (synced_line, replaced_property) def get_universe_line(property_name, universe_config): return \"%s=%s\\n\"", "= \"config/galaxy.ini\" if len(argv) > 2: universe_config_file = argv[2] parser", "ConfigParser() parser.read(universe_config_file) with open(reports_config_file, \"r\") as f: reports_config_lines = f.readlines()", "replacing as # needed. for reports_config_line in reports_config_lines: (line, replaced_property)", "argv[1] universe_config_file = \"config/galaxy.ini\" if len(argv) > 2: universe_config_file =", "if len(argv) > 2: universe_config_file = argv[2] parser = ConfigParser()", "universe_config) replaced_property = replacement_property break return (synced_line, replaced_property) def get_universe_line(property_name,", "universe config and not in # reports write these as", "from sys import argv REPLACE_PROPERTIES = [\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION", "if parser.has_option(MAIN_SECTION, replacement_property) and \\ not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property,", "write these as well. for replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION,", "relevant properites from galaxy.ini # into reports.ini reports_config_file = \"config/reports.ini\"", "= get_universe_line(replacement_property, universe_config) replaced_property = replacement_property break return (synced_line, replaced_property)", "len(argv) > 1: reports_config_file = argv[1] universe_config_file = \"config/galaxy.ini\" if", "for reports_config_line in reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line, parser) if", "= get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line) # If any", "= \"app:main\" def sync(): # Add or replace the relevant", "parser)) def get_synced_line(reports_line, universe_config): # Cycle through properties to replace", "not in # reports write these as well. for replacement_property", "universe_config_file = argv[2] parser = ConfigParser() parser.read(universe_config_file) with open(reports_config_file, \"r\")", "> 1: reports_config_file = argv[1] universe_config_file = \"config/galaxy.ini\" if len(argv)", "replaced_properties.add(replaced_property) f.write(line) # If any properties appear in universe config", "on # this line if needed. synced_line = reports_line replaced_property", "needed. for reports_config_line in reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line, parser)", "get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line) # If any properties", "import ConfigParser from sys import argv REPLACE_PROPERTIES = [\"file_path\", \"database_connection\",", "needed. synced_line = reports_line replaced_property = None for replacement_property in", "= replacement_property break return (synced_line, replaced_property) def get_universe_line(property_name, universe_config): return", "argv[2] parser = ConfigParser() parser.read(universe_config_file) with open(reports_config_file, \"r\") as f:", "if len(argv) > 1: reports_config_file = argv[1] universe_config_file = \"config/galaxy.ini\"", "replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and \\ not (replacement_property", "replaced_property = replacement_property break return (synced_line, replaced_property) def get_universe_line(property_name, universe_config):", "parser.read(universe_config_file) with open(reports_config_file, \"r\") as f: reports_config_lines = f.readlines() replaced_properties", "replaced_property) = get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line) # If", "replacement on # this line if needed. synced_line = reports_line", "replacement_property): synced_line = get_universe_line(replacement_property, universe_config) replaced_property = replacement_property break return", "Add or replace the relevant properites from galaxy.ini # into", "this line if needed. synced_line = reports_line replaced_property = None", "f.write(line) # If any properties appear in universe config and", "ConfigParser from sys import argv REPLACE_PROPERTIES = [\"file_path\", \"database_connection\", \"new_file_path\"]", "1: reports_config_file = argv[1] universe_config_file = \"config/galaxy.ini\" if len(argv) >", "these as well. for replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property)", "replace and perform replacement on # this line if needed.", "from reports config replacing as # needed. for reports_config_line in", "replaced_property = None for replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and", "= set([]) with open(reports_config_file, \"w\") as f: # Write all", "if needed. synced_line = reports_line replaced_property = None for replacement_property", "[\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION = \"app:main\" def sync(): # Add", "(line, replaced_property) = get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line) #", "reports write these as well. for replacement_property in REPLACE_PROPERTIES: if", "with open(reports_config_file, \"r\") as f: reports_config_lines = f.readlines() replaced_properties =", "properties to replace and perform replacement on # this line", "\\ not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config):", "and \\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property, universe_config) replaced_property =", "sys import argv REPLACE_PROPERTIES = [\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION =", "None for replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION,", "# Add or replace the relevant properites from galaxy.ini #", "\"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION, property_name)) if __name__ == '__main__': sync()", "as f: # Write all properties from reports config replacing", "replacement_property) and \\ not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def", "from ConfigParser import ConfigParser from sys import argv REPLACE_PROPERTIES =", "= [\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION = \"app:main\" def sync(): #", "= \"config/reports.ini\" if len(argv) > 1: reports_config_file = argv[1] universe_config_file", "(synced_line, replaced_property) def get_universe_line(property_name, universe_config): return \"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION,", "If any properties appear in universe config and not in", "break return (synced_line, replaced_property) def get_universe_line(property_name, universe_config): return \"%s=%s\\n\" %", "and \\ not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line,", "from galaxy.ini # into reports.ini reports_config_file = \"config/reports.ini\" if len(argv)", "and not in # reports write these as well. for", "reports_config_file = \"config/reports.ini\" if len(argv) > 1: reports_config_file = argv[1]", "get_synced_line(reports_line, universe_config): # Cycle through properties to replace and perform", "in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line =", "\"config/galaxy.ini\" if len(argv) > 2: universe_config_file = argv[2] parser =", "Cycle through properties to replace and perform replacement on #", "\\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property, universe_config) replaced_property = replacement_property", "\"app:main\" def sync(): # Add or replace the relevant properites", "sync(): # Add or replace the relevant properites from galaxy.ini", "parser = ConfigParser() parser.read(universe_config_file) with open(reports_config_file, \"r\") as f: reports_config_lines", "len(argv) > 2: universe_config_file = argv[2] parser = ConfigParser() parser.read(universe_config_file)", "replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config): # Cycle through properties", "if reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property, universe_config)", "parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line) # If any properties appear", "properties appear in universe config and not in # reports", "synced_line = get_universe_line(replacement_property, universe_config) replaced_property = replacement_property break return (synced_line,", "f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config): # Cycle through properties to", "= ConfigParser() parser.read(universe_config_file) with open(reports_config_file, \"r\") as f: reports_config_lines =", "as well. for replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and", "# this line if needed. synced_line = reports_line replaced_property =", "argv REPLACE_PROPERTIES = [\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION = \"app:main\" def", "replaced_properties = set([]) with open(reports_config_file, \"w\") as f: # Write", "all properties from reports config replacing as # needed. for", "universe_config_file = \"config/galaxy.ini\" if len(argv) > 2: universe_config_file = argv[2]", "reports_config_lines = f.readlines() replaced_properties = set([]) with open(reports_config_file, \"w\") as", "through properties to replace and perform replacement on # this", "= None for replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \\", "reports config replacing as # needed. for reports_config_line in reports_config_lines:", "to replace and perform replacement on # this line if", "properties from reports config replacing as # needed. for reports_config_line", "with open(reports_config_file, \"w\") as f: # Write all properties from", "if replaced_property: replaced_properties.add(replaced_property) f.write(line) # If any properties appear in", "config replacing as # needed. for reports_config_line in reports_config_lines: (line,", "import argv REPLACE_PROPERTIES = [\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION = \"app:main\"", "galaxy.ini # into reports.ini reports_config_file = \"config/reports.ini\" if len(argv) >", "get_universe_line(replacement_property, universe_config) replaced_property = replacement_property break return (synced_line, replaced_property) def", "as f: reports_config_lines = f.readlines() replaced_properties = set([]) with open(reports_config_file,", "REPLACE_PROPERTIES = [\"file_path\", \"database_connection\", \"new_file_path\"] MAIN_SECTION = \"app:main\" def sync():", "= reports_line replaced_property = None for replacement_property in REPLACE_PROPERTIES: if", "not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config): #", "f: # Write all properties from reports config replacing as", "well. for replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and \\", "ConfigParser import ConfigParser from sys import argv REPLACE_PROPERTIES = [\"file_path\",", "in # reports write these as well. for replacement_property in", "\"new_file_path\"] MAIN_SECTION = \"app:main\" def sync(): # Add or replace", "open(reports_config_file, \"w\") as f: # Write all properties from reports", "open(reports_config_file, \"r\") as f: reports_config_lines = f.readlines() replaced_properties = set([])", "replace the relevant properites from galaxy.ini # into reports.ini reports_config_file", "in reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property)", "# Cycle through properties to replace and perform replacement on", "(replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config): # Cycle", "in universe config and not in # reports write these", "and perform replacement on # this line if needed. synced_line", "REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and \\ not (replacement_property in replaced_properties):", "synced_line = reports_line replaced_property = None for replacement_property in REPLACE_PROPERTIES:", "f: reports_config_lines = f.readlines() replaced_properties = set([]) with open(reports_config_file, \"w\")", "MAIN_SECTION = \"app:main\" def sync(): # Add or replace the", "in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config): # Cycle through", "set([]) with open(reports_config_file, \"w\") as f: # Write all properties", "replaced_property) def get_universe_line(property_name, universe_config): return \"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION, property_name))", "properites from galaxy.ini # into reports.ini reports_config_file = \"config/reports.ini\" if", "reports_config_file = argv[1] universe_config_file = \"config/galaxy.ini\" if len(argv) > 2:", "parser.has_option(MAIN_SECTION, replacement_property) and \\ not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser))", "reports_line.startswith(replacement_property) and \\ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property, universe_config) replaced_property", "universe_config): return \"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION, property_name)) if __name__ ==", "reports_line replaced_property = None for replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property)", "appear in universe config and not in # reports write", "into reports.ini reports_config_file = \"config/reports.ini\" if len(argv) > 1: reports_config_file", "# needed. for reports_config_line in reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line,", "return \"%s=%s\\n\" % (property_name, universe_config.get(MAIN_SECTION, property_name)) if __name__ == '__main__':", "# If any properties appear in universe config and not" ]
[ "\"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER", "NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A", "grep \\\"processor\\\" | wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs -0\"))", "IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py # # ------------------------------------------------------------------------- from ssh import ExecutorFactory", "WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING", "| xargs -0\")) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e", "OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan", "under Mulan PSL v2. # You can use this software", "for more details. # ------------------------------------------------------------------------- # # test_ssh.py # #", "print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs -0\")) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0].count('\\n'))", "(c) 2020 Huawei Technologies Co.,Ltd. # # openGauss is licensed", "the terms and conditions of the Mulan PSL v2. #", "# src/gausskernel/dbmind/xtuner/test/test_ssh.py # # ------------------------------------------------------------------------- from ssh import ExecutorFactory def", "Mulan PSL v2. # You can use this software according", "test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your information print(exe.exec_command_sync(\"cat /proc/cpuinfo", "this software according to the terms and conditions of the", "use this software according to the terms and conditions of", "v2. # You may obtain a copy of Mulan PSL", "-e 'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo", "# THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS,", "conditions of the Mulan PSL v2. # You may obtain", "# # THIS SOFTWARE IS PROVIDED ON AN \"AS IS\"", "AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND, #", "ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,", "a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2", "exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your information print(exe.exec_command_sync(\"cat /proc/cpuinfo |", "IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR", "# # ------------------------------------------------------------------------- from ssh import ExecutorFactory def test_remote(): exe", "def test_local(): exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\")) if __name__ ==", "world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def test_local():", "details. # ------------------------------------------------------------------------- # # test_ssh.py # # IDENTIFICATION #", "/proc/cpuinfo | grep \\\"processor\\\" | wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline |", "print(exe.exec_command_sync('echo $SHELL')) def test_local(): exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\")) if", "# You may obtain a copy of Mulan PSL v2", "openGauss is licensed under Mulan PSL v2. # You can", "is licensed under Mulan PSL v2. # You can use", "See the Mulan PSL v2 for more details. # -------------------------------------------------------------------------", "\\\"processor\\\" | wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs -0\")) print(exe.exec_command_sync(\"echo", "copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 #", "of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # #", "A PARTICULAR PURPOSE. # See the Mulan PSL v2 for", "information print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep \\\"processor\\\" | wc -l\")) print(exe.exec_command_sync(\"cat", "OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT", "test_ssh.py # # IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py # # ------------------------------------------------------------------------- from", "# See the Mulan PSL v2 for more details. #", "PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY", "of the Mulan PSL v2. # You may obtain a", "wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs -0\")) print(exe.exec_command_sync(\"echo -e 'hello", "obtain a copy of Mulan PSL v2 at: # #", "exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\")) if __name__ == \"__main__\": test_remote()", "licensed under Mulan PSL v2. # You can use this", "INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT", "# ------------------------------------------------------------------------- # # test_ssh.py # # IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py", "# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See", "may obtain a copy of Mulan PSL v2 at: #", "# http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN", "terms and conditions of the Mulan PSL v2. # You", "print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0])", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, #", "Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS", "/proc/self/cmdline | xargs -0\")) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo", "You may obtain a copy of Mulan PSL v2 at:", "IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS", "v2 for more details. # ------------------------------------------------------------------------- # # test_ssh.py #", "FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL", "SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES", "You can use this software according to the terms and", "PARTICULAR PURPOSE. # See the Mulan PSL v2 for more", "ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your information print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep \\\"processor\\\"", "NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. #", "# openGauss is licensed under Mulan PSL v2. # You", "test_local(): exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\")) if __name__ == \"__main__\":", "# Copyright (c) 2020 Huawei Technologies Co.,Ltd. # # openGauss", "Mulan PSL v2 for more details. # ------------------------------------------------------------------------- # #", "padding your information print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep \\\"processor\\\" | wc", "PSL v2. # You can use this software according to", "world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def test_local(): exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\"))", "the Mulan PSL v2 for more details. # ------------------------------------------------------------------------- #", "v2. # You can use this software according to the", "from ssh import ExecutorFactory def test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() #", "= ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\")) if __name__ == \"__main__\": test_remote() test_local()", "KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY", "-e 'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def test_local(): exe =", "xargs -0\")) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello", "TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.", "http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN \"AS", "ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT", "# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "# IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py # # ------------------------------------------------------------------------- from ssh import", "'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL'))", "src/gausskernel/dbmind/xtuner/test/test_ssh.py # # ------------------------------------------------------------------------- from ssh import ExecutorFactory def test_remote():", "IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF", "ExecutorFactory def test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your information", "more details. # ------------------------------------------------------------------------- # # test_ssh.py # # IDENTIFICATION", "Huawei Technologies Co.,Ltd. # # openGauss is licensed under Mulan", "and conditions of the Mulan PSL v2. # You may", "Mulan PSL v2. # You may obtain a copy of", "# # test_ssh.py # # IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py # #", "Copyright (c) 2020 Huawei Technologies Co.,Ltd. # # openGauss is", "\\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def test_local(): exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping", "# test_ssh.py # # IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py # # -------------------------------------------------------------------------", "print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def test_local(): exe", "WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED,", "the Mulan PSL v2. # You may obtain a copy", "ssh import ExecutorFactory def test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding", "EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,", "PURPOSE. # See the Mulan PSL v2 for more details.", "PSL v2 for more details. # ------------------------------------------------------------------------- # # test_ssh.py", "to the terms and conditions of the Mulan PSL v2.", "-l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs -0\")) print(exe.exec_command_sync(\"echo -e 'hello \\\\n", "v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS", "BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR", "# # IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py # # ------------------------------------------------------------------------- from ssh", "$SHELL')) def test_local(): exe = ExecutorFactory().get_executor() print(exe.exec_command_sync(\"ping -h\")) if __name__", "PSL v2. # You may obtain a copy of Mulan", "according to the terms and conditions of the Mulan PSL", "-0\")) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello \\\\n", "THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT", "# You can use this software according to the terms", "FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2", "# ------------------------------------------------------------------------- from ssh import ExecutorFactory def test_remote(): exe =", "at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED", "print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep \\\"processor\\\" | wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline", "| grep \\\"processor\\\" | wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs", "= ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your information print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep", "Technologies Co.,Ltd. # # openGauss is licensed under Mulan PSL", "can use this software according to the terms and conditions", "LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR", "def test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your information print(exe.exec_command_sync(\"cat", "MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the", "------------------------------------------------------------------------- # # test_ssh.py # # IDENTIFICATION # src/gausskernel/dbmind/xtuner/test/test_ssh.py #", "'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def test_local(): exe = ExecutorFactory().get_executor()", "# padding your information print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep \\\"processor\\\" |", "# # openGauss is licensed under Mulan PSL v2. #", "2020 Huawei Technologies Co.,Ltd. # # openGauss is licensed under", "BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR", "------------------------------------------------------------------------- from ssh import ExecutorFactory def test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor()", "# # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON", "import ExecutorFactory def test_remote(): exe = ExecutorFactory().set_host('').set_user('').set_pwd('').get_executor() # padding your", "\\\\n world'\")[0].count('\\n')) print(exe.exec_command_sync(\"echo -e 'hello \\\\n world'\")[0]) print(exe.exec_command_sync('echo $SHELL')) def", "PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE", "| wc -l\")) print(exe.exec_command_sync(\"cat /proc/self/cmdline | xargs -0\")) print(exe.exec_command_sync(\"echo -e", "Co.,Ltd. # # openGauss is licensed under Mulan PSL v2.", "software according to the terms and conditions of the Mulan", "your information print(exe.exec_command_sync(\"cat /proc/cpuinfo | grep \\\"processor\\\" | wc -l\"))" ]
[ "numpy as np from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import", "\"\"\" :param vocab_prob: :param sent: :param length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent,", "= tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor, tf.shape(tensor) * repeats) return", ":param vocab_prob: :param sent: :param length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1,", "scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return np.max(scores), np.mean(scores)", "prior_mu, prior_logvar): kld = -0.5 * tf.reduce_sum(1 + (recog_logvar -", "import numpy as np from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score", "tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar),", "with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is None: length_mask =", "get_bow(embedding, avg=False): \"\"\" Assumption, the last dimension is the embedding", "None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input", "hyp in hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except:", "sentence length. The rank must be 3 \"\"\" embedding_size =", "- tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld def norm_log_liklihood(x, mu, logvar):", "reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption,", "tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor, tf.shape(tensor) * repeats) return repeated_tensor", ":param sent: :param length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask,", "tf_repeat(tensor, repeats): \"\"\" :param tensor: :param repeats: :return: \"\"\" with", "return z def get_bow(embedding, avg=False): \"\"\" Assumption, the last dimension", "with tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor, -1) multiples = [1] +", "-0.5 * tf.reduce_sum(1 + (recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu -", "sent: :param length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50))", "def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\" :param vocab_prob: :param sent: :param", "return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None):", "length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input =", "<NAME>, Carnegie Mellon University # Modified work Copyright 2018 <NAME>.", "smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu,", "+ (recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar))", "* logvar) z= mu + tf.multiply(std, epsilon) return z def", "3 The padding should have zero \"\"\" with tf.variable_scope(scope, 'RnnEncoding',", "2017 <NAME>, Carnegie Mellon University # Modified work Copyright 2018", "# Original work Copyright (C) 2017 <NAME>, Carnegie Mellon University", "length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor,", "reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell,", "[1] + repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor,", "\"\"\" Assumption, the last dimension is the embedding The second", "tf.random_normal(tf.shape(logvar), name=\"epsilon\") std = tf.exp(0.5 * logvar) z= mu +", "<NAME>. import tensorflow as tf import numpy as np from", "get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\" :param vocab_prob: :param sent: :param length_mask:", "return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\" :param vocab_prob:", "= tf.random_normal(tf.shape(logvar), name=\"epsilon\") std = tf.exp(0.5 * logvar) z= mu", "mu + tf.multiply(std, epsilon) return z def get_bow(embedding, avg=False): \"\"\"", "\"\"\" embedding_size = embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size", "+ tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar): epsilon =", "epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\") std = tf.exp(0.5 * logvar) z=", "is the embedding The second last dimension is the sentence", "1) return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\" :param", "tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return", "try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return np.max(scores),", "tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld def norm_log_liklihood(x, mu, logvar): return", "return kld def norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar", "logvar) z= mu + tf.multiply(std, epsilon) return z def get_bow(embedding,", "be 3 The padding should have zero \"\"\" with tf.variable_scope(scope,", "tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor, tf.shape(tensor) * repeats)", "logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1)", "tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell,", "hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return", "tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding),", "return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld =", "is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _,", "def get_bow(embedding, avg=False): \"\"\" Assumption, the last dimension is the", "b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1) return encoded_input,", "tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell, embedding,", "tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1) return", "length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask)", "z def get_bow(embedding, avg=False): \"\"\" Assumption, the last dimension is", "embedding_size def get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the", "length. The rank must be 3 \"\"\" embedding_size = embedding.get_shape()[2].value", "vocab_prob: :param sent: :param length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]),", ":param length_mask: :return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50)) def", "embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding,", "+ logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar):", "def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the", "mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)),", "sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size def", "= tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1)", "if length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask =", "sent, length_mask=None): \"\"\" :param vocab_prob: :param sent: :param length_mask: :return:", "padding should have zero \"\"\" with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if", "tf.exp(prior_logvar)), reduction_indices=1) return kld def norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi)", "scores = [] for hyp in hyps: try: scores.append(sentence_bleu([ref], hyp,", "embedding The second last dimension is the sentence length. The", "avg=False): \"\"\" Assumption, the last dimension is the embedding The", "must be 3 The padding should have zero \"\"\" with", "tf.multiply(std, epsilon) return z def get_bow(embedding, avg=False): \"\"\" Assumption, the", "= tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None):", "= -0.5 * tf.reduce_sum(1 + (recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu", "[] for hyp in hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3,", "must be 3 \"\"\" embedding_size = embedding.get_shape()[2].value if avg: return", "= [] for hyp in hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7,", "* tf.reduce_sum(1 + (recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu,", "def get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last", "reuse=None): \"\"\" Assumption, the last dimension is the embedding The", "Modified work Copyright 2018 <NAME>. import tensorflow as tf import", "length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask,", "b_cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last dimension is", "else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell, length_mask=None, scope=None,", "logvar): epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\") std = tf.exp(0.5 * logvar)", ":param repeats: :return: \"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor, -1)", "= tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32)", "The rank must be 3 \"\"\" embedding_size = embedding.get_shape()[2].value if", "def norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu),", "is the sentence length. The rank must be 3 The", "rank must be 3 \"\"\" embedding_size = embedding.get_shape()[2].value if avg:", "reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding,", "University # Modified work Copyright 2018 <NAME>. import tensorflow as", "epsilon) return z def get_bow(embedding, avg=False): \"\"\" Assumption, the last", "= tf.expand_dims(tensor, -1) multiples = [1] + repeats tiled_tensor =", "- recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld", "nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref, hyps): scores = [] for", "as tf import numpy as np from nltk.translate.bleu_score import sentence_bleu", "last dimension is the embedding The second last dimension is", "repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor, tf.shape(tensor) *", "sentence_bleu from nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref, hyps): scores =", "Original work Copyright (C) 2017 <NAME>, Carnegie Mellon University #", "second last dimension is the sentence length. The rank must", "if avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]),", "hyps): scores = [] for hyp in hyps: try: scores.append(sentence_bleu([ref],", "3 \"\"\" embedding_size = embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding, reduction_indices=[1]),", "from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref,", "gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld = -0.5 * tf.reduce_sum(1 +", "recog_logvar, prior_mu, prior_logvar): kld = -0.5 * tf.reduce_sum(1 + (recog_logvar", "-0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu,", "return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def", "f_cell, b_cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last dimension", "length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last dimension is the", "rank must be 3 The padding should have zero \"\"\"", "weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar,", "def sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\") std = tf.exp(0.5", "tf.exp(0.5 * logvar) z= mu + tf.multiply(std, epsilon) return z", "1./3,1./3])) except: scores.append(0.0) return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu,", "import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref, hyps): scores", "dimension is the embedding The second last dimension is the", "cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last dimension is", "the sentence length. The rank must be 3 \"\"\" embedding_size", "encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input,", "50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats): \"\"\" :param tensor: :param", "\"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor, -1) multiples = [1]", ":return: \"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats):", "kld = -0.5 * tf.reduce_sum(1 + (recog_logvar - prior_logvar) -", "should have zero \"\"\" with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask", "return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def", "sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None,", "in hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0)", "[-1, 50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats): \"\"\" :param tensor:", "embedding_size = embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else:", "multiples = [1] + repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor", "the last dimension is the embedding The second last dimension", "reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask,", "2018 <NAME>. import tensorflow as tf import numpy as np", "Copyright (C) 2017 <NAME>, Carnegie Mellon University # Modified work", "Assumption, the last dimension is the embedding The second last", "sentence length. The rank must be 3 The padding should", "get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last", "prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)),", "tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None): \"\"\"", "encoded_input = tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent,", "tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding,", "def tf_repeat(tensor, repeats): \"\"\" :param tensor: :param repeats: :return: \"\"\"", "scores.append(0.0) return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld", "= tf.exp(0.5 * logvar) z= mu + tf.multiply(std, epsilon) return", "prior_logvar): kld = -0.5 * tf.reduce_sum(1 + (recog_logvar - prior_logvar)", "Mellon University # Modified work Copyright 2018 <NAME>. import tensorflow", "cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption,", "recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld def", "dtype=tf.float32) return encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None,", "nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref, hyps):", "except: scores.append(0.0) return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar):", "np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld = -0.5 *", "dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob,", "embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size", "= tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size def get_bi_rnn_encode(embedding,", "The rank must be 3 The padding should have zero", "get_bleu_stats(ref, hyps): scores = [] for hyp in hyps: try:", "tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\") std", "50)) def tf_repeat(tensor, repeats): \"\"\" :param tensor: :param repeats: :return:", "_, encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size", "encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None, reuse=None): \"\"\"", "- tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1)", "\"\"\" with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is None: length_mask", "def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld = -0.5 * tf.reduce_sum(1", "for hyp in hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3]))", "(recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar)) -", "+ tf.multiply(std, epsilon) return z def get_bow(embedding, avg=False): \"\"\" Assumption,", "logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar): epsilon", "repeats: :return: \"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor, -1) multiples", "embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell, length_mask=None,", "2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\")", "= embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return", "encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size def", "tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\"", "length_mask=None): \"\"\" :param vocab_prob: :param sent: :param length_mask: :return: \"\"\"", "Carnegie Mellon University # Modified work Copyright 2018 <NAME>. import", "expanded_tensor = tf.expand_dims(tensor, -1) multiples = [1] + repeats tiled_tensor", "be 3 \"\"\" embedding_size = embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding,", "dimension is the sentence length. The rank must be 3", "-1) multiples = [1] + repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples)", "last dimension is the sentence length. The rank must be", "tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats): \"\"\" :param", "tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell,", "sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\") std = tf.exp(0.5 *", "tensorflow as tf import numpy as np from nltk.translate.bleu_score import", "get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None): \"\"\" Assumption, the last dimension", "\"\"\" :param tensor: :param repeats: :return: \"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor", "\"\"\" tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats): \"\"\"", "def get_bleu_stats(ref, hyps): scores = [] for hyp in hyps:", "_, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input =", "import tensorflow as tf import numpy as np from nltk.translate.bleu_score", "norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu), 2),", "length. The rank must be 3 The padding should have", ":return: \"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor, -1) multiples =", "tf.reduce_sum(1 + (recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu, 2),", "reduction_indices=1) def sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar), name=\"epsilon\") std =", "work Copyright (C) 2017 <NAME>, Carnegie Mellon University # Modified", "SmoothingFunction def get_bleu_stats(ref, hyps): scores = [] for hyp in", "The second last dimension is the sentence length. The rank", "reuse=reuse): if length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask", "tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats): \"\"\" :param tensor: :param repeats:", "the sentence length. The rank must be 3 The padding", "tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input,", "name=\"epsilon\") std = tf.exp(0.5 * logvar) z= mu + tf.multiply(std,", "z= mu + tf.multiply(std, epsilon) return z def get_bow(embedding, avg=False):", "std = tf.exp(0.5 * logvar) z= mu + tf.multiply(std, epsilon)", "zero \"\"\" with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is None:", "<reponame>wyshi/Unsupervised-Structure-Learning<gh_stars>10-100 # Original work Copyright (C) 2017 <NAME>, Carnegie Mellon", "= tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell,", "length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32)", ":param tensor: :param repeats: :return: \"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor =", "the embedding The second last dimension is the sentence length.", "encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\" :param vocab_prob: :param", "tensor: :param repeats: :return: \"\"\" with tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor,", "have zero \"\"\" with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is", "'RnnEncoding', reuse=reuse): if length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1)", "tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input", "2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld def norm_log_liklihood(x,", "Copyright 2018 <NAME>. import tensorflow as tf import numpy as", "- prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar),", "tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld def norm_log_liklihood(x, mu,", "tf.expand_dims(tensor, -1) multiples = [1] + repeats tiled_tensor = tf.tile(expanded_tensor,", "scope=None, reuse=None): \"\"\" Assumption, the last dimension is the embedding", "tf.variable_scope(\"repeat\"): expanded_tensor = tf.expand_dims(tensor, -1) multiples = [1] + repeats", "= [1] + repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor =", "reduction_indices=1) return kld def norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) +", "+ repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor, tf.shape(tensor)", "# Modified work Copyright 2018 <NAME>. import tensorflow as tf", "np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld = -0.5", "kld def norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar +", "tf import numpy as np from nltk.translate.bleu_score import sentence_bleu from", "= tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell,", "return encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None, reuse=None):", "embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell,", "avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size", "as np from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction", "import SmoothingFunction def get_bleu_stats(ref, hyps): scores = [] for hyp", "The padding should have zero \"\"\" with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse):", "from nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref, hyps): scores = []", "is the sentence length. The rank must be 3 \"\"\"", "np from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction def", "f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): \"\"\" :param vocab_prob: :param sent:", "(C) 2017 <NAME>, Carnegie Mellon University # Modified work Copyright", "hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return np.max(scores), np.mean(scores) def", "repeats): \"\"\" :param tensor: :param repeats: :return: \"\"\" with tf.variable_scope(\"repeat\"):", "work Copyright 2018 <NAME>. import tensorflow as tf import numpy", "= tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return" ]
[ "* height target_area = random.uniform(self.s_min, self.s_max) * area aspect_ratio =", "pad), (0, 0)) if isinstance(pad, int) else pad def forward(self,", "OF ANY # KIND, either express or implied. See the", "isinstance(self.s_max, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.ratio,", "erasing. s_min : float Min area to all area. s_max", "tensor with (Hi x Wi x C) shape. \"\"\" def", "more contributor license agreements. See the NOTICE file # distributed", "raise TypeError('Got inappropriate size arg') if not isinstance(self.s_max, float): raise", "= ['RandomCrop', 'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly crop `src` with `size`", "Apache Software Foundation (ASF) under one # or more contributor", "tensor with (Hi x Wi x C) shape. Outputs: -", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "(size x size x C) shape. \"\"\" def __init__(self, size,", "2.0 (the # \"License\"); you may not use this file", "governing permissions and limitations # under the License. # coding:", "w) y1 = random.randint(0, height - h) x[x1:x1+w, y1:y1+h, 0]", "TypeError('Got inappropriate size arg') if random.uniform(0, 1) > self.probability: return", "0] = self.mean[0] x[x1:x1+w, y1:y1+h, 1] = self.mean[1] x[x1:x1+w, y1:y1+h,", "of each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad", "x1 = random.randint(0, width - w) y1 = random.randint(0, height", "ratio between width and height. mean : int or tuple", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "specific language governing permissions and limitations # under the License.", "under the License is distributed on an # \"AS IS\"", ": float Min area to all area. s_max : float", "float): raise TypeError('Got inappropriate size arg') if not isinstance(self.s_min, float):", "x): if not isinstance(self.probability, float): raise TypeError('Got inappropriate size arg')", "0)) if isinstance(pad, int) else pad def forward(self, x): if", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "missing-docstring \"Addtional image transforms.\" import random import math import numpy", "for resizing. By default uses bilinear interpolation. See OpenCV's resize", "RandomCrop(Block): \"\"\"Randomly crop `src` with `size` (width, height). Padding is", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "((before_1, after_1), ... (before_N, after_N)) unique pad widths for each", "disable= missing-docstring \"Addtional image transforms.\" import random import math import", "or int is a shortcut for before = after =", "mxnet.gluon import Block __all__ = ['RandomCrop', 'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly", "(size, size) self._args = (size, interpolation) self.pad = ((pad, pad),", "all axes. interpolation : int Interpolation method for resizing. By", "resizing. By default uses bilinear interpolation. See OpenCV's resize function", "distributed with this work for additional information # regarding copyright", "widths for each axis. ((before, after),) yields same before and", "Max area to all area. ratio : float The ratio", "int or tuple if int, size of the zero-padding if", "before = after = pad width for all axes. interpolation", "for the # specific language governing permissions and limitations #", "arg') if not isinstance(self.s_min, float): raise TypeError('Got inappropriate size arg')", "\"\"\" def __init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)):", "shape. Outputs: - **out**: output tensor with (size[0] x size[1]", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "isinstance(pad, int) else pad def forward(self, x): if self.pad: return", "`s_max` with `probability`. `ratio` controls the ratio between width and", "interpolation : int Interpolation method for resizing. By default uses", "and after pad for each axis. (pad,) or int is", "ratio : float The ratio between width and height. mean", "Inputs: - **data**: input tensor with (Hi x Wi x", "int(round(math.sqrt(target_area / aspect_ratio))) if w < width and h <", "import math import numpy as np from mxnet import image,", "edges of each axis. ((before_1, after_1), ... (before_N, after_N)) unique", "x C) shape. \"\"\" def __init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3,", "x C) or (size x size x C) shape. \"\"\"", "file # distributed with this work for additional information #", ": int Interpolation method for resizing. By default uses bilinear", "(size, interpolation) self.pad = ((pad, pad), (pad, pad), (0, 0))", "erasing the area in `src` between `s_min` and `s_max` with", "Padding is optional. Upsample result if `src` is smaller than", "tuple of (R, G, B) The value in erasing area.", "not isinstance(self.probability, float): raise TypeError('Got inappropriate size arg') if not", "= random.randint(0, height - h) x[x1:x1+w, y1:y1+h, 0] = self.mean[0]", "utf-8 # pylint: disable= arguments-differ # pylint: disable= missing-docstring \"Addtional", "self.s_min = s_min self.s_max = s_max self.ratio = ratio def", "the zero-padding if tuple, number of values padded to the", "= (size, interpolation) self.pad = ((pad, pad), (pad, pad), (0,", "implied. See the License for the # specific language governing", "to you under the Apache License, Version 2.0 (the #", "axes. interpolation : int Interpolation method for resizing. By default", "area in `src` between `s_min` and `s_max` with `probability`. `ratio`", "forward(self, x): if not isinstance(self.probability, float): raise TypeError('Got inappropriate size", "after),) yields same before and after pad for each axis.", "isinstance(self.s_min, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.s_max,", "`mean` means the value in erasing area. Parameters ---------- probability", "may not use this file except in compliance # with", "= ((pad, pad), (pad, pad), (0, 0)) if isinstance(pad, int)", "License, Version 2.0 (the # \"License\"); you may not use", "if not isinstance(self.ratio, float): raise TypeError('Got inappropriate size arg') if", "either express or implied. See the License for the #", "permissions and limitations # under the License. # coding: utf-8", "each axis. (pad,) or int is a shortcut for before", "< width and h < height: x1 = random.randint(0, width", "mean self.s_min = s_min self.s_max = s_max self.ratio = ratio", "additional information # regarding copyright ownership. The ASF licenses this", "and limitations # under the License. # coding: utf-8 #", "Size of the final output. pad: int or tuple if", "See the NOTICE file # distributed with this work for", "after_1), ... (before_N, after_N)) unique pad widths for each axis.", "(float, int, np.generic) if isinstance(size, numeric_types): size = (size, size)", "math import numpy as np from mxnet import image, nd", "unique pad widths for each axis. ((before, after),) yields same", "if not isinstance(self.mean, (int, tuple)): raise TypeError('Got inappropriate size arg')", "**out**: output tensor with (Hi x Wi x C) shape.", "Apache License, Version 2.0 (the # \"License\"); you may not", "width for all axes. interpolation : int Interpolation method for", "if not isinstance(self.s_min, float): raise TypeError('Got inappropriate size arg') if", "zero-padding if tuple, number of values padded to the edges", "height). Padding is optional. Upsample result if `src` is smaller", "pad: int or tuple if int, size of the zero-padding", "= pad width for all axes. interpolation : int Interpolation", "C) shape. Outputs: - **out**: output tensor with (size[0] x", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "else: return image.random_crop(x, *self._args)[0] class RandomErasing(Block): \"\"\"Randomly erasing the area", "tuple)): raise TypeError('Got inappropriate size arg') if random.uniform(0, 1) >", "122.96, 113.86)): super(RandomErasing, self).__init__() self.probability = probability self.mean = mean", "file except in compliance # with the License. You may", "['RandomCrop', 'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly crop `src` with `size` (width,", "np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0] else: return image.random_crop(x, *self._args)[0] class", "Block __all__ = ['RandomCrop', 'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly crop `src`", "# specific language governing permissions and limitations # under the", "of (R, G, B) The value in erasing area. Inputs:", "crop `src` with `size` (width, height). Padding is optional. Upsample", "shape. \"\"\" def __init__(self, size, pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types", "you may not use this file except in compliance #", "erasing area. Parameters ---------- probability : float Probability of erasing.", "float): raise TypeError('Got inappropriate size arg') if not isinstance(self.mean, (int,", "w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio)))", "use this file except in compliance # with the License.", "target_area = random.uniform(self.s_min, self.s_max) * area aspect_ratio = random.uniform(self.ratio, 1/self.ratio)", "with (Hi x Wi x C) shape. Outputs: - **out**:", "s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__() self.probability =", "random.randint(0, width - w) y1 = random.randint(0, height - h)", "contributor license agreements. See the NOTICE file # distributed with", "numeric_types): size = (size, size) self._args = (size, interpolation) self.pad", "if w < width and h < height: x1 =", "tuple, number of values padded to the edges of each", "`size` (width, height). Padding is optional. Upsample result if `src`", "pad widths for each axis. ((before, after),) yields same before", "not isinstance(self.ratio, float): raise TypeError('Got inappropriate size arg') if not", "size arg') if not isinstance(self.mean, (int, tuple)): raise TypeError('Got inappropriate", ": float Probability of erasing. s_min : float Min area", "isinstance(size, numeric_types): size = (size, size) self._args = (size, interpolation)", "return x width, height, _ = x.shape area = width", "interpolation. See OpenCV's resize function for available choices. Inputs: -", "= random.uniform(self.s_min, self.s_max) * area aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w", "x size[1] x C) or (size x size x C)", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "__all__ = ['RandomCrop', 'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly crop `src` with", "x C) shape. Outputs: - **out**: output tensor with (size[0]", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "C) shape. \"\"\" def __init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31,", "import numpy as np from mxnet import image, nd from", "x.shape area = width * height target_area = random.uniform(self.s_min, self.s_max)", "with this work for additional information # regarding copyright ownership.", "arg') if not isinstance(self.s_max, float): raise TypeError('Got inappropriate size arg')", "`ratio` controls the ratio between width and height. `mean` means", "each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths", "work for additional information # regarding copyright ownership. The ASF", "size[1] x C) or (size x size x C) shape.", "int or tuple of (W, H) Size of the final", "and height. `mean` means the value in erasing area. Parameters", "output tensor with (Hi x Wi x C) shape. \"\"\"", "The ratio between width and height. mean : int or", "or tuple if int, size of the zero-padding if tuple,", "distributed under the License is distributed on an # \"AS", "B) The value in erasing area. Inputs: - **data**: input", "`src` between `s_min` and `s_max` with `probability`. `ratio` controls the", "return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0] else: return image.random_crop(x,", "int, size of the zero-padding if tuple, number of values", "- **data**: input tensor with (Hi x Wi x C)", "np.generic) if isinstance(size, numeric_types): size = (size, size) self._args =", "area = width * height target_area = random.uniform(self.s_min, self.s_max) *", "# software distributed under the License is distributed on an", "= random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h =", "in erasing area. Parameters ---------- probability : float Probability of", "not isinstance(self.mean, (int, tuple)): raise TypeError('Got inappropriate size arg') if", "the License. You may obtain a copy of the License", "**data**: input tensor with (Hi x Wi x C) shape.", "size of the zero-padding if tuple, number of values padded", "is optional. Upsample result if `src` is smaller than `size`.", "Probability of erasing. s_min : float Min area to all", "under the Apache License, Version 2.0 (the # \"License\"); you", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "regarding copyright ownership. The ASF licenses this file # to", "or agreed to in writing, # software distributed under the", "License. # coding: utf-8 # pylint: disable= arguments-differ # pylint:", "- w) y1 = random.randint(0, height - h) x[x1:x1+w, y1:y1+h,", "import random import math import numpy as np from mxnet", "and height. mean : int or tuple of (R, G,", "> self.probability: return x width, height, _ = x.shape area", "choices. Inputs: - **data**: input tensor with (Hi x Wi", "self.s_max) * area aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area", "super(RandomErasing, self).__init__() self.probability = probability self.mean = mean self.s_min =", "inappropriate size arg') if not isinstance(self.s_max, float): raise TypeError('Got inappropriate", "= (float, int, np.generic) if isinstance(size, numeric_types): size = (size,", "or more contributor license agreements. See the NOTICE file #", "def __init__(self, size, pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types = (float,", "this work for additional information # regarding copyright ownership. The", "Interpolation method for resizing. By default uses bilinear interpolation. See", "the NOTICE file # distributed with this work for additional", "raise TypeError('Got inappropriate size arg') if random.uniform(0, 1) > self.probability:", "def forward(self, x): if not isinstance(self.probability, float): raise TypeError('Got inappropriate", "image transforms.\" import random import math import numpy as np", "same before and after pad for each axis. (pad,) or", "size, pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types = (float, int, np.generic)", "class RandomErasing(Block): \"\"\"Randomly erasing the area in `src` between `s_min`", "probability : float Probability of erasing. s_min : float Min", "= ratio def forward(self, x): if not isinstance(self.probability, float): raise", "raise TypeError('Got inappropriate size arg') if not isinstance(self.mean, (int, tuple)):", "`s_min` and `s_max` with `probability`. `ratio` controls the ratio between", "C) shape. \"\"\" def __init__(self, size, pad=None, interpolation=2): super(RandomCrop, self).__init__()", "width and height. mean : int or tuple of (R,", "pylint: disable= missing-docstring \"Addtional image transforms.\" import random import math", "with (size[0] x size[1] x C) or (size x size", "area to all area. s_max : float Max area to", "probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__() self.probability", "self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0] else: return", "arguments-differ # pylint: disable= missing-docstring \"Addtional image transforms.\" import random", "if tuple, number of values padded to the edges of", "= after = pad width for all axes. interpolation :", "Upsample result if `src` is smaller than `size`. Parameters ----------", "TypeError('Got inappropriate size arg') if not isinstance(self.mean, (int, tuple)): raise", "default uses bilinear interpolation. See OpenCV's resize function for available", "TypeError('Got inappropriate size arg') if not isinstance(self.s_min, float): raise TypeError('Got", "(W, H) Size of the final output. pad: int or", "`probability`. `ratio` controls the ratio between width and height. `mean`", "(0, 0)) if isinstance(pad, int) else pad def forward(self, x):", "and h < height: x1 = random.randint(0, width - w)", "KIND, either express or implied. See the License for the", "`src` is smaller than `size`. Parameters ---------- size : int", "aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h", "inappropriate size arg') if random.uniform(0, 1) > self.probability: return x", "output. pad: int or tuple if int, size of the", "for each axis. ((before, after),) yields same before and after", "Outputs: - **out**: output tensor with (size[0] x size[1] x", "int, np.generic) if isinstance(size, numeric_types): size = (size, size) self._args", "disable= arguments-differ # pylint: disable= missing-docstring \"Addtional image transforms.\" import", "float Max area to all area. ratio : float The", "... (before_N, after_N)) unique pad widths for each axis. ((before,", "and `s_max` with `probability`. `ratio` controls the ratio between width", "pad for each axis. (pad,) or int is a shortcut", "size) self._args = (size, interpolation) self.pad = ((pad, pad), (pad,", "inappropriate size arg') if not isinstance(self.s_min, float): raise TypeError('Got inappropriate", "tuple of (W, H) Size of the final output. pad:", "random.uniform(0, 1) > self.probability: return x width, height, _ =", "((before, after),) yields same before and after pad for each", "the edges of each axis. ((before_1, after_1), ... (before_N, after_N))", "area to all area. ratio : float The ratio between", "or implied. See the License for the # specific language", "inappropriate size arg') if not isinstance(self.mean, (int, tuple)): raise TypeError('Got", "express or implied. See the License for the # specific", "h) x[x1:x1+w, y1:y1+h, 0] = self.mean[0] x[x1:x1+w, y1:y1+h, 1] =", "area. Inputs: - **data**: input tensor with (Hi x Wi", "height target_area = random.uniform(self.s_min, self.s_max) * area aspect_ratio = random.uniform(self.ratio,", "# pylint: disable= missing-docstring \"Addtional image transforms.\" import random import", "self).__init__() self.probability = probability self.mean = mean self.s_min = s_min", "self.mean = mean self.s_min = s_min self.s_max = s_max self.ratio", "the # specific language governing permissions and limitations # under", "self.pad, mode='constant', constant_values=0)), *self._args)[0] else: return image.random_crop(x, *self._args)[0] class RandomErasing(Block):", "s_min self.s_max = s_max self.ratio = ratio def forward(self, x):", "may obtain a copy of the License at # #", "y1 = random.randint(0, height - h) x[x1:x1+w, y1:y1+h, 0] =", "with `size` (width, height). Padding is optional. Upsample result if", "s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__() self.probability = probability", "*self._args)[0] else: return image.random_crop(x, *self._args)[0] class RandomErasing(Block): \"\"\"Randomly erasing the", "size arg') if not isinstance(self.ratio, float): raise TypeError('Got inappropriate size", "The ASF licenses this file # to you under the", "self.s_max = s_max self.ratio = ratio def forward(self, x): if", "x width, height, _ = x.shape area = width *", "(before_N, after_N)) unique pad widths for each axis. ((before, after),)", "(R, G, B) The value in erasing area. Inputs: -", "# Licensed to the Apache Software Foundation (ASF) under one", "final output. pad: int or tuple if int, size of", "if isinstance(size, numeric_types): size = (size, size) self._args = (size,", "axis. ((before, after),) yields same before and after pad for", "TypeError('Got inappropriate size arg') if not isinstance(self.ratio, float): raise TypeError('Got", "of (W, H) Size of the final output. pad: int", "for before = after = pad width for all axes.", ": float The ratio between width and height. mean :", "inappropriate size arg') if not isinstance(self.ratio, float): raise TypeError('Got inappropriate", "\"\"\"Randomly erasing the area in `src` between `s_min` and `s_max`", "law or agreed to in writing, # software distributed under", "Min area to all area. s_max : float Max area", "Foundation (ASF) under one # or more contributor license agreements.", "size arg') if not isinstance(self.s_max, float): raise TypeError('Got inappropriate size", "for all axes. interpolation : int Interpolation method for resizing.", "_ = x.shape area = width * height target_area =", "all area. s_max : float Max area to all area.", "---------- size : int or tuple of (W, H) Size", "of the zero-padding if tuple, number of values padded to", "forward(self, x): if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)),", "int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if w", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "1] = self.mean[1] x[x1:x1+w, y1:y1+h, 2] = self.mean[2] return x", "Software Foundation (ASF) under one # or more contributor license", "Outputs: - **out**: output tensor with (Hi x Wi x", "= random.randint(0, width - w) y1 = random.randint(0, height -", "# regarding copyright ownership. The ASF licenses this file #", "axis. (pad,) or int is a shortcut for before =", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "under the License. # coding: utf-8 # pylint: disable= arguments-differ", "OR CONDITIONS OF ANY # KIND, either express or implied.", "- **out**: output tensor with (Hi x Wi x C)", "self.ratio = ratio def forward(self, x): if not isinstance(self.probability, float):", "Parameters ---------- size : int or tuple of (W, H)", "< height: x1 = random.randint(0, width - w) y1 =", "else pad def forward(self, x): if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(),", "axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths for", "mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__() self.probability = probability self.mean =", "x[x1:x1+w, y1:y1+h, 0] = self.mean[0] x[x1:x1+w, y1:y1+h, 1] = self.mean[1]", "this file # to you under the Apache License, Version", "transforms.\" import random import math import numpy as np from", "copyright ownership. The ASF licenses this file # to you", "= s_max self.ratio = ratio def forward(self, x): if not", "in writing, # software distributed under the License is distributed", "s_min : float Min area to all area. s_max :", "# under the License. # coding: utf-8 # pylint: disable=", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "See OpenCV's resize function for available choices. Inputs: - **data**:", "= (size, size) self._args = (size, interpolation) self.pad = ((pad,", "height. mean : int or tuple of (R, G, B)", "size arg') if not isinstance(self.s_min, float): raise TypeError('Got inappropriate size", "random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area", "padded to the edges of each axis. ((before_1, after_1), ...", "y1:y1+h, 1] = self.mean[1] x[x1:x1+w, y1:y1+h, 2] = self.mean[2] return", "interpolation=2): super(RandomCrop, self).__init__() numeric_types = (float, int, np.generic) if isinstance(size,", "the ratio between width and height. `mean` means the value", "By default uses bilinear interpolation. See OpenCV's resize function for", "= probability self.mean = mean self.s_min = s_min self.s_max =", "values padded to the edges of each axis. ((before_1, after_1),", "# \"License\"); you may not use this file except in", "if not isinstance(self.probability, float): raise TypeError('Got inappropriate size arg') if", "TypeError('Got inappropriate size arg') if not isinstance(self.s_max, float): raise TypeError('Got", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to the Apache Software Foundation (ASF) under one # or", "pad def forward(self, x): if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad,", "\"License\"); you may not use this file except in compliance", "x C) shape. Outputs: - **out**: output tensor with (Hi", "self.pad = ((pad, pad), (pad, pad), (0, 0)) if isinstance(pad,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "uses bilinear interpolation. See OpenCV's resize function for available choices.", "of erasing. s_min : float Min area to all area.", "a shortcut for before = after = pad width for", "value in erasing area. Inputs: - **data**: input tensor with", "# distributed with this work for additional information # regarding", "`size`. Parameters ---------- size : int or tuple of (W,", "the area in `src` between `s_min` and `s_max` with `probability`.", "writing, # software distributed under the License is distributed on", "(int, tuple)): raise TypeError('Got inappropriate size arg') if random.uniform(0, 1)", "= mean self.s_min = s_min self.s_max = s_max self.ratio =", "to the edges of each axis. ((before_1, after_1), ... (before_N,", "self).__init__() numeric_types = (float, int, np.generic) if isinstance(size, numeric_types): size", "width, height, _ = x.shape area = width * height", "for each axis. (pad,) or int is a shortcut for", "of the final output. pad: int or tuple if int,", "arg') if not isinstance(self.ratio, float): raise TypeError('Got inappropriate size arg')", "arg') if random.uniform(0, 1) > self.probability: return x width, height,", "CONDITIONS OF ANY # KIND, either express or implied. See", "x Wi x C) shape. Outputs: - **out**: output tensor", "isinstance(self.ratio, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.mean,", "C) shape. Outputs: - **out**: output tensor with (Hi x", "OpenCV's resize function for available choices. Inputs: - **data**: input", "width - w) y1 = random.randint(0, height - h) x[x1:x1+w,", "means the value in erasing area. Parameters ---------- probability :", "shape. \"\"\" def __init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96,", "x[x1:x1+w, y1:y1+h, 1] = self.mean[1] x[x1:x1+w, y1:y1+h, 2] = self.mean[2]", "or tuple of (W, H) Size of the final output.", "if isinstance(pad, int) else pad def forward(self, x): if self.pad:", "available choices. Inputs: - **data**: input tensor with (Hi x", "ratio def forward(self, x): if not isinstance(self.probability, float): raise TypeError('Got", "or tuple of (R, G, B) The value in erasing", "for additional information # regarding copyright ownership. The ASF licenses", "the Apache Software Foundation (ASF) under one # or more", "bilinear interpolation. See OpenCV's resize function for available choices. Inputs:", "# # Unless required by applicable law or agreed to", "Version 2.0 (the # \"License\"); you may not use this", "return image.random_crop(x, *self._args)[0] class RandomErasing(Block): \"\"\"Randomly erasing the area in", "one # or more contributor license agreements. See the NOTICE", "from mxnet import image, nd from mxnet.gluon import Block __all__", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "self._args = (size, interpolation) self.pad = ((pad, pad), (pad, pad),", ": float Max area to all area. ratio : float", "\"\"\"Randomly crop `src` with `size` (width, height). Padding is optional.", "between width and height. mean : int or tuple of", "= width * height target_area = random.uniform(self.s_min, self.s_max) * area", "except in compliance # with the License. You may obtain", "raise TypeError('Got inappropriate size arg') if not isinstance(self.s_min, float): raise", "size = (size, size) self._args = (size, interpolation) self.pad =", "mxnet import image, nd from mxnet.gluon import Block __all__ =", "value in erasing area. Parameters ---------- probability : float Probability", "(pad, pad), (0, 0)) if isinstance(pad, int) else pad def", "in `src` between `s_min` and `s_max` with `probability`. `ratio` controls", "NOTICE file # distributed with this work for additional information", "area. s_max : float Max area to all area. ratio", "ratio between width and height. `mean` means the value in", "G, B) The value in erasing area. Inputs: - **data**:", "x C) shape. \"\"\" def __init__(self, size, pad=None, interpolation=2): super(RandomCrop,", "this file except in compliance # with the License. You", "image, nd from mxnet.gluon import Block __all__ = ['RandomCrop', 'RandomErasing']", "size arg') if random.uniform(0, 1) > self.probability: return x width,", "= x.shape area = width * height target_area = random.uniform(self.s_min,", "w < width and h < height: x1 = random.randint(0,", "probability self.mean = mean self.s_min = s_min self.s_max = s_max", "erasing area. Inputs: - **data**: input tensor with (Hi x", "area. ratio : float The ratio between width and height.", "resize function for available choices. Inputs: - **data**: input tensor", "license agreements. See the NOTICE file # distributed with this", "width * height target_area = random.uniform(self.s_min, self.s_max) * area aspect_ratio", "required by applicable law or agreed to in writing, #", "arg') if not isinstance(self.mean, (int, tuple)): raise TypeError('Got inappropriate size", "controls the ratio between width and height. `mean` means the", "((pad, pad), (pad, pad), (0, 0)) if isinstance(pad, int) else", "= s_min self.s_max = s_max self.ratio = ratio def forward(self,", "the License for the # specific language governing permissions and", "random.uniform(self.s_min, self.s_max) * area aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w =", "ANY # KIND, either express or implied. See the License", "# coding: utf-8 # pylint: disable= arguments-differ # pylint: disable=", "the License is distributed on an # \"AS IS\" BASIS,", "import image, nd from mxnet.gluon import Block __all__ = ['RandomCrop',", "**out**: output tensor with (size[0] x size[1] x C) or", "height. `mean` means the value in erasing area. Parameters ----------", "the License. # coding: utf-8 # pylint: disable= arguments-differ #", "image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0] else: return image.random_crop(x, *self._args)[0]", "y1:y1+h, 0] = self.mean[0] x[x1:x1+w, y1:y1+h, 1] = self.mean[1] x[x1:x1+w,", "mean : int or tuple of (R, G, B) The", "not use this file except in compliance # with the", "x Wi x C) shape. \"\"\" def __init__(self, probability=0.5, s_min=0.02,", "of values padded to the edges of each axis. ((before_1,", "the value in erasing area. Parameters ---------- probability : float", "np from mxnet import image, nd from mxnet.gluon import Block", "Unless required by applicable law or agreed to in writing,", "__init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__()", "is a shortcut for before = after = pad width", "width and height. `mean` means the value in erasing area.", "in erasing area. Inputs: - **data**: input tensor with (Hi", "(ASF) under one # or more contributor license agreements. See", "size : int or tuple of (W, H) Size of", "113.86)): super(RandomErasing, self).__init__() self.probability = probability self.mean = mean self.s_min", "# or more contributor license agreements. See the NOTICE file", "self.probability: return x width, height, _ = x.shape area =", "agreed to in writing, # software distributed under the License", "'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly crop `src` with `size` (width, height).", "size x C) shape. \"\"\" def __init__(self, size, pad=None, interpolation=2):", "\"\"\" def __init__(self, size, pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types =", "interpolation) self.pad = ((pad, pad), (pad, pad), (0, 0)) if", "def forward(self, x): if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant',", "Wi x C) shape. Outputs: - **out**: output tensor with", "RandomErasing(Block): \"\"\"Randomly erasing the area in `src` between `s_min` and", "super(RandomCrop, self).__init__() numeric_types = (float, int, np.generic) if isinstance(size, numeric_types):", "random.randint(0, height - h) x[x1:x1+w, y1:y1+h, 0] = self.mean[0] x[x1:x1+w,", "isinstance(self.mean, (int, tuple)): raise TypeError('Got inappropriate size arg') if random.uniform(0,", "height - h) x[x1:x1+w, y1:y1+h, 0] = self.mean[0] x[x1:x1+w, y1:y1+h,", "method for resizing. By default uses bilinear interpolation. See OpenCV's", "shape. Outputs: - **out**: output tensor with (Hi x Wi", "(the # \"License\"); you may not use this file except", "= self.mean[0] x[x1:x1+w, y1:y1+h, 1] = self.mean[1] x[x1:x1+w, y1:y1+h, 2]", "1/self.ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area /", "int Interpolation method for resizing. By default uses bilinear interpolation.", "smaller than `size`. Parameters ---------- size : int or tuple", "class RandomCrop(Block): \"\"\"Randomly crop `src` with `size` (width, height). Padding", "ASF licenses this file # to you under the Apache", "if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0] else:", ": int or tuple of (R, G, B) The value", "int) else pad def forward(self, x): if self.pad: return image.random_crop(nd.array(", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "height, _ = x.shape area = width * height target_area", "tuple if int, size of the zero-padding if tuple, number", "/ aspect_ratio))) if w < width and h < height:", "ownership. The ASF licenses this file # to you under", "import Block __all__ = ['RandomCrop', 'RandomErasing'] class RandomCrop(Block): \"\"\"Randomly crop", "---------- probability : float Probability of erasing. s_min : float", "all area. ratio : float The ratio between width and", "if int, size of the zero-padding if tuple, number of", "s_max : float Max area to all area. ratio :", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__() self.probability = probability self.mean", "coding: utf-8 # pylint: disable= arguments-differ # pylint: disable= missing-docstring", "= int(round(math.sqrt(target_area / aspect_ratio))) if w < width and h", "with the License. You may obtain a copy of the", "height: x1 = random.randint(0, width - w) y1 = random.randint(0,", "numeric_types = (float, int, np.generic) if isinstance(size, numeric_types): size =", "float Min area to all area. s_max : float Max", "(Hi x Wi x C) shape. \"\"\" def __init__(self, probability=0.5,", "applicable law or agreed to in writing, # software distributed", "the final output. pad: int or tuple if int, size", "pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types = (float, int, np.generic) if", "function for available choices. Inputs: - **data**: input tensor with", "# pylint: disable= arguments-differ # pylint: disable= missing-docstring \"Addtional image", "1) > self.probability: return x width, height, _ = x.shape", "(pad,) or int is a shortcut for before = after", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "self.mean[0] x[x1:x1+w, y1:y1+h, 1] = self.mean[1] x[x1:x1+w, y1:y1+h, 2] =", "file # to you under the Apache License, Version 2.0", "pad), (pad, pad), (0, 0)) if isinstance(pad, int) else pad", "- h) x[x1:x1+w, y1:y1+h, 0] = self.mean[0] x[x1:x1+w, y1:y1+h, 1]", "isinstance(self.probability, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.s_min,", "# with the License. You may obtain a copy of", "shortcut for before = after = pad width for all", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "language governing permissions and limitations # under the License. #", "Parameters ---------- probability : float Probability of erasing. s_min :", "x size x C) shape. \"\"\" def __init__(self, size, pad=None,", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "area. Parameters ---------- probability : float Probability of erasing. s_min", "yields same before and after pad for each axis. (pad,)", "* area aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area *", "to all area. ratio : float The ratio between width", "if not isinstance(self.s_max, float): raise TypeError('Got inappropriate size arg') if", "area aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area * aspect_ratio)))", "float): raise TypeError('Got inappropriate size arg') if not isinstance(self.ratio, float):", "nd from mxnet.gluon import Block __all__ = ['RandomCrop', 'RandomErasing'] class", "under one # or more contributor license agreements. See the", "each axis. ((before, after),) yields same before and after pad", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "after pad for each axis. (pad,) or int is a", "Wi x C) shape. \"\"\" def __init__(self, probability=0.5, s_min=0.02, s_max=0.4,", "(size[0] x size[1] x C) or (size x size x", "random import math import numpy as np from mxnet import", "aspect_ratio))) if w < width and h < height: x1", "information # regarding copyright ownership. The ASF licenses this file", "input tensor with (Hi x Wi x C) shape. Outputs:", "the Apache License, Version 2.0 (the # \"License\"); you may", "numpy as np from mxnet import image, nd from mxnet.gluon", "if `src` is smaller than `size`. Parameters ---------- size :", "optional. Upsample result if `src` is smaller than `size`. Parameters", "h = int(round(math.sqrt(target_area / aspect_ratio))) if w < width and", "float): raise TypeError('Got inappropriate size arg') if not isinstance(self.s_max, float):", "self.probability = probability self.mean = mean self.s_min = s_min self.s_max", "*self._args)[0] class RandomErasing(Block): \"\"\"Randomly erasing the area in `src` between", "after_N)) unique pad widths for each axis. ((before, after),) yields", "you under the Apache License, Version 2.0 (the # \"License\");", "C) or (size x size x C) shape. \"\"\" def", "if random.uniform(0, 1) > self.probability: return x width, height, _", "(width, height). Padding is optional. Upsample result if `src` is", "after = pad width for all axes. interpolation : int", "# KIND, either express or implied. See the License for", "H) Size of the final output. pad: int or tuple", "The value in erasing area. Inputs: - **data**: input tensor", "tensor with (size[0] x size[1] x C) or (size x", "than `size`. Parameters ---------- size : int or tuple of", "result if `src` is smaller than `size`. Parameters ---------- size", "pad width for all axes. interpolation : int Interpolation method", "agreements. See the NOTICE file # distributed with this work", "for available choices. Inputs: - **data**: input tensor with (Hi", "between `s_min` and `s_max` with `probability`. `ratio` controls the ratio", "licenses this file # to you under the Apache License,", "not isinstance(self.s_max, float): raise TypeError('Got inappropriate size arg') if not", "`src` with `size` (width, height). Padding is optional. Upsample result", "from mxnet.gluon import Block __all__ = ['RandomCrop', 'RandomErasing'] class RandomCrop(Block):", "= int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if", "output tensor with (size[0] x size[1] x C) or (size", "not isinstance(self.s_min, float): raise TypeError('Got inappropriate size arg') if not", "by applicable law or agreed to in writing, # software", "# Unless required by applicable law or agreed to in", ": int or tuple of (W, H) Size of the", "* aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if w <", "__init__(self, size, pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types = (float, int,", "width and h < height: x1 = random.randint(0, width -", "pylint: disable= arguments-differ # pylint: disable= missing-docstring \"Addtional image transforms.\"", "as np from mxnet import image, nd from mxnet.gluon import", "to all area. s_max : float Max area to all", "with (Hi x Wi x C) shape. \"\"\" def __init__(self,", "mode='constant', constant_values=0)), *self._args)[0] else: return image.random_crop(x, *self._args)[0] class RandomErasing(Block): \"\"\"Randomly", "float The ratio between width and height. mean : int", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "- **out**: output tensor with (size[0] x size[1] x C)", "limitations # under the License. # coding: utf-8 # pylint:", "int or tuple of (R, G, B) The value in", "raise TypeError('Got inappropriate size arg') if not isinstance(self.ratio, float): raise", "int is a shortcut for before = after = pad", "License. You may obtain a copy of the License at", "before and after pad for each axis. (pad,) or int", "or (size x size x C) shape. \"\"\" def __init__(self,", "float Probability of erasing. s_min : float Min area to", "\"Addtional image transforms.\" import random import math import numpy as", "h < height: x1 = random.randint(0, width - w) y1", "You may obtain a copy of the License at #", "(Hi x Wi x C) shape. Outputs: - **out**: output", "with `probability`. `ratio` controls the ratio between width and height.", "aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if w < width", "compliance # with the License. You may obtain a copy", "number of values padded to the edges of each axis.", "x): if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0]", "s_max self.ratio = ratio def forward(self, x): if not isinstance(self.probability,", "constant_values=0)), *self._args)[0] else: return image.random_crop(x, *self._args)[0] class RandomErasing(Block): \"\"\"Randomly erasing", "image.random_crop(x, *self._args)[0] class RandomErasing(Block): \"\"\"Randomly erasing the area in `src`", "def __init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing,", "between width and height. `mean` means the value in erasing", "is smaller than `size`. Parameters ---------- size : int or" ]
[ "each annotation annot_counts_df = annot_serie \\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\", "# MIT-BIH Arrhythmia DB Exploration ''' record_ids = [os.path.basename(file)[:-4] for", "contains `{annot_serie.size}` annotations ' f'among which `{beat_annot_count}` beat annotations and", "y=full_df[signal], mode='lines', name=signal)) for annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values, y=full_df[annot_matching_rows][signal].values,", "wfdb import os ANNOTATIONS_COL_NAME = 'annotations' ''' # MIT-BIH Arrhythmia", "annot in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot fig =", "name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie], axis=1) ''' ## Annotations '''", "= annot_serie \\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig =", "wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in this record :') for idx,", "directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr* files and such should be placed", "signal', record.sig_name) # Plot signals and annotations matching_rows_by_annot = {}", "in enumerate(record.sig_name): st.write(f'- `{signal}` : in {record.units[idx]}, with a frequency", "= full_df[ANNOTATIONS_COL_NAME] == annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with", "# Plot counts for each annotation annot_counts_df = annot_serie \\", "placed ', 'immediately under the ./data/ directory') else: record_ids.sort() record_id", "st.selectbox('Select a signal', record.sig_name) # Plot signals and annotations matching_rows_by_annot", "wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in this record", "## Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot", "= st.selectbox('Select a record id', record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation", "a frequency of ' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for this", "full_df = pd.concat([signals_df, annot_serie], axis=1) ''' ## Annotations ''' beat_annot_count", "annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal],", "*\\*.atr* files and such should be placed ', 'immediately under", "in unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More explanations on the", "columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie],", "' f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The annotations are the followings", "record :') for idx, signal in enumerate(record.sig_name): st.write(f'- `{signal}` :", "* import glob import wfdb import os ANNOTATIONS_COL_NAME = 'annotations'", "with a frequency of ' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for", "= wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in this record :') for", "st.write(f'This record contains `{annot_serie.size}` annotations ' f'among which `{beat_annot_count}` beat", "streamlit as st import pandas as pd from utils import", "st.write(f'- `{signal}` : in {record.units[idx]}, with a frequency of '", "f'among which `{beat_annot_count}` beat annotations and ' f'`{non_beat_annot_count}` non beat", "import glob import wfdb import os ANNOTATIONS_COL_NAME = 'annotations' '''", "annotation(s).') st.write('The annotations are the followings :') for annot in", "annotations are available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts", "Plot counts for each annotation annot_counts_df = annot_serie \\ .value_counts()", ".rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )])", "textposition='auto' )]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ##", "yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ## Explore full dataset ''' signal", "Plot signals and annotations matching_rows_by_annot = {} for annot in", "should be placed ', 'immediately under the ./data/ directory') else:", "text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for annot,", "annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in this record :')", "and such should be placed ', 'immediately under the ./data/", "= annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}` annotations", "by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ## Explore full dataset", "glob.glob('data/*.dat')] if len(record_ids) == 0: st.write('Warning ! No data could", "as pd from utils import * import glob import wfdb", "./data/ directory') else: record_ids.sort() record_id = st.selectbox('Select a record id',", "f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The annotations are the followings :')", "could be found under the ./data/ directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr*", "''' ## Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum()", "for annot in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot fig", "record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found", "{record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME)", "the annotations are available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot", "annotations matching_rows_by_annot = {} for annot in unique_annot: matching_rows_by_annot[annot] =", "matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal", "fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines',", "id', record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals", "in glob.glob('data/*.dat')] if len(record_ids) == 0: st.write('Warning ! No data", "from utils import * import glob import wfdb import os", "annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie], axis=1)", "which `{beat_annot_count}` beat annotations and ' f'`{non_beat_annot_count}` non beat annotation(s).')", "f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for this record : {record.comments}') signals_df", "go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for", "0: st.write('Warning ! No data could be found under the", "= [os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')] if len(record_ids) == 0:", "data could be found under the ./data/ directory.', '*\\*.dat*, *\\*.hea*,", "= annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}` annotations ' f'among which", "'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for each annotation annot_counts_df = annot_serie", "''' # MIT-BIH Arrhythmia DB Exploration ''' record_ids = [os.path.basename(file)[:-4]", ".reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by", "if len(record_ids) == 0: st.write('Warning ! No data could be", "! No data could be found under the ./data/ directory.',", "record_id = st.selectbox('Select a record id', record_ids) record = wfdb.rdrecord(f'data/{record_id}')", "non beat annotation(s).') st.write('The annotations are the followings :') for", ":') for annot in unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More", "for file in glob.glob('data/*.dat')] if len(record_ids) == 0: st.write('Warning !", "for idx, signal in enumerate(record.sig_name): st.write(f'- `{signal}` : in {record.units[idx]},", "annotations ' f'among which `{beat_annot_count}` beat annotations and ' f'`{non_beat_annot_count}`", "signal = st.selectbox('Select a signal', record.sig_name) # Plot signals and", "pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie], axis=1) ''' ##", "{} for annot in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot", "this record :') for idx, signal in enumerate(record.sig_name): st.write(f'- `{signal}`", "st.write('The annotations are the followings :') for annot in unique_annot:", "import * import glob import wfdb import os ANNOTATIONS_COL_NAME =", "for each annotation annot_counts_df = annot_serie \\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME)", "`{signal}` : in {record.units[idx]}, with a frequency of ' f'{record.fs", "record contains `{annot_serie.size}` annotations ' f'among which `{beat_annot_count}` beat annotations", "full_df[ANNOTATIONS_COL_NAME] == annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal))))", "frequency of ' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for this record", "utils import * import glob import wfdb import os ANNOTATIONS_COL_NAME", "''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values", "signals and annotations matching_rows_by_annot = {} for annot in unique_annot:", "found in this record :') for idx, signal in enumerate(record.sig_name):", "*\\*.hea*, *\\*.atr* files and such should be placed ', 'immediately", ": {record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample,", "unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{}", "= go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal))", "counts for each annotation annot_counts_df = annot_serie \\ .value_counts() \\", "./data/ directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr* files and such should be", "' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for each annotation annot_counts_df =", "with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for annot, annot_matching_rows in", "Explore full dataset ''' signal = st.selectbox('Select a signal', record.sig_name)", ": in {record.units[idx]}, with a frequency of ' f'{record.fs *", "'atr') st.write('Signals found in this record :') for idx, signal", "fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values,", "as go import streamlit as st import pandas as pd", "[os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')] if len(record_ids) == 0: st.write('Warning", "', 'immediately under the ./data/ directory') else: record_ids.sort() record_id =", "== 0: st.write('Warning ! No data could be found under", "st.write('Signals found in this record :') for idx, signal in", "= annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This record", "annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values, y=full_df[annot_matching_rows][signal].values, mode='markers', name='{} (annot)'.format(annot))) st.plotly_chart(fig)", "= {} for annot in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] ==", "y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig)", "record_ids = [os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')] if len(record_ids) ==", "annotation annot_counts_df = annot_serie \\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts')", "annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for annot, annot_matching_rows in matching_rows_by_annot.items():", "st import pandas as pd from utils import * import", "unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More explanations on the annotations", "st.write(bar_fig) ''' ## Explore full dataset ''' signal = st.selectbox('Select", "record.sig_name) # Plot signals and annotations matching_rows_by_annot = {} for", "followings :') for annot in unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}')", "''' record_ids = [os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')] if len(record_ids)", "= wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in this", "in {record.units[idx]}, with a frequency of ' f'{record.fs * record.samps_per_frame[idx]}hz')", "glob import wfdb import os ANNOTATIONS_COL_NAME = 'annotations' ''' #", "on the annotations are available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') #", "# Plot signals and annotations matching_rows_by_annot = {} for annot", "are the followings :') for annot in unique_annot: st.write(f'- `{annot}`", "go import streamlit as st import pandas as pd from", "here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for each annotation", "a signal', record.sig_name) # Plot signals and annotations matching_rows_by_annot =", "import wfdb import os ANNOTATIONS_COL_NAME = 'annotations' ''' # MIT-BIH", "in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot fig = go.Figure(layout=go.Layout(title=go.layout.Title(", "' f'among which `{beat_annot_count}` beat annotations and ' f'`{non_beat_annot_count}` non", "record_ids.sort() record_id = st.selectbox('Select a record id', record_ids) record =", "are available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for", "st.selectbox('Select a record id', record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation =", "axis=1) ''' ## Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count =", "'*\\*.dat*, *\\*.hea*, *\\*.atr* files and such should be placed ',", "the ./data/ directory') else: record_ids.sort() record_id = st.selectbox('Select a record", "= go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts',", "count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ## Explore full dataset '''", "xaxis_title='annotations') st.write(bar_fig) ''' ## Explore full dataset ''' signal =", "st.write('More explanations on the annotations are available here : '", "\\ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations", "in this record :') for idx, signal in enumerate(record.sig_name): st.write(f'-", "{annotation_definitions[annot]}') st.write('More explanations on the annotations are available here :", "= 'annotations' ''' # MIT-BIH Arrhythmia DB Exploration ''' record_ids", "\\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto'", "'immediately under the ./data/ directory') else: record_ids.sort() record_id = st.selectbox('Select", "'annotations' ''' # MIT-BIH Arrhythmia DB Exploration ''' record_ids =", "else: record_ids.sort() record_id = st.selectbox('Select a record id', record_ids) record", "`{annot}` : {annotation_definitions[annot]}') st.write('More explanations on the annotations are available", "{record.units[idx]}, with a frequency of ' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments", "beat annotations and ' f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The annotations", "file in glob.glob('data/*.dat')] if len(record_ids) == 0: st.write('Warning ! No", "annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This record contains", "record = wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in", "ANNOTATIONS_COL_NAME = 'annotations' ''' # MIT-BIH Arrhythmia DB Exploration '''", "`{annot_serie.size}` annotations ' f'among which `{beat_annot_count}` beat annotations and '", "annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}` annotations '", "st.write('Warning ! No data could be found under the ./data/", "pd from utils import * import glob import wfdb import", "== annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values,", "for annot in unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More explanations", "be found under the ./data/ directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr* files", ": {annotation_definitions[annot]}') st.write('More explanations on the annotations are available here", "explanations on the annotations are available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml')", "name=signal)) for annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values, y=full_df[annot_matching_rows][signal].values, mode='markers', name='{}", "annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}` annotations ' f'among which `{beat_annot_count}`", "signal in enumerate(record.sig_name): st.write(f'- `{signal}` : in {record.units[idx]}, with a", "annot_serie \\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME],", "* record.samps_per_frame[idx]}hz') st.write(f'Comments for this record : {record.comments}') signals_df =", "record id', record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr')", "be placed ', 'immediately under the ./data/ directory') else: record_ids.sort()", "for this record : {record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie", "DB Exploration ''' record_ids = [os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')]", "idx, signal in enumerate(record.sig_name): st.write(f'- `{signal}` : in {record.units[idx]}, with", "beat annotation(s).') st.write('The annotations are the followings :') for annot", "Exploration ''' record_ids = [os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')] if", ":') for idx, signal in enumerate(record.sig_name): st.write(f'- `{signal}` : in", "found under the ./data/ directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr* files and", "of ' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for this record :", "st.write(f'Comments for this record : {record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name)", "import pandas as pd from utils import * import glob", "## Explore full dataset ''' signal = st.selectbox('Select a signal',", ")]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ## Explore", "under the ./data/ directory') else: record_ids.sort() record_id = st.selectbox('Select a", "''' ## Explore full dataset ''' signal = st.selectbox('Select a", "annot_serie], axis=1) ''' ## Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count", "annotations are the followings :') for annot in unique_annot: st.write(f'-", "plotly.graph_objects as go import streamlit as st import pandas as", "a record id', record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}',", "bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ## Explore full", "import os ANNOTATIONS_COL_NAME = 'annotations' ''' # MIT-BIH Arrhythmia DB", "Arrhythmia DB Exploration ''' record_ids = [os.path.basename(file)[:-4] for file in", "record : {record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol,", "index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie], axis=1) ''' ## Annotations", "directory') else: record_ids.sort() record_id = st.selectbox('Select a record id', record_ids)", "text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) '''", "dataset ''' signal = st.selectbox('Select a signal', record.sig_name) # Plot", "as st import pandas as pd from utils import *", "for annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values, y=full_df[annot_matching_rows][signal].values, mode='markers', name='{} (annot)'.format(annot)))", "annot_counts_df = annot_serie \\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig", "under the ./data/ directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr* files and such", "len(record_ids) == 0: st.write('Warning ! No data could be found", "full dataset ''' signal = st.selectbox('Select a signal', record.sig_name) #", "unique_annot = annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}` annotations ' f'among", "the followings :') for annot in unique_annot: st.write(f'- `{annot}` :", "import plotly.graph_objects as go import streamlit as st import pandas", "this record : {record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie =", "and annotations matching_rows_by_annot = {} for annot in unique_annot: matching_rows_by_annot[annot]", "MIT-BIH Arrhythmia DB Exploration ''' record_ids = [os.path.basename(file)[:-4] for file", "No data could be found under the ./data/ directory.', '*\\*.dat*,", "pandas as pd from utils import * import glob import", "' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for this record : {record.comments}')", "st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More explanations on the annotations are", "''' signal = st.selectbox('Select a signal', record.sig_name) # Plot signals", "enumerate(record.sig_name): st.write(f'- `{signal}` : in {record.units[idx]}, with a frequency of", "beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This", "bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by count',", "non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}`", "os ANNOTATIONS_COL_NAME = 'annotations' ''' # MIT-BIH Arrhythmia DB Exploration", "annot in unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More explanations on", "pd.concat([signals_df, annot_serie], axis=1) ''' ## Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum()", "matching_rows_by_annot = {} for annot in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME]", "= pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df =", "= pd.concat([signals_df, annot_serie], axis=1) ''' ## Annotations ''' beat_annot_count =", "pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df,", "annotations and ' f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The annotations are", "signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df", "mode='lines', name=signal)) for annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values, y=full_df[annot_matching_rows][signal].values, mode='markers',", "Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot =", "= pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie], axis=1) '''", "the ./data/ directory.', '*\\*.dat*, *\\*.hea*, *\\*.atr* files and such should", "files and such should be placed ', 'immediately under the", "and ' f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The annotations are the", "`{beat_annot_count}` beat annotations and ' f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The", "such should be placed ', 'immediately under the ./data/ directory')", "record.samps_per_frame[idx]}hz') st.write(f'Comments for this record : {record.comments}') signals_df = pd.DataFrame(record.p_signal,", ".value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'],", "available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for each", "go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations')", "signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for annot, annot_matching_rows", "\\ .value_counts() \\ .rename_axis(ANNOTATIONS_COL_NAME) \\ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'],", ": ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for each annotation annot_counts_df", "= st.selectbox('Select a signal', record.sig_name) # Plot signals and annotations", "import streamlit as st import pandas as pd from utils" ]
[ "pass def __reduce_ex__(self,*args): pass def __repr__(self,*args): \"\"\" __repr__(self: object) ->", "This class cannot be inherited. \"\"\" def ZZZ(self): \"\"\"hardcoded/mock instance", "def __repr__(self,*args): \"\"\" __repr__(self: object) -> str \"\"\" pass Current=property(lambda", "self: None) \"\"\"Gets the currently referenced character in the string", "of the enumerated string. Returns: true if the index is", "__repr__(self,*args): \"\"\" __repr__(self: object) -> str \"\"\" pass Current=property(lambda self:", "__enter__(self,*args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self,*args):", "System.CharEnumerator object. \"\"\" pass def Dispose(self): \"\"\" Dispose(self: CharEnumerator) Releases", "of the System.CharEnumerator class. \"\"\" pass def MoveNext(self): \"\"\" MoveNext(self:", "\"\"\" pass def __exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)", "object. Returns: An System.Object that is a copy of the", "resources used by the current instance of the System.CharEnumerator class.", "\"\"\" pass def __contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char) -> bool", "reading its individual characters. This class cannot be inherited. \"\"\"", "if the index is successfully incremented and within the enumerated", "pass def __contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char) -> bool \"\"\"", "MoveNext(self: CharEnumerator) -> bool Increments the internal index of the", "the current System.CharEnumerator object to the next character of the", "Reset(self): \"\"\" Reset(self: CharEnumerator) Initializes the index to a position", "x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\"", "pass def next(self,*args): \"\"\" next(self: object) -> object \"\"\" pass", "the enumerated string; otherwise,false. \"\"\" pass def next(self,*args): \"\"\" next(self:", "pass def Reset(self): \"\"\" Reset(self: CharEnumerator) Initializes the index to", "\"\"\" pass def next(self,*args): \"\"\" next(self: object) -> object \"\"\"", "class cannot be inherited. \"\"\" def ZZZ(self): \"\"\"hardcoded/mock instance of", "__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self,*args): \"\"\"", "the current System.CharEnumerator object. \"\"\" pass def Dispose(self): \"\"\" Dispose(self:", "logically before the first character of the enumerated string. \"\"\"", "None) \"\"\"Gets the currently referenced character in the string enumerated", "__exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def", "An System.Object that is a copy of the current System.CharEnumerator", "def Dispose(self): \"\"\" Dispose(self: CharEnumerator) Releases all resources used by", "object \"\"\" pass def Reset(self): \"\"\" Reset(self: CharEnumerator) Initializes the", "__init__(self,*args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes", "otherwise,false. \"\"\" pass def next(self,*args): \"\"\" next(self: object) -> object", "pass def __repr__(self,*args): \"\"\" __repr__(self: object) -> str \"\"\" pass", "position logically before the first character of the enumerated string.", "__iter__(self: IEnumerator) -> object \"\"\" pass def __reduce_ex__(self,*args): pass def", "string. \"\"\" pass def __contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char) ->", "return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an instance of the class\"\"\" def", "of the current System.CharEnumerator object to the next character of", "the first character of the enumerated string. \"\"\" pass def", "used by the current instance of the System.CharEnumerator class. \"\"\"", "Initializes the index to a position logically before the first", "string; otherwise,false. \"\"\" pass def next(self,*args): \"\"\" next(self: object) ->", "instance of the System.CharEnumerator class. \"\"\" pass def MoveNext(self): \"\"\"", "pass Current=property(lambda self: object(),lambda self,v: None,lambda self: None) \"\"\"Gets the", "character of the enumerated string. Returns: true if the index", "\"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char) -> bool \"\"\" pass def __enter__(self,*args):", "Char) -> bool \"\"\" pass def __enter__(self,*args): \"\"\" __enter__(self: IDisposable)", "initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__", "str \"\"\" pass Current=property(lambda self: object(),lambda self,v: None,lambda self: None)", "Dispose(self): \"\"\" Dispose(self: CharEnumerator) Releases all resources used by the", "\"\"\" Reset(self: CharEnumerator) Initializes the index to a position logically", "\"\"\"hardcoded/mock instance of the class\"\"\" return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an", "the enumerated string. \"\"\" pass def __contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value:", "\"\"\" Dispose(self: CharEnumerator) Releases all resources used by the current", "the next character of the enumerated string. Returns: true if", "pass def __enter__(self,*args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass", "self: object(),lambda self,v: None,lambda self: None) \"\"\"Gets the currently referenced", "def __enter__(self,*args): \"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def", "enumerated string. \"\"\" pass def __contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char)", "instance=ZZZ() \"\"\"hardcoded/returns an instance of the class\"\"\" def Clone(self): \"\"\"", "the System.CharEnumerator class. \"\"\" pass def MoveNext(self): \"\"\" MoveNext(self: CharEnumerator)", "Current=property(lambda self: object(),lambda self,v: None,lambda self: None) \"\"\"Gets the currently", "object to the next character of the enumerated string. Returns:", "see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature", "System.CharEnumerator class. \"\"\" pass def MoveNext(self): \"\"\" MoveNext(self: CharEnumerator) ->", "object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self,*args): \"\"\" x.__init__(...) initializes", "System.CharEnumerator object. Returns: An System.Object that is a copy of", "for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x;", "copy of the current System.CharEnumerator object. \"\"\" pass def Dispose(self):", "index is successfully incremented and within the enumerated string; otherwise,false.", "IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self,*args): \"\"\" x.__init__(...)", "Increments the internal index of the current System.CharEnumerator object to", "next(self,*args): \"\"\" next(self: object) -> object \"\"\" pass def Reset(self):", "__reduce_ex__(self,*args): pass def __repr__(self,*args): \"\"\" __repr__(self: object) -> str \"\"\"", "characters. This class cannot be inherited. \"\"\" def ZZZ(self): \"\"\"hardcoded/mock", "Creates a copy of the current System.CharEnumerator object. Returns: An", "the current System.CharEnumerator object. Returns: An System.Object that is a", "internal index of the current System.CharEnumerator object to the next", "before the first character of the enumerated string. \"\"\" pass", "next(self: object) -> object \"\"\" pass def Reset(self): \"\"\" Reset(self:", "cannot be inherited. \"\"\" def ZZZ(self): \"\"\"hardcoded/mock instance of the", "current System.CharEnumerator object. \"\"\" pass def Dispose(self): \"\"\" Dispose(self: CharEnumerator)", "def __reduce_ex__(self,*args): pass def __repr__(self,*args): \"\"\" __repr__(self: object) -> str", "instance of the class\"\"\" return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an instance", "def Clone(self): \"\"\" Clone(self: CharEnumerator) -> object Creates a copy", "__iter__(self,*args): \"\"\" __iter__(self: IEnumerator) -> object \"\"\" pass def __reduce_ex__(self,*args):", "IEnumerator) -> object \"\"\" pass def __reduce_ex__(self,*args): pass def __repr__(self,*args):", "x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes", "the string enumerated by this System.CharEnumerator object. Get: Current(self: CharEnumerator)", "-> object \"\"\" pass def Reset(self): \"\"\" Reset(self: CharEnumerator) Initializes", "by this System.CharEnumerator object. Get: Current(self: CharEnumerator) -> Char \"\"\"", "\"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x;", "index to a position logically before the first character of", "of the class\"\"\" return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an instance of", "\"\"\" next(self: object) -> object \"\"\" pass def Reset(self): \"\"\"", "a copy of the current System.CharEnumerator object. Returns: An System.Object", "signature \"\"\" pass def __iter__(self,*args): \"\"\" __iter__(self: IEnumerator) -> object", "initializes x; see x.__class__.__doc__ for signature \"\"\" pass def __iter__(self,*args):", "by the current instance of the System.CharEnumerator class. \"\"\" pass", "None,lambda self: None) \"\"\"Gets the currently referenced character in the", "individual characters. This class cannot be inherited. \"\"\" def ZZZ(self):", "the currently referenced character in the string enumerated by this", "x; see x.__class__.__doc__ for signature \"\"\" pass def __iter__(self,*args): \"\"\"", "enumerated string. Returns: true if the index is successfully incremented", "the class\"\"\" return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an instance of the", "class\"\"\" def Clone(self): \"\"\" Clone(self: CharEnumerator) -> object Creates a", "for signature \"\"\" pass def __iter__(self,*args): \"\"\" __iter__(self: IEnumerator) ->", "of the current System.CharEnumerator object. \"\"\" pass def Dispose(self): \"\"\"", "Reset(self: CharEnumerator) Initializes the index to a position logically before", "Returns: An System.Object that is a copy of the current", "def __exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass", "of the current System.CharEnumerator object. Returns: An System.Object that is", "x.__class__.__doc__ for signature \"\"\" pass def __iter__(self,*args): \"\"\" __iter__(self: IEnumerator)", "\"\"\" pass def __reduce_ex__(self,*args): pass def __repr__(self,*args): \"\"\" __repr__(self: object)", "the current instance of the System.CharEnumerator class. \"\"\" pass def", "\"\"\" pass def __enter__(self,*args): \"\"\" __enter__(self: IDisposable) -> object \"\"\"", "\"\"\" Clone(self: CharEnumerator) -> object Creates a copy of the", "CharEnumerator) Releases all resources used by the current instance of", "CharEnumerator) -> object Creates a copy of the current System.CharEnumerator", "pass def __exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\"", "\"\"\" pass def __iter__(self,*args): \"\"\" __iter__(self: IEnumerator) -> object \"\"\"", "-> bool \"\"\" pass def __enter__(self,*args): \"\"\" __enter__(self: IDisposable) ->", "iterating over a System.String object and reading its individual characters.", "object,exc_back: object) \"\"\" pass def __init__(self,*args): \"\"\" x.__init__(...) initializes x;", "be inherited. \"\"\" def ZZZ(self): \"\"\"hardcoded/mock instance of the class\"\"\"", "character in the string enumerated by this System.CharEnumerator object. Get:", "x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see", "def ZZZ(self): \"\"\"hardcoded/mock instance of the class\"\"\" return CharEnumerator() instance=ZZZ()", "inherited. \"\"\" def ZZZ(self): \"\"\"hardcoded/mock instance of the class\"\"\" return", "\"\"\" pass def MoveNext(self): \"\"\" MoveNext(self: CharEnumerator) -> bool Increments", "object(),lambda self,v: None,lambda self: None) \"\"\"Gets the currently referenced character", "index of the current System.CharEnumerator object to the next character", "see x.__class__.__doc__ for signature \"\"\" pass def __iter__(self,*args): \"\"\" __iter__(self:", "object Creates a copy of the current System.CharEnumerator object. Returns:", "all resources used by the current instance of the System.CharEnumerator", "\"\"\" pass Current=property(lambda self: object(),lambda self,v: None,lambda self: None) \"\"\"Gets", "def next(self,*args): \"\"\" next(self: object) -> object \"\"\" pass def", "string enumerated by this System.CharEnumerator object. Get: Current(self: CharEnumerator) ->", "CharEnumerator) -> bool Increments the internal index of the current", "__contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char) -> bool \"\"\" pass def", "IDisposable) -> object \"\"\" pass def __exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type:", "and reading its individual characters. This class cannot be inherited.", "bool Increments the internal index of the current System.CharEnumerator object", "enumerated string; otherwise,false. \"\"\" pass def next(self,*args): \"\"\" next(self: object)", "to the next character of the enumerated string. Returns: true", "object. \"\"\" pass def Dispose(self): \"\"\" Dispose(self: CharEnumerator) Releases all", "-> bool Increments the internal index of the current System.CharEnumerator", "for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass", "the internal index of the current System.CharEnumerator object to the", "of the enumerated string. \"\"\" pass def __contains__(self,*args): \"\"\" __contains__[Char](enumerator:", "def __contains__(self,*args): \"\"\" __contains__[Char](enumerator: IEnumerator[Char],value: Char) -> bool \"\"\" pass", "to a position logically before the first character of the", "see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...)", "\"\"\" __iter__(self: IEnumerator) -> object \"\"\" pass def __reduce_ex__(self,*args): pass", "\"\"\"Gets the currently referenced character in the string enumerated by", "Clone(self: CharEnumerator) -> object Creates a copy of the current", "__contains__[Char](enumerator: IEnumerator[Char],value: Char) -> bool \"\"\" pass def __enter__(self,*args): \"\"\"", "Returns: true if the index is successfully incremented and within", "object \"\"\" pass def __reduce_ex__(self,*args): pass def __repr__(self,*args): \"\"\" __repr__(self:", "is a copy of the current System.CharEnumerator object. \"\"\" pass", "System.CharEnumerator object to the next character of the enumerated string.", "object) -> str \"\"\" pass Current=property(lambda self: object(),lambda self,v: None,lambda", "its individual characters. This class cannot be inherited. \"\"\" def", "the index to a position logically before the first character", "def MoveNext(self): \"\"\" MoveNext(self: CharEnumerator) -> bool Increments the internal", "\"\"\"hardcoded/returns an instance of the class\"\"\" def Clone(self): \"\"\" Clone(self:", "first character of the enumerated string. \"\"\" pass def __contains__(self,*args):", "true if the index is successfully incremented and within the", "__enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self,*args): \"\"\" __exit__(self:", "\"\"\" pass def Reset(self): \"\"\" Reset(self: CharEnumerator) Initializes the index", "-> object \"\"\" pass def __reduce_ex__(self,*args): pass def __repr__(self,*args): \"\"\"", "def __iter__(self,*args): \"\"\" __iter__(self: IEnumerator) -> object \"\"\" pass def", "the class\"\"\" def Clone(self): \"\"\" Clone(self: CharEnumerator) -> object Creates", "\"\"\" Supports iterating over a System.String object and reading its", "\"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) \"\"\" pass def __init__(self,*args):", "System.String object and reading its individual characters. This class cannot", "current System.CharEnumerator object to the next character of the enumerated", "-> str \"\"\" pass Current=property(lambda self: object(),lambda self,v: None,lambda self:", "object and reading its individual characters. This class cannot be", "MoveNext(self): \"\"\" MoveNext(self: CharEnumerator) -> bool Increments the internal index", "enumerated by this System.CharEnumerator object. Get: Current(self: CharEnumerator) -> Char", "successfully incremented and within the enumerated string; otherwise,false. \"\"\" pass", "signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see", "__repr__(self: object) -> str \"\"\" pass Current=property(lambda self: object(),lambda self,v:", "in the string enumerated by this System.CharEnumerator object. Get: Current(self:", "\"\"\" def ZZZ(self): \"\"\"hardcoded/mock instance of the class\"\"\" return CharEnumerator()", "object) -> object \"\"\" pass def Reset(self): \"\"\" Reset(self: CharEnumerator)", "character of the enumerated string. \"\"\" pass def __contains__(self,*args): \"\"\"", "object) \"\"\" pass def __init__(self,*args): \"\"\" x.__init__(...) initializes x; see", "a System.String object and reading its individual characters. This class", "incremented and within the enumerated string; otherwise,false. \"\"\" pass def", "class CharEnumerator(object): \"\"\" Supports iterating over a System.String object and", "over a System.String object and reading its individual characters. This", "\"\"\" __enter__(self: IDisposable) -> object \"\"\" pass def __exit__(self,*args): \"\"\"", "def __init__(self,*args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...)", "and within the enumerated string; otherwise,false. \"\"\" pass def next(self,*args):", "signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature \"\"\" pass def", "-> object Creates a copy of the current System.CharEnumerator object.", "referenced character in the string enumerated by this System.CharEnumerator object.", "of the class\"\"\" def Clone(self): \"\"\" Clone(self: CharEnumerator) -> object", "Dispose(self: CharEnumerator) Releases all resources used by the current instance", "\"\"\" MoveNext(self: CharEnumerator) -> bool Increments the internal index of", "CharEnumerator(object): \"\"\" Supports iterating over a System.String object and reading", "pass def __init__(self,*args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__ for", "CharEnumerator) Initializes the index to a position logically before the", "CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an instance of the class\"\"\" def Clone(self):", "pass def Dispose(self): \"\"\" Dispose(self: CharEnumerator) Releases all resources used", "bool \"\"\" pass def __enter__(self,*args): \"\"\" __enter__(self: IDisposable) -> object", "class\"\"\" return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns an instance of the class\"\"\"", "currently referenced character in the string enumerated by this System.CharEnumerator", "copy of the current System.CharEnumerator object. Returns: An System.Object that", "the enumerated string. Returns: true if the index is successfully", "instance of the class\"\"\" def Clone(self): \"\"\" Clone(self: CharEnumerator) ->", "next character of the enumerated string. Returns: true if the", "Clone(self): \"\"\" Clone(self: CharEnumerator) -> object Creates a copy of", "a position logically before the first character of the enumerated", "self,v: None,lambda self: None) \"\"\"Gets the currently referenced character in", "-> object \"\"\" pass def __exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value:", "pass def __iter__(self,*args): \"\"\" __iter__(self: IEnumerator) -> object \"\"\" pass", "System.Object that is a copy of the current System.CharEnumerator object.", "a copy of the current System.CharEnumerator object. \"\"\" pass def", "that is a copy of the current System.CharEnumerator object. \"\"\"", "class. \"\"\" pass def MoveNext(self): \"\"\" MoveNext(self: CharEnumerator) -> bool", "ZZZ(self): \"\"\"hardcoded/mock instance of the class\"\"\" return CharEnumerator() instance=ZZZ() \"\"\"hardcoded/returns", "\"\"\" __repr__(self: object) -> str \"\"\" pass Current=property(lambda self: object(),lambda", "current System.CharEnumerator object. Returns: An System.Object that is a copy", "current instance of the System.CharEnumerator class. \"\"\" pass def MoveNext(self):", "Supports iterating over a System.String object and reading its individual", "pass def MoveNext(self): \"\"\" MoveNext(self: CharEnumerator) -> bool Increments the", "within the enumerated string; otherwise,false. \"\"\" pass def next(self,*args): \"\"\"", "Releases all resources used by the current instance of the", "string. Returns: true if the index is successfully incremented and", "IEnumerator[Char],value: Char) -> bool \"\"\" pass def __enter__(self,*args): \"\"\" __enter__(self:", "x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for", "is successfully incremented and within the enumerated string; otherwise,false. \"\"\"", "an instance of the class\"\"\" def Clone(self): \"\"\" Clone(self: CharEnumerator)", "the index is successfully incremented and within the enumerated string;", "\"\"\" pass def Dispose(self): \"\"\" Dispose(self: CharEnumerator) Releases all resources", "object \"\"\" pass def __exit__(self,*args): \"\"\" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back:", "\"\"\" pass def __init__(self,*args): \"\"\" x.__init__(...) initializes x; see x.__class__.__doc__", "def Reset(self): \"\"\" Reset(self: CharEnumerator) Initializes the index to a" ]
[ "from .config_store import ConfigStore config = ConfigStore() config.set_mqtt_broker(\"mqtt\", 1883) config.set_redis_config(\"redis\",", "import ConfigStore config = ConfigStore() config.set_mqtt_broker(\"mqtt\", 1883) config.set_redis_config(\"redis\", 6379, 0)", "<filename>src/home_automation_hub/config.py from .config_store import ConfigStore config = ConfigStore() config.set_mqtt_broker(\"mqtt\", 1883)", ".config_store import ConfigStore config = ConfigStore() config.set_mqtt_broker(\"mqtt\", 1883) config.set_redis_config(\"redis\", 6379," ]
[ "= b\"\" self.status = 0 def connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self):", "def send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket() if not sock: return False", "__init__ (self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole) self.buffer = b\"\" self.status =", "#h short integer 2 #H unsigned short integer 2 #i", "HarpeServer.objects.filter(is_active=True)[:1] if not ser: return False ser = ser[0] sock.connect(ser.ip,ser.port)", "error code : %d\" % self.status else: return unpack(\"!\"+ret_type,self.buffer)[0] return", "not ser: return False ser = ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion()", "size: if self.status != 0: print \"recive error code :", "if not sock: return False data = analyseMfg.mgf.read() + '\\0'", "create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1] if not ser:", "int integer 4 #l long integer 4 #L unsigned long", "self.add(\"i\",func_id) if types: self.add(types,*args) self.send() size = self.receive() if size:", "1 #? _Bool bool 1 #h short integer 2 #H", "% (self.status,msg) self.clear() return self.status def _unpack_str(self): i = 0", "enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO =", "= self.sock.send(data) if sent == 0: print \"Connexion lost\" return", "4 #l long integer 4 #L unsigned long integer 4", "1 #b signed char integer 1 #B unsigned char integer", "(), enums) class Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM,", "self.sock.recv(size) return len(recv) + len(self.buffer) #Format C Type Python type", "and self.status == self.NTW_ERROR_NO: print \"verify_connexion <%d : %s>\" %", "ser = HarpeServer.objects.filter(is_active=True)[:1] if not ser: return False ser =", "msg = self._unpack_str() if msg == self.NTW_WELCOM_MSG and self.status ==", "enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG =", "self.buffer = b\"\" self.status = 0 def call(self,ret_type,func_id,types=\"\",*args): if len(types)", "from struct import pack,unpack from website.contrib.communication.models import * def enum(**enums):", "data = _size + self.buffer sent = self.sock.send(data) if sent", "== self.NTW_ERROR_NO: print \"verify_connexion <%d : %s>\" % (self.status,msg) else:", "i+=1 res = self.buffer[:i] self.buffer = self.buffer[i:] return res def", "def add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def clear(self): self.buffer = b\"\" self.status", "recv = b'' recv = self.sock.recv(6) if recv == b'':", "= enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO = 0 def __init__", "Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down =", "#i int integer 4 #I unsigned int integer 4 #l", "1 #h short integer 2 #H unsigned short integer 2", "length 1 #b signed char integer 1 #B unsigned char", "return 0 self.clear() self.add(\"i\",func_id) if types: self.add(types,*args) self.send() size =", "#? _Bool bool 1 #h short integer 2 #H unsigned", "self.status = 0 def call(self,ret_type,func_id,types=\"\",*args): if len(types) < len(args): print", "lost\" return False return True def receive(self): recv = b''", "True def receive(self): recv = b'' recv = self.sock.recv(6) if", "class Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down", "= ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion() != sock.NTW_ERROR_NO: print \"An error", "of args/type\" return 0 self.clear() self.add(\"i\",func_id) if types: self.add(types,*args) self.send()", "8 #s char[] string #p char[] string #P void *", "print \"verify_connexion <%d : %s>\" % (self.status,msg) else: print \"verify_connexion", "unsigned int integer 4 #l long integer 4 #L unsigned", "2 #H unsigned short integer 2 #i int integer 4", "#x pad byte no value #c char string of length", "#b signed char integer 1 #B unsigned char integer 1", "= 0 def __init__ (self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole) self.buffer =", "long integer 4 #q long long integer 8 #Q unsigned", "if types: self.add(types,*args) self.send() size = self.receive() if size: if", "float 8 #s char[] string #p char[] string #P void", "= \"hello!\\0\" NTW_ERROR_NO = 0 def __init__ (self,dommaine,type,protocole=0): self.sock =", "len(args): print \"Wrong number of args/type\" return 0 self.clear() self.add(\"i\",func_id)", "sock = create_socket() if not sock: return False data =", "self.receive() > 0: msg = self._unpack_str() if msg == self.NTW_WELCOM_MSG", "b\"\" self.status = 0 def call(self,ret_type,func_id,types=\"\",*args): if len(types) < len(args):", "occur\" return None return sock def send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket()", "value #c char string of length 1 #b signed char", "struct import pack,unpack from website.contrib.communication.models import * def enum(**enums): return", "def verify_connexion(self): code = 404 if self.receive() > 0: msg", "len(recv) + len(self.buffer) #Format C Type Python type Standard size", "size,self.status = unpack('!Ih',recv) self.buffer = self.sock.recv(size) return len(recv) + len(self.buffer)", "None return sock def send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket() if not", "else: return unpack(\"!\"+ret_type,self.buffer)[0] return 0 def create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP)", "> 0: msg = self._unpack_str() if msg == self.NTW_WELCOM_MSG and", "4 #d double float 8 #s char[] string #p char[]", "char string of length 1 #b signed char integer 1", "sock.verify_connexion() != sock.NTW_ERROR_NO: print \"An error occur\" return None return", "\"Wrong number of args/type\" return 0 self.clear() self.add(\"i\",func_id) if types:", "call(self,ret_type,func_id,types=\"\",*args): if len(types) < len(args): print \"Wrong number of args/type\"", "code = 404 if self.receive() > 0: msg = self._unpack_str()", "NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO = 0 def __init__ (self,dommaine,type,protocole=0): self.sock", "_size = pack('!Ih',size,self.status) data = _size + self.buffer sent =", "4 #L unsigned long integer 4 #q long long integer", "self.status def _unpack_str(self): i = 0 while self.buffer[i]!= '\\0': i+=1", "= self.receive() if size: if self.status != 0: print \"recive", "if msg == self.NTW_WELCOM_MSG and self.status == self.NTW_ERROR_NO: print \"verify_connexion", "404 if self.receive() > 0: msg = self._unpack_str() if msg", "self.buffer +=pack('!'+typ,*args) def clear(self): self.buffer = b\"\" self.status = 0", "i+=1 i+=1 res = self.buffer[:i] self.buffer = self.buffer[i:] return res", "0 def call(self,ret_type,func_id,types=\"\",*args): if len(types) < len(args): print \"Wrong number", "sock def send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket() if not sock: return", "return unpack(\"!\"+ret_type,self.buffer)[0] return 0 def create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser", "integer def add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def clear(self): self.buffer = b\"\"", "\"verify_connexion <%d : %s>\" % (self.status,msg) else: print \"verify_connexion <%d", "unpack('!Ih',recv) self.buffer = self.sock.recv(size) return len(recv) + len(self.buffer) #Format C", "self.buffer[:i] self.buffer = self.buffer[i:] return res def send(self): size =", "= self.buffer[i:] return res def send(self): size = len(self.buffer) _size", "+=pack('!'+typ,*args) def clear(self): self.buffer = b\"\" self.status = 0 def", "def receive(self): recv = b'' recv = self.sock.recv(6) if recv", ": %s>\" % (self.status,msg) else: print \"verify_connexion <%d : %s>\"", "= create_socket() if not sock: return False data = analyseMfg.mgf.read()", "create_socket() if not sock: return False data = analyseMfg.mgf.read() +", "of length 1 #b signed char integer 1 #B unsigned", "self.clear() self.add(\"i\",func_id) if types: self.add(types,*args) self.send() size = self.receive() if", "-*- import socket as csocket from struct import pack,unpack from", "len(self.buffer) _size = pack('!Ih',size,self.status) data = _size + self.buffer sent", "None size,self.status = unpack('!Ih',recv) self.buffer = self.sock.recv(size) return len(recv) +", "integer 8 #Q unsigned long long integer 8 #f float", "types: self.add(types,*args) self.send() size = self.receive() if size: if self.status", "Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO = 0 def", "unsigned char integer 1 #? _Bool bool 1 #h short", "_Bool bool 1 #h short integer 2 #H unsigned short", "= b'' recv = self.sock.recv(6) if recv == b'': print", "\"An error occur\" return None return sock def send_AnalyseMgf_to_calc(analyseMfg): sock", "0 self.clear() self.add(\"i\",func_id) if types: self.add(types,*args) self.send() size = self.receive()", "+ self.buffer sent = self.sock.send(data) if sent == 0: print", "char[] string #P void * integer def add(self,typ,*args): self.buffer +=pack('!'+typ,*args)", "\"recive error code : %d\" % self.status else: return unpack(\"!\"+ret_type,self.buffer)[0]", "= HarpeServer.objects.filter(is_active=True)[:1] if not ser: return False ser = ser[0]", "0 while self.buffer[i]!= '\\0': i+=1 i+=1 res = self.buffer[:i] self.buffer", "send(self): size = len(self.buffer) _size = pack('!Ih',size,self.status) data = _size", "self.sock.send(data) if sent == 0: print \"Connexion lost\" return False", "integer 4 #I unsigned int integer 4 #l long integer", "float float 4 #d double float 8 #s char[] string", "Standard size #x pad byte no value #c char string", "add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def clear(self): self.buffer = b\"\" self.status =", "self.status else: return unpack(\"!\"+ret_type,self.buffer)[0] return 0 def create_socket(): sock =", "= csocket.socket(dommaine,type,protocole) self.buffer = b\"\" self.status = 0 def connect(self,host,port):", "pack('!Ih',size,self.status) data = _size + self.buffer sent = self.sock.send(data) if", "\"verify_connexion <%d : %s>\" % (self.status,msg) self.clear() return self.status def", "unpack(\"!\"+ret_type,self.buffer)[0] return 0 def create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser =", "4 #q long long integer 8 #Q unsigned long long", "< len(args): print \"Wrong number of args/type\" return 0 self.clear()", "= self.sock.recv(size) return len(recv) + len(self.buffer) #Format C Type Python", "recv = self.sock.recv(6) if recv == b'': print \"Connexion lost\"", "void * integer def add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def clear(self): self.buffer", "type('Enum', (), enums) class Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type =", "csocket from struct import pack,unpack from website.contrib.communication.models import * def", "def __init__ (self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole) self.buffer = b\"\" self.status", "unsigned long integer 4 #q long long integer 8 #Q", "else: print \"verify_connexion <%d : %s>\" % (self.status,msg) self.clear() return", "(self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole) self.buffer = b\"\" self.status = 0", "sock.NTW_ERROR_NO: print \"An error occur\" return None return sock def", "#Format C Type Python type Standard size #x pad byte", "double float 8 #s char[] string #p char[] string #P", "sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1] if not ser: return", "size #x pad byte no value #c char string of", "sent == 0: print \"Connexion lost\" return False return True", "0: print \"recive error code : %d\" % self.status else:", "self.buffer = b\"\" self.status = 0 def connect(self,host,port): self.sock.connect((host,port)) def", "connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self): code = 404 if self.receive() >", "sent = self.sock.send(data) if sent == 0: print \"Connexion lost\"", "utf-8 -*- import socket as csocket from struct import pack,unpack", "= 0 def call(self,ret_type,func_id,types=\"\",*args): if len(types) < len(args): print \"Wrong", "b'': print \"Connexion lost\" return None size,self.status = unpack('!Ih',recv) self.buffer", "len(types) < len(args): print \"Wrong number of args/type\" return 0", "(self.status,msg) else: print \"verify_connexion <%d : %s>\" % (self.status,msg) self.clear()", "False ser = ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion() != sock.NTW_ERROR_NO: print", "enum(**enums): return type('Enum', (), enums) class Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX)", "<%d : %s>\" % (self.status,msg) else: print \"verify_connexion <%d :", "= b\"\" self.status = 0 def call(self,ret_type,func_id,types=\"\",*args): if len(types) <", "% (self.status,msg) else: print \"verify_connexion <%d : %s>\" % (self.status,msg)", "no value #c char string of length 1 #b signed", "8 #f float float 4 #d double float 8 #s", "as csocket from struct import pack,unpack from website.contrib.communication.models import *", "integer 4 #l long integer 4 #L unsigned long integer", "string #P void * integer def add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def", "= len(self.buffer) _size = pack('!Ih',size,self.status) data = _size + self.buffer", "self._unpack_str() if msg == self.NTW_WELCOM_MSG and self.status == self.NTW_ERROR_NO: print", "b\"\" self.status = 0 def connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self): code", "string of length 1 #b signed char integer 1 #B", "= self.buffer[:i] self.buffer = self.buffer[i:] return res def send(self): size", "while self.buffer[i]!= '\\0': i+=1 i+=1 res = self.buffer[:i] self.buffer =", "def clear(self): self.buffer = b\"\" self.status = 0 def call(self,ret_type,func_id,types=\"\",*args):", "% self.status else: return unpack(\"!\"+ret_type,self.buffer)[0] return 0 def create_socket(): sock", "size = len(self.buffer) _size = pack('!Ih',size,self.status) data = _size +", "code : %d\" % self.status else: return unpack(\"!\"+ret_type,self.buffer)[0] return 0", "unsigned long long integer 8 #f float float 4 #d", "error occur\" return None return sock def send_AnalyseMgf_to_calc(analyseMfg): sock =", "#l long integer 4 #L unsigned long integer 4 #q", "long integer 8 #f float float 4 #d double float", "self.status = 0 def connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self): code =", "return False return True def receive(self): recv = b'' recv", "\"Connexion lost\" return None size,self.status = unpack('!Ih',recv) self.buffer = self.sock.recv(size)", "UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO = 0", "'\\0': i+=1 i+=1 res = self.buffer[:i] self.buffer = self.buffer[i:] return", "self.status != 0: print \"recive error code : %d\" %", "self.sock.recv(6) if recv == b'': print \"Connexion lost\" return None", "string #p char[] string #P void * integer def add(self,typ,*args):", "res def send(self): size = len(self.buffer) _size = pack('!Ih',size,self.status) data", "self.send() size = self.receive() if size: if self.status != 0:", "coding: utf-8 -*- import socket as csocket from struct import", "ser = ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion() != sock.NTW_ERROR_NO: print \"An", "return None return sock def send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket() if", "return sock def send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket() if not sock:", "self.status == self.NTW_ERROR_NO: print \"verify_connexion <%d : %s>\" % (self.status,msg)", "False data = analyseMfg.mgf.read() + '\\0' return sock.call(\"i\",HarpeServer.FUNCTION_ID.ANALYSE,\"i%ds\" % (analyseMfg.mgf.size+1)", "self.buffer = self.buffer[i:] return res def send(self): size = len(self.buffer)", "integer 8 #f float float 4 #d double float 8", "long long integer 8 #Q unsigned long long integer 8", "8 #Q unsigned long long integer 8 #f float float", "signed char integer 1 #B unsigned char integer 1 #?", "0 def connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self): code = 404 if", "#c char string of length 1 #b signed char integer", "self.buffer[i:] return res def send(self): size = len(self.buffer) _size =", "args/type\" return 0 self.clear() self.add(\"i\",func_id) if types: self.add(types,*args) self.send() size", "clear(self): self.buffer = b\"\" self.status = 0 def call(self,ret_type,func_id,types=\"\",*args): if", "i = 0 while self.buffer[i]!= '\\0': i+=1 i+=1 res =", "pad byte no value #c char string of length 1", "integer 4 #q long long integer 8 #Q unsigned long", "(self.status,msg) self.clear() return self.status def _unpack_str(self): i = 0 while", "short integer 2 #i int integer 4 #I unsigned int", "= _size + self.buffer sent = self.sock.send(data) if sent ==", "def call(self,ret_type,func_id,types=\"\",*args): if len(types) < len(args): print \"Wrong number of", "\"hello!\\0\" NTW_ERROR_NO = 0 def __init__ (self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole)", "1 #B unsigned char integer 1 #? _Bool bool 1", "csocket.socket(dommaine,type,protocole) self.buffer = b\"\" self.status = 0 def connect(self,host,port): self.sock.connect((host,port))", "_size + self.buffer sent = self.sock.send(data) if sent == 0:", "import * def enum(**enums): return type('Enum', (), enums) class Socket:", "!= 0: print \"recive error code : %d\" % self.status", "if len(types) < len(args): print \"Wrong number of args/type\" return", "print \"verify_connexion <%d : %s>\" % (self.status,msg) self.clear() return self.status", "not sock: return False data = analyseMfg.mgf.read() + '\\0' return", "# -*- coding: utf-8 -*- import socket as csocket from", "ser: return False ser = ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion() !=", "#f float float 4 #d double float 8 #s char[]", "self.NTW_WELCOM_MSG and self.status == self.NTW_ERROR_NO: print \"verify_connexion <%d : %s>\"", "def connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self): code = 404 if self.receive()", "0: msg = self._unpack_str() if msg == self.NTW_WELCOM_MSG and self.status", "= pack('!Ih',size,self.status) data = _size + self.buffer sent = self.sock.send(data)", "= 0 while self.buffer[i]!= '\\0': i+=1 i+=1 res = self.buffer[:i]", "return len(recv) + len(self.buffer) #Format C Type Python type Standard", "socket as csocket from struct import pack,unpack from website.contrib.communication.models import", ": %s>\" % (self.status,msg) self.clear() return self.status def _unpack_str(self): i", "pack,unpack from website.contrib.communication.models import * def enum(**enums): return type('Enum', (),", "len(self.buffer) #Format C Type Python type Standard size #x pad", "Type Python type Standard size #x pad byte no value", "#Q unsigned long long integer 8 #f float float 4", "#s char[] string #p char[] string #P void * integer", "def send(self): size = len(self.buffer) _size = pack('!Ih',size,self.status) data =", "res = self.buffer[:i] self.buffer = self.buffer[i:] return res def send(self):", "-*- coding: utf-8 -*- import socket as csocket from struct", "type Standard size #x pad byte no value #c char", "int integer 4 #I unsigned int integer 4 #l long", "0 def __init__ (self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole) self.buffer = b\"\"", "= enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG", "self.receive() if size: if self.status != 0: print \"recive error", "char[] string #p char[] string #P void * integer def", "lost\" return None size,self.status = unpack('!Ih',recv) self.buffer = self.sock.recv(size) return", "recv == b'': print \"Connexion lost\" return None size,self.status =", "send_AnalyseMgf_to_calc(analyseMfg): sock = create_socket() if not sock: return False data", "!= sock.NTW_ERROR_NO: print \"An error occur\" return None return sock", "return True def receive(self): recv = b'' recv = self.sock.recv(6)", "= self._unpack_str() if msg == self.NTW_WELCOM_MSG and self.status == self.NTW_ERROR_NO:", "= Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1] if not ser: return False", "4 #I unsigned int integer 4 #l long integer 4", "%d\" % self.status else: return unpack(\"!\"+ret_type,self.buffer)[0] return 0 def create_socket():", "b'' recv = self.sock.recv(6) if recv == b'': print \"Connexion", "self.sock.connect((host,port)) def verify_connexion(self): code = 404 if self.receive() > 0:", "byte no value #c char string of length 1 #b", "#q long long integer 8 #Q unsigned long long integer", "if not ser: return False ser = ser[0] sock.connect(ser.ip,ser.port) if", ": %d\" % self.status else: return unpack(\"!\"+ret_type,self.buffer)[0] return 0 def", "enums) class Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM)", "0 def create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1] if", "self.sock = csocket.socket(dommaine,type,protocole) self.buffer = b\"\" self.status = 0 def", "return 0 def create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1]", "#P void * integer def add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def clear(self):", "bool 1 #h short integer 2 #H unsigned short integer", "if recv == b'': print \"Connexion lost\" return None size,self.status", "enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO = 0 def __init__ (self,dommaine,type,protocole=0):", "return res def send(self): size = len(self.buffer) _size = pack('!Ih',size,self.status)", "def enum(**enums): return type('Enum', (), enums) class Socket: Dommaine =", "#p char[] string #P void * integer def add(self,typ,*args): self.buffer", "long integer 4 #L unsigned long integer 4 #q long", "def create_socket(): sock = Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1] if not", "= enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\" NTW_ERROR_NO", "website.contrib.communication.models import * def enum(**enums): return type('Enum', (), enums) class", "Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2)", "short integer 2 #H unsigned short integer 2 #i int", "verify_connexion(self): code = 404 if self.receive() > 0: msg =", "sock.connect(ser.ip,ser.port) if sock.verify_connexion() != sock.NTW_ERROR_NO: print \"An error occur\" return", "print \"Wrong number of args/type\" return 0 self.clear() self.add(\"i\",func_id) if", "integer 4 #L unsigned long integer 4 #q long long", "== b'': print \"Connexion lost\" return None size,self.status = unpack('!Ih',recv)", "self.buffer sent = self.sock.send(data) if sent == 0: print \"Connexion", "ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion() != sock.NTW_ERROR_NO: print \"An error occur\"", "#B unsigned char integer 1 #? _Bool bool 1 #h", "if size: if self.status != 0: print \"recive error code", "if self.receive() > 0: msg = self._unpack_str() if msg ==", "== self.NTW_WELCOM_MSG and self.status == self.NTW_ERROR_NO: print \"verify_connexion <%d :", "data = analyseMfg.mgf.read() + '\\0' return sock.call(\"i\",HarpeServer.FUNCTION_ID.ANALYSE,\"i%ds\" % (analyseMfg.mgf.size+1) ,analyseMfg.pk,data)", "C Type Python type Standard size #x pad byte no", "char integer 1 #B unsigned char integer 1 #? _Bool", "= 404 if self.receive() > 0: msg = self._unpack_str() if", "<%d : %s>\" % (self.status,msg) self.clear() return self.status def _unpack_str(self):", "= 0 def connect(self,host,port): self.sock.connect((host,port)) def verify_connexion(self): code = 404", "+ len(self.buffer) #Format C Type Python type Standard size #x", "number of args/type\" return 0 self.clear() self.add(\"i\",func_id) if types: self.add(types,*args)", "0: print \"Connexion lost\" return False return True def receive(self):", "* def enum(**enums): return type('Enum', (), enums) class Socket: Dommaine", "long long integer 8 #f float float 4 #d double", "print \"An error occur\" return None return sock def send_AnalyseMgf_to_calc(analyseMfg):", "return False data = analyseMfg.mgf.read() + '\\0' return sock.call(\"i\",HarpeServer.FUNCTION_ID.ANALYSE,\"i%ds\" %", "\"Connexion lost\" return False return True def receive(self): recv =", "#d double float 8 #s char[] string #p char[] string", "NTW_ERROR_NO = 0 def __init__ (self,dommaine,type,protocole=0): self.sock = csocket.socket(dommaine,type,protocole) self.buffer", "size = self.receive() if size: if self.status != 0: print", "return type('Enum', (), enums) class Socket: Dommaine = enum(IP=csocket.AF_INET,LOCAL=csocket.AF_UNIX) Type", "== 0: print \"Connexion lost\" return False return True def", "return None size,self.status = unpack('!Ih',recv) self.buffer = self.sock.recv(size) return len(recv)", "print \"Connexion lost\" return None size,self.status = unpack('!Ih',recv) self.buffer =", "from website.contrib.communication.models import * def enum(**enums): return type('Enum', (), enums)", "Python type Standard size #x pad byte no value #c", "self.NTW_ERROR_NO: print \"verify_connexion <%d : %s>\" % (self.status,msg) else: print", "if sock.verify_connexion() != sock.NTW_ERROR_NO: print \"An error occur\" return None", "%s>\" % (self.status,msg) self.clear() return self.status def _unpack_str(self): i =", "if self.status != 0: print \"recive error code : %d\"", "print \"Connexion lost\" return False return True def receive(self): recv", "if sent == 0: print \"Connexion lost\" return False return", "self.buffer[i]!= '\\0': i+=1 i+=1 res = self.buffer[:i] self.buffer = self.buffer[i:]", "self.clear() return self.status def _unpack_str(self): i = 0 while self.buffer[i]!=", "integer 1 #B unsigned char integer 1 #? _Bool bool", "unsigned short integer 2 #i int integer 4 #I unsigned", "print \"recive error code : %d\" % self.status else: return", "float 4 #d double float 8 #s char[] string #p", "* integer def add(self,typ,*args): self.buffer +=pack('!'+typ,*args) def clear(self): self.buffer =", "= self.sock.recv(6) if recv == b'': print \"Connexion lost\" return", "receive(self): recv = b'' recv = self.sock.recv(6) if recv ==", "_unpack_str(self): i = 0 while self.buffer[i]!= '\\0': i+=1 i+=1 res", "char integer 1 #? _Bool bool 1 #h short integer", "integer 2 #H unsigned short integer 2 #i int integer", "Socket(Socket.Dommaine.IP,Socket.Type.TCP) ser = HarpeServer.objects.filter(is_active=True)[:1] if not ser: return False ser", "msg == self.NTW_WELCOM_MSG and self.status == self.NTW_ERROR_NO: print \"verify_connexion <%d", "long integer 8 #Q unsigned long long integer 8 #f", "2 #i int integer 4 #I unsigned int integer 4", "= unpack('!Ih',recv) self.buffer = self.sock.recv(size) return len(recv) + len(self.buffer) #Format", "sock: return False data = analyseMfg.mgf.read() + '\\0' return sock.call(\"i\",HarpeServer.FUNCTION_ID.ANALYSE,\"i%ds\"", "return self.status def _unpack_str(self): i = 0 while self.buffer[i]!= '\\0':", "%s>\" % (self.status,msg) else: print \"verify_connexion <%d : %s>\" %", "False return True def receive(self): recv = b'' recv =", "return False ser = ser[0] sock.connect(ser.ip,ser.port) if sock.verify_connexion() != sock.NTW_ERROR_NO:", "import pack,unpack from website.contrib.communication.models import * def enum(**enums): return type('Enum',", "self.add(types,*args) self.send() size = self.receive() if size: if self.status !=", "self.buffer = self.sock.recv(size) return len(recv) + len(self.buffer) #Format C Type", "#L unsigned long integer 4 #q long long integer 8", "#H unsigned short integer 2 #i int integer 4 #I", "#I unsigned int integer 4 #l long integer 4 #L", "import socket as csocket from struct import pack,unpack from website.contrib.communication.models", "def _unpack_str(self): i = 0 while self.buffer[i]!= '\\0': i+=1 i+=1", "integer 2 #i int integer 4 #I unsigned int integer", "Type = enum(TCP=csocket.SOCK_STREAM, UDP=csocket.SOCK_DGRAM) Down = enum(SEND=0,RECIVE=1,BOTH=2) NTW_WELCOM_MSG = \"hello!\\0\"", "integer 1 #? _Bool bool 1 #h short integer 2" ]
[ "= 8, style = \"circle\", color = 'red') elif value", "def plot_tree(pt_tree, target_node, out): #pt_tree, feats, pf2color = get_tree(phenotype =", "= [0,1] lines = [ax.plot(x, pd.np.ones(len(x)), 'o', color = \"#%06x\"", "for i in range(feats.shape[0])] #if include_class: # labels= [\"%s %s\"", "pd.read_csv(sample_mapping, index_col = 0, sep = \"\\t\") #read node and", "elif ns < threshold: style['fgcolor'] = 'darkred' else: style['fgcolor'] =", "my custom layout ts.layout_fn = my_layout return ts def plot_tree(pt_tree,", "\"circle\", color = 'grey') n.add_face(rf, column = i, position =", "ts.show_leaf_name = False ts.show_scale = True ts.force_topology = False #", "= \"output file\") parser.add_argument(\"--max_feats\", type = int, default = 10,", "True, include_class = False): fig = pylab.figure() figlegend = pylab.figure(figsize", "= \"\\t\", index_col = 0) gain_recon = pd.read_csv(gain_recon, sep =", "= pd.read_csv(sample_mapping, index_col = 0, sep = \"\\t\") #read node", "= faces.TextFace(\"misclassified\") n.add_face(tf, column = 0, position = \"branch-right\") #set", "and names\") parser.add_argument(\"out\", help = \"output file\") parser.add_argument(\"--max_feats\", type =", "%s\" %(labels[i], feats.loc[:, \"class\"].iloc[i]) for i in range(len(labels))] #if pf_desc:", "\"__main__\": import argparse parser = argparse.ArgumentParser(\"\"\"visualize target list of features\"\"\")", "character state reconstruction\") parser.add_argument(\"tree\", help = \"tree with internal nodes", "1]) for i in range(len(labels))] figlegend.legend(lines, labels, markerscale = 2.5,", "events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id,", "if n.name == \"N1\": continue if not node_annotation is None:", "= 0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in gain_recon.index.values]", "AttrFace(\"name\") else: # If internal node, draws label with smaller", "AttrFace(\"name\", fsize=10) # Adds the name face to the image", "loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping, threshold = 0.5, target_node =", "= a.feat_list, phenotype = a.phenotype, target_node = a.target_node, threshold =", "preferred position faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color, val, recon_min,", "= kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]]", "= 0, sep = \"\\t\") pt_tree = ete2.Tree(tree, format =", "pt_tree.traverse(strategy = 'preorder')) pfams_with_event = set() pfam2color = {} #set", "style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"] = 3 elif", "tf = faces.TextFace(\"+\") cf = faces.CircleFace(radius = 8, style =", "branch_id = n.name + \"_\" + n.up.name if gain_recon.loc[branch_id, phenotype]", "help = \"tree with internal nodes labeled\") parser.add_argument(\"pfam_mapping\", help =", "tree = a.tree, feat_list = a.feat_list, phenotype = a.phenotype, target_node", "parser.add_argument(\"--max_feats\", type = int, default = 10, help = \"visualize", "pd.read_csv(loss_recon, sep = \"\\t\", index_col = 0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]),", "Vivid Orange 0xA6BDD7, # Very Light Blue 0xC10020, # Vivid", "Red 0xCEA262, # Grayish Yellow 0x817066, # Medium Gray #", "node2name = dict((i.name, i.name) for i in pt_tree.traverse(strategy = 'preorder'))", "pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] figlegend.legend(lines, labels, markerscale =", "h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 - (recon_max", "= \"circle\", color = 'green') else: rf = faces.CircleFace(radius =", "parser.add_argument(\"feat_list\", help = \"list of features\") parser.add_argument(\"--target_node\", default = \"N1\",", "events.append(cf) #loss events elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] =", "feats, pf2color def plot_legend(feats, out, pf2color, pf_desc = False, pf_acc", "miscl is None: miscl_m = pd.read_csv(miscl, sep = \"\\t\", index_col", "add misclassified label if not miscl is None: if node2name[n.name]", "labeled\") parser.add_argument(\"pfam_mapping\", help = \"feature mapping/list\") parser.add_argument(\"feat_list\", help = \"list", "a.node_recon, gain_recon = a.gain_recon, loss_recon = a.loss_recon, pfam_mapping = a.pfam_mapping,", "= fig.add_subplot(111) x = [0,1] lines = [ax.plot(x, pd.np.ones(len(x)), 'o',", "feats.iloc[:max_feats,] #for visualization of continuous feature get the range of", "- (recon_max - val) / (recon_max - recon_min) v_new =", "phenotype\") parser.add_argument(\"threshold\", type = float, help = \"threshold to call", "color = \"#%06x\" % (pf2color[feats.index[i]]))[0] for i in range(len(pf2color))] labels=", "\"output file\") parser.add_argument(\"--max_feats\", type = int, default = 10, help", "phenotype = a.phenotype, target_node = a.target_node, threshold = a.threshold, sample_mapping", "in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority feature gains and", "= get_style()) return target, feats, pf2color def plot_legend(feats, out, pf2color,", "range(len(labels))] figlegend.legend(lines, labels, markerscale = 2.5, numpoints = 1, frameon", "def get_tree(phenotype, tree, gain_recon, loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping, threshold", "pandas as pd import ete2 from ete2 import faces, Tree,", "according to change in continuous reconstruction value\"\"\" h, s, v", "style[\"shape\"] = 'square' style['size'] = 10 if pd.isnull(ns): style['fgcolor'] =", "target_node is not None: pt_tree = pt_tree.search_nodes(name = target_node)[0] node2name", "in node2name: n.name = node2name[n.name] #filtered_pfams = filter(lambda i: i", "filter(lambda i: i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids =", "node, draws its name name_face = AttrFace(\"name\") else: # If", "10, miscl = None, node_annotation = None): #read target feats", "the range of values for each feature if are_continuous_features_with_discrete_phenotype: recon_min", "id if n.name in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority", "= \"feature mapping/list\") parser.add_argument(\"feat_list\", help = \"list of features\") parser.add_argument(\"--target_node\",", "\"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true', help = \"set if", "help = \"output file\") parser.add_argument(\"--max_feats\", type = int, default =", "threshold = 0.5, target_node = None, are_continuous_features_with_discrete_phenotype = False, max_feats", "dict((i.name, i.name) for i in pt_tree.traverse(strategy = 'preorder')) pfams_with_event =", "to call genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help = \"mapping between sample", "i: i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams,", "the posterior probability top10_feats = feats.iloc[:max_feats,] #for visualization of continuous", "= argparse.ArgumentParser(\"\"\"visualize target list of features\"\"\") parser.add_argument(\"node_recon\", help = \"node", "pd.isnull(value): if value == 0: rf = ete2.CircleFace(radius = 8,", "node if target_node is not None: pt_tree = pt_tree.search_nodes(name =", "type = int, default = 10, help = \"visualize at", "1]) for i in range(len(labels))] #if pf_acc: # labels =", "v_new]))) def get_style(): ts = TreeStyle() # Do not add", "name name_face = AttrFace(\"name\") else: # If internal node, draws", "name_face = AttrFace(\"name\", fsize=10) # Adds the name face to", "and add misclassified label if not miscl is None: if", "style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"] = 3 elif loss_recon.loc[branch_id, phenotype] >", "pd.read_csv(node_annotation, sep = \"\\t\", index_col = 0) sample_mapping = pd.read_csv(sample_mapping,", "0xFF8E00, # Vivid Orange Yellow 0xB32851, # Strong Purplish Red", "feature gains and losses events = [] for i in", "3 elif loss_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"]", "pfam2color if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(\"\"\"visualize", "= 8, style = \"circle\", color = 'grey') n.add_face(rf, column", "tree_style = get_style()) #target.render(out + '_tree.png', tree_style = get_style()) return", "filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node annotation return pt_tree, top10_feats,", "= a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl = a.miscl, node_annotation =", "index_col = 0) gain_recon = pd.read_csv(gain_recon, sep = \"\\t\", index_col", "+ '_tree.pdf', tree_style = get_style()) #target.render(out + '_tree.png', tree_style =", "node annotation return pt_tree, top10_feats, pfam2color if __name__ == \"__main__\":", "= get_tree(phenotype = phenotype, feat_list = \"top_cor\", is_ml_plus_phypat = True,", "\"circle\", color = 'red') elif value == 2: rf =", "fig = pylab.figure() figlegend = pylab.figure(figsize = (9, 6)) ax", "style = ete2.NodeStyle() style[\"shape\"] = 'square' style['size'] = 10 if", "= \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true', help = \"set", "in range(len(pf2color))] labels= [i for i in feats.index] #labels= [\"%s\"", "# Grayish Yellow 0x817066, # Medium Gray # The following", "0x7F180D, # Strong Reddish Brown 0x93AA00, # Vivid Yellowish Green", "plot_legend(feats, out, pf2color, pf_desc = False, pf_acc = True, include_class", "include_class: # labels= [\"%s %s\" %(labels[i], feats.loc[:, \"class\"].iloc[i]) for i", "= [ 0xFFB300, # Vivid Yellow 0x803E75, # Strong Purple", "0xA6BDD7, # Very Light Blue 0xC10020, # Vivid Red 0xCEA262,", "pd.isnull(ns): style['fgcolor'] = 'grey' elif ns < threshold: style['fgcolor'] =", "is None: if node2name[n.name] in miscl_m.index: tf = faces.TextFace(\"misclassified\") n.add_face(tf,", "help = \"mapping between sample ids and names\") parser.add_argument(\"out\", help", "recon_max): \"\"\"set brightness according to change in continuous reconstruction value\"\"\"", "= 'grey' elif ns < threshold: style['fgcolor'] = 'darkred' else:", "smaller font size name_face = AttrFace(\"name\", fsize=10) # Adds the", "Do not add leaf names automatically ts.show_leaf_name = False ts.show_scale", "of features\"\"\") parser.add_argument(\"node_recon\", help = \"node ancestral character state reconstruction\")", "pf_desc: # labels = [\"%s %s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1])", "= True, include_class = False): fig = pylab.figure() figlegend =", "majority feature gains and losses events = [] for i", "= \"branch-top\") for n in pt_tree.traverse(): if n.name in node2name:", "a.max_feats, miscl = a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree, a.target_node, a.out)", "(recon_max - val) / (recon_max - recon_min) v_new = v", "Yellow 0xB32851, # Strong Purplish Red 0xF4C800, # Vivid Greenish", "i in range(len(labels))] figlegend.legend(lines, labels, markerscale = 2.5, numpoints =", "Tree, AttrFace, TreeStyle import pylab from matplotlib.colors import hex2color, rgb2hex,", "sep = \"\\t\") #read node and edge reconstruction matrices node_recon", "= 0) gain_recon = pd.read_csv(gain_recon, sep = \"\\t\", index_col =", "= [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in loss_recon.index.values] #prune to target", "parser.add_argument(\"threshold\", type = float, help = \"threshold to call genotype/phenotype", "ete2.Tree(tree, format = 1) pt_tree.ladderize() if not node_annotation is None:", "The following don't work well for people with defective color", "node, draws label with smaller font size name_face = AttrFace(\"name\",", "% (pf2color[feats.index[i]]))[0] for i in range(len(pf2color))] labels= [i for i", "attr] if not pd.isnull(value): if value == 0: rf =", "'red') elif value == 2: rf = faces.CircleFace(radius = 8,", "\"loss events ancestral character state reconstruction\") parser.add_argument(\"tree\", help = \"tree", "pd.read_csv(node_recon, sep = \"\\t\", index_col = 0) gain_recon = pd.read_csv(gain_recon,", "= dict((i.name, i.name) for i in pt_tree.traverse(strategy = 'preorder')) pfams_with_event", "0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in loss_recon.index.values] #prune", "= \"circle\", color = 'red') elif value == 2: rf", "ete2.CircleFace(radius = 8, style = \"circle\", color = 'red') elif", "parser.add_argument(\"loss_recon\", help = \"loss events ancestral character state reconstruction\") parser.add_argument(\"tree\",", "recon_min = gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if not miscl is", "= a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree, a.target_node, a.out) plot_legend(feats, a.out,", "labels= [\"%s %s\" %(labels[i], feats.loc[:, \"class\"].iloc[i]) for i in range(len(labels))]", "n.name == \"N1\": continue if not node_annotation is None: if", "node_recon, pfam_mapping, feat_list, sample_mapping, threshold = 0.5, target_node = None,", "0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in gain_recon.index.values] loss_recon", "\"aligned\") ns = node_recon.loc[n.name, phenotype] style = ete2.NodeStyle() style[\"shape\"] =", "8, style = \"circle\", color = kelly_colors_hex[i]) #gain events if", "Vivid Yellow 0x803E75, # Strong Purple 0xFF6800, # Vivid Orange", "'grey' elif ns < threshold: style['fgcolor'] = 'darkred' else: style['fgcolor']", "continue if not node_annotation is None: if n.name in node_table.index:", "= faces.TextFace(\"+\") cf = faces.CircleFace(radius = 8, style = \"circle\",", "for people with defective color vision 0x007D34, # Vivid Green", "get_tree(phenotype = phenotype, feat_list = \"top_cor\", is_ml_plus_phypat = True, target_node", "kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i in range(len(events)): n.add_face(events[i], column", "terminal node, draws its name name_face = AttrFace(\"name\") else: #", "# Vivid Red 0xCEA262, # Grayish Yellow 0x817066, # Medium", "layout ts.layout_fn = my_layout return ts def plot_tree(pt_tree, target_node, out):", "between sample ids and names\") parser.add_argument(\"out\", help = \"output file\")", "= gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if not miscl is None:", "nodes labeled\") parser.add_argument(\"pfam_mapping\", help = \"feature mapping/list\") parser.add_argument(\"feat_list\", help =", "\"visualize at most max_feats features\") parser.add_argument(\"--miscl\", help = \"table of", "top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf = faces.TextFace(\"-\") else:", "= \"top_cor\", is_ml_plus_phypat = True, target_node = target_node) pt_tree.dist =", "= \"circle\", color = 'grey') n.add_face(rf, column = i, position", "node2name[n.name] in miscl_m.index: tf = faces.TextFace(\"misclassified\") n.add_face(tf, column = 0,", "values for each feature if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max", "= set() pfam2color = {} #set the style of the", "= 'store_true', help = \"set if using continuous features with", "get_tree(node_recon = a.node_recon, gain_recon = a.gain_recon, loss_recon = a.loss_recon, pfam_mapping", "n.name == \"N1\": branch_id = n.name + \"_\" + n.up.name", "feature get the range of values for each feature if", "in range(feats.shape[0])] #if include_class: # labels= [\"%s %s\" %(labels[i], feats.loc[:,", "#print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node annotation return pt_tree,", "misclassified and add misclassified label if not miscl is None:", "fig.add_subplot(111) x = [0,1] lines = [ax.plot(x, pd.np.ones(len(x)), 'o', color", "Strong Purplish Red 0xF4C800, # Vivid Greenish Yellow 0x7F180D, #", "= 0.5, target_node = None, are_continuous_features_with_discrete_phenotype = False, max_feats =", "style[\"hz_line_type\"] = 0 style[\"hz_line_color\"] = 'black' n.set_style(style) #check if sample", "0x007D34, # Vivid Green 0xF6768E, # Strong Purplish Pink 0x00538A,", "\"circle\", color = kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id, top10_feats.index[i]] >", "Light Blue 0xC10020, # Vivid Red 0xCEA262, # Grayish Yellow", "i, position = \"branch-top\") for n in pt_tree.traverse(): if n.name", "= \"threshold to call genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help = \"mapping", "= a.pfam_mapping, tree = a.tree, feat_list = a.feat_list, phenotype =", "0x817066, # Medium Gray # The following don't work well", "= faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf =", "events if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf", "__name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(\"\"\"visualize target list", "for i in pt_tree.traverse(strategy = 'preorder')) pfams_with_event = set() pfam2color", "= 0, position = \"branch-right\") #set species name instead of", "\"#%06x\" % (pf2color[feats.index[i]]))[0] for i in range(len(pf2color))] labels= [i for", "\"_legend.png\") return figlegend def get_tree(phenotype, tree, gain_recon, loss_recon, node_recon, pfam_mapping,", "style[\"hz_line_width\"] = 3 elif loss_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] =", "Strong Purplish Pink 0x00538A, # Strong Blue 0xFF7A5C, # Strong", "color = 'grey') n.add_face(rf, column = i, position = \"aligned\")", "# Vivid Orange Yellow 0xB32851, # Strong Purplish Red 0xF4C800,", "[\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep", "# Vivid Yellowish Green 0x593315, # Deep Yellowish Brown 0xF13A13,", "help = \"table of misclassified samples\") parser.add_argument(\"--node_annotation\", help = \"table", "change in continuous reconstruction value\"\"\" h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color)))", "#for visualization of continuous feature get the range of values", "miscl_m = pd.read_csv(miscl, sep = \"\\t\", index_col = 0) for", "events ancestral character state reconstruction\") parser.add_argument(\"loss_recon\", help = \"loss events", "of tax id if n.name in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0]", "if pd.isnull(ns): style['fgcolor'] = 'grey' elif ns < threshold: style['fgcolor']", "False ts.show_scale = True ts.force_topology = False # Use my", "'red' style[\"hz_line_width\"] = 3 else: style[\"hz_line_type\"] = 0 style[\"hz_line_color\"] =", "# Use my custom layout ts.layout_fn = my_layout return ts", "recon_min) v_new = v - (v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h,", "= 0 style[\"hz_line_color\"] = 'black' n.set_style(style) #check if sample was", "Strong Reddish Brown 0x93AA00, # Vivid Yellowish Green 0x593315, #", "Pink 0x00538A, # Strong Blue 0xFF7A5C, # Strong Yellowish Pink", "faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i],", "a = parser.parse_args() pt_tree, feats, pf2color = get_tree(node_recon = a.node_recon,", "if node.is_leaf(): # If terminal node, draws its name name_face", "= pd.read_csv(feat_list, index_col = 0, sep = \"\\t\") pt_tree =", "are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if not miscl", "if not pd.isnull(value): if value == 0: rf = ete2.CircleFace(radius", "\"feature mapping/list\") parser.add_argument(\"feat_list\", help = \"list of features\") parser.add_argument(\"--target_node\", default", "= \"list of features\") parser.add_argument(\"--target_node\", default = \"N1\", help =", "#labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in range(feats.shape[0])] #if include_class: #", "phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"]", "'store_true', help = \"set if using continuous features with a", "parser.add_argument(\"--miscl\", help = \"table of misclassified samples\") parser.add_argument(\"--node_annotation\", help =", "get the range of values for each feature if are_continuous_features_with_discrete_phenotype:", "= a.phenotype, target_node = a.target_node, threshold = a.threshold, sample_mapping =", "= target_node)[0] node2name = dict((i.name, i.name) for i in pt_tree.traverse(strategy", "Green 0xF6768E, # Strong Purplish Pink 0x00538A, # Strong Blue", "= 0, sep = \"\\t\") #read node and edge reconstruction", "i in pt_tree.traverse(strategy = 'preorder')) pfams_with_event = set() pfam2color =", "top10_feats.index[i]] < 0: tf = faces.TextFace(\"-\") else: tf = faces.TextFace(\"+\")", "range(feats.shape[0])] #if include_class: # labels= [\"%s %s\" %(labels[i], feats.loc[:, \"class\"].iloc[i])", "% (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] figlegend.legend(lines, labels,", "0) gain_recon = pd.read_csv(gain_recon, sep = \"\\t\", index_col = 0)", "0) sample_mapping = pd.read_csv(sample_mapping, index_col = 0, sep = \"\\t\")", "TreeStyle() # Do not add leaf names automatically ts.show_leaf_name =", "position faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color, val, recon_min, recon_max):", "continuous feature get the range of values for each feature", "= phenotype, feat_list = \"top_cor\", is_ml_plus_phypat = True, target_node =", "n.add_face(tf, column = 0, position = \"branch-right\") #set species name", "feats, pf2color = get_tree(phenotype = phenotype, feat_list = \"top_cor\", is_ml_plus_phypat", "pt_tree.traverse(): if n.name in node2name: n.name = node2name[n.name] #filtered_pfams =", "abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id,", "# Vivid Reddish Orange 0x232C16, # Dark Olive Green ]", "[ax.plot(x, pd.np.ones(len(x)), 'o', color = \"#%06x\" % (pf2color[feats.index[i]]))[0] for i", "for i in range(len(labels))] figlegend.legend(lines, labels, markerscale = 2.5, numpoints", "in pt_tree.traverse(strategy = 'preorder')) pfams_with_event = set() pfam2color = {}", "not n.name == \"N1\": branch_id = n.name + \"_\" +", "Yellow 0x817066, # Medium Gray # The following don't work", "'o', color = \"#%06x\" % (pf2color[feats.index[i]]))[0] for i in range(len(pf2color))]", "target_node)[0] target.render(out + '_tree.pdf', tree_style = get_style()) #target.render(out + '_tree.png',", "if target_node is not None: pt_tree = pt_tree.search_nodes(name = target_node)[0]", "style[\"hz_line_color\"] = 'black' n.set_style(style) #check if sample was misclassified and", "\"N1\", help = \"list of features\") parser.add_argument(\"phenotype\", help = \"target", "type = float, help = \"threshold to call genotype/phenotype events\")", "None, are_continuous_features_with_discrete_phenotype = False, max_feats = 10, miscl = None,", "name face to the image at the preferred position faces.add_face_to_node(name_face,", "not miscl is None: miscl_m = pd.read_csv(miscl, sep = \"\\t\",", "Blue 0xFF7A5C, # Strong Yellowish Pink 0x53377A, # Strong Violet", "#if include_class: # labels= [\"%s %s\" %(labels[i], feats.loc[:, \"class\"].iloc[i]) for", "\"circle\", color = adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf)", "color vision 0x007D34, # Vivid Green 0xF6768E, # Strong Purplish", "Brown 0xF13A13, # Vivid Reddish Orange 0x232C16, # Dark Olive", "range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius = 8, style", "if n.name in node2name: n.name = node2name[n.name] #filtered_pfams = filter(lambda", "features for labeling the nodes\") a = parser.parse_args() pt_tree, feats,", "= a.loss_recon, pfam_mapping = a.pfam_mapping, tree = a.tree, feat_list =", "Vivid Greenish Yellow 0x7F180D, # Strong Reddish Brown 0x93AA00, #", "in range(len(labels))] figlegend.legend(lines, labels, markerscale = 2.5, numpoints = 1,", "0x53377A, # Strong Violet 0xFF8E00, # Vivid Orange Yellow 0xB32851,", "int, default = 10, help = \"visualize at most max_feats", "= target_node)[0] target.render(out + '_tree.pdf', tree_style = get_style()) #target.render(out +", "names\") parser.add_argument(\"out\", help = \"output file\") parser.add_argument(\"--max_feats\", type = int,", "10, help = \"visualize at most max_feats features\") parser.add_argument(\"--miscl\", help", "action = 'store_true', help = \"set if using continuous features", "draws label with smaller font size name_face = AttrFace(\"name\", fsize=10)", "= a.max_feats, miscl = a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree, a.target_node,", "figlegend.legend(lines, labels, markerscale = 2.5, numpoints = 1, frameon =", "'_tree.pdf', tree_style = get_style()) #target.render(out + '_tree.png', tree_style = get_style())", "top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0] - 1 #print", "in range(len(labels))] #if pf_acc: # labels = [\"%s %s\" %", "to the image at the preferred position faces.add_face_to_node(name_face, node, column=0,", "index_col = 0) sample_mapping = pd.read_csv(sample_mapping, index_col = 0, sep", "feats feats = pd.read_csv(feat_list, index_col = 0, sep = \"\\t\")", "# Strong Violet 0xFF8E00, # Vivid Orange Yellow 0xB32851, #", "Strong Yellowish Pink 0x53377A, # Strong Violet 0xFF8E00, # Vivid", "default = \"N1\", help = \"list of features\") parser.add_argument(\"phenotype\", help", "misclassified samples\") parser.add_argument(\"--node_annotation\", help = \"table of binary features for", "feat_list = \"top_cor\", is_ml_plus_phypat = True, target_node = target_node) pt_tree.dist", "= a.target_node, threshold = a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype =", "color = adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for", "8, style = \"circle\", color = 'red') elif value ==", "i in range(len(pf2color))] labels= [i for i in feats.index] #labels=", "not node_annotation is None: node_table = pd.read_csv(node_annotation, sep = \"\\t\",", "threshold: style['fgcolor'] = 'darkred' else: style['fgcolor'] = 'green' if not", "] def my_layout(node): if node.is_leaf(): # If terminal node, draws", "a.phenotype, target_node = a.target_node, threshold = a.threshold, sample_mapping = a.sample_mapping,", "= 'black' n.set_style(style) #check if sample was misclassified and add", "= 0) sample_mapping = pd.read_csv(sample_mapping, index_col = 0, sep =", "target_node = None, are_continuous_features_with_discrete_phenotype = False, max_feats = 10, miscl", "parser.add_argument(\"out\", help = \"output file\") parser.add_argument(\"--max_feats\", type = int, default", "if value == 0: rf = ete2.CircleFace(radius = 8, style", "top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf)", "#continuous features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]])", "mapping/list\") parser.add_argument(\"feat_list\", help = \"list of features\") parser.add_argument(\"--target_node\", default =", "faces, Tree, AttrFace, TreeStyle import pylab from matplotlib.colors import hex2color,", "(recon_max - recon_min) v_new = v - (v * (scale_factor))", "gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\")", "pt_tree = pt_tree.search_nodes(name = target_node)[0] node2name = dict((i.name, i.name) for", "sample ids and names\") parser.add_argument(\"out\", help = \"output file\") parser.add_argument(\"--max_feats\",", "\"table of binary features for labeling the nodes\") a =", "recon_min, recon_max): \"\"\"set brightness according to change in continuous reconstruction", "\"class\"].iloc[i]) for i in range(len(labels))] #if pf_desc: # labels =", "column = 0, position = \"branch-right\") #set species name instead", "= parser.parse_args() pt_tree, feats, pf2color = get_tree(node_recon = a.node_recon, gain_recon", "0xF13A13, # Vivid Reddish Orange 0x232C16, # Dark Olive Green", "not miscl is None: if node2name[n.name] in miscl_m.index: tf =", "feats, pf2color = get_tree(node_recon = a.node_recon, gain_recon = a.gain_recon, loss_recon", "format = 1) pt_tree.ladderize() if not node_annotation is None: node_table", "if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(\"\"\"visualize target", "i in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius =", "pf2color = get_tree(node_recon = a.node_recon, gain_recon = a.gain_recon, loss_recon =", "= \"\\t\") pt_tree = ete2.Tree(tree, format = 1) pt_tree.ladderize() if", "# labels = [\"%s %s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for", "pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous", "= float, help = \"threshold to call genotype/phenotype events\") parser.add_argument(\"sample_mapping\",", "= 'green' if not n.name == \"N1\": branch_id = n.name", "for each feature if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max =", "Vivid Yellowish Green 0x593315, # Deep Yellowish Brown 0xF13A13, #", "for i in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep = \"\\t\",", "== \"N1\": branch_id = n.name + \"_\" + n.up.name if", "lines = [ax.plot(x, pd.np.ones(len(x)), 'o', color = \"#%06x\" % (pf2color[feats.index[i]]))[0]", "import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [ 0xFFB300, #", "def adjust_kelly_brightness(hex_color, val, recon_min, recon_max): \"\"\"set brightness according to change", "= False): fig = pylab.figure() figlegend = pylab.figure(figsize = (9,", "2.5, numpoints = 1, frameon = False) #fig.show() fig.tight_layout() figlegend.savefig(out", "for i in range(len(labels))] #if pf_acc: # labels = [\"%s", "of binary features for labeling the nodes\") a = parser.parse_args()", "adjust_kelly_brightness(hex_color, val, recon_min, recon_max): \"\"\"set brightness according to change in", "AttrFace, TreeStyle import pylab from matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb,", "and nodes according to the posterior probability top10_feats = feats.iloc[:max_feats,]", "= 10 if pd.isnull(ns): style['fgcolor'] = 'grey' elif ns <", "sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority feature gains and losses", "0x232C16, # Dark Olive Green ] def my_layout(node): if node.is_leaf():", "to change in continuous reconstruction value\"\"\" h, s, v =", "in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius = 8,", "= \"table of binary features for labeling the nodes\") a", "tree, gain_recon, loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping, threshold = 0.5,", "# Strong Yellowish Pink 0x53377A, # Strong Violet 0xFF8E00, #", "continuous reconstruction value\"\"\" h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor =", "= pylab.figure(figsize = (9, 6)) ax = fig.add_subplot(111) x =", "% (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] #if pf_acc:", "of the branches and nodes according to the posterior probability", "== \"N1\": continue if not node_annotation is None: if n.name", "rf = ete2.CircleFace(radius = 8, style = \"circle\", color =", "elif loss_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] =", "style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"] = 3 else: style[\"hz_line_type\"] = 0", "species name instead of tax id if n.name in sample_mapping.index:", "n.up.name if gain_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"]", "#tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf", "Pink 0x53377A, # Strong Violet 0xFF8E00, # Vivid Orange Yellow", "= [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon,", "file\") parser.add_argument(\"--max_feats\", type = int, default = 10, help =", "target_node) pt_tree.dist = 0 target = pt_tree.search_nodes(name = target_node)[0] target.render(out", "pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss", "import pylab from matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex", "val, recon_min, recon_max): \"\"\"set brightness according to change in continuous", "%(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in range(feats.shape[0])] #if include_class: # labels= [\"%s", "If internal node, draws label with smaller font size name_face", "help = \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true', help =", "phenotype, feat_list = \"top_cor\", is_ml_plus_phypat = True, target_node = target_node)", "are_continuous_features_with_discrete_phenotype = False, max_feats = 10, miscl = None, node_annotation", "Brown 0x93AA00, # Vivid Yellowish Green 0x593315, # Deep Yellowish", "and losses events = [] for i in range(top10_feats.shape[0]): if", "nodes according to the posterior probability top10_feats = feats.iloc[:max_feats,] #for", "# Deep Yellowish Brown 0xF13A13, # Vivid Reddish Orange 0x232C16,", "is_ml_plus_phypat = True, target_node = target_node) pt_tree.dist = 0 target", "get_tree(phenotype, tree, gain_recon, loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping, threshold =", "is None: node_table = pd.read_csv(node_annotation, sep = \"\\t\", index_col =", "None: if n.name in node_table.index: for attr,i in zip(node_table.columns, range(len(node_table.columns))):", "node_table.index: for attr,i in zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name, attr]", "faces.CircleFace(radius = 8, style = \"circle\", color = adjusted_color) pfam2color[top10_feats.index[i]]", "list of features\"\"\") parser.add_argument(\"node_recon\", help = \"node ancestral character state", "help = \"threshold to call genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help =", "0.5, target_node = None, are_continuous_features_with_discrete_phenotype = False, max_feats = 10,", "a.tree, feat_list = a.feat_list, phenotype = a.phenotype, target_node = a.target_node,", "recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] <", "Red 0xF4C800, # Vivid Greenish Yellow 0x7F180D, # Strong Reddish", "in continuous reconstruction value\"\"\" h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor", "0x593315, # Deep Yellowish Brown 0xF13A13, # Vivid Reddish Orange", "pylab.figure(figsize = (9, 6)) ax = fig.add_subplot(111) x = [0,1]", "= 3 elif loss_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1", "= 'orange') else: rf = faces.CircleFace(radius = 8, style =", "'darkred' else: style['fgcolor'] = 'green' if not n.name == \"N1\":", "True ts.force_topology = False # Use my custom layout ts.layout_fn", "style = \"circle\", color = 'green') else: rf = faces.CircleFace(radius", "# labels = [\"%s %s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for", "a.feat_list, phenotype = a.phenotype, target_node = a.target_node, threshold = a.threshold,", "color = kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold:", "a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl = a.miscl, node_annotation = a.node_annotation)", "threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"] = 3", "automatically ts.show_leaf_name = False ts.show_scale = True ts.force_topology = False", "target_node = target_node) pt_tree.dist = 0 target = pt_tree.search_nodes(name =", "= 'red' style[\"hz_line_width\"] = 3 else: style[\"hz_line_type\"] = 0 style[\"hz_line_color\"]", "\"\"\"set brightness according to change in continuous reconstruction value\"\"\" h,", "not None: pt_tree = pt_tree.search_nodes(name = target_node)[0] node2name = dict((i.name,", "Strong Blue 0xFF7A5C, # Strong Yellowish Pink 0x53377A, # Strong", "\"list of features\") parser.add_argument(\"--target_node\", default = \"N1\", help = \"list", "reconstruction matrices node_recon = pd.read_csv(node_recon, sep = \"\\t\", index_col =", "set() pfam2color = {} #set the style of the branches", "if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf =", "Greenish Yellow 0x7F180D, # Strong Reddish Brown 0x93AA00, # Vivid", "= \"\\t\", index_col = 0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for", "0, sep = \"\\t\") #read node and edge reconstruction matrices", "phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"]", "nodes\") a = parser.parse_args() pt_tree, feats, pf2color = get_tree(node_recon =", "0xFF6800, # Vivid Orange 0xA6BDD7, # Very Light Blue 0xC10020,", "top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]]", "vision 0x007D34, # Vivid Green 0xF6768E, # Strong Purplish Pink", "my_layout(node): if node.is_leaf(): # If terminal node, draws its name", "if not miscl is None: if node2name[n.name] in miscl_m.index: tf", "root if n.name == \"N1\": continue if not node_annotation is", "#check if sample was misclassified and add misclassified label if", "Very Light Blue 0xC10020, # Vivid Red 0xCEA262, # Grayish", "name instead of tax id if n.name in sample_mapping.index: node2name[n.name]", "0: rf = ete2.CircleFace(radius = 8, style = \"circle\", color", "= kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features", "= 'preorder')) pfams_with_event = set() pfam2color = {} #set the", "a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl = a.miscl,", "= top10_feats.loc[filtered_ids,] #process node annotation return pt_tree, top10_feats, pfam2color if", "scale_factor = 1 - (recon_max - val) / (recon_max -", "events elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf", "are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl = a.miscl, node_annotation", "/ (recon_max - recon_min) v_new = v - (v *", "node_table = pd.read_csv(node_annotation, sep = \"\\t\", index_col = 0) sample_mapping", "= 1 style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"] = 3 else: style[\"hz_line_type\"]", "= \"gain events ancestral character state reconstruction\") parser.add_argument(\"loss_recon\", help =", "\"table of misclassified samples\") parser.add_argument(\"--node_annotation\", help = \"table of binary", "= 0 target = pt_tree.search_nodes(name = target_node)[0] target.render(out + '_tree.pdf',", "= None, are_continuous_features_with_discrete_phenotype = False, max_feats = 10, miscl =", "include_class = False): fig = pylab.figure() figlegend = pylab.figure(figsize =", "faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif loss_recon.loc[branch_id, top10_feats.index[i]] >", "max_feats features\") parser.add_argument(\"--miscl\", help = \"table of misclassified samples\") parser.add_argument(\"--node_annotation\",", "genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help = \"mapping between sample ids and", "= True ts.force_topology = False # Use my custom layout", "#add majority feature gains and losses events = [] for", "# labels= [\"%s %s\" %(labels[i], feats.loc[:, \"class\"].iloc[i]) for i in", "out): #pt_tree, feats, pf2color = get_tree(phenotype = phenotype, feat_list =", "= \"tree with internal nodes labeled\") parser.add_argument(\"pfam_mapping\", help = \"feature", "most max_feats features\") parser.add_argument(\"--miscl\", help = \"table of misclassified samples\")", "posterior probability top10_feats = feats.iloc[:max_feats,] #for visualization of continuous feature", "If terminal node, draws its name name_face = AttrFace(\"name\") else:", "node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority feature gains and losses events", "if not n.name == \"N1\": branch_id = n.name + \"_\"", "parser.add_argument(\"phenotype\", help = \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true', help", "image at the preferred position faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\") def", "= \"aligned\") ns = node_recon.loc[n.name, phenotype] style = ete2.NodeStyle() style[\"shape\"]", "parser.add_argument(\"tree\", help = \"tree with internal nodes labeled\") parser.add_argument(\"pfam_mapping\", help", "# Strong Purplish Pink 0x00538A, # Strong Blue 0xFF7A5C, #", "the root if n.name == \"N1\": continue if not node_annotation", "column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color, val, recon_min, recon_max): \"\"\"set brightness according", "else: rf = faces.CircleFace(radius = 8, style = \"circle\", color", "= \"\\t\", index_col = 0) sample_mapping = pd.read_csv(sample_mapping, index_col =", "pfam2color = {} #set the style of the branches and", "phenotype] style = ete2.NodeStyle() style[\"shape\"] = 'square' style['size'] = 10", "+ \"_\" + n.up.name if gain_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"]", "= \"circle\", color = adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf)", "max_feats = 10, miscl = None, node_annotation = None): #read", "i in feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in range(feats.shape[0])]", "target_node, out): #pt_tree, feats, pf2color = get_tree(phenotype = phenotype, feat_list", "= faces.CircleFace(radius = 8, style = \"circle\", color = adjusted_color)", "= \"mapping between sample ids and names\") parser.add_argument(\"out\", help =", "None: miscl_m = pd.read_csv(miscl, sep = \"\\t\", index_col = 0)", "not pd.isnull(value): if value == 0: rf = ete2.CircleFace(radius =", "help = \"loss events ancestral character state reconstruction\") parser.add_argument(\"tree\", help", "kelly_colors_hex = [ 0xFFB300, # Vivid Yellow 0x803E75, # Strong", "label if not miscl is None: if node2name[n.name] in miscl_m.index:", "feats = pd.read_csv(feat_list, index_col = 0, sep = \"\\t\") pt_tree", "elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf =", "hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [ 0xFFB300, # Vivid Yellow 0x803E75,", "None: pt_tree = pt_tree.search_nodes(name = target_node)[0] node2name = dict((i.name, i.name)", "\"gain events ancestral character state reconstruction\") parser.add_argument(\"loss_recon\", help = \"loss", "# If terminal node, draws its name name_face = AttrFace(\"name\")", "reconstruction value\"\"\" h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1", "return figlegend def get_tree(phenotype, tree, gain_recon, loss_recon, node_recon, pfam_mapping, feat_list,", "faces.CircleFace(radius = 8, style = \"circle\", color = 'green') else:", "events.append(tf) for i in range(len(events)): n.add_face(events[i], column = i, position", "parser.add_argument(\"--target_node\", default = \"N1\", help = \"list of features\") parser.add_argument(\"phenotype\",", "add leaf names automatically ts.show_leaf_name = False ts.show_scale = True", "features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf", "with internal nodes labeled\") parser.add_argument(\"pfam_mapping\", help = \"feature mapping/list\") parser.add_argument(\"feat_list\",", "for i in range(len(pf2color))] labels= [i for i in feats.index]", "\"\\t\") pt_tree = ete2.Tree(tree, format = 1) pt_tree.ladderize() if not", "- val) / (recon_max - recon_min) v_new = v -", "= 1) pt_tree.ladderize() if not node_annotation is None: node_table =", "#prune to target node if target_node is not None: pt_tree", "pylab from matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex =", "= {} #set the style of the branches and nodes", "style = \"circle\", color = 'red') elif value == 2:", "ete2 import faces, Tree, AttrFace, TreeStyle import pylab from matplotlib.colors", "in feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in range(feats.shape[0])] #if", "ancestral character state reconstruction\") parser.add_argument(\"gain_recon\", help = \"gain events ancestral", "# Medium Gray # The following don't work well for", "x = [0,1] lines = [ax.plot(x, pd.np.ones(len(x)), 'o', color =", "node_table.loc[n.name, attr] if not pd.isnull(value): if value == 0: rf", "= False ts.show_scale = True ts.force_topology = False # Use", "list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0] - 1", "reconstruction\") parser.add_argument(\"loss_recon\", help = \"loss events ancestral character state reconstruction\")", "\"tree with internal nodes labeled\") parser.add_argument(\"pfam_mapping\", help = \"feature mapping/list\")", "= 10, help = \"visualize at most max_feats features\") parser.add_argument(\"--miscl\",", "= pd.read_csv(miscl, sep = \"\\t\", index_col = 0) for n", "in range(len(events)): n.add_face(events[i], column = i, position = \"branch-top\") for", "branches and nodes according to the posterior probability top10_feats =", "(v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style(): ts", "= a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats =", "leaf names automatically ts.show_leaf_name = False ts.show_scale = True ts.force_topology", "pt_tree, top10_feats, pfam2color if __name__ == \"__main__\": import argparse parser", "[0,1] lines = [ax.plot(x, pd.np.ones(len(x)), 'o', color = \"#%06x\" %", "pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i in range(len(events)): n.add_face(events[i], column =", "following don't work well for people with defective color vision", "= 1 style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"] = 3 elif loss_recon.loc[branch_id,", "False) #fig.show() fig.tight_layout() figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out + \"_legend.png\") return", "annotation return pt_tree, top10_feats, pfam2color if __name__ == \"__main__\": import", "= AttrFace(\"name\", fsize=10) # Adds the name face to the", "range of values for each feature if are_continuous_features_with_discrete_phenotype: recon_min =", "rgb_to_hsv kelly_colors_hex = [ 0xFFB300, # Vivid Yellow 0x803E75, #", "Dark Olive Green ] def my_layout(node): if node.is_leaf(): # If", "#ignore the root if n.name == \"N1\": continue if not", "color = 'orange') else: rf = faces.CircleFace(radius = 8, style", "as pd import ete2 from ete2 import faces, Tree, AttrFace,", "if n.name in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority feature", "= \"N1\", help = \"list of features\") parser.add_argument(\"phenotype\", help =", "position = \"branch-right\") #set species name instead of tax id", "= None): #read target feats feats = pd.read_csv(feat_list, index_col =", "= filter(lambda i: i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids", "of continuous feature get the range of values for each", "= False, pf_acc = True, include_class = False): fig =", "%s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] figlegend.legend(lines,", "loss_recon = pd.read_csv(loss_recon, sep = \"\\t\", index_col = 0) loss_recon.index", "#gain events if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i]", "top10_feats.loc[filtered_ids,] #process node annotation return pt_tree, top10_feats, pfam2color if __name__", "if not node_annotation is None: node_table = pd.read_csv(node_annotation, sep =", "= a.gain_recon, loss_recon = a.loss_recon, pfam_mapping = a.pfam_mapping, tree =", "with defective color vision 0x007D34, # Vivid Green 0xF6768E, #", "sep = \"\\t\", index_col = 0) sample_mapping = pd.read_csv(sample_mapping, index_col", "in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep = \"\\t\", index_col =", "index_col = 0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in", "in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0] -", "parser.add_argument(\"sample_mapping\", help = \"mapping between sample ids and names\") parser.add_argument(\"out\",", "import pandas as pd import ete2 from ete2 import faces,", "from matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [", "figlegend.savefig(out + \"_legend.png\") return figlegend def get_tree(phenotype, tree, gain_recon, loss_recon,", "target feats feats = pd.read_csv(feat_list, index_col = 0, sep =", "pt_tree = ete2.Tree(tree, format = 1) pt_tree.ladderize() if not node_annotation", "'black' n.set_style(style) #check if sample was misclassified and add misclassified", "+ \"_legend.svg\") figlegend.savefig(out + \"_legend.png\") return figlegend def get_tree(phenotype, tree,", "8, style = \"circle\", color = 'grey') n.add_face(rf, column =", "if sample was misclassified and add misclassified label if not", "pf2color, pf_desc = False, pf_acc = True, include_class = False):", "sample was misclassified and add misclassified label if not miscl", "%s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] #if", "= ete2.CircleFace(radius = 8, style = \"circle\", color = 'red')", "(labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] figlegend.legend(lines, labels, markerscale", "faces.TextFace(\"misclassified\") n.add_face(tf, column = 0, position = \"branch-right\") #set species", "else: # If internal node, draws label with smaller font", "= a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl =", "rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style(): ts = TreeStyle() # Do", "# Strong Reddish Brown 0x93AA00, # Vivid Yellowish Green 0x593315,", "\"\\t\") #read node and edge reconstruction matrices node_recon = pd.read_csv(node_recon,", "node and edge reconstruction matrices node_recon = pd.read_csv(node_recon, sep =", "feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in range(feats.shape[0])] #if include_class:", "range(len(labels))] #if pf_acc: # labels = [\"%s %s\" % (labels[i],", "= target_node) pt_tree.dist = 0 target = pt_tree.search_nodes(name = target_node)[0]", "misclassified label if not miscl is None: if node2name[n.name] in", "tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif loss_recon.loc[branch_id,", "value\"\"\" h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 -", "= kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events", "the nodes\") a = parser.parse_args() pt_tree, feats, pf2color = get_tree(node_recon", "False, max_feats = 10, miscl = None, node_annotation = None):", "if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if not", "0xCEA262, # Grayish Yellow 0x817066, # Medium Gray # The", "threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf)", "= 0) for n in pt_tree.traverse(): #ignore the root if", "value == 0: rf = ete2.CircleFace(radius = 8, style =", "< threshold: style['fgcolor'] = 'darkred' else: style['fgcolor'] = 'green' if", "for i in loss_recon.index.values] #prune to target node if target_node", "loss_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'red'", "\"_\" + n.up.name if gain_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] =", "miscl = None, node_annotation = None): #read target feats feats", "features\") parser.add_argument(\"--target_node\", default = \"N1\", help = \"list of features\")", "pt_tree.traverse(): #ignore the root if n.name == \"N1\": continue if", "label with smaller font size name_face = AttrFace(\"name\", fsize=10) #", "= get_style()) #target.render(out + '_tree.png', tree_style = get_style()) return target,", "discrete phenotype\") parser.add_argument(\"threshold\", type = float, help = \"threshold to", "#process node annotation return pt_tree, top10_feats, pfam2color if __name__ ==", "value = node_table.loc[n.name, attr] if not pd.isnull(value): if value ==", "1 style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"] = 3 elif loss_recon.loc[branch_id, phenotype]", "adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if", "node, column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color, val, recon_min, recon_max): \"\"\"set brightness", "the branches and nodes according to the posterior probability top10_feats", "internal node, draws label with smaller font size name_face =", "\"\\t\", index_col = 0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i", "= get_tree(node_recon = a.node_recon, gain_recon = a.gain_recon, loss_recon = a.loss_recon,", "= kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i in range(len(events)): n.add_face(events[i],", "a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats,", "not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius = 8, style = \"circle\",", "0xF4C800, # Vivid Greenish Yellow 0x7F180D, # Strong Reddish Brown", "gain_recon = pd.read_csv(gain_recon, sep = \"\\t\", index_col = 0) gain_recon.index", "= AttrFace(\"name\") else: # If internal node, draws label with", "pf_desc = False, pf_acc = True, include_class = False): fig", "figlegend def get_tree(phenotype, tree, gain_recon, loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping,", "color = 'green') else: rf = faces.CircleFace(radius = 8, style", "# The following don't work well for people with defective", "= False, max_feats = 10, miscl = None, node_annotation =", "faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color, val, recon_min, recon_max): \"\"\"set", "out, pf2color, pf_desc = False, pf_acc = True, include_class =", "for attr,i in zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name, attr] if", "threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"] = 3", "loss_recon = a.loss_recon, pfam_mapping = a.pfam_mapping, tree = a.tree, feat_list", "Yellow 0x803E75, # Strong Purple 0xFF6800, # Vivid Orange 0xA6BDD7,", "n.set_style(style) #check if sample was misclassified and add misclassified label", "zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name, attr] if not pd.isnull(value): if", "= 3 else: style[\"hz_line_type\"] = 0 style[\"hz_line_color\"] = 'black' n.set_style(style)", "- recon_min) v_new = v - (v * (scale_factor)) return", "faces.TextFace(\"+\") cf = faces.CircleFace(radius = 8, style = \"circle\", color", "state reconstruction\") parser.add_argument(\"tree\", help = \"tree with internal nodes labeled\")", "[i for i in feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i", "to target node if target_node is not None: pt_tree =", "not add leaf names automatically ts.show_leaf_name = False ts.show_scale =", "def plot_legend(feats, out, pf2color, pf_desc = False, pf_acc = True,", "{} #set the style of the branches and nodes according", "pt_tree, feats, pf2color = get_tree(node_recon = a.node_recon, gain_recon = a.gain_recon,", "#set the style of the branches and nodes according to", "\"branch-top\") for n in pt_tree.traverse(): if n.name in node2name: n.name", "= a.tree, feat_list = a.feat_list, phenotype = a.phenotype, target_node =", "gain_recon.abs().apply(pd.np.max) if not miscl is None: miscl_m = pd.read_csv(miscl, sep", "# Vivid Greenish Yellow 0x7F180D, # Strong Reddish Brown 0x93AA00,", "call genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help = \"mapping between sample ids", "return target, feats, pf2color def plot_legend(feats, out, pf2color, pf_desc =", "node_annotation is None: if n.name in node_table.index: for attr,i in", "# If internal node, draws label with smaller font size", "[\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in range(feats.shape[0])] #if include_class: # labels=", "#filtered_pfams = filter(lambda i: i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams", "pd import ete2 from ete2 import faces, Tree, AttrFace, TreeStyle", "hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [ 0xFFB300, # Vivid", "feats.loc[:, \"class\"].iloc[i]) for i in range(len(labels))] #if pf_desc: # labels", "= feats.iloc[:max_feats,] #for visualization of continuous feature get the range", "pt_tree.dist = 0 target = pt_tree.search_nodes(name = target_node)[0] target.render(out +", "import argparse parser = argparse.ArgumentParser(\"\"\"visualize target list of features\"\"\") parser.add_argument(\"node_recon\",", "gain_recon = a.gain_recon, loss_recon = a.loss_recon, pfam_mapping = a.pfam_mapping, tree", "color = 'red') elif value == 2: rf = faces.CircleFace(radius", "= 1 - (recon_max - val) / (recon_max - recon_min)", "= sample_mapping.loc[n.name,][0] #add majority feature gains and losses events =", "TreeStyle import pylab from matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv", "recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] < 0:", "sep = \"\\t\", index_col = 0) for n in pt_tree.traverse():", "= adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]])", "else: tf = faces.TextFace(\"+\") cf = faces.CircleFace(radius = 8, style", "node_recon.loc[n.name, phenotype] style = ete2.NodeStyle() style[\"shape\"] = 'square' style['size'] =", "i.name) for i in pt_tree.traverse(strategy = 'preorder')) pfams_with_event = set()", "with smaller font size name_face = AttrFace(\"name\", fsize=10) # Adds", "well for people with defective color vision 0x007D34, # Vivid", "the image at the preferred position faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\")", "miscl_m.index: tf = faces.TextFace(\"misclassified\") n.add_face(tf, column = 0, position =", "(labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] #if pf_acc: #", "= 8, style = \"circle\", color = kelly_colors_hex[i]) #gain events", "rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [ 0xFFB300, # Vivid Yellow", "pf_acc: # labels = [\"%s %s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1])", "node2name[n.name] #filtered_pfams = filter(lambda i: i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print", "pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))] #if pf_acc: # labels", "if using continuous features with a discrete phenotype\") parser.add_argument(\"threshold\", type", "pd.read_csv(miscl, sep = \"\\t\", index_col = 0) for n in", "Green 0x593315, # Deep Yellowish Brown 0xF13A13, # Vivid Reddish", "range(len(labels))] #if pf_desc: # labels = [\"%s %s\" % (labels[i],", "node_recon = pd.read_csv(node_recon, sep = \"\\t\", index_col = 0) gain_recon", "character state reconstruction\") parser.add_argument(\"gain_recon\", help = \"gain events ancestral character", "= pylab.figure() figlegend = pylab.figure(figsize = (9, 6)) ax =", "\"N1\": branch_id = n.name + \"_\" + n.up.name if gain_recon.loc[branch_id,", "parser = argparse.ArgumentParser(\"\"\"visualize target list of features\"\"\") parser.add_argument(\"node_recon\", help =", "tf = faces.TextFace(\"misclassified\") n.add_face(tf, column = 0, position = \"branch-right\")", "i, position = \"aligned\") ns = node_recon.loc[n.name, phenotype] style =", "# Vivid Green 0xF6768E, # Strong Purplish Pink 0x00538A, #", "float, help = \"threshold to call genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help", "sep = \"\\t\", index_col = 0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1]))", "pt_tree.search_nodes(name = target_node)[0] node2name = dict((i.name, i.name) for i in", "its name name_face = AttrFace(\"name\") else: # If internal node,", "= i, position = \"aligned\") ns = node_recon.loc[n.name, phenotype] style", "pd.np.ones(len(x)), 'o', color = \"#%06x\" % (pf2color[feats.index[i]]))[0] for i in", "Reddish Orange 0x232C16, # Dark Olive Green ] def my_layout(node):", "plot_tree(pt_tree, target_node, out): #pt_tree, feats, pf2color = get_tree(phenotype = phenotype,", "help = \"set if using continuous features with a discrete", "= faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif loss_recon.loc[branch_id, top10_feats.index[i]]", "in loss_recon.index.values] #prune to target node if target_node is not", "face to the image at the preferred position faces.add_face_to_node(name_face, node,", "#loss events elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i]", "Yellow 0x7F180D, # Strong Reddish Brown 0x93AA00, # Vivid Yellowish", "Orange Yellow 0xB32851, # Strong Purplish Red 0xF4C800, # Vivid", "#fig.show() fig.tight_layout() figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out + \"_legend.png\") return figlegend", "#read node and edge reconstruction matrices node_recon = pd.read_csv(node_recon, sep", "ts.layout_fn = my_layout return ts def plot_tree(pt_tree, target_node, out): #pt_tree,", "'green') else: rf = faces.CircleFace(radius = 8, style = \"circle\",", "= 'square' style['size'] = 10 if pd.isnull(ns): style['fgcolor'] = 'grey'", "pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]),", "= adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i", "custom layout ts.layout_fn = my_layout return ts def plot_tree(pt_tree, target_node,", "n.add_face(events[i], column = i, position = \"branch-top\") for n in", "node_annotation = None): #read target feats feats = pd.read_csv(feat_list, index_col", "i.split(\"_\")[-1])) for i in loss_recon.index.values] #prune to target node if", "name_face = AttrFace(\"name\") else: # If internal node, draws label", "i in range(len(labels))] #if pf_desc: # labels = [\"%s %s\"", "= v - (v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new])))", "0xF6768E, # Strong Purplish Pink 0x00538A, # Strong Blue 0xFF7A5C,", "labels = [\"%s %s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i", "\"circle\", color = 'orange') else: rf = faces.CircleFace(radius = 8,", "events.append(cf) events.append(tf) for i in range(len(events)): n.add_face(events[i], column = i,", "return pt_tree, top10_feats, pfam2color if __name__ == \"__main__\": import argparse", "Vivid Orange Yellow 0xB32851, # Strong Purplish Red 0xF4C800, #", "labels = [\"%s %s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i", "= faces.TextFace(\"-\") else: tf = faces.TextFace(\"+\") cf = faces.CircleFace(radius =", "sep = \"\\t\") pt_tree = ete2.Tree(tree, format = 1) pt_tree.ladderize()", "range(len(pf2color))] labels= [i for i in feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i])", "#print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0] - 1 #print filtered_ids", "Yellowish Pink 0x53377A, # Strong Violet 0xFF8E00, # Vivid Orange", "[\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in loss_recon.index.values] #prune to target node", "s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 - (recon_max -", "ts.show_scale = True ts.force_topology = False # Use my custom", "\"node ancestral character state reconstruction\") parser.add_argument(\"gain_recon\", help = \"gain events", "True, target_node = target_node) pt_tree.dist = 0 target = pt_tree.search_nodes(name", "s, v_new]))) def get_style(): ts = TreeStyle() # Do not", "kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif", "Blue 0xC10020, # Vivid Red 0xCEA262, # Grayish Yellow 0x817066,", "in pt_tree.traverse(): #ignore the root if n.name == \"N1\": continue", "v - (v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def", "0x93AA00, # Vivid Yellowish Green 0x593315, # Deep Yellowish Brown", "# Dark Olive Green ] def my_layout(node): if node.is_leaf(): #", "Purplish Red 0xF4C800, # Vivid Greenish Yellow 0x7F180D, # Strong", "= my_layout return ts def plot_tree(pt_tree, target_node, out): #pt_tree, feats,", "pf_acc = True, include_class = False): fig = pylab.figure() figlegend", "#set species name instead of tax id if n.name in", "of features\") parser.add_argument(\"--target_node\", default = \"N1\", help = \"list of", "Medium Gray # The following don't work well for people", "[\"%s %s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))]", "= faces.CircleFace(radius = 8, style = \"circle\", color = 'orange')", "style of the branches and nodes according to the posterior", "Vivid Green 0xF6768E, # Strong Purplish Pink 0x00538A, # Strong", "0xFF7A5C, # Strong Yellowish Pink 0x53377A, # Strong Violet 0xFF8E00,", "is None: if n.name in node_table.index: for attr,i in zip(node_table.columns,", "#filtered_ids = pt_gt2id.loc[filtered_pfams, 0] - 1 #print filtered_ids #top10_feats_with_event =", "parser.add_argument(\"pfam_mapping\", help = \"feature mapping/list\") parser.add_argument(\"feat_list\", help = \"list of", "# Do not add leaf names automatically ts.show_leaf_name = False", "style = \"circle\", color = adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i])", "= pd.read_csv(node_recon, sep = \"\\t\", index_col = 0) gain_recon =", "pylab.figure() figlegend = pylab.figure(figsize = (9, 6)) ax = fig.add_subplot(111)", "= faces.CircleFace(radius = 8, style = \"circle\", color = kelly_colors_hex[i])", "0 style[\"hz_line_color\"] = 'black' n.set_style(style) #check if sample was misclassified", "help = \"list of features\") parser.add_argument(\"phenotype\", help = \"target phenotype\")", "== \"__main__\": import argparse parser = argparse.ArgumentParser(\"\"\"visualize target list of", "parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true', help = \"set if using continuous", "\"set if using continuous features with a discrete phenotype\") parser.add_argument(\"threshold\",", "Orange 0x232C16, # Dark Olive Green ] def my_layout(node): if", "to the posterior probability top10_feats = feats.iloc[:max_feats,] #for visualization of", "figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out + \"_legend.png\") return figlegend def get_tree(phenotype,", "#target.render(out + '_tree.png', tree_style = get_style()) return target, feats, pf2color", "if node2name[n.name] in miscl_m.index: tf = faces.TextFace(\"misclassified\") n.add_face(tf, column =", "0 target = pt_tree.search_nodes(name = target_node)[0] target.render(out + '_tree.pdf', tree_style", "size name_face = AttrFace(\"name\", fsize=10) # Adds the name face", "i in range(feats.shape[0])] #if include_class: # labels= [\"%s %s\" %(labels[i],", "1 - (recon_max - val) / (recon_max - recon_min) v_new", "Yellowish Brown 0xF13A13, # Vivid Reddish Orange 0x232C16, # Dark", "\"N1\": continue if not node_annotation is None: if n.name in", "= None, node_annotation = None): #read target feats feats =", "sample_mapping, threshold = 0.5, target_node = None, are_continuous_features_with_discrete_phenotype = False,", "internal nodes labeled\") parser.add_argument(\"pfam_mapping\", help = \"feature mapping/list\") parser.add_argument(\"feat_list\", help", "[\"%s %s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in range(len(labels))]", "range(len(node_table.columns))): value = node_table.loc[n.name, attr] if not pd.isnull(value): if value", "import ete2 from ete2 import faces, Tree, AttrFace, TreeStyle import", "= 2.5, numpoints = 1, frameon = False) #fig.show() fig.tight_layout()", "state reconstruction\") parser.add_argument(\"loss_recon\", help = \"loss events ancestral character state", "markerscale = 2.5, numpoints = 1, frameon = False) #fig.show()", "frameon = False) #fig.show() fig.tight_layout() figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out +", "= pd.read_csv(loss_recon, sep = \"\\t\", index_col = 0) loss_recon.index =", "target_node)[0] node2name = dict((i.name, i.name) for i in pt_tree.traverse(strategy =", "if loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf = faces.TextFace(\"-\") else: tf", "(scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style(): ts = TreeStyle()", "= \"#%06x\" % (pf2color[feats.index[i]]))[0] for i in range(len(pf2color))] labels= [i", "Olive Green ] def my_layout(node): if node.is_leaf(): # If terminal", "gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in gain_recon.index.values] loss_recon =", "for i in range(len(labels))] #if pf_desc: # labels = [\"%s", "if gain_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] =", "gains and losses events = [] for i in range(top10_feats.shape[0]):", "node2name: n.name = node2name[n.name] #filtered_pfams = filter(lambda i: i in", "faces.CircleFace(radius = 8, style = \"circle\", color = 'grey') n.add_face(rf,", "= faces.CircleFace(radius = 8, style = \"circle\", color = 'grey')", "ns < threshold: style['fgcolor'] = 'darkred' else: style['fgcolor'] = 'green'", "phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true', help = \"set if using", "a.loss_recon, pfam_mapping = a.pfam_mapping, tree = a.tree, feat_list = a.feat_list,", "> threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i])", "Vivid Reddish Orange 0x232C16, # Dark Olive Green ] def", "n.name in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority feature gains", "sep = \"\\t\", index_col = 0) gain_recon = pd.read_csv(gain_recon, sep", "the preferred position faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color, val,", "ts = TreeStyle() # Do not add leaf names automatically", "= 10, miscl = None, node_annotation = None): #read target", "10 if pd.isnull(ns): style['fgcolor'] = 'grey' elif ns < threshold:", "argparse parser = argparse.ArgumentParser(\"\"\"visualize target list of features\"\"\") parser.add_argument(\"node_recon\", help", "parser.add_argument(\"node_recon\", help = \"node ancestral character state reconstruction\") parser.add_argument(\"gain_recon\", help", "adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i in", "feat_list = a.feat_list, phenotype = a.phenotype, target_node = a.target_node, threshold", "3 else: style[\"hz_line_type\"] = 0 style[\"hz_line_color\"] = 'black' n.set_style(style) #check", "feature if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if", "don't work well for people with defective color vision 0x007D34,", "for i in range(len(events)): n.add_face(events[i], column = i, position =", "= False # Use my custom layout ts.layout_fn = my_layout", "pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]]", "= \"table of misclassified samples\") parser.add_argument(\"--node_annotation\", help = \"table of", "\"\\t\", index_col = 0) gain_recon = pd.read_csv(gain_recon, sep = \"\\t\",", "for i in feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for i in", "else: style['fgcolor'] = 'green' if not n.name == \"N1\": branch_id", "in pt_tree.traverse(): if n.name in node2name: n.name = node2name[n.name] #filtered_pfams", "# Strong Purplish Red 0xF4C800, # Vivid Greenish Yellow 0x7F180D,", "ete2.NodeStyle() style[\"shape\"] = 'square' style['size'] = 10 if pd.isnull(ns): style['fgcolor']", "features\") parser.add_argument(\"phenotype\", help = \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action = 'store_true',", "position = \"aligned\") ns = node_recon.loc[n.name, phenotype] style = ete2.NodeStyle()", "index_col = 0, sep = \"\\t\") #read node and edge", "is None: miscl_m = pd.read_csv(miscl, sep = \"\\t\", index_col =", "elif value == 2: rf = faces.CircleFace(radius = 8, style", "in range(len(labels))] #if pf_desc: # labels = [\"%s %s\" %", "for n in pt_tree.traverse(): #ignore the root if n.name ==", "1) pt_tree.ladderize() if not node_annotation is None: node_table = pd.read_csv(node_annotation,", "Purplish Pink 0x00538A, # Strong Blue 0xFF7A5C, # Strong Yellowish", "tax id if n.name in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add", "if not node_annotation is None: if n.name in node_table.index: for", "instead of tax id if n.name in sample_mapping.index: node2name[n.name] =", "- 1 #print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node annotation", "== 2: rf = faces.CircleFace(radius = 8, style = \"circle\",", "using continuous features with a discrete phenotype\") parser.add_argument(\"threshold\", type =", "in miscl_m.index: tf = faces.TextFace(\"misclassified\") n.add_face(tf, column = 0, position", "= 'green') else: rf = faces.CircleFace(radius = 8, style =", "faces.CircleFace(radius = 8, style = \"circle\", color = kelly_colors_hex[i]) #gain", "get_style(): ts = TreeStyle() # Do not add leaf names", "\"\\t\", index_col = 0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i", "loss_recon.index.values] #prune to target node if target_node is not None:", "if not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius = 8, style =", "target, feats, pf2color def plot_legend(feats, out, pf2color, pf_desc = False,", "= \"\\t\", index_col = 0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for", "8, style = \"circle\", color = 'green') else: rf =", "= int, default = 10, help = \"visualize at most", "node_annotation is None: node_table = pd.read_csv(node_annotation, sep = \"\\t\", index_col", "top10_feats, pfam2color if __name__ == \"__main__\": import argparse parser =", "at most max_feats features\") parser.add_argument(\"--miscl\", help = \"table of misclassified", "matrices node_recon = pd.read_csv(node_recon, sep = \"\\t\", index_col = 0)", "miscl is None: if node2name[n.name] in miscl_m.index: tf = faces.TextFace(\"misclassified\")", "* (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style(): ts =", "import faces, Tree, AttrFace, TreeStyle import pylab from matplotlib.colors import", "6)) ax = fig.add_subplot(111) x = [0,1] lines = [ax.plot(x,", "events\") parser.add_argument(\"sample_mapping\", help = \"mapping between sample ids and names\")", "Reddish Brown 0x93AA00, # Vivid Yellowish Green 0x593315, # Deep", "\"\\t\", index_col = 0) for n in pt_tree.traverse(): #ignore the", "events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold:", "tree_style = get_style()) return target, feats, pf2color def plot_legend(feats, out,", "\"circle\", color = 'green') else: rf = faces.CircleFace(radius = 8,", "position=\"branch-right\") def adjust_kelly_brightness(hex_color, val, recon_min, recon_max): \"\"\"set brightness according to", "position = \"branch-top\") for n in pt_tree.traverse(): if n.name in", "at the preferred position faces.add_face_to_node(name_face, node, column=0, position=\"branch-right\") def adjust_kelly_brightness(hex_color,", "gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if not miscl is None: miscl_m", "pt_gt2id.loc[filtered_pfams, 0] - 1 #print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process", "parser.add_argument(\"gain_recon\", help = \"gain events ancestral character state reconstruction\") parser.add_argument(\"loss_recon\",", "node.is_leaf(): # If terminal node, draws its name name_face =", "of values for each feature if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min)", "def my_layout(node): if node.is_leaf(): # If terminal node, draws its", "== 0: rf = ete2.CircleFace(radius = 8, style = \"circle\",", "i in loss_recon.index.values] #prune to target node if target_node is", "loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in loss_recon.index.values] #prune to", "a.pfam_mapping, tree = a.tree, feat_list = a.feat_list, phenotype = a.phenotype,", "from ete2 import faces, Tree, AttrFace, TreeStyle import pylab from", "0, sep = \"\\t\") pt_tree = ete2.Tree(tree, format = 1)", "attr,i in zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name, attr] if not", "v_new = v - (v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s,", "(9, 6)) ax = fig.add_subplot(111) x = [0,1] lines =", "in node_table.index: for attr,i in zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name,", "# Strong Purple 0xFF6800, # Vivid Orange 0xA6BDD7, # Very", "else: style[\"hz_line_type\"] = 0 style[\"hz_line_color\"] = 'black' n.set_style(style) #check if", "val) / (recon_max - recon_min) v_new = v - (v", "tf = faces.TextFace(\"-\") else: tf = faces.TextFace(\"+\") cf = faces.CircleFace(radius", "of features\") parser.add_argument(\"phenotype\", help = \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action =", "Purple 0xFF6800, # Vivid Orange 0xA6BDD7, # Very Light Blue", "> threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'green' style[\"hz_line_width\"] =", "parser.add_argument(\"--node_annotation\", help = \"table of binary features for labeling the", "#if pf_acc: # labels = [\"%s %s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i],", "n.name in node_table.index: for attr,i in zip(node_table.columns, range(len(node_table.columns))): value =", "if not miscl is None: miscl_m = pd.read_csv(miscl, sep =", "0xFFB300, # Vivid Yellow 0x803E75, # Strong Purple 0xFF6800, #", "rf = faces.CircleFace(radius = 8, style = \"circle\", color =", "Grayish Yellow 0x817066, # Medium Gray # The following don't", "get_style()) return target, feats, pf2color def plot_legend(feats, out, pf2color, pf_desc", "edge reconstruction matrices node_recon = pd.read_csv(node_recon, sep = \"\\t\", index_col", "else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf =", "range(len(events)): n.add_face(events[i], column = i, position = \"branch-top\") for n", "ts def plot_tree(pt_tree, target_node, out): #pt_tree, feats, pf2color = get_tree(phenotype", "faces.CircleFace(radius = 8, style = \"circle\", color = 'orange') else:", "i in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep = \"\\t\", index_col", "None: if node2name[n.name] in miscl_m.index: tf = faces.TextFace(\"misclassified\") n.add_face(tf, column", "= \"loss events ancestral character state reconstruction\") parser.add_argument(\"tree\", help =", "sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl", "brightness according to change in continuous reconstruction value\"\"\" h, s,", "\"top_cor\", is_ml_plus_phypat = True, target_node = target_node) pt_tree.dist = 0", "cf = faces.CircleFace(radius = 8, style = \"circle\", color =", "the style of the branches and nodes according to the", "v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 - (recon_max - val)", "index_col = 0) for n in pt_tree.traverse(): #ignore the root", "= 8, style = \"circle\", color = 'orange') else: rf", "people with defective color vision 0x007D34, # Vivid Green 0xF6768E,", "i in range(len(events)): n.add_face(events[i], column = i, position = \"branch-top\")", "n in pt_tree.traverse(): if n.name in node2name: n.name = node2name[n.name]", "parser.parse_args() pt_tree, feats, pf2color = get_tree(node_recon = a.node_recon, gain_recon =", "figlegend = pylab.figure(figsize = (9, 6)) ax = fig.add_subplot(111) x", "= [ax.plot(x, pd.np.ones(len(x)), 'o', color = \"#%06x\" % (pf2color[feats.index[i]]))[0] for", "target = pt_tree.search_nodes(name = target_node)[0] target.render(out + '_tree.pdf', tree_style =", "recon_max = gain_recon.abs().apply(pd.np.max) if not miscl is None: miscl_m =", "style[\"hz_line_width\"] = 3 else: style[\"hz_line_type\"] = 0 style[\"hz_line_color\"] = 'black'", "gain_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'green'", "0xB32851, # Strong Purplish Red 0xF4C800, # Vivid Greenish Yellow", "n.name in node2name: n.name = node2name[n.name] #filtered_pfams = filter(lambda i:", "style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"] = 3 else:", "column = i, position = \"branch-top\") for n in pt_tree.traverse():", "draws its name name_face = AttrFace(\"name\") else: # If internal", "#if pf_desc: # labels = [\"%s %s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i],", "+ \"_legend.png\") return figlegend def get_tree(phenotype, tree, gain_recon, loss_recon, node_recon,", "i in range(len(labels))] #if pf_acc: # labels = [\"%s %s\"", "for n in pt_tree.traverse(): if n.name in node2name: n.name =", "Strong Purple 0xFF6800, # Vivid Orange 0xA6BDD7, # Very Light", "'square' style['size'] = 10 if pd.isnull(ns): style['fgcolor'] = 'grey' elif", "# Vivid Yellow 0x803E75, # Strong Purple 0xFF6800, # Vivid", "gain_recon, loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping, threshold = 0.5, target_node", "(pf2color[feats.index[i]]))[0] for i in range(len(pf2color))] labels= [i for i in", "'preorder')) pfams_with_event = set() pfam2color = {} #set the style", "= 8, style = \"circle\", color = 'green') else: rf", "1 style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"] = 3 else: style[\"hz_line_type\"] =", "style = \"circle\", color = 'orange') else: rf = faces.CircleFace(radius", "for i in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius", "pd.read_csv(feat_list, index_col = 0, sep = \"\\t\") pt_tree = ete2.Tree(tree,", "None): #read target feats feats = pd.read_csv(feat_list, index_col = 0,", "[\"%s %s\" %(labels[i], feats.loc[:, \"class\"].iloc[i]) for i in range(len(labels))] #if", "1 #print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node annotation return", "ax = fig.add_subplot(111) x = [0,1] lines = [ax.plot(x, pd.np.ones(len(x)),", "for labeling the nodes\") a = parser.parse_args() pt_tree, feats, pf2color", "pf2color def plot_legend(feats, out, pf2color, pf_desc = False, pf_acc =", "help = \"feature mapping/list\") parser.add_argument(\"feat_list\", help = \"list of features\")", "ids and names\") parser.add_argument(\"out\", help = \"output file\") parser.add_argument(\"--max_feats\", type", "target_node = a.target_node, threshold = a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype", "sep = \"\\t\", index_col = 0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1]))", "+ n.up.name if gain_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"] = 1", "\"mapping between sample ids and names\") parser.add_argument(\"out\", help = \"output", "argparse.ArgumentParser(\"\"\"visualize target list of features\"\"\") parser.add_argument(\"node_recon\", help = \"node ancestral", "style = \"circle\", color = 'grey') n.add_face(rf, column = i,", "a discrete phenotype\") parser.add_argument(\"threshold\", type = float, help = \"threshold", "= [\"%s %s\" % (labels[i], pf2short_desc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in", "was misclassified and add misclassified label if not miscl is", "max_feats = a.max_feats, miscl = a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree,", "fsize=10) # Adds the name face to the image at", "def get_style(): ts = TreeStyle() # Do not add leaf", "each feature if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max)", "Orange 0xA6BDD7, # Very Light Blue 0xC10020, # Vivid Red", "features with a discrete phenotype\") parser.add_argument(\"threshold\", type = float, help", "> threshold: style[\"hz_line_type\"] = 1 style[\"hz_line_color\"] = 'red' style[\"hz_line_width\"] =", "matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [ 0xFFB300,", "sample_mapping.loc[n.name,][0] #add majority feature gains and losses events = []", "\"list of features\") parser.add_argument(\"phenotype\", help = \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\", action", "ns = node_recon.loc[n.name, phenotype] style = ete2.NodeStyle() style[\"shape\"] = 'square'", "style['fgcolor'] = 'grey' elif ns < threshold: style['fgcolor'] = 'darkred'", "0xC10020, # Vivid Red 0xCEA262, # Grayish Yellow 0x817066, #", "\"\\t\", index_col = 0) sample_mapping = pd.read_csv(sample_mapping, index_col = 0,", "2: rf = faces.CircleFace(radius = 8, style = \"circle\", color", "loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace(\"-\")", "style['fgcolor'] = 'darkred' else: style['fgcolor'] = 'green' if not n.name", "sample_mapping = pd.read_csv(sample_mapping, index_col = 0, sep = \"\\t\") #read", "adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id,", "= \"\\t\", index_col = 0) for n in pt_tree.traverse(): #ignore", "in zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name, attr] if not pd.isnull(value):", "kelly_colors_hex[i] tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else:", "labels, markerscale = 2.5, numpoints = 1, frameon = False)", "= 8, style = \"circle\", color = adjusted_color) pfam2color[top10_feats.index[i]] =", "= pd.read_csv(gain_recon, sep = \"\\t\", index_col = 0) gain_recon.index =", "= 'red') elif value == 2: rf = faces.CircleFace(radius =", "= pt_tree.search_nodes(name = target_node)[0] target.render(out + '_tree.pdf', tree_style = get_style())", "names automatically ts.show_leaf_name = False ts.show_scale = True ts.force_topology =", "labeling the nodes\") a = parser.parse_args() pt_tree, feats, pf2color =", "miscl = a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree, a.target_node, a.out) plot_legend(feats,", "n.name = node2name[n.name] #filtered_pfams = filter(lambda i: i in list(pfams_with_event),", "n.name + \"_\" + n.up.name if gain_recon.loc[branch_id, phenotype] > threshold:", "events ancestral character state reconstruction\") parser.add_argument(\"tree\", help = \"tree with", "= True, target_node = target_node) pt_tree.dist = 0 target =", "= (9, 6)) ax = fig.add_subplot(111) x = [0,1] lines", "pf2color = get_tree(phenotype = phenotype, feat_list = \"top_cor\", is_ml_plus_phypat =", "= a.node_recon, gain_recon = a.gain_recon, loss_recon = a.loss_recon, pfam_mapping =", "= TreeStyle() # Do not add leaf names automatically ts.show_leaf_name", "8, style = \"circle\", color = 'orange') else: rf =", "ancestral character state reconstruction\") parser.add_argument(\"loss_recon\", help = \"loss events ancestral", "default = 10, help = \"visualize at most max_feats features\")", "< 0: tf = faces.TextFace(\"-\") else: tf = faces.TextFace(\"+\") cf", "[] for i in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf =", "tf = faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else: adjusted_color", "style['fgcolor'] = 'green' if not n.name == \"N1\": branch_id =", "rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 - (recon_max - val) / (recon_max", "Strong Violet 0xFF8E00, # Vivid Orange Yellow 0xB32851, # Strong", "= 1, frameon = False) #fig.show() fig.tight_layout() figlegend.savefig(out + \"_legend.svg\")", "index_col = 0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in", "= node_recon.loc[n.name, phenotype] style = ete2.NodeStyle() style[\"shape\"] = 'square' style['size']", "= pd.read_csv(node_annotation, sep = \"\\t\", index_col = 0) sample_mapping =", "= 0) loss_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]), i.split(\"_\")[-1])) for i in loss_recon.index.values]", "kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] =", "= i, position = \"branch-top\") for n in pt_tree.traverse(): if", "= rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 - (recon_max - val) /", "n.add_face(rf, column = i, position = \"aligned\") ns = node_recon.loc[n.name,", "= [] for i in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf", "help = \"visualize at most max_feats features\") parser.add_argument(\"--miscl\", help =", "a.gain_recon, loss_recon = a.loss_recon, pfam_mapping = a.pfam_mapping, tree = a.tree,", "of misclassified samples\") parser.add_argument(\"--node_annotation\", help = \"table of binary features", "\"_legend.svg\") figlegend.savefig(out + \"_legend.png\") return figlegend def get_tree(phenotype, tree, gain_recon,", "[ 0xFFB300, # Vivid Yellow 0x803E75, # Strong Purple 0xFF6800,", "= gain_recon.abs().apply(pd.np.max) if not miscl is None: miscl_m = pd.read_csv(miscl,", "value == 2: rf = faces.CircleFace(radius = 8, style =", "are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius = 8, style = \"circle\", color", "help = \"table of binary features for labeling the nodes\")", "filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0] - 1 #print filtered_ids #top10_feats_with_event", "'grey') n.add_face(rf, column = i, position = \"aligned\") ns =", "index_col = 0, sep = \"\\t\") pt_tree = ete2.Tree(tree, format", "pd.read_csv(gain_recon, sep = \"\\t\", index_col = 0) gain_recon.index = [\"_\".join((\"_\".join(i.split(\"_\")[:-1]),", "and edge reconstruction matrices node_recon = pd.read_csv(node_recon, sep = \"\\t\",", "column = i, position = \"aligned\") ns = node_recon.loc[n.name, phenotype]", "gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep = \"\\t\", index_col = 0)", "# Vivid Orange 0xA6BDD7, # Very Light Blue 0xC10020, #", "binary features for labeling the nodes\") a = parser.parse_args() pt_tree,", "a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree, a.target_node, a.out) plot_legend(feats, a.out, pf2color)", "= n.name + \"_\" + n.up.name if gain_recon.loc[branch_id, phenotype] >", "the name face to the image at the preferred position", "faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf = faces.TextFace(\"-\")", "False): fig = pylab.figure() figlegend = pylab.figure(figsize = (9, 6))", "0, position = \"branch-right\") #set species name instead of tax", "fig.tight_layout() figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out + \"_legend.png\") return figlegend def", "ete2 from ete2 import faces, Tree, AttrFace, TreeStyle import pylab", "Violet 0xFF8E00, # Vivid Orange Yellow 0xB32851, # Strong Purplish", "0x00538A, # Strong Blue 0xFF7A5C, # Strong Yellowish Pink 0x53377A,", "1, frameon = False) #fig.show() fig.tight_layout() figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out", "= \"circle\", color = kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id, top10_feats.index[i]]", "labels= [i for i in feats.index] #labels= [\"%s\" %(feats.loc[:,\"Pfam_acc\"].iloc[i]) for", "Vivid Red 0xCEA262, # Grayish Yellow 0x817066, # Medium Gray", "False # Use my custom layout ts.layout_fn = my_layout return", "numpoints = 1, frameon = False) #fig.show() fig.tight_layout() figlegend.savefig(out +", "= \"visualize at most max_feats features\") parser.add_argument(\"--miscl\", help = \"table", "'orange') else: rf = faces.CircleFace(radius = 8, style = \"circle\",", "events.append(cf) #continuous features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]],", "'_tree.png', tree_style = get_style()) return target, feats, pf2color def plot_legend(feats,", "faces.TextFace(\"-\") else: tf = faces.TextFace(\"+\") cf = faces.CircleFace(radius = 8,", "help = \"node ancestral character state reconstruction\") parser.add_argument(\"gain_recon\", help =", "features\") parser.add_argument(\"--miscl\", help = \"table of misclassified samples\") parser.add_argument(\"--node_annotation\", help", "# Adds the name face to the image at the", "= \"list of features\") parser.add_argument(\"phenotype\", help = \"target phenotype\") parser.add_argument(\"--are_continuous_features_with_discrete_phenotype\",", "return ts def plot_tree(pt_tree, target_node, out): #pt_tree, feats, pf2color =", "= False) #fig.show() fig.tight_layout() figlegend.savefig(out + \"_legend.svg\") figlegend.savefig(out + \"_legend.png\")", "#read target feats feats = pd.read_csv(feat_list, index_col = 0, sep", "with a discrete phenotype\") parser.add_argument(\"threshold\", type = float, help =", "according to the posterior probability top10_feats = feats.iloc[:max_feats,] #for visualization", "= ete2.Tree(tree, format = 1) pt_tree.ladderize() if not node_annotation is", "# Very Light Blue 0xC10020, # Vivid Red 0xCEA262, #", "visualization of continuous feature get the range of values for", "n in pt_tree.traverse(): #ignore the root if n.name == \"N1\":", "style = \"circle\", color = kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id,", "loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf = faces.TextFace(\"-\") else: tf =", "reconstruction\") parser.add_argument(\"tree\", help = \"tree with internal nodes labeled\") parser.add_argument(\"pfam_mapping\",", "+ '_tree.png', tree_style = get_style()) return target, feats, pf2color def", "character state reconstruction\") parser.add_argument(\"loss_recon\", help = \"loss events ancestral character", "Yellowish Green 0x593315, # Deep Yellowish Brown 0xF13A13, # Vivid", "0x803E75, # Strong Purple 0xFF6800, # Vivid Orange 0xA6BDD7, #", "0) for n in pt_tree.traverse(): #ignore the root if n.name", "if n.name in node_table.index: for attr,i in zip(node_table.columns, range(len(node_table.columns))): value", "losses events = [] for i in range(top10_feats.shape[0]): if not", "Adds the name face to the image at the preferred", "continuous features with a discrete phenotype\") parser.add_argument(\"threshold\", type = float,", "get_style()) #target.render(out + '_tree.png', tree_style = get_style()) return target, feats,", "help = \"gain events ancestral character state reconstruction\") parser.add_argument(\"loss_recon\", help", "pfam_mapping = a.pfam_mapping, tree = a.tree, feat_list = a.feat_list, phenotype", "return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style(): ts = TreeStyle() #", "pt_tree.search_nodes(name = target_node)[0] target.render(out + '_tree.pdf', tree_style = get_style()) #target.render(out", "target.render(out + '_tree.pdf', tree_style = get_style()) #target.render(out + '_tree.png', tree_style", "pfam_mapping, feat_list, sample_mapping, threshold = 0.5, target_node = None, are_continuous_features_with_discrete_phenotype", "top10_feats = feats.iloc[:max_feats,] #for visualization of continuous feature get the", "\"branch-right\") #set species name instead of tax id if n.name", "\"threshold to call genotype/phenotype events\") parser.add_argument(\"sample_mapping\", help = \"mapping between", "pt_tree.ladderize() if not node_annotation is None: node_table = pd.read_csv(node_annotation, sep", "style['size'] = 10 if pd.isnull(ns): style['fgcolor'] = 'grey' elif ns", "0] - 1 #print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node", "= 'darkred' else: style['fgcolor'] = 'green' if not n.name ==", "None: node_table = pd.read_csv(node_annotation, sep = \"\\t\", index_col = 0)", "= \"set if using continuous features with a discrete phenotype\")", "#top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node annotation return pt_tree, top10_feats, pfam2color", "#pt_tree, feats, pf2color = get_tree(phenotype = phenotype, feat_list = \"top_cor\",", "my_layout return ts def plot_tree(pt_tree, target_node, out): #pt_tree, feats, pf2color", "Gray # The following don't work well for people with", "= ete2.NodeStyle() style[\"shape\"] = 'square' style['size'] = 10 if pd.isnull(ns):", "target node if target_node is not None: pt_tree = pt_tree.search_nodes(name", "= node_table.loc[n.name, attr] if not pd.isnull(value): if value == 0:", "= pt_gt2id.loc[filtered_pfams, 0] - 1 #print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,]", "ancestral character state reconstruction\") parser.add_argument(\"tree\", help = \"tree with internal", "threshold = a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats", "target list of features\"\"\") parser.add_argument(\"node_recon\", help = \"node ancestral character", "Green ] def my_layout(node): if node.is_leaf(): # If terminal node,", "- (v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style():", "%(labels[i], feats.loc[:, \"class\"].iloc[i]) for i in range(len(labels))] #if pf_desc: #", "Use my custom layout ts.layout_fn = my_layout return ts def", "i.split(\"_\")[-1])) for i in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep =", "8, style = \"circle\", color = adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i]", "pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i in range(len(events)):", "i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values) #print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0]", "defective color vision 0x007D34, # Vivid Green 0xF6768E, # Strong", "= \"\\t\") #read node and edge reconstruction matrices node_recon =", "probability top10_feats = feats.iloc[:max_feats,] #for visualization of continuous feature get", "= node2name[n.name] #filtered_pfams = filter(lambda i: i in list(pfams_with_event), top10_feats.loc[:,\"Pfam_acc\"].values)", "ts.force_topology = False # Use my custom layout ts.layout_fn =", "not node_annotation is None: if n.name in node_table.index: for attr,i", "= faces.TextFace(\"-\") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else: adjusted_color =", "0: tf = faces.TextFace(\"-\") else: tf = faces.TextFace(\"+\") cf =", "state reconstruction\") parser.add_argument(\"gain_recon\", help = \"gain events ancestral character state", "font size name_face = AttrFace(\"name\", fsize=10) # Adds the name", "pfams_with_event = set() pfam2color = {} #set the style of", "# Strong Blue 0xFF7A5C, # Strong Yellowish Pink 0x53377A, #", "is not None: pt_tree = pt_tree.search_nodes(name = target_node)[0] node2name =", "events = [] for i in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype:", "None, node_annotation = None): #read target feats feats = pd.read_csv(feat_list,", "= faces.CircleFace(radius = 8, style = \"circle\", color = 'green')", "= [\"%s %s\" % (labels[i], pf2acc.loc[feats.loc[:,\"Pfam_acc\"].iloc[i], 1]) for i in", "reconstruction\") parser.add_argument(\"gain_recon\", help = \"gain events ancestral character state reconstruction\")", "a.target_node, threshold = a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype,", "feat_list, sample_mapping, threshold = 0.5, target_node = None, are_continuous_features_with_discrete_phenotype =", "= 'grey') n.add_face(rf, column = i, position = \"aligned\") ns", "= \"circle\", color = 'orange') else: rf = faces.CircleFace(radius =", "Deep Yellowish Brown 0xF13A13, # Vivid Reddish Orange 0x232C16, #", "'green' if not n.name == \"N1\": branch_id = n.name +", "= \"branch-right\") #set species name instead of tax id if", "samples\") parser.add_argument(\"--node_annotation\", help = \"table of binary features for labeling", "'green' style[\"hz_line_width\"] = 3 elif loss_recon.loc[branch_id, phenotype] > threshold: style[\"hz_line_type\"]", "help = \"list of features\") parser.add_argument(\"--target_node\", default = \"N1\", help", "features\"\"\") parser.add_argument(\"node_recon\", help = \"node ancestral character state reconstruction\") parser.add_argument(\"gain_recon\",", "= pt_tree.search_nodes(name = target_node)[0] node2name = dict((i.name, i.name) for i", "= 'green' style[\"hz_line_width\"] = 3 elif loss_recon.loc[branch_id, phenotype] > threshold:", "False, pf_acc = True, include_class = False): fig = pylab.figure()", "= \"node ancestral character state reconstruction\") parser.add_argument(\"gain_recon\", help = \"gain", "work well for people with defective color vision 0x007D34, #" ]
[ "list(), \"Symmetric\": list(), \"nnz\": list(), \"dofs\": list(), \"h\": list(), \"Condition", "n) * dS a += -dot(u, grad(q)) * dx +", ":return: Filtered array with only real numbers. \"\"\" real_part_array =", "= L0 * h # method B in the Badia-Codina", "**kwargs): \"\"\"Provides a plot of a full hybrid-mixed matrix.\"\"\" fig,", "dS # Edge stabilizing terms # ** Badia-Codina based a", "* ds A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric", "* (p- p_boundaries) * q * ds # is this", "Stabilizing terms a += delta_1 * inner(u + grad(p), v", "a += jump(u_hat, n) * mu_h(\"+\") * dS # Weakly", "dS # Weakly imposed BC a += lambda_h * dot(v,", "(q(\"+\") - mu_h(\"+\")) * dS # a += delta_4 *", "Numerical flux trace u = -grad(p) u_hat = u +", "= singular_values.max() / singular_values.min() elif backend == \"slepc\": S =", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def hp_refinement_cond_number_calculation( solver,", "solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg, # \"cgh\": solve_poisson_cgh,", "delta_5 = Constant(1) # LARGE_NUMBER = Constant(1e0) delta = h", "nnz = Mnp.nnz number_of_dofs = V.dim() num_of_factors = int(number_of_dofs) -", "- dot(u_hat, n)(\"+\")) * (dot(v, n)(\"+\") - dot(v_hat, n)(\"+\")) *", "else: hdiv_family = 'RT' pressure_family = 'DG' U = FunctionSpace(mesh,", "import os matplotlib.use('Agg') @attr.s class ConditionNumberResult(object): form = attr.ib() assembled_form", "if not quadrilateral else 1 / n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of", "Constant(1.0) # delta = h delta_0 = delta delta_1 =", "'CG' U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family,", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_cgls(mesh, degree=1):", "# delta_0 = Constant(1) # delta_1 = Constant(1) # delta_2", "are unsymmetric # a += delta_1 * jump(u_hat, n=n) *", "bcs = DirichletBC(V, 0.0, \"on_boundary\") # Variational form a =", "mesh.ufl_cell(), degree) C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else:", "inner(grad(p), grad(q))) # * delta_1 # * dx # )", "* div(v) * dx a += delta_2 * inner(curl(u), curl(v))", "np.ma.masked_values(Mnp, 0, rtol=1e-13) # Plot the matrix plot = ax.matshow(Am,", "n) * jump(v, n) * dS # not considered in", "np.ndarray, imag_threshold: float = 1e-5) -> np.ndarray: \"\"\"Utility function to", "f * q * dx # DG edge terms a", "Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[..., :] == 0, axis=0)) Mnp =", "# solution = Function(W) # u, p, lambda_h = split(solution)", "BC a += lambda_h * dot(v, n) * ds a", "* h delta_2 = Constant(0.5) * h * h delta_3", "= beta_0 # Numerical flux trace u = -grad(p) u_hat", "Plotting the resulting matrix # matplotlib.use('TkAgg') # import copy #", "0.0, \"on_boundary\") # Variational form a = inner(grad(u), grad(v)) *", "lhs(F) _A = Tensor(a_form) A = _A.blocks S = A[2,", "n), jump(q, n)) * dS # ** Mesh independent (original)", "beta = beta_0 # Stabilization parameters delta_0 = Constant(-1) delta_1", "* dS a += delta_1 * lambda_h * dot(v, n)", "jump(u_hat, n=n) * dS a += delta_4(\"+\") * (p(\"+\") -", "n) - dot(v_hat, n)) * ds # Weakly imposed BC", "Function(V).interpolate(f_expression) # Edge stabilizing parameter beta0 = Constant(1e1) beta =", "dS a += (avg(eta_u) / h_avg) * dot(jump(p, n), jump(q,", "method B in the Badia-Codina paper # eta_p = L0", "dot(p * n, grad(q)) * ds - dot(grad(p), q *", "** Badia-Codina based a += (avg(eta_p) / h_avg) * (jump(u,", "is not a good way to impose BC, but this", "Badia-Codina paper # Mixed classical terms a = (dot(u, v)", "W = U * V # Trial and test functions", "beta = beta_0 / h beta = beta_0 # Stabilization", "# \"hdg\": solve_poisson_hdg, # \"cgh\": solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc, #", "solve_poisson_mixed_RT(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "n # HDG classical form a = (dot(u, v) -", "and columns filled with zero entries Mnp = Mnp[~(Mnp==0).all(1)] idx", "n)) * dS a += (avg(eta_u) / h_avg) * dot(jump(p,", "25), quadrilateral=True, name=\"\", **kwargs ): results_dict = { \"Element\": list(),", "a classical Nitsche's method a += (eta_p / h) *", "singular_values = svd(M, compute_uv=False, check_finite=False) singular_values = singular_values[singular_values > zero_tol]", "# a += jump(u, n) * jump(v, n) * dS", "parameters delta_0 = Constant(-1) delta_1 = Constant(-0.5) * h *", "grad(q)) * dx a += eta_p * div(u) * div(v)", "= div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier =", "# a += ( # (mu_h - q) * (lambda_h", "= petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp = Mnp.toarray()", "mu_h(\"+\")) * dS # a += delta_4 * (p -", "= np.delete(Mnp, idx, axis=1) Am = np.ma.masked_values(Mnp, 0, rtol=1e-13) #", "beta * (p - lambda_h) * n v_hat = v", "paper # a += dot(jump(p, n), jump(q, n)) * dS", "may decrease convergente rates # ** The terms below are", "s * dot(grad(q), n) * p_boundaries * ds F =", "backend = backend.lower() if backend == \"scipy\": size = A.getSize()", "Weakly imposed BC a += lambda_h * dot(v, n) *", "FunctionSpace(mesh, hdiv_family, degree + 1) V = FunctionSpace(mesh, pressure_family, degree)", "off imaginary part in complex number. :return: Filtered array with", "dx # Stabilizing terms a += -0.5 * inner((u +", "output file name name = f\"{current_solver}\" # Selecting the solver", "to set this bc?? # a += (beta / h)", "= 'RTCF' pressure_family = 'DQ' else: hdiv_family = 'RT' pressure_family", "* T # Trial and test functions # solution =", "+ beta * (p - lambda_h) * n # HDG", "Badia-Codina based a += -eta_u * inner(u + grad(p), v", "scipy.sparse import csr_matrix from slepc4py import SLEPc import pandas as", "return_singular_vectors=False, solver=\"lobpcg\" ) else: M = Mnp.toarray() singular_values = svd(M,", "= FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(),", "1 / n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n * n) results_dict[\"Degree\"].append(degree)", "+= lambda_h(\"+\") * dot(v, n)(\"+\") * dS + mu_h(\"+\") *", "Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = V.dim() num_of_factors = int(number_of_dofs)", "# Hybridization terms a += lambda_h(\"+\") * dot(v, n)(\"+\") *", "list(), \"Degree\": list(), \"Symmetric\": list(), \"nnz\": list(), \"dofs\": list(), \"h\":", "BCs bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0", "Forcing function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # BCs", "print(f'Condition Number: {result.condition_number}') # # Plotting the resulting matrix #", "numpy array. :param array: Array with real and complex numbers.", "* inner((u + grad(p)), v + grad(q)) * dx #", "a += delta_3 * inner(curl(u), curl(v)) * dx # Hybridization", "ds # may decrease convergente rates (Nitsche) A = assemble(a,", "+= 0.5 * div(u) * div(v) * dx a +=", "Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" if use_quads:", "solve_poisson_lsh(mesh, degree=1) # print(f'Is symmetric? {result.is_operator_symmetric}') # print(f'nnz: {result.nnz}') #", "BCs bcs = DirichletBC(V, 0.0, \"on_boundary\") # Variational form a", "= attr.ib() number_of_dofs = attr.ib() nnz = attr.ib() is_operator_symmetric =", "= beta_0 / h # Mixed classical terms a =", "1) V = FunctionSpace(mesh, pressure_family, degree) W = U *", "weights delta = Constant(1.0) # delta = h delta_0 =", "beta0 / h # Symmetry term. Choose if the method", "delta_0 * q * div(u)) * dx L = delta_0", "div(v) * p + delta_0 * q * div(u)) *", "A[1, 1] - A[1, :1] * A[:1, :1].inv * A[:1,", "* dS # a += delta_1 * lambda_h * dot(v,", "attr from firedrake import * import numpy as np import", "# method B in the Badia-Codina paper eta_u = 1", "lambda_h(\"+\")) * dS a += -dot(grad(p), n)(\"+\") * (q(\"+\") -", "Least-squares terms a = delta_0 * inner(u + grad(p), v", "n=n) * q(\"+\") * dS # a += delta_1(\"+\") *", "a += 0.5 * div(u) * div(v) * dx a", "+ f1_size[0] - 0.5, color=\"k\") return plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2,", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dls(mesh, degree=1): #", "n), jump(q, n)) * dS # a += p *", "h delta_5 = delta # Numerical flux trace u_hat =", "* dot(v, n) * ds # # L = delta_1", "there is the spy alternative # plot = plt.spy(Am, **kwargs)", "= TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities n", "spy alternative # plot = plt.spy(Am, **kwargs) # Remove axis", "* dx # Hybridization terms a += s * dot(grad(q),", "TrialFunction(V) q = TestFunction(V) # Mesh entities n = FacetNormal(mesh)", "zero_tol] condition_number = singular_values.max() / singular_values.min() elif backend == \"slepc\":", "complex number. :return: Filtered array with only real numbers. \"\"\"", "declaration V = FunctionSpace(mesh, \"CG\", degree) # Trial and test", "* ds a += beta * (lambda_h - p_boundaries) *", "in the Badia-Codina paper eta_u_bc = 1 # Least-Squares weights", "eta_u = 1 # eta_u_bc = h / L0 #", "solve_poisson_dls, \"lsh\": solve_poisson_lsh, # \"vms\": solve_poisson_vms, # \"dvms\": solve_poisson_dvms, #", "raise NotImplementedError(\"The required method for condition number estimation is currently", "dx # DG terms a += jump(v, n) * avg(p)", "** Badia-Codina based a += eta_u * inner(u + grad(p),", "= inner(grad(u), grad(v)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\")", "= Constant(1) # delta_1 = Constant(1) # delta_2 = Constant(1)", "False, zero_tol: float = 1e-5 ): backend = backend.lower() if", "df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results) return", "= plt.spy(Am, **kwargs) # Remove axis ticks and values ax.tick_params(length=0)", "(2010), it is not a classical Nitsche's method a +=", "n) * jump(v, n)) * dS a += eta_p *", "q * ds # # L = -delta_1 * dot(u_projected,", "method B in the Badia-Codina paper # eta_u = 1", "= csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if use_sparse: singular_values = svds( A=Mnp,", "div(v) + inner(grad(p), grad(q))) # * delta_1 # * dx", "in pbar: for n in numel_xy: pbar.set_description(f\"Processing {name} - degree", "+ grad(p), v + grad(q)) * dx a += delta_2", "- dot(u_projected, n))) * ds a += beta * (lambda_h", "* dx L = delta_0 * f * q *", "h_avg) * (jump(u, n) * jump(v, n)) * dS a", "inner(u + grad(p), grad(q) - v) * dx # a", "div(u) * div(v) * dx a += eta_p * inner(curl(u),", "q = TestFunction(V) # Mesh entities n = FacetNormal(mesh) h", "return result def solve_poisson_dls(mesh, degree=1): # Function space declaration use_quads", "solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True ): # Function space declaration use_quads", "method B in the Badia-Codina paper # Mixed classical terms", "- q * dot(u, n) * ds # ** The", "= Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") sigma_e = Function(U, name='Exact velocity')", "\"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh, # \"vms\": solve_poisson_vms, # \"dvms\": solve_poisson_dvms,", "# Stabilizing terms a += -0.5 * inner((u + grad(p)),", "cut off imaginary part in complex number. :return: Filtered array", "Darcy eq. first-order terms as stabilizing terms a += delta_1", "= delta delta_4 = delta # delta_4 = LARGE_NUMBER /", "* dS + mu_h(\"+\") * dot(u, n)(\"+\") * dS a", "delta_4 = 1 / h # Least-squares terms a =", "size and mesh dependent stabilization h_avg = (h(\"+\") + h(\"-\"))", "Forcing function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Edge", "/ h # Least-squares terms a = delta_0 * inner(u", "L0 # method D in the Badia-Codina paper eta_u =", "'DQ' else: hdiv_family = 'RT' pressure_family = 'DG' U =", "nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def hp_refinement_cond_number_calculation( solver, min_degree=1,", "n) * dS # a += dot(jump(p, n), jump(q, n))", "= Constant(1) # delta_2 = Constant(1) # delta_3 = Constant(1)", "p, lambda_h = split(solution) p, lambda_h = TrialFunctions(W) q, mu_h", "a = -dot(u, grad(q)) * dx + jump(u_hat, n) *", "p = TrialFunction(V) q = TestFunction(V) # Mesh entities n", "+= dot(jump(p, n), jump(q, n)) * dS # Volumetric stabilizing", "delta delta_1 = delta delta_2 = delta delta_3 = 1", "jump(u_hat, n=n) * q(\"+\") * dS # a += delta_1(\"+\")", "eta_u_bc = h / L0 # method B in the", "eta_p * inner(curl(u), curl(v)) * dx # Weakly imposed boundary", "dot(avg(grad(p)), jump(q, n)) * dS # Edge stabilizing terms a", "* (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) * dS", "= np.array(singular_values_list) singular_values = singular_values[singular_values > zero_tol] condition_number = singular_values.max()", "# BCs u_projected = sigma_e p_boundaries = p_exact bcs =", "a += jump(v, n) * avg(p) * dS - avg(q)", "* dot(u, n) * ds # ** The terms below", "= A[1, 1] - A[1, :1] * A[:1, :1].inv *", "part in complex number. :return: Filtered array with only real", "* (lambda_h(\"+\") - p(\"+\")) * (mu_h(\"+\") - q(\"+\")) * dS", "a_form = lhs(F) _A = Tensor(a_form) A = _A.blocks S", "DirichletBC(W[0], sigma_e, \"on_boundary\") # Mixed classical terms a = (dot(u,", "(beta / h_avg) * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") -", "fig, ax = plt.subplots(1, 1) _A = Tensor(a_form) A =", "= attr.ib() nnz = attr.ib() is_operator_symmetric = attr.ib() bcs =", "Average cell size and mesh dependent stabilization h_avg = (h(\"+\")", "Array with real and complex numbers. :param imag_threshold: Threshold to", "exact_solution.rename(\"Exact pressure\", \"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) #", "\"\"\" real_part_array = array.real[abs(array.imag) < 1e-5] return real_part_array def calculate_condition_number(", "q * n) * ds a += beta * p", "+ grad(q)) * dx a += delta_1 * div(u) *", "# plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap) #", "* div(v) * dx # ** Badia-Codina based a +=", "are based on ASGS Badia-Codina (2010), it is not a", "element_kind = \"Quad\" if quadrilateral else \"Tri\" pbar = tqdm(range(min_degree,", "n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" %", "beta_0 / h # beta = beta_0 # Numerical flux", "declaration pressure_family = 'CG' velocity_family = 'CG' U = VectorFunctionSpace(mesh,", "beta_0 / h beta = beta_0 # Stabilization parameters delta_0", "= avg(h) # Classical term a = dot(grad(p), grad(q)) *", "= S.getConverged() singular_values_list = list() if num_converged_values > 0: for", "# HDG classical form a = -dot(u, grad(q)) * dx", "x) * sin(2 * pi * y) exact_solution = Function(V).interpolate(p_exact)", "a += 0.5 * inner(curl(u), curl(v)) * dx A =", "\"on_boundary\") # Variational form a = inner(grad(u), grad(v)) * dx", "Hybridization parameter beta_0 = Constant(1.0) beta = beta_0 / h", "= sigma_e p_boundaries = p_exact bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\")", "T = FunctionSpace(mesh, trace_family, degree) W = V * T", "a += mu_h * (lambda_h - p_boundaries) * ds #", "* dx # Weakly imposed boundary conditions a += dot(v,", "lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) * dS # Boundary terms", "function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # BCs u_projected", "* (dot(u, v) - div(v) * p) * dx a", "# eta_u_bc = h / L0 # method B in", "= assemble(S, bcs=bcs) petsc_mat = Smat.M.handle size = petsc_mat.getSize() Mnp", "1 condition_number = calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=A,", "* (q - mu_h) * n # Flux least-squares #", "a += eta_p * avg(delta_4) * dot(jump(p, n), jump(q, n))", "stabilizing terms a += beta(\"+\") * dot(jump(p, n), jump(q, n))", "+= beta(\"+\") * (lambda_h(\"+\") - p(\"+\")) * (mu_h(\"+\") - q(\"+\"))", "q * ds # # a += delta_1 * dot(u,", "term a = dot(grad(p), grad(q)) * dx L = f", "terms a = inner(grad(p), grad(q)) * dx L = f", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_dgls(mesh, degree=1): # Function space", "dot(u, n) * q * ds # # L =", "= 1 / h # Least-squares terms a = delta_0", "mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle", "delta_1 * lambda_h * dot(v, n) * ds # #", "max_degree=4, numel_xy=(5, 10, 15, 20, 25), quadrilateral=True, name=\"\", **kwargs ):", "str(mesh.ufl_cell()) == \"quadrilateral\" if use_quads: hdiv_family = 'RTCF' pressure_family =", "= h * h # delta = Constant(1) # delta", "pi * y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") sigma_e", "# Edge stabilizing parameter beta0 = Constant(1e1) beta = beta0", "nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def solve_poisson_hdg( mesh, degree=1,", "= -delta_1 * dot(u_projected, n) * q * ds #", "inner((u + grad(p)), v + grad(q)) * dx # a", "conditions a += dot(v, n) * p * ds -", "* avg(p) * dS - avg(q) * jump(u, n) *", "+= beta * p * q * ds # may", "grad(q)) * dx a += delta_1 * div(u) * div(v)", "f0_size = assembled_form.M[0, 0].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "stabilizing terms # ** Badia-Codina based a += (avg(eta_p) /", "= lhs(F) _A = Tensor(a_form) A = _A.blocks S =", "= DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e-18)", "nnz = Mnp.nnz number_of_dofs = Mnp.shape[0] num_of_factors = int(number_of_dofs) -", "* dS a += (beta / h_avg) * (p(\"+\") -", "= div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Edge stabilizing parameter beta0", "set this bc?? # a += (beta / h) *", "+ grad(p), v + grad(q)) * dx # a +=", "delta_1 * jump(u_hat, n=n) * q(\"+\") * dS # a", "= (dot(u, v) - div(v) * p + q *", "a good way to impose BC, but this necessary _A", "eta_u_bc * delta_4 * dot(u, n) * dot(v, n) *", "Trace\" T = FunctionSpace(mesh, trace_family, degree) W = V *", "v + grad(q)) * dx # Classical mixed Darcy eq.", "color=\"k\") return plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot", "a += -0.5 * inner((u + grad(p)), v + grad(q))", "= A[2, 2] - A[2, :2] * A[:2, :2].inv *", "# ** Classical Nitsche # a += beta * p", "Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "* inner(curl(u), curl(v)) * dx # Edge stabilizing terms #", "return plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs): \"\"\"Provides a plot", "if quadrilateral else \"Tri\" pbar = tqdm(range(min_degree, max_degree)) for degree", "last_degree = 1 for current_solver in solvers_options: # Setting the", "* A[:idx, :idx].inv * A[:idx, idx] Smat = assemble(S, bcs=bcs)", "L = delta_0 * f * q * dx #", ") return result def solve_poisson_mixed_RT(mesh, degree=1): # Function space declaration", "imposed BC from hybridization # a += mu_h * (lambda_h", "tqdm import tqdm import os matplotlib.use('Agg') @attr.s class ConditionNumberResult(object): form", "else \"Tri\" pbar = tqdm(range(min_degree, max_degree)) for degree in pbar:", "* dS a += beta(\"+\") * (lambda_h(\"+\") - p(\"+\")) *", "V = FunctionSpace(mesh, primal_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\",", "result def solve_poisson_sipg(mesh, degree=1): # Function space declaration use_quads =", "div(u)) * dx L = delta_0 * f * q", "trace_family = \"HDiv Trace\" T = FunctionSpace(mesh, trace_family, degree) W", "# Trial and test functions u, p = TrialFunctions(W) v,", "= assembled_form.M[0, 0].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size)", "independent (original) # a += jump(u, n) * jump(v, n)", "= L0 * h_avg # method B in the Badia-Codina", "+= delta_4(\"+\") * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\"))", "inner(curl(u), curl(v)) * dx # Edge stabilizing terms # **", "# * delta_1 # * dx # ) # #", "UnitSquareMesh(N, N, quadrilateral=True) # result = solve_poisson_lsh(mesh, degree=1) # print(f'Is", "+ mu_h(\"+\") * dot(u, n)(\"+\") * dS a += beta(\"+\")", "* dx # ** Badia-Codina based a += eta_u *", "= plt.subplots(1, 1) assembled_form = assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat =", "= DirichletBC(V, 0.0, \"on_boundary\") # Variational form a = inner(grad(u),", "+= delta_3 * inner(curl(u), curl(v)) * dx # Hybridization terms", "pressure_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement", "* p) * dx + lambda_h(\"+\") * jump(v, n) *", "# eta_u = 1 # Nitsche's penalizing term beta_0 =", "dx # Stabilizing terms a += 0.5 * inner(u +", "for n in numel_xy: pbar.set_description(f\"Processing {name} - degree = {degree}", "* div(v) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat", "* V # Trial and test functions u, p =", "assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size =", "= singular_values.max() / singular_values.min() else: raise NotImplementedError(\"The required method for", "sigma_e.project(-grad(p_exact)) # Dirichlet BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") #", "BCs p_boundaries = Constant(0.0) bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") #", "+= 0.5 * inner(u + grad(p), grad(q) - v) *", ":1] * A[:1, :1].inv * A[:1, 1] Smat = assemble(S,", "# Setting the output file name name = f\"{current_solver}\" #", "petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp = Mnp.toarray() #", "eta_p * avg(delta_4) * dot(jump(p, n), jump(q, n)) * dS", "bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 =", "= CellDiameter(mesh) h_avg = avg(h) # Classical term a =", "eta_u = h / L0 # method B in the", "sparse_operator = attr.ib() number_of_dofs = attr.ib() nnz = attr.ib() is_operator_symmetric", "trace_index=2, bcs=[], **kwargs): \"\"\"Provides a plot of a condensed hybrid-mixed", "1] Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric =", "a += eta_p * div(u) * div(v) * dx #", "terms # a += 0.5 * h * h *", "= assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size", "* dx # Classical mixed Darcy eq. first-order terms as", "solver(mesh, degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min() if not quadrilateral else 1", "* f * div(v) * dx # ** Badia-Codina based", "BCs # bcs = DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\") # Average", "= delta_0 * inner(u + grad(p), v + grad(q)) *", "LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement = LagrangeElement[\"facet\"] T =", "** Classical Nitsche # a += beta * p *", "* pi * x) * sin(2 * pi * y)", "delta # Numerical flux trace u_hat = u + beta", "is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False", "cmap=my_cmap) # # plot_matrix(result.assembled_form, cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form, cmap=my_cmap) #", "return result def solve_poisson_dvms(mesh, degree=1): # Function space declaration use_quads", "is_operator_symmetric=is_symmetric, bcs=bcs ) return result def solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False", "# print(f'DoFs: {result.number_of_dofs}') # print(f'Condition Number: {result.condition_number}') # # Plotting", "+= eta_u * inner(u + grad(p), grad(q) - v) *", "(lambda_h - p_boundaries) * ds # a += mu_h *", "= str(mesh.ufl_cell()) == \"quadrilateral\" if use_quads: hdiv_family = 'RTCF' pressure_family", "filter real part in a numpy array. :param array: Array", "based on ASGS Badia-Codina (2010), it is not a classical", "parameter beta_0 = Constant(1.0) beta = beta_0 / h beta_avg", "quadrilateral=quadrilateral) result = solver(mesh, degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min() if not", "dot(v, n)(\"+\") * dS + mu_h(\"+\") * dot(u, n)(\"+\") *", "Constant(1e1) beta = beta0 / h # Symmetry term. Choose", "+= delta_2 * div(u) * div(v) * dx # L", "= Constant(1e1) beta = beta0 / h # Symmetry term.", "dot(v, n) + mu_h * (dot(u, n) - dot(u_projected, n)))", "(p - lambda_h) * n v_hat = v + beta", "good way to impose BC, but this necessary _A =", "a = (dot(u, v) - div(v) * p + delta_0", ":2] * A[:2, :2].inv * A[:2, 2] Smat = assemble(S,", "\"ldgc\": solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg, } degree = 1 last_degree", "list(), \"h\": list(), \"Condition Number\": list(), } element_kind = \"Quad\"", "pbar: for n in numel_xy: pbar.set_description(f\"Processing {name} - degree =", "* dS a += eta_u_bc * delta_3 * p *", "single scale problems.\"\"\" fig, ax = plt.subplots(1, 1) _A =", "* f * div(v) * dx a += 0.5 *", "matrix plot = ax.matshow(Am, **kwargs) # Remove axis ticks and", "= Mnp.nnz number_of_dofs = W.dim() num_of_factors = int(number_of_dofs) - 1", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dls(mesh,", "{ # \"cg\": solve_poisson_cg, # \"cgls\": solve_poisson_cgls, # \"dgls\": solve_poisson_dgls,", "n) * q * ds # # a += delta_1", "is_operator_symmetric = attr.ib() bcs = attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs): \"\"\"Provides", "a += -dot(grad(p), n)(\"+\") * (q(\"+\") - mu_h(\"+\")) * dS", "is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False", "= attr.ib() is_operator_symmetric = attr.ib() bcs = attr.ib(default=list()) def plot_matrix(assembled_form,", "complex numbers. :param imag_threshold: Threshold to cut off imaginary part", "+ lambda_h(\"+\") * jump(v, n) * dS a += -dot(u,", "* n) * ds A = assemble(a, mat_type=\"aij\") petsc_mat =", "Constant(0.5) * h * h delta_3 = Constant(0.5) * h", "= 1 # eta_p = L0 * L0 # method", "in DG a = delta_0 * inner(u + grad(p), v", "pressure_family = 'DQ' else: hdiv_family = 'RT' pressure_family = 'DG'", "'DG' U = FunctionSpace(mesh, hdiv_family, degree + 1) V =", "ds F = a - L a_form = lhs(F) _A", "v = TestFunction(V) # Dirichlet BCs bcs = DirichletBC(V, 0.0,", "a += -dot(u, grad(q)) * dx + jump(u_hat, n) *", "* div(v) * dx a += 0.5 * div(u) *", "Nitsche # a += beta * p * q *", "# Eliminate rows and columns filled with zero entries Mnp", "dependent stabilization h_avg = (h(\"+\") + h(\"-\")) / 2.0 #", "delta_0 * f * q * dx # Stabilizing terms", "Irrotational least-squares a += delta_3 * inner(curl(u), curl(v)) * dx", "div(u) * div(v) * dx # Weakly imposed boundary conditions", "* inner(curl(u), curl(v)) * dx # ** Badia-Codina based a", "use_sparse: singular_values = svds( A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\"", "dS # a += delta_4 * (p - lambda_h) *", "result def solve_poisson_dgls(mesh, degree=1): # Function space declaration use_quads =", "dx # Stabilizing terms a += delta_1 * inner(u +", "Trace\" T = FunctionSpace(mesh, trace_family, degree) W = U *", "list(), \"dofs\": list(), \"h\": list(), \"Condition Number\": list(), } element_kind", "Constant(-1.0) beta = Constant(32.0) h = CellDiameter(mesh) h_avg = avg(h)", "exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") sigma_e = Function(U, name='Exact", "grad(q)) * dx # a += 0.5 * div(u) *", "terms a += s * dot(grad(q), n)(\"+\") * (p(\"+\") -", "and mesh dependent stabilization h_avg = (h(\"+\") + h(\"-\")) /", "n)) * ds # Weakly imposed BC from hybridization #", "* (dot(u, n) - dot(u_projected, n))) * ds a +=", "= delta_0 * f * q * dx # Stabilizing", "method # L0 = 1 # eta_p = L0 *", "# \"cgls\": solve_poisson_cgls, # \"dgls\": solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm, #", "nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_ldgc( mesh, degree=1,", "degree) W = U * V * T # Trial", "edge terms a += s * dot(jump(p, n), avg(grad(q))) *", "= f * q * dx # DG edge terms", "if backend == \"scipy\": size = A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1],", "20, 25), quadrilateral=True, name=\"\", **kwargs ): results_dict = { \"Element\":", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sipg(mesh, degree=1): # Function", "a += dot(v, n) * p * ds - q", "FunctionSpace(mesh, trace_family, degree) W = U * V * T", "div(u)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat =", "* (jump(u, n) * jump(v, n)) * dS a +=", "shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = W.dim() num_of_factors =", "dS # Weak boundary conditions a += s * dot(p", "* inner(u + grad(p), v + grad(q)) * dx #", "_A = Tensor(a_form) A = _A.blocks S = A[1, 1]", "(p - lambda_h) * (q - mu_h) * ds #", "0.5, color=\"k\") return plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a", "n = FacetNormal(mesh) h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh)", "n), jump(q, n)) * dS # ** Mesh independent terms", "beta = beta_0 # Numerical flux trace u = -grad(p)", "jump(q, n)) * dS # ** Mesh independent (original) #", "ds - q * dot(u, n) * ds a +=", "current_solver in solvers_options: # Setting the output file name name", "* dx # Hybridization terms a += mu_h(\"+\") * jump(u_hat,", "numbers. :param imag_threshold: Threshold to cut off imaginary part in", "v) * dx a += eta_p * div(u) * div(v)", "= \"Quad\" if quadrilateral else \"Tri\" pbar = tqdm(range(min_degree, max_degree))", "0.5 * inner(curl(u), curl(v)) * dx # L += 0.5", "(q(\"+\") - mu_h(\"+\")) * dS a += (beta / h_avg)", "+ grad(q)) * dx # Classical mixed Darcy eq. first-order", "* V * T # Trial and test functions #", "y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") sigma_e = Function(U,", "\"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Forcing function", "Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(2), p_exact, \"on_boundary\") #", "imag_threshold: float = 1e-5) -> np.ndarray: \"\"\"Utility function to filter", "dx # L += 0.5 * f * div(v) *", "name name = f\"{current_solver}\" # Selecting the solver and its", "delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) * dS # a", "div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(1),", "= array.real[abs(array.imag) < 1e-5] return real_part_array def calculate_condition_number( A, num_of_factors,", "def solve_poisson_ls(mesh, degree=1): # Function space declaration pressure_family = 'CG'", "bcs=bc_multiplier ) return result def solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True ):", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_vms(mesh, degree=1):", "A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12)", "# Hybridization parameter s = Constant(-1.0) beta = Constant(32.0) h", "import numpy as np import matplotlib.pyplot as plt import matplotlib", "csr_matrix from slepc4py import SLEPc import pandas as pd from", "+ 1) V = FunctionSpace(mesh, pressure_family, degree) W = U", "= beta0 / h # Symmetry term. Choose if the", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_cgls(mesh,", "jump(u, n) * dS # Edge stabilizing terms # **", "a += -eta_u * inner(u + grad(p), v + grad(q))", "if the method is SIPG (-1) or NIPG (1) s", "* dS # Weak boundary conditions a += s *", "import csr_matrix from slepc4py import SLEPc import pandas as pd", "\"scipy\", use_sparse: bool = False, zero_tol: float = 1e-5 ):", "degree = 1 last_degree = 1 for current_solver in solvers_options:", "fig, ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle size =", "Badia-Codina stabilized dG method # L0 = 1 # eta_p", "= 'DQ' if use_quads else 'DG' U = VectorFunctionSpace(mesh, velocity_family,", "singular_values_list = list() if num_converged_values > 0: for i in", "* dot(p * n, q * n) * ds #", "min_degree=degree, max_degree=degree + last_degree, quadrilateral=True, name=name ) # N =", "= u + beta * (p - lambda_h) * n", "assemble(S, bcs=bcs) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size =", "+= -dot(u, grad(q)) * dx + jump(u_hat, n) * q(\"+\")", "div(v) * dx # a += 0.5 * h *", "parameters delta_1 = Constant(1) delta_2 = Constant(1) delta_3 = Constant(1)", "\"lsh\": solve_poisson_lsh, # \"vms\": solve_poisson_vms, # \"dvms\": solve_poisson_dvms, # \"mixed_RT\":", "== \"slepc\": S = SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000)", "FunctionSpace(mesh, \"CG\", degree) # Trial and test functions u =", "10, 15, 20, 25), quadrilateral=True, name=\"\", **kwargs ): results_dict =", "= Smat.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "{ \"Element\": list(), \"Number of Elements\": list(), \"Degree\": list(), \"Symmetric\":", "/ n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n * n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric)", "dS L = f * q * dx # Transmission", "delta_0 = Constant(1) # delta_1 = Constant(1) # delta_2 =", "div(v) * p) * dx a += delta_1(\"+\") * lambda_h(\"+\")", "- 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def", "symmetric? {result.is_operator_symmetric}') # print(f'nnz: {result.nnz}') # print(f'DoFs: {result.number_of_dofs}') # print(f'Condition", "ConditionNumberResult(object): form = attr.ib() assembled_form = attr.ib() condition_number = attr.ib()", "paper # eta_p = L0 * L0 # method D", "+ f1_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0] - 0.5,", "'DG' trace_family = \"HDiv Trace\" U = VectorFunctionSpace(mesh, velocity_family, degree)", "- lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) * dS # a", "* jump(v, n) * dS # not considered in the", "pbar = tqdm(range(min_degree, max_degree)) for degree in pbar: for n", "n) * avg(p) * dS - avg(q) * jump(u, n)", "Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") # Forcing function f_expression = div(-grad(p_exact))", "conditions a += s * dot(p * n, grad(q)) *", "mu_h * lambda_h * ds # ### # a +=", "array. :param array: Array with real and complex numbers. :param", "# a += 0.5 * div(u) * div(v) * dx", "A[2, 2] - A[2, :2] * A[:2, :2].inv * A[:2,", "-dot(vel_projected, n) * v * ds # How to set", "/ singular_values.min() elif backend == \"slepc\": S = SLEPc.SVD() S.create()", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dvms(mesh, degree=1): #", "inner(grad(p), grad(q)) * dx L = f * q *", "solve_poisson_ls, # \"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh, # \"vms\": solve_poisson_vms, #", "avg(delta_3) * (jump(u, n) * jump(v, n)) * dS a", "return result def solve_poisson_dgls(mesh, degree=1): # Function space declaration use_quads", "+= (avg(eta_p) / h_avg) * (jump(u, n) * jump(v, n))", "dot(u_hat, n)) * (dot(v, n) - dot(v_hat, n)) * ds", "* h_avg # method B in the Badia-Codina paper eta_p", "# How to set this bc?? # a += (beta", "= LARGE_NUMBER / h delta_5 = delta # Numerical flux", "div(u) * div(v) * dx # a += 0.5 *", "bcs=[], **kwargs): \"\"\"Provides a plot of a full hybrid-mixed matrix.\"\"\"", "def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs): \"\"\"Provides a plot of a", "S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values = S.getConverged() singular_values_list = list() if", "f0_size = assembled_form.M[0, 0].handle.getSize() f1_size = assembled_form.M[1, 1].handle.getSize() size =", "is SIPG (-1) or NIPG (1) s = Constant(-1) #", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_ldgc( mesh,", "A = _A.blocks idx = trace_index S = A[idx, idx]", "= singular_values[singular_values > zero_tol] condition_number = singular_values.max() / singular_values.min() elif", "primal_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement", "(eta_u / h) * dot(p * n, q * n)", "> zero_tol] condition_number = singular_values.max() / singular_values.min() elif backend ==", "- q * div(u) - p * div(v) + inner(grad(p),", "= Constant(0.0) bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter", "(h(\"+\") + h(\"-\")) / 2.0 # Jump stabilizing parameters based", "def solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True ): # Function space declaration", "n))) * ds a += beta * (lambda_h - p_boundaries)", "n) * p * ds - q * dot(u, n)", "L0 # method B in the Badia-Codina paper eta_u_bc =", "delta_2 = delta delta_3 = delta delta_4 = delta #", "a += eta_u * avg(delta_3) * (jump(u, n) * jump(v,", "range(num_converged_values): singular_value = S.getValue(i) singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc SVD has", "\"cgls\": solve_poisson_cgls, # \"dgls\": solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm, # \"ls\":", "kwargs solver = solvers_options[current_solver] # Performing the convergence study hp_refinement_cond_number_calculation(", "# \"cgh\": solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg, }", "of a full hybrid-mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1)", "mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration use_quads =", "a plot of a mixed matrix.\"\"\" fig, ax = plt.subplots(1,", "ds # ### # a += ( # (mu_h -", "dS # Weakly imposed BC a += dot(u_hat, n) *", "* div(v) * dx # a += 0.5 * h", "L += 0.5 * h * h * f *", "assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size = petsc_mat.getSize() Mnp =", "dS # a += dot(jump(p, n), jump(q, n)) * dS", "# Forcing function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) #", "(p(\"+\") - lambda_h(\"+\")) * dS a += -dot(grad(p), n)(\"+\") *", "Edge stabilizing terms a += beta(\"+\") * dot(jump(p, n), jump(q,", "v + grad(q)) * dx a += eta_p * div(u)", "delta_0 * inner(u + grad(p), v + grad(q)) * dx", "bcs=bc_multiplier ) return result def solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False ):", "{result.is_operator_symmetric}') # print(f'nnz: {result.nnz}') # print(f'DoFs: {result.number_of_dofs}') # print(f'Condition Number:", "< 1e-5] return real_part_array def calculate_condition_number( A, num_of_factors, backend: str", "pressure_family = 'DQ' if use_quads else 'DG' velocity_family = 'DQ'", "# Weakly imposed BC a += (p_boundaries * dot(v, n)", "beta_0 / h # Mixed classical terms a = (dot(u,", "dot(u, n) * ds a += beta * p *", "Jump stabilizing parameters based on Badia-Codina stabilized dG method #", "+= delta_1(\"+\") * dot(u_hat, n) * q * ds #", "BC a += dot(u_hat, n) * q * ds F", "dx L += delta_2 * f * div(v) * dx", "degree=1): # Function space declaration pressure_family = 'CG' velocity_family =", "= TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities h", "+ grad(p), grad(q) - v) * dx # a +=", "beta_0 = Constant(1.0e-18) # beta = beta_0 / h beta", "- p_boundaries) * mu_h * ds F = a -", "- div(v) * p) * dx + lambda_h(\"+\") * jump(v,", "result def solve_poisson_dls(mesh, degree=1): # Function space declaration use_quads =", "* dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat = A.M.handle", "parameter beta_0 = Constant(1.0e0) beta = beta_0 / h #", "-dot(u, grad(q)) * dx + jump(u_hat, n) * q(\"+\") *", "q * ds F = a - L a_form =", "import copy # my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") # #", "+ delta_0 * q * div(u)) * dx L =", "* inner(curl(u), curl(v)) * dx L += delta_2 * f", "Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot", "/ h) * (p- p_boundaries) * q * ds #", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_ls(mesh, degree=1): # Function", "1 # Nitsche's penalizing term beta_0 = Constant(1.0) beta =", "* n, q * n) * ds A = assemble(a,", "delta_2 * div(u) * div(v) * dx a += delta_3", "eta_u = h_avg / L0 # method B in the", "* h * h # Mixed classical terms a =", "Badia-Codina paper eta_u = 1 # eta_u_bc = h /", "= Constant(1.0e0) beta = beta_0 / h # beta =", "* f * div(v) * dx # Irrotational least-squares a", "q = TestFunctions(W) # Mesh entities n = FacetNormal(mesh) h", "i in range(num_converged_values): singular_value = S.getValue(i) singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc", "of Elements\": list(), \"Degree\": list(), \"Symmetric\": list(), \"nnz\": list(), \"dofs\":", "_A = Tensor(a_form) A = _A.blocks S = A[2, 2]", "1 # eta_u_bc = h / L0 # method B", "Badia-Codina based a += eta_u * inner(u + grad(p), grad(q)", "delta_1(\"+\") * dot(u_hat, n) * q * ds # #", "= assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8)", "p_boundaries) * mu_h * ds F = a - L", "= A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if use_sparse: singular_values", "\"slepc\": S = SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST)", "the Badia-Codina paper # eta_p = L0 * L0 #", "* dx # a += 0.5 * h * h", "L0 * h # method B in the Badia-Codina paper", "= 5 # mesh = UnitSquareMesh(N, N, quadrilateral=True) # result", "sin(2 * pi * x) * sin(2 * pi *", "_A = Tensor(a) A = _A.blocks S = A[2, 2]", "hybrid-mixed matrix for single scale problems.\"\"\" fig, ax = plt.subplots(1,", "* jump(v, n) * dS a += -dot(u, grad(q)) *", "num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors) result", "ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\")", "inner(u + grad(p), v + grad(q)) * dx # Classical", "degree) C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: trace_family", "h # beta = beta_0 # Numerical flux trace u", "L = f * q * dx # Transmission condition", "stabilized dG method # L0 = 1 # eta_p =", "# Nitsche's penalizing term beta_0 = Constant(1.0) beta = beta_0", "# eta_p = L0 * L0 # method D in", "# a += delta_5 * (dot(u, n)(\"+\") - dot(u_hat, n)(\"+\"))", "= Mnp.toarray() # Eliminate rows and columns filled with zero", "else: T = FunctionSpace(mesh, trace_family, degree) W = U *", "Trial and test functions p = TrialFunction(V) q = TestFunction(V)", "lambda_h = split(solution) u, p, lambda_h = TrialFunctions(W) v, q,", "results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True)", "= Constant(1) # delta_5 = Constant(1) # LARGE_NUMBER = Constant(1e0)", "or NIPG (1) s = Constant(-1) # Classical volumetric terms", "h # Mixed classical terms a = (dot(u, v) -", "return condition_number def solve_poisson_cg(mesh, degree=1, use_quads=False): # Function space declaration", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_dvms(mesh, degree=1): # Function space", "How to set this bc?? # a += (beta /", "terms a += delta_1 * (dot(u, v) - div(v) *", "* p * q * ds A = assemble(a, mat_type=\"aij\")", "result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap) # # plot_matrix(result.assembled_form,", "a += (eta_p / h) * dot(u, n) * dot(v,", "number_of_dofs = Mnp.shape[0] num_of_factors = int(number_of_dofs) - 1 condition_number =", "color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0]", "Mass balance least-square a += delta_2 * div(u) * div(v)", "Smat.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp", "= petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "hybridization # a += mu_h * (lambda_h - p_boundaries) *", "* dx # DG terms a += jump(v, n) *", "attr.ib() is_operator_symmetric = attr.ib() bcs = attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs):", "* h # Mixed classical terms a = (dot(u, v)", "A[idx, :idx] * A[:idx, :idx].inv * A[:idx, idx] Smat =", "stabilization h_avg = (h(\"+\") + h(\"-\")) / 2.0 # Jump", "= assembled_form.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "* h * f * div(v) * dx # a", "a += jump(u, n) * jump(v, n) * dS #", "delta_4 = delta # delta_4 = LARGE_NUMBER / h delta_5", "Least-squares terms a = delta_1 * inner(u + grad(p), v", "Flux least-squares # a = ( # (inner(u, v) -", "Numerical flux trace u_hat = u + beta * (p", "* dx # Irrotational least-squares a += delta_3 * inner(curl(u),", "pressure_family, degree) # Trial and test functions p = TrialFunction(V)", "# Solver options solvers_options = { # \"cg\": solve_poisson_cg, #", "* dx # a += 0.5 * inner(curl(u), curl(v)) *", "delta_3 = Constant(1) # delta_4 = Constant(1) # delta_5 =", "calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs,", "stabilizing parameters based on Badia-Codina stabilized dG method L0 =", "method B in the Badia-Codina paper # eta_p = 1", "exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") # Forcing function f_expression", "entities h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh) # Exact", "a += lambda_h(\"+\") * dot(v, n)(\"+\") * dS + mu_h(\"+\")", "# ** Mesh independent (original) # a += jump(u, n)", "* q * dx # Stabilizing terms a += delta_1", "ds # a += delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n)", "degree=1) # print(f'Is symmetric? {result.is_operator_symmetric}') # print(f'nnz: {result.nnz}') # print(f'DoFs:", "= svds( A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" ) else:", "ds a += beta * p * q * ds", "div(u) * div(v) * dx a += 0.5 * inner(curl(u),", "q, mu_h = TestFunctions(W) # Mesh entities n = FacetNormal(mesh)", "curl(v)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat =", "Constant(1) delta_2 = Constant(1) delta_3 = Constant(1) # Least-squares terms", "* n # HDG classical form a = (dot(u, v)", "v + grad(q)) * dx # a += 0.5 *", "Badia-Codina paper eta_p = 1 # eta_p = L0 *", "** Badia-Codina based (better results) ** a += eta_u *", "* ds # ** The terms below are based on", "\"\"\"Provides a plot of a full hybrid-mixed matrix.\"\"\" fig, ax", "* dot(u, n)(\"+\") * dS a += beta(\"+\") * (lambda_h(\"+\")", "condition_number = attr.ib() sparse_operator = attr.ib() number_of_dofs = attr.ib() nnz", "RuntimeError(\"SLEPc SVD has not converged.\") singular_values = np.array(singular_values_list) singular_values =", "A[2, :2] * A[:2, :2].inv * A[:2, 2] Smat =", "V * T # Trial and test functions # solution", "= delta delta_2 = delta delta_3 = delta delta_4 =", "div(v) * dx # Irrotational least-squares a += delta_3 *", "): results_dict = { \"Element\": list(), \"Number of Elements\": list(),", "jump(q, n)) * dS # Weak boundary conditions a +=", "mu_h(\"+\") * dot(u, n)(\"+\") * dS a += beta(\"+\") *", "degree) W = U * V # Trial and test", "dx # Irrotational least-squares a += delta_3 * inner(curl(u), curl(v))", "a += delta_1(\"+\") * dot(u_hat, n) * q * ds", "Function(V).interpolate(f_expression) # BCs u_projected = sigma_e p_boundaries = p_exact bcs", "primal_family = \"DQ\" if use_quads else \"DG\" V = FunctionSpace(mesh,", "parameters based on Badia-Codina stabilized dG method # L0 =", "1 last_degree = 1 for current_solver in solvers_options: # Setting", "df_cond_number.to_csv(path_to_save_results) return df_cond_number # Solver options solvers_options = { #", "str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG'", "- lambda_h) * n v_hat = v + beta *", "= DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\") # Average cell size and", "= Constant(1) delta_2 = Constant(1) delta_3 = Constant(1) # Least-squares", "declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" primal_family = \"DQ\" if", "as stabilizing terms a += delta_1 * (dot(u, v) -", "svds( A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" ) else: M", "p_boundaries = p_exact bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization", "delta delta_2 = delta delta_3 = delta delta_4 = delta", "* ds - q * dot(u, n) * ds a", "Number\": list(), } element_kind = \"Quad\" if quadrilateral else \"Tri\"", "a full hybrid-mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1) assembled_form", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sdhm(", "a += 0.5 * inner(curl(u), curl(v)) * dx # **", "* ds # # a += delta_1 * dot(u, n)", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_cgls(mesh, degree=1): # Function space", "else 'DG' trace_family = \"HDiv Trace\" U = VectorFunctionSpace(mesh, velocity_family,", "* ds - dot(grad(p), q * n) * ds a", "mu_h * ds F = a - L a_form =", "a += dot(jump(p, n), jump(q, n)) * dS # Volumetric", "= Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp =", "pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results) return df_cond_number #", "15, 20, 25), quadrilateral=True, name=\"\", **kwargs ): results_dict = {", "p - q * div(u)) * dx # DG terms", "* dx # ) # # These terms below are", "a += (eta_u / h) * dot(p * n, q", "ds # ** Mesh independent ** # a += jump(u,", "u, p = TrialFunctions(W) v, q = TestFunctions(W) # Mesh", "# a += beta * p * q * ds", "= L0 * L0 # method D in the Badia-Codina", "\"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e0) beta = beta_0", "f * div(v) * dx # ** Badia-Codina based a", "which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" ) else: M = Mnp.toarray() singular_values", "n), jump(q, n)) * dS # Weak boundary conditions a", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_mixed_RT(mesh,", "TestFunctions(W) # Mesh entities x, y = SpatialCoordinate(mesh) # Exact", "test functions # solution = Function(W) # u, p, lambda_h", "* ds # ** Mesh independent ** # a +=", "n) * jump(v, n) * dS # a += dot(jump(p,", "+= (eta_u / h) * dot(p * n, q *", "Edge stabilizing terms # ** Badia-Codina based a += (avg(eta_p)", "* dx # L = delta_2 * f * div(v)", "V = FunctionSpace(mesh, pressure_family, degree) W = U * V", "+= jump(u, n) * jump(v, n) * dS # not", "inner(curl(u), curl(v)) * dx # Weakly imposed boundary conditions a", "use_quads: hdiv_family = 'RTCF' pressure_family = 'DQ' else: hdiv_family =", "ds # may decrease convergente rates # ** The terms", "ds # may decrease convergente rates a += eta_u_bc *", "ds # # L = -delta_1 * dot(u_projected, n) *", "def solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration", "a += delta_1 * inner(u + grad(p), v + grad(q))", "n # HDG classical form a = -dot(u, grad(q)) *", "dS # Boundary terms # a += -dot(vel_projected, n) *", "array: Array with real and complex numbers. :param imag_threshold: Threshold", "p + q * div(u)) * dx A = assemble(a,", "dG method # L0 = 1 # eta_p = L0", "ax.set_yticklabels([]) return plot def filter_real_part_in_array(array: np.ndarray, imag_threshold: float = 1e-5)", "ASGS Badia-Codina (2010), it is not a classical Nitsche's method", "slepc4py import SLEPc import pandas as pd from tqdm import", "1) petsc_mat = assembled_form.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "grad(p), grad(q) - v) * dx # a += 0.5", "**kwargs) # Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([])", "sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # BCs bcs =", "dot(u_hat, n)(\"+\")) * (dot(v, n)(\"+\") - dot(v_hat, n)(\"+\")) * dS", "quadrilateral else \"Tri\" pbar = tqdm(range(min_degree, max_degree)) for degree in", "# Classical term a = dot(grad(p), grad(q)) * dx L", "* (lambda_h - p_boundaries) * mu_h * ds F =", "* (lambda_h - p_boundaries) * ds # ) # maybe", "2] Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric =", "beta * p * q * ds # may decrease", "def solve_poisson_mixed_RT(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell())", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_ls(mesh,", "= 'DQ' else: hdiv_family = 'RT' pressure_family = 'DG' U", "* dS # Edge stabilizing terms # ** Badia-Codina based", "# ** The terms below are based on ASGS Badia-Codina", "a += delta_1 * lambda_h * dot(v, n) * ds", "div(u)) * dx # DG terms a += jump(v, n)", "\"HDiv Trace\" T = FunctionSpace(mesh, trace_family, degree) W = U", "bc_multiplier = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 =", "Exact solution p_exact = sin(2 * pi * x) *", "solve_poisson_cgls(mesh, degree=1): # Function space declaration pressure_family = 'CG' velocity_family", "* f * q * dx # Stabilizing terms a", "real part in a numpy array. :param array: Array with", "2] - A[2, :2] * A[:2, :2].inv * A[:2, 2]", "petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz", "= ax.matshow(Am, **kwargs) # Below there is the spy alternative", "beta_0 # Numerical flux trace u_hat = u + beta", "S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values = S.getConverged() singular_values_list", "name='Exact velocity') sigma_e.project(-grad(p_exact)) # Forcing function f_expression = div(-grad(p_exact)) f", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sdhm( mesh, degree=1,", "beta = beta_0 # Numerical flux trace u_hat = u", "ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a plot", "# These terms below are unsymmetric # a += delta_1", ") return result def hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4, numel_xy=(5, 10,", "delta delta_2 = delta delta_3 = 1 / h delta_4", "# # a += delta_1 * dot(u, n) * q", "* dx a += 0.5 * div(u) * div(v) *", "the Badia-Codina paper eta_u = 1 # eta_u_bc = h", "dS a += -dot(grad(p), n)(\"+\") * (q(\"+\") - mu_h(\"+\")) *", "\"cgh\": solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg, } degree", "dS # Edge stabilizing terms a += beta(\"+\") * dot(jump(p,", "mu_h * (lambda_h - p_boundaries) * ds # a +=", "# Hybridization parameter beta_0 = Constant(1.0e-18) # beta = beta_0", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_ls(mesh, degree=1): #", "+= eta_p * avg(delta_4) * dot(jump(p, n), jump(q, n)) *", "= Constant(1e0) delta = h * h # delta =", "dS # a += p * q * ds A", "= plt.subplots(1, 1) _A = Tensor(a_form) A = _A.blocks idx", "delta_1 = delta delta_2 = delta delta_3 = 1 /", "solve_poisson_ls(mesh, degree=1): # Function space declaration pressure_family = 'CG' velocity_family", "only real numbers. \"\"\" real_part_array = array.real[abs(array.imag) < 1e-5] return", "not a classical Nitsche's method a += (eta_p / h)", "Mnp.nnz number_of_dofs = Mnp.shape[0] num_of_factors = int(number_of_dofs) - 1 condition_number", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_vms(mesh,", "condensed hybrid-mixed matrix for single scale problems.\"\"\" fig, ax =", "# Hybridization parameter beta_0 = Constant(1.0) beta = beta_0 /", "Nitsche's method a += (eta_p / h) * dot(u, n)", "test functions p = TrialFunction(V) q = TestFunction(V) # Mesh", "* dS - dot(avg(grad(p)), jump(q, n)) * dS # Edge", "Tensor(a_form) A = _A.blocks S = A[1, 1] - A[1,", "v) * dx # a += 0.5 * h *", "bcs=bcs ) return result def solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False ):", "boundary conditions a += dot(v, n) * p * ds", "* dx a += delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n)", "= np.ma.masked_values(Mnp, 0, rtol=1e-13) # Plot the matrix plot =", "A, num_of_factors, backend: str = \"scipy\", use_sparse: bool = False,", "a mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat =", "# delta = h delta_0 = delta delta_1 = delta", "F = a - L a_form = lhs(F) _A =", "q * div(u)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\")", "num_of_factors) result = ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz,", "dx # Hybridization terms a += mu_h(\"+\") * jump(u_hat, n=n)", "dS # ** Mesh independent terms # a += jump(u,", "div(v) * p + q * div(u)) * dx A", "q * ds # may decrease convergente rates # **", "convergente rates # ** Classical Nitsche # a += beta", "+= -dot(grad(p), n)(\"+\") * (q(\"+\") - mu_h(\"+\")) * dS a", "* inner(u + grad(p), grad(q) - v) * dx a", "h(\"-\")) / 2.0 # Jump stabilizing parameters based on Badia-Codina", "Classical term a = dot(grad(p), grad(q)) * dx L =", "parameters based on Badia-Codina stabilized dG method L0 = 1", "Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family =", "_A.blocks S = A[2, 2] - A[2, :2] * A[:2,", "B in the Badia-Codina paper # eta_u = 1 #", "stabilizing parameter beta0 = Constant(1e1) beta = beta0 / h", "firedrake import * import numpy as np import matplotlib.pyplot as", "as plt import matplotlib from scipy.linalg import svd from scipy.sparse.linalg", "dx # DG edge terms a += s * dot(jump(p,", "Constant(-1) delta_1 = Constant(-0.5) * h * h delta_2 =", "filter_real_part_in_array(array: np.ndarray, imag_threshold: float = 1e-5) -> np.ndarray: \"\"\"Utility function", "ax = plt.subplots(1, 1) _A = Tensor(a_form) A = _A.blocks", "form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return", "bcs = attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs): \"\"\"Provides a plot of", "S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values = S.getConverged() singular_values_list = list()", "# Trial and test functions # solution = Function(W) #", "Symmetry term. Choose if the method is SIPG (-1) or", "a += (beta / h) * (p- p_boundaries) * q", "degree) V = FunctionSpace(mesh, pressure_family, degree) W = U *", "calculate_condition_number( A, num_of_factors, backend: str = \"scipy\", use_sparse: bool =", "* dot(v, n) + mu_h * (dot(u, n) - dot(u_projected,", "Boundary terms # a += -dot(vel_projected, n) * v *", "= TestFunction(V) # Mesh entities n = FacetNormal(mesh) h =", "dS a += delta_4(\"+\") * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\")", "* div(u)) * dx L = delta_0 * f *", "+= delta_1 * (dot(u, v) - div(v) * p) *", "this necessary? L += s * dot(grad(q), n) * p_boundaries", "p + q * div(u)) * dx # Stabilizing terms", "parameter beta0 = Constant(1e1) beta = beta0 / h #", "result def solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False ): # Function space", "str(mesh.ufl_cell()) == \"quadrilateral\" primal_family = \"DQ\" if use_quads else \"DG\"", "= Function(W) # u, p, lambda_h = split(solution) u, p,", "lambda_h(\"+\") * dot(v, n)(\"+\") * dS + mu_h(\"+\") * dot(u,", "def solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration", "# L = delta_1 * p_exact * dot(v, n) *", "result.bcs, cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2,", "list() if num_converged_values > 0: for i in range(num_converged_values): singular_value", "use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" if use_quads: hdiv_family = 'RTCF'", "bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Mixed classical terms a", "= calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp,", "bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize()", "avg(h) # Classical term a = dot(grad(p), grad(q)) * dx", "n)(\"+\")) * (dot(v, n)(\"+\") - dot(v_hat, n)(\"+\")) * dS #", "h delta_3 = Constant(0.5) * h * h # Mixed", "# a += p * q * ds A =", "C0TraceElement) else: T = FunctionSpace(mesh, trace_family, degree) W = V", "condition_number = singular_values.max() / singular_values.min() elif backend == \"slepc\": S", "**kwargs): \"\"\"Provides a plot of a mixed matrix.\"\"\" fig, ax", "method a += (eta_p / h) * dot(u, n) *", "Weakly imposed BC a += dot(u_hat, n) * q *", "# is this necessary? L += s * dot(grad(q), n)", "div(u) * div(v) * dx # L = delta_2 *", "(avg(eta_u) / h_avg) * dot(jump(p, n), jump(q, n)) * dS", "mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size =", "filled with zero entries Mnp = Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[...,", "v) - q * div(u) - p * div(v) +", "axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def", "is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size)", "dS a += eta_p * avg(delta_4) * dot(jump(p, n), jump(q,", "* q * ds # # L = -delta_1 *", "+= mu_h(\"+\") * jump(u_hat, n=n) * dS a += delta_4(\"+\")", "n, quadrilateral=quadrilateral) result = solver(mesh, degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min() if", "Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact))", "num_converged_values = S.getConverged() singular_values_list = list() if num_converged_values > 0:", "delta_4(\"+\") * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) *", "* dx a += eta_p * inner(curl(u), curl(v)) * dx", "velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement", "return result def solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False ): # Function", "(dot(u, n)(\"+\") - dot(u_hat, n)(\"+\")) * (dot(v, n)(\"+\") - dot(v_hat,", "= 'CG' velocity_family = 'CG' U = VectorFunctionSpace(mesh, velocity_family, degree)", "cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs,", "real_part_array = array.real[abs(array.imag) < 1e-5] return real_part_array def calculate_condition_number( A,", "classical Nitsche's method a += (eta_p / h) * dot(u,", "jump(v, n) * dS # not considered in the original", "/ h) * dot(p * n, q * n) *", "= U * V # Trial and test functions u,", "lambda_h(\"+\") * jump(v, n=n) * dS a += delta_1 *", "on Badia-Codina stabilized dG method # L0 = 1 #", "method B in the Badia-Codina paper eta_u = 1 #", "mu_h(\"+\") * dS # Weakly imposed BC a += lambda_h", "numpy as np import matplotlib.pyplot as plt import matplotlib from", "import attr from firedrake import * import numpy as np", "= h delta_0 = delta delta_1 = delta delta_2 =", "the Badia-Codina paper # eta_u = h_avg / L0 #", "** Mesh independent ** # a += jump(u, n) *", "# a += mu_h * (lambda_h - p_boundaries) * ds", "Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs bcs = DirichletBC(W[0],", "LARGE_NUMBER / h delta_5 = delta # Numerical flux trace", "trace_family, degree) W = U * V * T #", "hdiv_family, degree + 1) V = FunctionSpace(mesh, pressure_family, degree) W", "full hybrid-mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1) assembled_form =", "== \"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG' velocity_family", "q * dx # Stabilizing terms a += delta_1 *", "+= 0.5 * inner(curl(u), curl(v)) * dx A = assemble(a,", "div(v) * dx a += delta_2 * inner(curl(u), curl(v)) *", "* dx # Transmission condition a += jump(u_hat, n) *", "Constant(1.0) beta = beta_0 / h beta_avg = beta_0 /", "mesh = UnitSquareMesh(n, n, quadrilateral=quadrilateral) result = solver(mesh, degree=degree) current_cell_size", "= 'RT' pressure_family = 'DG' U = FunctionSpace(mesh, hdiv_family, degree", "n) * jump(v, n)) * dS a += (avg(eta_u) /", "q(\"+\") * dS L = f * q * dx", "# ** Badia-Codina based (better results) ** a += eta_u", "div(v) * dx # L = delta_2 * f *", "= DirichletBC(W[0], sigma_e, \"on_boundary\") # Stabilization parameters delta_1 = Constant(1)", "L += delta_2 * f * div(v) * dx #", "results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n * n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs)", "\"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results) return df_cond_number # Solver options solvers_options", "\"hdg\": solve_poisson_hdg, # \"cgh\": solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc, # \"sipg\":", "= Tensor(a_form) A = _A.blocks idx = trace_index S =", ") else: M = Mnp.toarray() singular_values = svd(M, compute_uv=False, check_finite=False)", "from scipy.linalg import svd from scipy.sparse.linalg import svds from scipy.sparse", "dot(u_projected, n))) * ds a += beta * (lambda_h -", "float = 1e-5 ): backend = backend.lower() if backend ==", "+= -0.5 * inner(u + grad(p), v + grad(q)) *", "to filter real part in a numpy array. :param array:", "v) - div(v) * p + q * div(u)) *", "A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if use_sparse: singular_values =", "h_avg) * dot(jump(p, n), jump(q, n)) * dS # **", "= csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp = Mnp.toarray() # Eliminate rows", "f * q * dx # Transmission condition a +=", "n)) * dS # ** Mesh independent terms # a", "A[:1, :1].inv * A[:1, 1] Smat = assemble(S, bcs=bc_multiplier) petsc_mat", "n) * ds # Mass balance least-square a += delta_2", "ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier )", "Least-Squares weights delta = Constant(1.0) # delta = h delta_0", "/ 2.0 # Jump stabilizing parameters based on Badia-Codina stabilized", "delta_3 * inner(curl(u), curl(v)) * dx L += delta_2 *", "a - L a_form = lhs(F) _A = Tensor(a_form) A", "raise RuntimeError(\"SLEPc SVD has not converged.\") singular_values = np.array(singular_values_list) singular_values", "delta_2 * div(u) * div(v) * dx # L =", "lambda_h = TrialFunctions(W) v, q, mu_h = TestFunctions(W) # Mesh", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_lsh( mesh,", "as pd from tqdm import tqdm import os matplotlib.use('Agg') @attr.s", "a += delta_2 * div(u) * div(v) * dx #", "pressure_family = 'CG' velocity_family = 'CG' U = VectorFunctionSpace(mesh, velocity_family,", "* div(u) - p * div(v) + inner(grad(p), grad(q))) #", "# delta_2 = Constant(1) # delta_3 = Constant(1) # delta_4", "* dot(v, n)(\"+\") * dS + mu_h(\"+\") * dot(u, n)(\"+\")", "plot of a condensed hybrid-mixed matrix for single scale problems.\"\"\"", "Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8)", "= (dot(u, v) - div(v) * p) * dx +", "+= -0.5 * inner((u + grad(p)), v + grad(q)) *", "= Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\")", "sigma_e.project(-grad(p_exact)) # BCs bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization", "assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize()", "a += delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) * dS", "sigma_e.project(-grad(p_exact)) # Dirichlet BCs # bcs = DirichletBC(W[0], sigma_e, \"on_boundary\",", "dx a += 0.5 * inner(curl(u), curl(v)) * dx A", "and test functions p = TrialFunction(V) q = TestFunction(V) #", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_cgh( mesh,", "and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def filter_real_part_in_array(array: np.ndarray,", "Mnp = Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[..., :] == 0, axis=0))", "= delta delta_3 = 1 / h delta_4 = 1", "# L += 0.5 * f * div(v) * dx", "h * h # delta = Constant(1) # delta =", "Classical mixed Darcy eq. first-order terms as stabilizing terms a", "= Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(2), p_exact, \"on_boundary\")", "assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size =", "* dS a += delta_4(\"+\") * (p(\"+\") - lambda_h(\"+\")) *", "n=n) * dS a += delta_1 * lambda_h * dot(v,", "a = inner(grad(u), grad(v)) * dx A = assemble(a, bcs=bcs,", "a = (dot(u, v) - div(v) * p - q", "= TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities x,", "* delta_4 * dot(u, n) * dot(v, n) * ds", "= f\"{current_solver}\" # Selecting the solver and its kwargs solver", "terms a += s * dot(jump(p, n), avg(grad(q))) * dS", "a plot of a condensed hybrid-mixed matrix for single scale", "a += eta_u_bc * delta_4 * dot(u, n) * dot(v,", "\"\"\"Provides a plot of a matrix.\"\"\" fig, ax = plt.subplots(1,", "= -grad(p) u_hat = u + beta * (p -", "q * div(u)) * dx L = delta_0 * f", "ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs )", "h(\"+\") # Stabilizing parameter # delta_0 = Constant(1) # delta_1", "alternative # plot = plt.spy(Am, **kwargs) # Remove axis ticks", "mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize()", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def hp_refinement_cond_number_calculation(", "bcs=bcs) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize()", "plot = ax.matshow(Am, **kwargs) # Below there is the spy", "* (p - lambda_h) * n v_hat = v +", "* (dot(u, n) - dot(u_hat, n)) * (dot(v, n) -", "degree=1, is_multiplier_continuous=True ): # Function space declaration use_quads = str(mesh.ufl_cell())", "(lambda_h - p_boundaries) * mu_h * ds F = a", "copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) # #", "matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle size", "- A[2, :2] * A[:2, :2].inv * A[:2, 2] Smat", "below are based on ASGS Badia-Codina (2010), it is not", "5 # mesh = UnitSquareMesh(N, N, quadrilateral=True) # result =", "petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp", "n) * ds a += dot(u_hat, n) * q *", "# plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap) # # plot_matrix(result.assembled_form, cmap=my_cmap) #", "LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: trace_family = \"HDiv Trace\"", "# L = -delta_1 * dot(u_projected, n) * q *", "backend == \"scipy\": size = A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size)", "sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs bcs", "is_multiplier_continuous=False ): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "delta_5 * (dot(u, n) - dot(u_hat, n)) * (dot(v, n)", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_mixed_RT(mesh, degree=1):", "the matrix plot = ax.matshow(Am, **kwargs) # Below there is", "balance least-square a += delta_2 * div(u) * div(v) *", "this bc?? # a += (beta / h) * (p-", "beta * (p - lambda_h) * n # HDG classical", "else 'DG' V = FunctionSpace(mesh, pressure_family, degree) # Trial and", "solver and its kwargs solver = solvers_options[current_solver] # Performing the", "**kwargs): \"\"\"Provides a plot of a condensed hybrid-mixed matrix for", "= 'DG' U = FunctionSpace(mesh, hdiv_family, degree + 1) V", "svd from scipy.sparse.linalg import svds from scipy.sparse import csr_matrix from", "+ inner(grad(p), grad(q))) # * delta_1 # * dx #", "a += delta_4 * (p - lambda_h) * (q -", "BCs bc_multiplier = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0", "form a = -dot(u, grad(q)) * dx + jump(u_hat, n)", "* dS a += -dot(grad(p), n)(\"+\") * (q(\"+\") - mu_h(\"+\"))", "delta = Constant(1.0) # delta = h delta_0 = delta", "scipy.sparse.linalg import svds from scipy.sparse import csr_matrix from slepc4py import", "h * f * div(v) * dx # a +=", "h delta_0 = delta delta_1 = delta delta_2 = delta", "a += (p_boundaries * dot(v, n) + mu_h * (dot(u,", "= a - L a_form = lhs(F) _A = Tensor(a_form)", "beta * p * q * ds A = assemble(a,", "Constant(32.0) h = CellDiameter(mesh) h_avg = avg(h) # Classical term", "# Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0]", "0.5 * inner(u + grad(p), grad(q) - v) * dx", "> 0: for i in range(num_converged_values): singular_value = S.getValue(i) singular_values_list.append(singular_value)", "idx, axis=1) Am = np.ma.masked_values(Mnp, 0, rtol=1e-13) # Plot the", "* jump(v, n) * dS # a += dot(jump(p, n),", "# Transmission condition a += jump(u_hat, n) * mu_h(\"+\") *", "* q * ds # is this necessary? L +=", "V # Trial and test functions u, p = TrialFunctions(W)", "** Badia-Codina based a += -eta_u * inner(u + grad(p),", "= plt.subplots(1, 1) petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize()", "U * V # Trial and test functions u, p", "p_exact bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0", "grad(q) - v) * dx # a += 0.5 *", "Weakly imposed boundary conditions a += dot(v, n) * p", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_vms(mesh, degree=1): # Function space", "DG edge terms a += s * dot(jump(p, n), avg(grad(q)))", "the method is SIPG (-1) or NIPG (1) s =", "it is not a classical Nitsche's method a += (eta_p", "\"Quad\" if quadrilateral else \"Tri\" pbar = tqdm(range(min_degree, max_degree)) for", "FunctionSpace(mesh, trace_family, degree) W = V * T # Trial", "A[:idx, idx] Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle size", "Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" primal_family =", "return plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of", "jump(v, n=n) * dS # a += delta_1 * lambda_h", "+= (eta_p / h) * dot(u, n) * dot(v, n)", "Trace\" V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement =", "= petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz", "dot(jump(p, n), jump(q, n)) * dS # Volumetric stabilizing terms", "* h * div(u) * div(v) * dx # a", "# delta_1 = Constant(1) # delta_2 = Constant(1) # delta_3", "DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e-18) #", "n=n) * dS a += delta_4(\"+\") * (p(\"+\") - lambda_h(\"+\"))", "in solvers_options: # Setting the output file name name =", "attr.ib() assembled_form = attr.ib() condition_number = attr.ib() sparse_operator = attr.ib()", "# Function space declaration V = FunctionSpace(mesh, \"CG\", degree) #", "{result.number_of_dofs}') # print(f'Condition Number: {result.condition_number}') # # Plotting the resulting", "ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def plot_matrix_mixed(assembled_form,", "= ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric )", "+= lambda_h * dot(v, n) * ds a += dot(u_hat,", "* dx L += delta_2 * f * div(v) *", "color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0] - 0.5,", "# Mesh entities x, y = SpatialCoordinate(mesh) # Exact solution", "# Edge stabilizing terms a += beta(\"+\") * dot(jump(p, n),", "ds a += beta * (lambda_h - p_boundaries) * mu_h", "n)) * dS # a += p * q *", "q(\"+\")) * dS # Weakly imposed BC a += (p_boundaries", "= dot(grad(p), grad(q)) * dx L = f * q", "sigma_e, \"on_boundary\") # Mixed classical terms a = (dot(u, v)", "* y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") # Forcing", "div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Edge stabilizing parameter beta0 =", "f1_size = assembled_form.M[1, 1].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "U * V * T # Trial and test functions", "A = _A.blocks S = A[2, 2] - A[2, :2]", "\"on_boundary\") # Stabilization parameters delta_1 = Constant(1) delta_2 = Constant(1)", "paper eta_u_bc = 1 # Least-Squares weights delta = Constant(1.0)", "+ grad(p), grad(q) - v) * dx a += eta_p", "# print(f'nnz: {result.nnz}') # print(f'DoFs: {result.number_of_dofs}') # print(f'Condition Number: {result.condition_number}')", "import matplotlib from scipy.linalg import svd from scipy.sparse.linalg import svds", "a += (avg(eta_p) / h_avg) * (jump(u, n) * jump(v,", "L0 = 1 # eta_p = L0 * h_avg #", "# ** Badia-Codina based a += (avg(eta_p) / h_avg) *", "= split(solution) u, p, lambda_h = TrialFunctions(W) v, q, mu_h", "# # Plotting the resulting matrix # matplotlib.use('TkAgg') # import", "+= (beta / h) * (p- p_boundaries) * q *", "number_of_dofs = attr.ib() nnz = attr.ib() is_operator_symmetric = attr.ib() bcs", "v, q, mu_h = TestFunctions(W) # Mesh entities n =", "sigma_e p_boundaries = p_exact bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") #", "delta = h * h # delta = Constant(1) #", "eq. first-order terms as stabilizing terms a += delta_1 *", "# Stabilization parameters delta_0 = Constant(-1) delta_1 = Constant(-0.5) *", "# plot_matrix(result.assembled_form, cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form, cmap=my_cmap) # plt.tight_layout() #", "grad(p), v + grad(q)) * dx # a += 0.5", "u, p, lambda_h = TrialFunctions(W) v, q, mu_h = TestFunctions(W)", "dot(grad(q), n)(\"+\") * (p(\"+\") - lambda_h(\"+\")) * dS a +=", "least-squares # a = ( # (inner(u, v) - q", "return result def solve_poisson_sipg(mesh, degree=1): # Function space declaration use_quads", "/ h) * dot(u, n) * dot(v, n) * ds", "* jump(u_hat, n=n) * q(\"+\") * dS # a +=", "dS a += beta(\"+\") * (lambda_h(\"+\") - p(\"+\")) * (mu_h(\"+\")", "way to impose BC, but this necessary _A = Tensor(a)", "jump(u, n) * jump(v, n) * dS # a +=", "(jump(u, n) * jump(v, n)) * dS a += eta_p", "bcs=bcs) petsc_mat = Smat.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "+ grad(q)) * dx # a += 0.5 * div(u)", "attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs): \"\"\"Provides a plot of a matrix.\"\"\"", "+ q * div(u)) * dx # DG terms a", "Mesh entities x, y = SpatialCoordinate(mesh) # Exact solution p_exact", "= Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Forcing function f_expression =", "with real and complex numbers. :param imag_threshold: Threshold to cut", "return plot def filter_real_part_in_array(array: np.ndarray, imag_threshold: float = 1e-5) ->", "* div(u)) * dx # Stabilizing terms a += -0.5", "exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results)", "eta_p = L0 * h # method B in the", "* ds # may decrease convergente rates # ** Classical", "/ h beta_avg = beta_0 / h(\"+\") # Stabilizing parameter", "bcs=bcs, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size =", "nnz = attr.ib() is_operator_symmetric = attr.ib() bcs = attr.ib(default=list()) def", "degree=1, is_multiplier_continuous=False ): # Function space declaration use_quads = str(mesh.ufl_cell())", "v) - div(v) * p - q * div(u)) *", "* dot(grad(q), n) * p_boundaries * ds F = a", "= FunctionSpace(mesh, C0TraceElement) else: T = FunctionSpace(mesh, trace_family, degree) W", "to impose BC, but this necessary _A = Tensor(a) A", "inner(u + grad(p), v + grad(q)) * dx # a", "+ grad(p)), v + grad(q)) * dx # a +=", "return plot def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of", "v + beta * (q - mu_h) * n #", "(dot(u, v) - div(v) * p + q * div(u))", "ds # Flux Least-squares as in DG a = delta_0", "parameter # delta_0 = Constant(1) # delta_1 = Constant(1) #", "velocity') sigma_e.project(-grad(p_exact)) # Forcing function f_expression = div(-grad(p_exact)) f =", "0.5 * f * div(v) * dx # ** Badia-Codina", "Function(V).interpolate(f_expression) # Dirichlet BCs p_boundaries = Constant(0.0) bc_multiplier = DirichletBC(W.sub(1),", "= attr.ib() condition_number = attr.ib() sparse_operator = attr.ib() number_of_dofs =", "return df_cond_number # Solver options solvers_options = { # \"cg\":", "= A[idx, idx] - A[idx, :idx] * A[:idx, :idx].inv *", "form a = (dot(u, v) - div(v) * p) *", "the output file name name = f\"{current_solver}\" # Selecting the", "attr.ib() bcs = attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs): \"\"\"Provides a plot", "solve_poisson_sdhm, # \"ls\": solve_poisson_ls, # \"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh, #", "p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0) beta =", "delta_3 = delta delta_4 = delta # delta_4 = LARGE_NUMBER", "a += p * q * ds A = assemble(a,", "inner(curl(u), curl(v)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat", "a = (dot(u, v) - div(v) * p) * dx", "# may decrease convergente rates # ** The terms below", "idx] Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle size =", "petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() f1_size = assembled_form.M[1,", "f = Function(V).interpolate(f_expression) # BCs u_projected = sigma_e p_boundaries =", "= Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[..., :] == 0, axis=0)) Mnp", "dx a += delta_3 * inner(curl(u), curl(v)) * dx A", "T = FunctionSpace(mesh, C0TraceElement) else: T = FunctionSpace(mesh, trace_family, degree)", "Setting the output file name name = f\"{current_solver}\" # Selecting", "p_exact * dot(v, n) * ds # Flux Least-squares as", "# u, p, lambda_h = split(solution) u, p, lambda_h =", "is_operator_symmetric=is_symmetric, bcs=bcs ) return result def hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4,", "for single scale problems.\"\"\" fig, ax = plt.subplots(1, 1) _A", "delta delta_3 = delta delta_4 = delta # delta_4 =", "a += mu_h * lambda_h * ds # ### #", "div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs p_boundaries = Constant(0.0)", "0.5 * f * div(v) * dx A = assemble(a,", "a numpy array. :param array: Array with real and complex", "petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz", "* dx a += 0.5 * inner(curl(u), curl(v)) * dx", "TrialFunctions(W) q, mu_h = TestFunctions(W) # Mesh entities n =", "solution = Function(W) # u, p, lambda_h = split(solution) p,", "return result def solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True ): # Function", "q * ds # may decrease convergente rates a +=", "plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs): \"\"\"Provides a plot of a condensed", "Hybridization parameter beta_0 = Constant(1.0e0) beta = beta_0 / h", "C0TraceElement) else: trace_family = \"HDiv Trace\" T = FunctionSpace(mesh, trace_family,", "rates # ** The terms below are based on ASGS", "* ds # a += delta_1(\"+\") * lambda_h(\"+\") * jump(v,", ":2].inv * A[:2, 2] Smat = assemble(S, bcs=bcs) petsc_mat =", "= ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier", "below are unsymmetric # a += delta_1 * jump(u_hat, n=n)", "dot(grad(p), grad(q)) * dx L = f * q *", "result def hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4, numel_xy=(5, 10, 15, 20,", "0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def plot_matrix_mixed_hybrid_full(a_form,", "of a mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat", "space declaration V = FunctionSpace(mesh, \"CG\", degree) # Trial and", "independent ** # a += jump(u, n) * jump(v, n)", "= csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = V.dim()", "-0.5 * inner((u + grad(p)), v + grad(q)) * dx", "* jump(v, n=n) * dS a += delta_1 * lambda_h", "h_avg = (h(\"+\") + h(\"-\")) / 2.0 # Jump stabilizing", "class ConditionNumberResult(object): form = attr.ib() assembled_form = attr.ib() condition_number =", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dgls(mesh, degree=1):", "Dirichlet BCs bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter", "else \"DG\" V = FunctionSpace(mesh, primal_family, degree) if is_multiplier_continuous: LagrangeElement", "eta_u = 1 # Nitsche's penalizing term beta_0 = Constant(1.0)", "div(v) * dx # Hybridization terms a += lambda_h(\"+\") *", "delta_2 * inner(curl(u), curl(v)) * dx # Edge stabilizing terms", "n) * v * ds # How to set this", "dot(grad(q), n) * p_boundaries * ds F = a -", "a plot of a matrix.\"\"\" fig, ax = plt.subplots(1, 1)", "has not converged.\") singular_values = np.array(singular_values_list) singular_values = singular_values[singular_values >", "q * ds # a += delta_1(\"+\") * lambda_h(\"+\") *", "'DQ' if use_quads else 'DG' trace_family = \"HDiv Trace\" U", "a += 0.5 * inner(u + grad(p), grad(q) - v)", ") return result def solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True ): #", "matplotlib from scipy.linalg import svd from scipy.sparse.linalg import svds from", "0.5, color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0] - 0.5, color=\"k\") return plot", "ax.axhline(y=f0_size[0] + f1_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0] -", "TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities n =", "* div(v) * dx # Weakly imposed boundary conditions a", "q * ds # is this necessary? L += s", "M = Mnp.toarray() singular_values = svd(M, compute_uv=False, check_finite=False) singular_values =", "q = TestFunctions(W) # Mesh entities h = CellDiameter(mesh) x,", "the Badia-Codina paper # Mixed classical terms a = (dot(u,", "/ h # Symmetry term. Choose if the method is", "terms a = delta_1 * inner(u + grad(p), v +", "terms # a += jump(u, n) * jump(v, n) *", "name='Exact velocity') sigma_e.project(-grad(p_exact)) # BCs bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\")", "def solve_poisson_dgls(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell())", "0.5 * inner(curl(u), curl(v)) * dx A = assemble(a, bcs=bcs,", "and test functions u = TrialFunction(V) v = TestFunction(V) #", "dx a += eta_p * div(u) * div(v) * dx", "# a += 0.5 * inner(u + grad(p), grad(q) -", "* dx # Edge stabilizing terms # ** Badia-Codina based", "= FunctionSpace(mesh, trace_family, degree) W = U * V *", "= SpatialCoordinate(mesh) # Exact solution p_exact = sin(2 * pi", "delta_3 * inner(curl(u), curl(v)) * dx # Hybridization terms a", "# Weak boundary conditions a += s * dot(p *", "+= delta_1 * jump(u_hat, n=n) * q(\"+\") * dS #", "of a matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat =", "- div(v) * p) * dx a += delta_1(\"+\") *", "hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4, numel_xy=(5, 10, 15, 20, 25), quadrilateral=True,", "h # Least-squares terms a = delta_0 * inner(u +", "B in the Badia-Codina paper eta_u = 1 # eta_u_bc", "= Constant(1) delta_3 = Constant(1) # Least-squares terms a =", "solvers_options = { # \"cg\": solve_poisson_cg, # \"cgls\": solve_poisson_cgls, #", "dot(u_hat, n) * q * ds F = a -", "pressure\", \"label\") # Forcing function f_expression = div(-grad(p_exact)) f =", "pressure_family, degree) W = U * V # Trial and", "+= jump(v, n) * avg(p) * dS - avg(q) *", "* ds # Weakly imposed BC from hybridization # a", "solution p_exact = sin(2 * pi * x) * sin(2", "* div(v) * dx a += 0.5 * inner(curl(u), curl(v))", "paper eta_u = h / L0 # method B in", "pressure\", \"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # BCs", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_mixed_RT(mesh, degree=1): # Function", "a += beta(\"+\") * dot(jump(p, n), jump(q, n)) * dS", "= TestFunctions(W) # Mesh entities n = FacetNormal(mesh) h =", "form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result", "0.5, color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] +", "the convergence study hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree + last_degree, quadrilateral=True,", "DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter s = Constant(-1.0) beta", "np.argwhere(np.all(Mnp[..., :] == 0, axis=0)) Mnp = np.delete(Mnp, idx, axis=1)", "return result def solve_poisson_mixed_RT(mesh, degree=1): # Function space declaration use_quads", "degree) V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement =", "pbar.set_description(f\"Processing {name} - degree = {degree} - N = {n}\")", "avg(q) * jump(u, n) * dS # Edge stabilizing terms", "* dot(v, n) * ds # Flux Least-squares as in", "(jump(u, n) * jump(v, n)) * dS a += (avg(eta_u)", "stabilizing terms # ** Badia-Codina based (better results) ** a", "values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] -", "/ h_avg) * dot(jump(p, n), jump(q, n)) * dS #", "'RT' pressure_family = 'DG' U = FunctionSpace(mesh, hdiv_family, degree +", "C0TraceElement) else: T = FunctionSpace(mesh, trace_family, degree) W = U", "dx L = f * q * dx # Hybridization", "\"Symmetric\": list(), \"nnz\": list(), \"dofs\": list(), \"h\": list(), \"Condition Number\":", "quadrilateral else 1 / n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n *", "# my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form, result.bcs,", "petsc_mat = assembled_form.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size)", "(dot(u, n) - dot(u_projected, n))) * ds a += beta", "- dot(grad(p), q * n) * ds a += beta", "'DG' velocity_family = 'DQ' if use_quads else 'DG' trace_family =", "= { \"Element\": list(), \"Number of Elements\": list(), \"Degree\": list(),", "Mnp.toarray() # Eliminate rows and columns filled with zero entries", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_vms(mesh, degree=1): # Function", "velocity') sigma_e.project(-grad(p_exact)) # BCs bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") #", "- v) * dx # a += 0.5 * h", "from scipy.sparse import csr_matrix from slepc4py import SLEPc import pandas", "least-square a += delta_2 * div(u) * div(v) * dx", "singular_values = singular_values[singular_values > zero_tol] condition_number = singular_values.max() / singular_values.min()", "S = SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve()", "real_part_array def calculate_condition_number( A, num_of_factors, backend: str = \"scipy\", use_sparse:", "ax.axvline(x=f0_size[0] - 0.5, color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0] - 0.5, color=\"k\")", "# Trial and test functions u = TrialFunction(V) v =", "p - q * div(u)) * dx # Stabilizing terms", "DirichletBC(V, 0.0, \"on_boundary\") # Variational form a = inner(grad(u), grad(v))", "if use_quads else 'DG' U = VectorFunctionSpace(mesh, velocity_family, degree) V", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dls(mesh, degree=1):", "ds # Weakly imposed BC from hybridization # a +=", "= delta_2 * f * div(v) * dx # Irrotational", "# Mesh entities h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh)", "S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values = S.getConverged() singular_values_list =", "Constant(1) # delta_2 = Constant(1) # delta_3 = Constant(1) #", "* dot(u, n) * dot(v, n) * ds # **", "lambda_h(\"+\") * jump(v, n) * dS a += -dot(u, grad(q))", "delta_1 * p_exact * dot(v, n) * ds # Flux", "if use_quads else \"DG\" V = FunctionSpace(mesh, primal_family, degree) if", "function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Edge stabilizing", "solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration use_quads", "Hybridization terms a += lambda_h(\"+\") * dot(v, n)(\"+\") * dS", "* L0 # method D in the Badia-Codina paper #", "svd(M, compute_uv=False, check_finite=False) singular_values = singular_values[singular_values > zero_tol] condition_number =", "float = 1e-5) -> np.ndarray: \"\"\"Utility function to filter real", "result = ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric,", "assembled_form = attr.ib() condition_number = attr.ib() sparse_operator = attr.ib() number_of_dofs", "options solvers_options = { # \"cg\": solve_poisson_cg, # \"cgls\": solve_poisson_cgls,", "Flux Least-squares as in DG a = delta_0 * inner(u", "Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = Mnp.shape[0] num_of_factors = int(number_of_dofs)", "= Constant(1) # delta_3 = Constant(1) # delta_4 = Constant(1)", "Stabilization parameters delta_0 = Constant(-1) delta_1 = Constant(-0.5) * h", "terms a += delta_1 * inner(u + grad(p), v +", "TestFunctions(W) # Mesh entities h = CellDiameter(mesh) x, y =", "# Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return", "= 'CG' U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh,", "color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def plot_matrix_primal_hybrid_full(a_form, bcs=[],", "def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a plot of a mixed matrix.\"\"\"", "* n) * ds a += beta * p *", "S.getValue(i) singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc SVD has not converged.\") singular_values", "A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric =", "df_cond_number # Solver options solvers_options = { # \"cg\": solve_poisson_cg,", "size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp =", "dot(v, n) * ds # Flux Least-squares as in DG", "Eliminate rows and columns filled with zero entries Mnp =", "stabilizing terms a += delta_1 * (dot(u, v) - div(v)", "return real_part_array def calculate_condition_number( A, num_of_factors, backend: str = \"scipy\",", "* q(\"+\") * dS # a += delta_1(\"+\") * dot(u_hat,", "\"\"\"Provides a plot of a mixed matrix.\"\"\" fig, ax =", "bcs=bc_multiplier ) return result def solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False ):", "# Stabilization parameters delta_1 = Constant(1) delta_2 = Constant(1) delta_3", "Constant(1) # delta_5 = Constant(1) # LARGE_NUMBER = Constant(1e0) delta", "+= (beta / h_avg) * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\")", "= LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: trace_family = \"HDiv", "= p_exact bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter", "Trial and test functions u = TrialFunction(V) v = TestFunction(V)", "and test functions u, p = TrialFunctions(W) v, q =", "mu_h(\"+\")) * dS # Boundary terms # a += -dot(vel_projected,", "* h # delta = Constant(1) # delta = h", "BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Mixed classical terms", "/ h # beta = beta_0 # Numerical flux trace", "dot(v, n) * p * ds - q * dot(u,", "use_quads else 'DG' trace_family = \"HDiv Trace\" U = VectorFunctionSpace(mesh,", "= Function(V).interpolate(f_expression) # Dirichlet BCs p_boundaries = Constant(0.0) bc_multiplier =", "singular_values[singular_values > zero_tol] condition_number = singular_values.max() / singular_values.min() else: raise", "Edge stabilizing terms # ** Badia-Codina based (better results) **", "2] Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle is_symmetric =", "solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg, } degree = 1 last_degree =", "A[:2, :2].inv * A[:2, 2] Smat = assemble(S, bcs=bc_multiplier) petsc_mat", "= \"scipy\", use_sparse: bool = False, zero_tol: float = 1e-5", "+= delta_2 * inner(curl(u), curl(v)) * dx # Edge stabilizing", "entities n = FacetNormal(mesh) h = CellDiameter(mesh) x, y =", "= singular_values[singular_values > zero_tol] condition_number = singular_values.max() / singular_values.min() else:", "\"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # BCs bcs", "results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name,", "B in the Badia-Codina paper # eta_p = L0 *", "# Weakly imposed BC a += dot(u_hat, n) * q", "dx # Hybridization terms a += lambda_h(\"+\") * dot(v, n)(\"+\")", "= beta_0 / h(\"+\") # Stabilizing parameter # delta_0 =", "div(v) * dx a += delta_3 * inner(curl(u), curl(v)) *", "curl(v)) * dx # ** Badia-Codina based a += -eta_u", "h) * dot(p * n, q * n) * ds", "petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize() Mnp", "= calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp,", "a += eta_u_bc * delta_3 * p * q *", "else 'DG' U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh,", "+= delta_2 * f * div(v) * dx # Hybridization", "def plot_matrix(assembled_form, **kwargs): \"\"\"Provides a plot of a matrix.\"\"\" fig,", "np.ndarray: \"\"\"Utility function to filter real part in a numpy", "SIPG (-1) or NIPG (1) s = Constant(-1) # Classical", "0.5, color=\"k\") return plot def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a", "a += delta_3 * inner(curl(u), curl(v)) * dx L +=", "# LARGE_NUMBER = Constant(1e0) delta = h * h #", "( # (mu_h - q) * (lambda_h - p_boundaries) *", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dgls(mesh, degree=1): # Function", "inner(curl(u), curl(v)) * dx # L += 0.5 * f", "a = delta_0 * inner(u + grad(p), v + grad(q))", "- v) * dx a += eta_p * div(u) *", "# # L = delta_1 * p_exact * dot(v, n)", "paper # Mixed classical terms a = (dot(u, v) -", ") return result def solve_poisson_dgls(mesh, degree=1): # Function space declaration", "\"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0) beta = beta_0", "ds A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric =", ":idx].inv * A[:idx, idx] Smat = assemble(S, bcs=bcs) petsc_mat =", "eta_p = L0 * h_avg # method B in the", "= FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh,", "N, quadrilateral=True) # result = solve_poisson_lsh(mesh, degree=1) # print(f'Is symmetric?", "plt.subplots(1, 1) assembled_form = assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle", "UnitSquareMesh(n, n, quadrilateral=quadrilateral) result = solver(mesh, degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min()", "# \"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg, # \"cgh\": solve_poisson_cgh, #", "= A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp =", "Constant(-0.5) * h * h delta_2 = Constant(0.5) * h", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_vms(mesh, degree=1): #", "paper eta_p = 1 # eta_p = L0 * L0", "ds a += (eta_u / h) * dot(p * n,", "N = 5 # mesh = UnitSquareMesh(N, N, quadrilateral=True) #", "### # a += ( # (mu_h - q) *", "# Weakly imposed boundary conditions a += dot(v, n) *", "degree + 1) V = FunctionSpace(mesh, pressure_family, degree) W =", "a += s * dot(jump(p, n), avg(grad(q))) * dS -", "Number: {result.condition_number}') # # Plotting the resulting matrix # matplotlib.use('TkAgg')", "boundary conditions a += s * dot(p * n, grad(q))", "} element_kind = \"Quad\" if quadrilateral else \"Tri\" pbar =", "singular_value = S.getValue(i) singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc SVD has not", "p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e0) beta =", "- 0.5, color=\"k\") return plot def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides", "# Volumetric stabilizing terms # a += 0.5 * h", "-delta_1 * dot(u_projected, n) * q * ds # a", "0.5 * h * h * f * div(v) *", "p_boundaries * ds F = a - L a_form =", "- dot(v_hat, n)) * ds # Weakly imposed BC from", "# * dx # ) # # These terms below", "and test functions # solution = Function(W) # u, p,", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def", "= TestFunctions(W) # Mesh entities x, y = SpatialCoordinate(mesh) #", "Solver options solvers_options = { # \"cg\": solve_poisson_cg, # \"cgls\":", "p_boundaries) * ds # ) # maybe this is not", "* inner(curl(u), curl(v)) * dx # L += 0.5 *", "a += 0.5 * inner(curl(u), curl(v)) * dx # L", "Constant(1) # delta_1 = Constant(1) # delta_2 = Constant(1) #", "B in the Badia-Codina paper eta_p = 1 # eta_p", "* f * div(v) * dx A = assemble(a, bcs=bcs,", "p) * dx + lambda_h(\"+\") * jump(v, n) * dS", "solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg, # \"cgh\": solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc,", "os matplotlib.use('Agg') @attr.s class ConditionNumberResult(object): form = attr.ib() assembled_form =", "V = FunctionSpace(mesh, pressure_family, degree) # Trial and test functions", "= TestFunctions(W) # Mesh entities h = CellDiameter(mesh) x, y", "terms a += mu_h(\"+\") * jump(u_hat, n=n) * dS a", "eta_p = L0 * L0 # method D in the", "# result = solve_poisson_lsh(mesh, degree=1) # print(f'Is symmetric? {result.is_operator_symmetric}') #", "= 1 # eta_p = L0 * h_avg # method", "attr.ib() sparse_operator = attr.ib() number_of_dofs = attr.ib() nnz = attr.ib()", "= _A.blocks idx = trace_index S = A[idx, idx] -", "* inner(curl(u), curl(v)) * dx # Weakly imposed boundary conditions", "ax.axvline(x=f0_size[0] + f1_size[0] - 0.5, color=\"k\") return plot def plot_matrix_hybrid_multiplier(a_form,", "shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = Mnp.shape[0] num_of_factors =", "trace_family = \"HDiv Trace\" V = FunctionSpace(mesh, pressure_family, degree) if", "* p) * dx a += delta_1(\"+\") * lambda_h(\"+\") *", "color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[],", "str = \"scipy\", use_sparse: bool = False, zero_tol: float =", "0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0] -", "): # Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\"", "# Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" if", "delta_3 = Constant(0.5) * h * h # Mixed classical", "+= 0.5 * inner(curl(u), curl(v)) * dx # ** Badia-Codina", "lambda_h) * n # HDG classical form a = -dot(u,", "else: T = FunctionSpace(mesh, trace_family, degree) W = V *", "+ h(\"-\")) / 2.0 # Jump stabilizing parameters based on", "def hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4, numel_xy=(5, 10, 15, 20, 25),", "list(), } element_kind = \"Quad\" if quadrilateral else \"Tri\" pbar", "n, grad(q)) * ds - dot(grad(p), q * n) *", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_mixed_RT(mesh, degree=1): # Function space", "n, q * n) * ds # may decrease convergente", "n v_hat = v + beta * (q - mu_h)", "result def solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False ): # Function space", "csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = W.dim() num_of_factors", "is not a classical Nitsche's method a += (eta_p /", "solve_poisson_dvms(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "= div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs p_boundaries =", "= FunctionSpace(mesh, pressure_family, degree) # Trial and test functions p", "{result.condition_number}') # # Plotting the resulting matrix # matplotlib.use('TkAgg') #", "(mu_h - q) * (lambda_h - p_boundaries) * ds #", "p = TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities", "the spy alternative # plot = plt.spy(Am, **kwargs) # Remove", "number_of_dofs = W.dim() num_of_factors = int(number_of_dofs) - 1 condition_number =", "'DQ' if use_quads else 'DG' V = FunctionSpace(mesh, pressure_family, degree)", "on Badia-Codina stabilized dG method L0 = 1 eta_p =", "L0 # method B in the Badia-Codina paper # Mixed", "* n) * ds # may decrease convergente rates #", "# Volumetric stabilizing terms # a += 0.5 * inner(u", "v) - div(v) * p) * dx + lambda_h(\"+\") *", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False", "= LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: T = FunctionSpace(mesh,", "(dot(u, v) - div(v) * p) * dx a +=", "form = attr.ib() assembled_form = attr.ib() condition_number = attr.ib() sparse_operator", "1e-5) -> np.ndarray: \"\"\"Utility function to filter real part in", "dx a += 0.5 * div(u) * div(v) * dx", "= assemble(S, bcs=bcs) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size", "+= 0.5 * h * h * div(u) * div(v)", "color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0] - 0.5, color=\"k\") return plot def", "* mu_h * ds F = a - L a_form", "condition_number = calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number,", "Mesh independent (original) # a += jump(u, n) * jump(v,", "u_projected = sigma_e p_boundaries = p_exact bcs = DirichletBC(W.sub(2), p_exact,", "entities x, y = SpatialCoordinate(mesh) # Exact solution p_exact =", "h * h # Mixed classical terms a = (dot(u,", "* lambda_h(\"+\") * jump(v, n=n) * dS a += delta_1", "n)) * (dot(v, n) - dot(v_hat, n)) * ds #", "# Hybridization terms a += s * dot(grad(q), n)(\"+\") *", "* dx a += delta_3 * inner(curl(u), curl(v)) * dx", "dx a += delta_2 * inner(curl(u), curl(v)) * dx #", "original paper # a += dot(jump(p, n), jump(q, n)) *", "a += delta_2 * inner(curl(u), curl(v)) * dx # Edge", "else 'DG' velocity_family = 'DQ' if use_quads else 'DG' U", "its kwargs solver = solvers_options[current_solver] # Performing the convergence study", "if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement = LagrangeElement[\"facet\"]", "= Mnp.nnz number_of_dofs = Mnp.shape[0] num_of_factors = int(number_of_dofs) - 1", "results_dict[\"Number of Elements\"].append(n * n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size)", "cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap) # # plot_matrix(result.assembled_form, cmap=my_cmap)", "/ L0 # method B in the Badia-Codina paper eta_u_bc", "of Elements\"].append(n * n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition", "- q * div(u)) * dx # DG terms a", "+= delta_1 * div(u) * div(v) * dx a +=", "terms below are based on ASGS Badia-Codina (2010), it is", "matrix plot = ax.matshow(Am, **kwargs) # Below there is the", "inner(u + grad(p), v + grad(q)) * dx a +=", "result def solve_poisson_cgls(mesh, degree=1): # Function space declaration pressure_family =", "decrease convergente rates # ** Classical Nitsche # a +=", "+= eta_p * div(u) * div(v) * dx a +=", "h) * (p- p_boundaries) * q * ds # is", "# ### # a += ( # (mu_h - q)", "= pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results) return df_cond_number", "= str(mesh.ufl_cell()) == \"quadrilateral\" primal_family = \"DQ\" if use_quads else", "bcs=result.bcs, cmap=my_cmap) # # plot_matrix(result.assembled_form, cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form, cmap=my_cmap)", "dot(u, n) * ds # ** The terms below are", "Mnp = np.delete(Mnp, idx, axis=1) Am = np.ma.masked_values(Mnp, 0, rtol=1e-13)", "the Badia-Codina paper eta_u_bc = 1 # Least-Squares weights delta", "* dS # a += p * q * ds", "= Constant(0.5) * h * h delta_3 = Constant(0.5) *", "TrialFunction(V) v = TestFunction(V) # Dirichlet BCs bcs = DirichletBC(V,", "import matplotlib.pyplot as plt import matplotlib from scipy.linalg import svd", "# a += delta_1 * lambda_h * dot(v, n) *", "= \"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results) return df_cond_number # Solver options", "calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs,", "h delta_2 = Constant(0.5) * h * h delta_3 =", "DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\") # Average cell size and mesh", "pressure_family = 'DG' U = FunctionSpace(mesh, hdiv_family, degree + 1)", "+= 0.5 * f * div(v) * dx # **", "considered in the original paper # a += dot(jump(p, n),", "plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap) # # plot_matrix(result.assembled_form, cmap=my_cmap) # #", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def", "ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return", "NotImplementedError(\"The required method for condition number estimation is currently unavailable.\")", "velocity_family = 'CG' U = VectorFunctionSpace(mesh, velocity_family, degree) V =", "= delta # delta_4 = LARGE_NUMBER / h delta_5 =", "1 / h delta_4 = 1 / h # Least-squares", "= 'DQ' if use_quads else 'DG' V = FunctionSpace(mesh, pressure_family,", "mu_h(\"+\")) * dS a += (beta / h_avg) * (p(\"+\")", "ds # ) # maybe this is not a good", "is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True", "grad(p), grad(q) - v) * dx a += eta_p *", "# Plotting the resulting matrix # matplotlib.use('TkAgg') # import copy", "assembled_form.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp", "* dx a += delta_1 * div(u) * div(v) *", "q * ds # may decrease convergente rates (Nitsche) A", "mixed Darcy eq. first-order terms as stabilizing terms a +=", "the Badia-Codina paper eta_u = h / L0 # method", "petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size = petsc_mat.getSize()", "# Least-squares terms a = delta_1 * inner(u + grad(p),", "* dot(u, n) * dot(v, n) * ds a +=", "dot(jump(p, n), jump(q, n)) * dS a += eta_u_bc *", "1 # eta_p = L0 * L0 # method D", "+= -eta_u * inner(u + grad(p), v + grad(q)) *", "+ jump(u_hat, n) * q(\"+\") * dS L = f", "* ds # a += delta_5 * (dot(u, n)(\"+\") -", "x, y = SpatialCoordinate(mesh) # Exact solution p_exact = sin(2", "* sin(2 * pi * y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact", "eta_p = 1 # eta_p = L0 * L0 #", "* dot(v, n) * ds a += dot(u_hat, n) *", "jump(q, n)) * dS # Volumetric stabilizing terms # a", "= (dot(u, v) - div(v) * p + delta_0 *", ") return result def solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False ): #", "# ** Mesh independent terms # a += jump(u, n)", "delta delta_4 = delta # delta_4 = LARGE_NUMBER / h", "the Badia-Codina paper eta_p = 1 # eta_p = L0", "mu_h(\"+\") * jump(u_hat, n=n) * dS a += delta_4(\"+\") *", "singular_values.max() / singular_values.min() else: raise NotImplementedError(\"The required method for condition", "this is not a good way to impose BC, but", "# a += (beta / h) * (p- p_boundaries) *", "* div(u)) * dx # DG terms a += jump(v,", "p_boundaries) * ds # a += mu_h * lambda_h *", "in the original paper # a += dot(jump(p, n), jump(q,", "Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # BCs bcs = DirichletBC(W.sub(2), p_exact,", "else 'DG' velocity_family = 'DQ' if use_quads else 'DG' trace_family", "solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration use_quads", "* A[:1, 1] Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle", "jump(u_hat, n) * q(\"+\") * dS L = f *", "1].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp", "convergente rates (Nitsche) A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle", "dx L = delta_0 * f * q * dx", "# method D in the Badia-Codina paper eta_u = h", "jump(q, n)) * dS # Edge stabilizing terms a +=", "impose BC, but this necessary _A = Tensor(a) A =", "max_degree=degree + last_degree, quadrilateral=True, name=name ) # N = 5", "plot of a full hybrid-mixed matrix.\"\"\" fig, ax = plt.subplots(1,", "beta * (lambda_h - p_boundaries) * mu_h * ds F", "- mu_h(\"+\")) * dS # Boundary terms # a +=", "= V.dim() num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat,", "- p_boundaries) * ds # a += mu_h * lambda_h", "result def solve_poisson_mixed_RT(mesh, degree=1): # Function space declaration use_quads =", "- mu_h) * ds # a += delta_5 * (dot(u,", "Jump stabilizing parameters based on Badia-Codina stabilized dG method L0", "dS + mu_h(\"+\") * dot(u, n)(\"+\") * dS a +=", "f * div(v) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\")", "nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_lsh( mesh, degree=1,", "print(f'Is symmetric? {result.is_operator_symmetric}') # print(f'nnz: {result.nnz}') # print(f'DoFs: {result.number_of_dofs}') #", "# delta_4 = Constant(1) # delta_5 = Constant(1) # LARGE_NUMBER", "jump(v, n)) * dS a += eta_p * avg(delta_4) *", "Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs # bcs =", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sipg(mesh, degree=1): #", "# \"vms\": solve_poisson_vms, # \"dvms\": solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT, #", "* inner(u + grad(p), grad(q) - v) * dx #", "Trial and test functions # solution = Function(W) # u,", "h = CellDiameter(mesh) h_avg = avg(h) # Classical term a", "decrease convergente rates # ** The terms below are based", "\"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg, # \"cgh\": solve_poisson_cgh, # \"ldgc\":", ") return result def solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False ): #", "# Selecting the solver and its kwargs solver = solvers_options[current_solver]", "= Mnp.toarray() singular_values = svd(M, compute_uv=False, check_finite=False) singular_values = singular_values[singular_values", "* ds a += (eta_u / h) * dot(p *", "copy # my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form,", "bcs = DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\") # Average cell size", "= assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size = petsc_mat.getSize() Mnp", ":idx] * A[:idx, :idx].inv * A[:idx, idx] Smat = assemble(S,", "def solve_poisson_dls(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell())", "* p + delta_0 * q * div(u)) * dx", "f * q * dx # Stabilizing terms a +=", "h / L0 # method B in the Badia-Codina paper", "* div(v) * dx a += eta_p * inner(curl(u), curl(v))", "delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) * dS a +=", "= Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs # bcs", ") # N = 5 # mesh = UnitSquareMesh(N, N,", "n in numel_xy: pbar.set_description(f\"Processing {name} - degree = {degree} -", "decrease convergente rates (Nitsche) A = assemble(a, mat_type=\"aij\") petsc_mat =", "with zero entries Mnp = Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[..., :]", "dS # Weakly imposed BC a += (p_boundaries * dot(v,", "singular_values.min() else: raise NotImplementedError(\"The required method for condition number estimation", "f * q * dx # Hybridization terms a +=", "delta_4 = Constant(1) # delta_5 = Constant(1) # LARGE_NUMBER =", "* f * div(v) * dx # a += -0.5", "* h * f * div(v) * dx a +=", "+= (avg(eta_u) / h_avg) * dot(jump(p, n), jump(q, n)) *", "# Mass balance least-square a += delta_2 * div(u) *", "delta_1 * inner(u + grad(p), v + grad(q)) * dx", "numbers. \"\"\" real_part_array = array.real[abs(array.imag) < 1e-5] return real_part_array def", "1e-5 ): backend = backend.lower() if backend == \"scipy\": size", "= backend.lower() if backend == \"scipy\": size = A.getSize() Mnp", "B in the Badia-Codina paper # Mixed classical terms a", "n) + mu_h * (dot(u, n) - dot(u_projected, n))) *", "+= delta_4 * (p - lambda_h) * (q - mu_h)", "0.5 * inner(curl(u), curl(v)) * dx # ** Badia-Codina based", "(dot(u, n) - dot(u_hat, n)) * (dot(v, n) - dot(v_hat,", "ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def filter_real_part_in_array(array: np.ndarray, imag_threshold: float =", "# print(f'Condition Number: {result.condition_number}') # # Plotting the resulting matrix", "ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a", "* (q(\"+\") - mu_h(\"+\")) * dS # Boundary terms #", "- 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0]", "beta_0 = Constant(1.0) beta = beta_0 / h # Mixed", "TrialFunctions(W) v, q, mu_h = TestFunctions(W) # Mesh entities n", "import tqdm import os matplotlib.use('Agg') @attr.s class ConditionNumberResult(object): form =", "+= eta_u_bc * delta_4 * dot(u, n) * dot(v, n)", ") return result def solve_poisson_dls(mesh, degree=1): # Function space declaration", "space declaration pressure_family = 'CG' velocity_family = 'CG' U =", "dx a += delta_2 * div(u) * div(v) * dx", "\"dgls\": solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm, # \"ls\": solve_poisson_ls, # \"dls\":", "+= ( # (mu_h - q) * (lambda_h - p_boundaries)", "h * div(u) * div(v) * dx # a +=", "= assembled_form.M[0, 0].handle.getSize() f1_size = assembled_form.M[1, 1].handle.getSize() size = petsc_mat.getSize()", "solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration use_quads", "\"Degree\": list(), \"Symmetric\": list(), \"nnz\": list(), \"dofs\": list(), \"h\": list(),", "h * h * f * div(v) * dx a", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dvms(mesh, degree=1): # Function", "U = FunctionSpace(mesh, hdiv_family, degree + 1) V = FunctionSpace(mesh,", "n)(\"+\") * dS + mu_h(\"+\") * dot(u, n)(\"+\") * dS", "* ds # # L = -delta_1 * dot(u_projected, n)", "T = FunctionSpace(mesh, trace_family, degree) W = U * V", "+= delta_3 * inner(curl(u), curl(v)) * dx L += delta_2", "(p - lambda_h) * n # HDG classical form a", "+ grad(q)) * dx # a += 0.5 * h", "quadrilateral=True) # result = solve_poisson_lsh(mesh, degree=1) # print(f'Is symmetric? {result.is_operator_symmetric}')", "\"h\": list(), \"Condition Number\": list(), } element_kind = \"Quad\" if", "div(u) * div(v) * dx a += delta_2 * inner(curl(u),", "mesh, degree=1, is_multiplier_continuous=True ): # Function space declaration use_quads =", "Trial and test functions u, p = TrialFunctions(W) v, q", "ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") ax.axhline(y=f0_size[0] +", "\"HDiv Trace\" U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh,", "inner(curl(u), curl(v)) * dx # L += 0.5 * h", "ax = plt.subplots(1, 1) assembled_form = assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat", "= DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e0)", "check_finite=False) singular_values = singular_values[singular_values > zero_tol] condition_number = singular_values.max() /", "** Mesh independent (original) # a += jump(u, n) *", "* ds a += dot(u_hat, n) * q * ds", "not converged.\") singular_values = np.array(singular_values_list) singular_values = singular_values[singular_values > zero_tol]", "plt.subplots(1, 1) _A = Tensor(a_form) A = _A.blocks idx =", "dx # a += -0.5 * inner(u + grad(p), v", "# eta_p = 1 # eta_p = L0 * L0", "from scipy.sparse.linalg import svds from scipy.sparse import csr_matrix from slepc4py", "plot_matrix(assembled_form, **kwargs): \"\"\"Provides a plot of a matrix.\"\"\" fig, ax", "matrix.\"\"\" fig, ax = plt.subplots(1, 1) assembled_form = assemble(a_form, bcs=bcs,", "= Constant(1.0) # delta = h delta_0 = delta delta_1", "-eta_u * inner(u + grad(p), v + grad(q)) * dx", "f * div(v) * dx a += 0.5 * div(u)", "a += eta_u * inner(u + grad(p), grad(q) - v)", "\"sipg\": solve_poisson_sipg, } degree = 1 last_degree = 1 for", "# a += 0.5 * inner(curl(u), curl(v)) * dx #", "# a = ( # (inner(u, v) - q *", "paper # eta_u = 1 # Nitsche's penalizing term beta_0", "mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize()", "dx # Transmission condition a += jump(u_hat, n) * mu_h(\"+\")", "* q * div(u)) * dx L = delta_0 *", "functions u, p = TrialFunctions(W) v, q = TestFunctions(W) #", "def filter_real_part_in_array(array: np.ndarray, imag_threshold: float = 1e-5) -> np.ndarray: \"\"\"Utility", "dot(p * n, q * n) * ds # may", "1 # Least-Squares weights delta = Constant(1.0) # delta =", "Function space declaration V = FunctionSpace(mesh, \"CG\", degree) # Trial", "1 for current_solver in solvers_options: # Setting the output file", "imaginary part in complex number. :return: Filtered array with only", "lambda_h * ds # ### # a += ( #", "+ beta * (q - mu_h) * n # Flux", "D in the Badia-Codina paper # eta_u = h_avg /", "parameter s = Constant(-1.0) beta = Constant(32.0) h = CellDiameter(mesh)", "n) * ds # ** Mesh independent ** # a", "singular_values.min() elif backend == \"slepc\": S = SLEPc.SVD() S.create() S.setOperator(A)", "* A[:2, 2] Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle", "# a += delta_5 * (dot(u, n) - dot(u_hat, n))", "- div(v) * p + q * div(u)) * dx", "n) * dot(v, n) * ds a += (eta_u /", "def solve_poisson_dvms(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell())", "use_quads=False): # Function space declaration V = FunctionSpace(mesh, \"CG\", degree)", "* jump(v, n)) * dS a += eta_p * avg(delta_4)", "method for condition number estimation is currently unavailable.\") return condition_number", "* p_boundaries * ds F = a - L a_form", "beta_0 / h beta_avg = beta_0 / h(\"+\") # Stabilizing", "num_converged_values > 0: for i in range(num_converged_values): singular_value = S.getValue(i)", "bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter s =", "a = (dot(u, v) - div(v) * p + q", "* h * h * div(u) * div(v) * dx", "W = V * T # Trial and test functions", "* dS L = f * q * dx #", "# plot = plt.spy(Am, **kwargs) # Remove axis ticks and", "(dot(u, v) - div(v) * p - q * div(u))", "DG a = delta_0 * inner(u + grad(p), v +", "n)) * dS a += eta_p * avg(delta_4) * dot(jump(p,", "# Boundary terms # a += -dot(vel_projected, n) * v", "# a += delta_1 * dot(u, n) * q *", "the Badia-Codina paper # eta_p = 1 # eta_p =", "* h * h * inner(curl(u), curl(v)) * dx #", "backend.lower() if backend == \"scipy\": size = A.getSize() Mnp =", "= 1 # eta_u_bc = h / L0 # method", "s * dot(p * n, grad(q)) * ds - dot(grad(p),", "(eta_p / h) * dot(u, n) * dot(v, n) *", "Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if use_sparse: singular_values = svds(", "velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs # bcs = DirichletBC(W[0], sigma_e,", "* dS # Edge stabilizing terms a += beta(\"+\") *", "result = solve_poisson_lsh(mesh, degree=1) # print(f'Is symmetric? {result.is_operator_symmetric}') # print(f'nnz:", "a += -dot(vel_projected, n) * v * ds # How", "for condition number estimation is currently unavailable.\") return condition_number def", "= delta_1 * inner(u + grad(p), v + grad(q)) *", "h * h * div(u) * div(v) * dx #", "plt.subplots(1, 1) petsc_mat = assembled_form.M.handle size = petsc_mat.getSize() Mnp =", "tqdm import os matplotlib.use('Agg') @attr.s class ConditionNumberResult(object): form = attr.ib()", "singular_values[singular_values > zero_tol] condition_number = singular_values.max() / singular_values.min() elif backend", "mesh dependent stabilization h_avg = (h(\"+\") + h(\"-\")) / 2.0", "# may decrease convergente rates # ** Classical Nitsche #", "= VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree) if", "delta delta_3 = 1 / h delta_4 = 1 /", "is the spy alternative # plot = plt.spy(Am, **kwargs) #", "on ASGS Badia-Codina (2010), it is not a classical Nitsche's", "ds # # L = delta_1 * p_exact * dot(v,", "Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs =", "Mnp.eliminate_zeros() Mnp = Mnp.toarray() # Eliminate rows and columns filled", "return plot def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a plot of a", "delta_4 * dot(u, n) * dot(v, n) * ds #", "A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "n) * q * ds # # L = -delta_1", "a += dot(u_hat, n) * q * ds F =", "- dot(u_hat, n)) * (dot(v, n) - dot(v_hat, n)) *", "a matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle", "plot_matrix(result.assembled_form, cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form, cmap=my_cmap) # plt.tight_layout() # plt.savefig(\"sparse_pattern.png\")", "beta_0 = Constant(1.0) beta = beta_0 / h beta_avg =", "Tensor(a_form) A = _A.blocks idx = trace_index S = A[idx,", "+= beta(\"+\") * dot(jump(p, n), jump(q, n)) * dS #", "plot of a mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1)", "= Mnp.nnz number_of_dofs = V.dim() num_of_factors = int(number_of_dofs) - 1", "return result def hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4, numel_xy=(5, 10, 15,", "= trace_index S = A[idx, idx] - A[idx, :idx] *", "# \"dvms\": solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg, #", "space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" if use_quads: hdiv_family", "n)(\"+\") * (p(\"+\") - lambda_h(\"+\")) * dS a += -dot(grad(p),", "csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = V.dim() num_of_factors", "dS # not considered in the original paper # a", "h * h delta_3 = Constant(0.5) * h * h", "+= delta_3 * inner(curl(u), curl(v)) * dx A = assemble(a,", "* inner(curl(u), curl(v)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\")", "Weakly imposed BC a += (p_boundaries * dot(v, n) +", "v + grad(q)) * dx a += delta_2 * div(u)", "plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of a full hybrid-mixed", "curl(v)) * dx # L += 0.5 * f *", "Constant(1.0e-18) # beta = beta_0 / h beta = beta_0", "* dS # a += delta_5 * (dot(u, n) -", "resulting matrix # matplotlib.use('TkAgg') # import copy # my_cmap =", "n) * mu_h(\"+\") * dS # Weakly imposed BC a", "= 1e-5) -> np.ndarray: \"\"\"Utility function to filter real part", "+= s * dot(grad(q), n) * p_boundaries * ds F", "= SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values", "* p - q * div(u)) * dx # DG", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_sipg(mesh, degree=1): # Function space", "dot(v, n) * ds a += dot(u_hat, n) * q", "Function space declaration pressure_family = 'CG' velocity_family = 'CG' U", "delta # delta_4 = LARGE_NUMBER / h delta_5 = delta", "import SLEPc import pandas as pd from tqdm import tqdm", "# ) # maybe this is not a good way", "Badia-Codina based a += (avg(eta_p) / h_avg) * (jump(u, n)", "* ds - q * dot(u, n) * ds #", "Hybridization terms a += s * dot(grad(q), n)(\"+\") * (p(\"+\")", "rtol=1e-13) # Plot the matrix plot = ax.matshow(Am, **kwargs) #", "= attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs): \"\"\"Provides a plot of a", "beta = beta_0 / h # beta = beta_0 #", "min_degree=1, max_degree=4, numel_xy=(5, 10, 15, 20, 25), quadrilateral=True, name=\"\", **kwargs", "= U * V * T # Trial and test", "* n # HDG classical form a = -dot(u, grad(q))", "= V * T # Trial and test functions #", "f = Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(2), p_exact,", "dS a += -dot(u, grad(q)) * dx + jump(u_hat, n)", "assembled_form.M[0, 0].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "= CellDiameter(mesh) x, y = SpatialCoordinate(mesh) # Exact solution p_exact", "CellDiameter(mesh) x, y = SpatialCoordinate(mesh) # Exact solution p_exact =", "svds from scipy.sparse import csr_matrix from slepc4py import SLEPc import", "# ** Badia-Codina based a += -eta_u * inner(u +", "* v * ds # How to set this bc??", "- q(\"+\")) * dS # Weakly imposed BC a +=", "= csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = Mnp.shape[0]", "/ L0 # method B in the Badia-Codina paper #", "results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True) df_cond_number =", "eta_p * div(u) * div(v) * dx a += eta_p", "else 1 / n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n * n)", "= FunctionSpace(mesh, \"CG\", degree) # Trial and test functions u", "+= 0.5 * f * div(v) * dx A =", "# a += delta_1 * jump(u_hat, n=n) * q(\"+\") *", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_lsh(", "* p + q * div(u)) * dx # DG", "degree) C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: T", "p) * dx a += delta_1(\"+\") * lambda_h(\"+\") * jump(v,", "# eta_u = h_avg / L0 # method B in", "* A[:1, :1].inv * A[:1, 1] Smat = assemble(S, bcs=bc_multiplier)", "= beta_0 / h beta = beta_0 # Stabilization parameters", "S = A[idx, idx] - A[idx, :idx] * A[:idx, :idx].inv", "/ h(\"+\") # Stabilizing parameter # delta_0 = Constant(1) #", "= FacetNormal(mesh) h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh) #", "h * h * inner(curl(u), curl(v)) * dx # L", "jump(u_hat, n) * mu_h(\"+\") * dS # Weakly imposed BC", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_ls(mesh, degree=1): # Function space", "DG terms a += jump(v, n) * avg(p) * dS", "v + grad(q)) * dx a += delta_1 * div(u)", "plt.spy(Am, **kwargs) # Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([])", "# mesh = UnitSquareMesh(N, N, quadrilateral=True) # result = solve_poisson_lsh(mesh,", "= assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0,", "D in the Badia-Codina paper eta_u = h / L0", "* dx a += delta_2 * inner(curl(u), curl(v)) * dx", "form a = inner(grad(u), grad(v)) * dx A = assemble(a,", "n) * dS # Edge stabilizing terms # ** Badia-Codina", "# Hybridization terms a += mu_h(\"+\") * jump(u_hat, n=n) *", "in the Badia-Codina paper # eta_p = 1 # eta_p", "f1_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0] - 0.5, color=\"k\")", "- p * div(v) + inner(grad(p), grad(q))) # * delta_1", "beta = beta_0 / h beta_avg = beta_0 / h(\"+\")", "= plt.subplots(1, 1) petsc_mat = assembled_form.M.handle size = petsc_mat.getSize() Mnp", "Weakly imposed BC from hybridization # a += mu_h *", "converged.\") singular_values = np.array(singular_values_list) singular_values = singular_values[singular_values > zero_tol] condition_number", "L += s * dot(grad(q), n) * p_boundaries * ds", "solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg, } degree =", "return result def solve_poisson_vms(mesh, degree=1): # Function space declaration pressure_family", "terms # a += -dot(vel_projected, n) * v * ds", "* ds # a += mu_h * lambda_h * ds", "but this necessary _A = Tensor(a) A = _A.blocks S", "solve_poisson_dgls(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "grad(v)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat =", "p * ds - q * dot(u, n) * ds", "* q * ds # may decrease convergente rates (Nitsche)", "# \"sdhm\": solve_poisson_sdhm, # \"ls\": solve_poisson_ls, # \"dls\": solve_poisson_dls, \"lsh\":", "function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs", "* ds # # L = delta_1 * p_exact *", "p * q * ds A = assemble(a, mat_type=\"aij\") petsc_mat", "y = SpatialCoordinate(mesh) # Exact solution p_exact = sin(2 *", "ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5,", "* dx a += delta_2 * div(u) * div(v) *", "T = FunctionSpace(mesh, C0TraceElement) else: trace_family = \"HDiv Trace\" T", "dot(p * n, q * n) * ds A =", "* dS # Weakly imposed BC a += (p_boundaries *", "= petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "p * div(v) + inner(grad(p), grad(q))) # * delta_1 #", "Mnp.nnz number_of_dofs = W.dim() num_of_factors = int(number_of_dofs) - 1 condition_number", "quadrilateral=True, name=\"\", **kwargs ): results_dict = { \"Element\": list(), \"Number", "volumetric terms a = inner(grad(p), grad(q)) * dx L =", "_A.blocks idx = trace_index S = A[idx, idx] - A[idx,", "mesh.cell_sizes.dat.data_ro.min() if not quadrilateral else 1 / n results_dict[\"Element\"].append(element_kind) results_dict[\"Number", "= FunctionSpace(mesh, primal_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(),", "Stabilizing parameter # delta_0 = Constant(1) # delta_1 = Constant(1)", "dot(jump(p, n), jump(q, n)) * dS # Weak boundary conditions", "f\"{current_solver}\" # Selecting the solver and its kwargs solver =", "BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Stabilization parameters delta_1", "# Dirichlet BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Mixed", "n) * ds # may decrease convergente rates # **", "L = f * q * dx # Hybridization terms", "= \"HDiv Trace\" T = FunctionSpace(mesh, trace_family, degree) W =", "f * div(v) * dx # a += -0.5 *", "% name df_cond_number.to_csv(path_to_save_results) return df_cond_number # Solver options solvers_options =", "delta_2 = Constant(1) # delta_3 = Constant(1) # delta_4 =", "TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities h =", "terms as stabilizing terms a += delta_1 * (dot(u, v)", "* inner(curl(u), curl(v)) * dx # Hybridization terms a +=", "classical terms a = (dot(u, v) - div(v) * p", "jump(v, n=n) * dS a += delta_1 * lambda_h *", "Constant(1.0e0) beta = beta_0 / h # beta = beta_0", "method is SIPG (-1) or NIPG (1) s = Constant(-1)", "# a += delta_1(\"+\") * dot(u_hat, n) * q *", "VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous:", "ax.matshow(Am, **kwargs) # Below there is the spy alternative #", "+= jump(u, n) * jump(v, n) * dS # a", "_A.blocks S = A[1, 1] - A[1, :1] * A[:1,", "from firedrake import * import numpy as np import matplotlib.pyplot", "= Constant(1) # delta_4 = Constant(1) # delta_5 = Constant(1)", "size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz =", "array.real[abs(array.imag) < 1e-5] return real_part_array def calculate_condition_number( A, num_of_factors, backend:", "trace u_hat = u + beta * (p - lambda_h)", "* q * dx # DG edge terms a +=", "p, lambda_h = split(solution) u, p, lambda_h = TrialFunctions(W) v,", "* div(u) * div(v) * dx a += delta_2 *", "S = A[1, 1] - A[1, :1] * A[:1, :1].inv", "\"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs", "np import matplotlib.pyplot as plt import matplotlib from scipy.linalg import", "matplotlib.pyplot as plt import matplotlib from scipy.linalg import svd from", "(q(\"+\") - mu_h(\"+\")) * dS # Boundary terms # a", "# Weakly imposed BC from hybridization # a += mu_h", "* dot(u, n) * ds a += beta * p", "n) * ds a += beta * p * q", "* p * q * ds # may decrease convergente", "dx + lambda_h(\"+\") * jump(v, n) * dS a +=", "# a += mu_h * lambda_h * ds # ###", "a += delta_5 * (dot(u, n)(\"+\") - dot(u_hat, n)(\"+\")) *", "Constant(1) delta_3 = Constant(1) # Least-squares terms a = delta_1", "condition_number = calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number,", "degree) # Trial and test functions u = TrialFunction(V) v", "** Mesh independent terms # a += jump(u, n) *", "The terms below are based on ASGS Badia-Codina (2010), it", "a += delta_1 * jump(u_hat, n=n) * q(\"+\") * dS", "array with only real numbers. \"\"\" real_part_array = array.real[abs(array.imag) <", "Plot the matrix plot = ax.matshow(Am, **kwargs) # Below there", "inner(curl(u), curl(v)) * dx L += delta_2 * f *", "**kwargs): \"\"\"Provides a plot of a matrix.\"\"\" fig, ax =", "name df_cond_number.to_csv(path_to_save_results) return df_cond_number # Solver options solvers_options = {", "Classical Nitsche # a += beta * p * q", "p, lambda_h = TrialFunctions(W) v, q, mu_h = TestFunctions(W) #", "= { # \"cg\": solve_poisson_cg, # \"cgls\": solve_poisson_cgls, # \"dgls\":", "(q - mu_h) * n # Flux least-squares # a", "* (p(\"+\") - lambda_h(\"+\")) * dS a += -dot(grad(p), n)(\"+\")", "= delta delta_3 = delta delta_4 = delta # delta_4", "mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() f1_size =", "use_quads else 'DG' U = VectorFunctionSpace(mesh, velocity_family, degree) V =", "beta = beta0 / h # Symmetry term. Choose if", "imposed BC a += lambda_h * dot(v, n) * ds", "+= delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) * dS a", ":1].inv * A[:1, 1] Smat = assemble(S, bcs=bc_multiplier) petsc_mat =", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_ldgc(", "zero_tol: float = 1e-5 ): backend = backend.lower() if backend", "else: trace_family = \"HDiv Trace\" T = FunctionSpace(mesh, trace_family, degree)", "# not considered in the original paper # a +=", "necessary? L += s * dot(grad(q), n) * p_boundaries *", "may decrease convergente rates (Nitsche) A = assemble(a, mat_type=\"aij\") petsc_mat", "results) ** a += eta_u * avg(delta_3) * (jump(u, n)", "+= s * dot(p * n, grad(q)) * ds -", "a condensed hybrid-mixed matrix for single scale problems.\"\"\" fig, ax", "1) assembled_form = assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size", "velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree) W = U", "U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree)", "delta_3 = Constant(1) # Least-squares terms a = delta_1 *", "dx # a += 0.5 * div(u) * div(v) *", "parameter beta_0 = Constant(1.0e-18) # beta = beta_0 / h", "assembled_form.M[0, 0].handle.getSize() f1_size = assembled_form.M[1, 1].handle.getSize() size = petsc_mat.getSize() Mnp", "# Plot the matrix plot = ax.matshow(Am, **kwargs) # Remove", "* div(v) * dx # a += -0.5 * inner(u", "# Function space declaration pressure_family = 'CG' velocity_family = 'CG'", "DirichletBC(W[0], sigma_e, \"on_boundary\") # Stabilization parameters delta_1 = Constant(1) delta_2", "the solver and its kwargs solver = solvers_options[current_solver] # Performing", "\"\"\"Utility function to filter real part in a numpy array.", "delta_1 # * dx # ) # # These terms", "A[:2, :2].inv * A[:2, 2] Smat = assemble(S, bcs=bcs) petsc_mat", "\"ls\": solve_poisson_ls, # \"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh, # \"vms\": solve_poisson_vms,", "ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot", "* A[:idx, idx] Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle", "Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp = Mnp.toarray() # Eliminate", "# Flux Least-squares as in DG a = delta_0 *", "Dirichlet BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Stabilization parameters", "delta delta_1 = delta delta_2 = delta delta_3 = delta", "# Mesh entities n = FacetNormal(mesh) h = CellDiameter(mesh) x,", "# method B in the Badia-Codina paper # eta_u =", "1 # eta_p = L0 * h_avg # method B", "FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement)", "div(u) - p * div(v) + inner(grad(p), grad(q))) # *", "= delta delta_2 = delta delta_3 = 1 / h", "L0 * h_avg # method B in the Badia-Codina paper", "delta_1 * lambda_h * dot(v, n) * ds # Mass", "jump(v, n) * dS # a += dot(jump(p, n), jump(q,", "Mesh independent ** # a += jump(u, n) * jump(v,", "rates (Nitsche) A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric", "n) * dot(v, n) * ds # ** Mesh independent", "is this necessary? L += s * dot(grad(q), n) *", "'DQ' if use_quads else 'DG' velocity_family = 'DQ' if use_quads", "= TrialFunctions(W) q, mu_h = TestFunctions(W) # Mesh entities n", "p + q * div(u)) * dx # DG terms", "= 1e-5 ): backend = backend.lower() if backend == \"scipy\":", "dot(grad(p), q * n) * ds a += beta *", "# BCs bcs = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter", "backend: str = \"scipy\", use_sparse: bool = False, zero_tol: float", "else 'DG' trace_family = \"HDiv Trace\" V = FunctionSpace(mesh, pressure_family,", "# Dirichlet BCs bc_multiplier = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization", "# beta = beta_0 # Numerical flux trace u_hat =", "p, lambda_h = TrialFunctions(W) q, mu_h = TestFunctions(W) # Mesh", "bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size", "N = {n}\") mesh = UnitSquareMesh(n, n, quadrilateral=quadrilateral) result =", "may decrease convergente rates a += eta_u_bc * delta_4 *", "# \"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh, # \"vms\": solve_poisson_vms, # \"dvms\":", "result def solve_poisson_dvms(mesh, degree=1): # Function space declaration use_quads =", "beta * (q - mu_h) * n # Flux least-squares", "1 / h # Least-squares terms a = delta_0 *", "\"on_boundary\") # Mixed classical terms a = (dot(u, v) -", "= 1 for current_solver in solvers_options: # Setting the output", "for i in range(num_converged_values): singular_value = S.getValue(i) singular_values_list.append(singular_value) else: raise", "term beta_0 = Constant(1.0) beta = beta_0 / h #", "solver = solvers_options[current_solver] # Performing the convergence study hp_refinement_cond_number_calculation( solver,", "# delta_4 = LARGE_NUMBER / h delta_5 = delta #", "plot def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of a", "def solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration", "f = Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(1), p_exact,", "bcs=bcs ) return result def hp_refinement_cond_number_calculation( solver, min_degree=1, max_degree=4, numel_xy=(5,", "test functions u, p = TrialFunctions(W) v, q = TestFunctions(W)", "assembled_form = assemble(a_form, bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size =", "Dirichlet BCs bc_multiplier = DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter", "def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of a full", "= Constant(1) # Least-squares terms a = delta_1 * inner(u", "0.5 * div(u) * div(v) * dx # a +=", "= \"DQ\" if use_quads else \"DG\" V = FunctionSpace(mesh, primal_family,", "- N = {n}\") mesh = UnitSquareMesh(n, n, quadrilateral=quadrilateral) result", "h * h delta_2 = Constant(0.5) * h * h", "inner(curl(u), curl(v)) * dx # Hybridization terms a += mu_h(\"+\")", "* div(v) * dx # a += 0.5 * div(u)", "* dS # Weakly imposed BC a += lambda_h *", "test functions u = TrialFunction(V) v = TestFunction(V) # Dirichlet", "FunctionSpace(mesh, primal_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree)", "degree = {degree} - N = {n}\") mesh = UnitSquareMesh(n,", "\"vms\": solve_poisson_vms, # \"dvms\": solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\":", "Variational form a = inner(grad(u), grad(v)) * dx A =", "results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict)", "in the Badia-Codina paper eta_u = h / L0 #", "L0 # method B in the Badia-Codina paper eta_u =", "\"sdhm\": solve_poisson_sdhm, # \"ls\": solve_poisson_ls, # \"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh,", "(dot(u, v) - div(v) * p) * dx + lambda_h(\"+\")", "beta_0 # Numerical flux trace u = -grad(p) u_hat =", "* jump(u_hat, n=n) * dS a += delta_4(\"+\") * (p(\"+\")", "# Numerical flux trace u_hat = u + beta *", "f * div(v) * dx # Hybridization terms a +=", "velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\")", "convergence study hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree + last_degree, quadrilateral=True, name=name", "assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size", "trace_family = \"HDiv Trace\" U = VectorFunctionSpace(mesh, velocity_family, degree) V", "real and complex numbers. :param imag_threshold: Threshold to cut off", "degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min() if not quadrilateral else 1 /", "delta_1 * (dot(u, v) - div(v) * p) * dx", "\"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG' trace_family =", "form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return", "# Exact solution p_exact = sin(2 * pi * x)", ") # # These terms below are unsymmetric # a", "trace_index=2, bcs=result.bcs, cmap=my_cmap) # # plot_matrix(result.assembled_form, cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form,", "size = A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if use_sparse:", "method B in the Badia-Codina paper eta_u_bc = 1 #", "= v + beta * (q - mu_h) * n", "# Numerical flux trace u = -grad(p) u_hat = u", "FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree)", "+= eta_u_bc * delta_3 * p * q * ds", "solver, min_degree=1, max_degree=4, numel_xy=(5, 10, 15, 20, 25), quadrilateral=True, name=\"\",", "= FunctionSpace(mesh, C0TraceElement) else: trace_family = \"HDiv Trace\" T =", "import pandas as pd from tqdm import tqdm import os", "* delta_1 # * dx # ) # # These", "L0 # method B in the Badia-Codina paper # eta_u", "dx a += delta_1 * div(u) * div(v) * dx", "# method B in the Badia-Codina paper eta_u_bc = 1", "beta = Constant(32.0) h = CellDiameter(mesh) h_avg = avg(h) #", "div(v) * p) * dx + lambda_h(\"+\") * jump(v, n)", "curl(v)) * dx # Hybridization terms a += mu_h(\"+\") *", "in numel_xy: pbar.set_description(f\"Processing {name} - degree = {degree} - N", "\"on_boundary\") # Hybridization parameter s = Constant(-1.0) beta = Constant(32.0)", "C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: T =", "print(f'DoFs: {result.number_of_dofs}') # print(f'Condition Number: {result.condition_number}') # # Plotting the", "* dx # Stabilizing terms a += 0.5 * inner(u", "lambda_h) * n v_hat = v + beta * (q", "* lambda_h * dot(v, n) * ds # Mass balance", "eta_u * avg(delta_3) * (jump(u, n) * jump(v, n)) *", "Constant(-1) # Classical volumetric terms a = inner(grad(p), grad(q)) *", "+= 0.5 * div(u) * div(v) * dx # a", "= _A.blocks S = A[2, 2] - A[2, :2] *", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dls(mesh, degree=1): # Function", "+ mu_h * (dot(u, n) - dot(u_projected, n))) * ds", "a += 0.5 * h * h * div(u) *", "/ h # Mixed classical terms a = (dot(u, v)", "a += 0.5 * div(u) * div(v) * dx #", "q * dx # DG edge terms a += s", "'DQ' if use_quads else 'DG' U = VectorFunctionSpace(mesh, velocity_family, degree)", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sdhm( mesh,", "= solvers_options[current_solver] # Performing the convergence study hp_refinement_cond_number_calculation( solver, min_degree=degree,", "+= jump(u_hat, n) * mu_h(\"+\") * dS # Weakly imposed", "+= delta_5 * (dot(u, n)(\"+\") - dot(u_hat, n)(\"+\")) * (dot(v,", "entries Mnp = Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[..., :] == 0,", "Constant(1) # delta_4 = Constant(1) # delta_5 = Constant(1) #", "= DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e0)", "= int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors) result =", "p + delta_0 * q * div(u)) * dx L", "real numbers. \"\"\" real_part_array = array.real[abs(array.imag) < 1e-5] return real_part_array", "# Dirichlet BCs bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization", "convergente rates # ** The terms below are based on", "paper # eta_p = 1 # eta_p = L0 *", "delta_0 = Constant(-1) delta_1 = Constant(-0.5) * h * h", "in the Badia-Codina paper eta_p = 1 # eta_p =", "csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if use_sparse: singular_values = svds( A=Mnp, k=num_of_factors,", "singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc SVD has not converged.\") singular_values =", "+ grad(q)) * dx a += eta_p * div(u) *", "div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(2),", "Threshold to cut off imaginary part in complex number. :return:", "matrix for single scale problems.\"\"\" fig, ax = plt.subplots(1, 1)", "* ds # Flux Least-squares as in DG a =", "sigma_e.project(-grad(p_exact)) # Forcing function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression)", "part in a numpy array. :param array: Array with real", "Nitsche's penalizing term beta_0 = Constant(1.0) beta = beta_0 /", "a += delta_1 * (dot(u, v) - div(v) * p)", "# (inner(u, v) - q * div(u) - p *", "else: raise NotImplementedError(\"The required method for condition number estimation is", "= inner(grad(p), grad(q)) * dx L = f * q", "path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" % name df_cond_number.to_csv(path_to_save_results) return df_cond_number # Solver", "the Badia-Codina paper # eta_u = 1 # Nitsche's penalizing", "* div(u) * div(v) * dx # Weakly imposed boundary", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_cgls(mesh, degree=1): #", "# method B in the Badia-Codina paper # Mixed classical", "+= 0.5 * h * h * inner(curl(u), curl(v)) *", "# method B in the Badia-Codina paper # eta_p =", "* (q - mu_h) * ds # a += delta_5", "# Mixed classical terms a = (dot(u, v) - div(v)", "a += eta_p * div(u) * div(v) * dx a", "( # (inner(u, v) - q * div(u) - p", "trace u = -grad(p) u_hat = u + beta *", "least-squares a += delta_3 * inner(curl(u), curl(v)) * dx #", "f * div(v) * dx # Irrotational least-squares a +=", "dx # Hybridization terms a += s * dot(grad(q), n)(\"+\")", "ds - q * dot(u, n) * ds # **", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dvms(mesh,", "# print(f'Is symmetric? {result.is_operator_symmetric}') # print(f'nnz: {result.nnz}') # print(f'DoFs: {result.number_of_dofs}')", "+= beta * (lambda_h - p_boundaries) * mu_h * ds", "a += delta_4(\"+\") * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") -", "# DG edge terms a += s * dot(jump(p, n),", "flux trace u = -grad(p) u_hat = u + beta", "* p + q * div(u)) * dx A =", "bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter beta_0 =", "== \"quadrilateral\" primal_family = \"DQ\" if use_quads else \"DG\" V", "= Tensor(a_form) A = _A.blocks S = A[2, 2] -", "delta_2 = Constant(0.5) * h * h delta_3 = Constant(0.5)", "h * f * div(v) * dx a += 0.5", "ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0,", "= copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) #", "mu_h) * n # Flux least-squares # a = (", "- q) * (lambda_h - p_boundaries) * ds # )", "# Classical mixed Darcy eq. first-order terms as stabilizing terms", "eta_u_bc * delta_3 * p * q * ds #", "a += 0.5 * h * h * inner(curl(u), curl(v))", "terms a = (dot(u, v) - div(v) * p -", "S.getConverged() singular_values_list = list() if num_converged_values > 0: for i", "plot def filter_real_part_in_array(array: np.ndarray, imag_threshold: float = 1e-5) -> np.ndarray:", "* ds # Mass balance least-square a += delta_2 *", "# Average cell size and mesh dependent stabilization h_avg =", "in the Badia-Codina paper # eta_p = L0 * L0", "# Symmetry term. Choose if the method is SIPG (-1)", "* div(u)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat", "= TrialFunction(V) q = TestFunction(V) # Mesh entities n =", "sigma_e, \"on_boundary\") # Stabilization parameters delta_1 = Constant(1) delta_2 =", "scipy.linalg import svd from scipy.sparse.linalg import svds from scipy.sparse import", "n)) * dS # Edge stabilizing terms a += beta(\"+\")", "jump(q, n)) * dS # a += p * q", "Transmission condition a += jump(u_hat, n) * mu_h(\"+\") * dS", "def calculate_condition_number( A, num_of_factors, backend: str = \"scipy\", use_sparse: bool", "= svd(M, compute_uv=False, check_finite=False) singular_values = singular_values[singular_values > zero_tol] condition_number", "u_hat = u + beta * (p - lambda_h) *", "Dirichlet BCs # bcs = DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\") #", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dgls(mesh, degree=1): #", "in the Badia-Codina paper # Mixed classical terms a =", "A[:2, 2] Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric", "mu_h(\"+\") * dS # Weakly imposed BC a += dot(u_hat,", "stabilizing parameters based on Badia-Codina stabilized dG method # L0", "# delta_3 = Constant(1) # delta_4 = Constant(1) # delta_5", "jump(u, n) * jump(v, n) * dS # not considered", "rates a += eta_u_bc * delta_4 * dot(u, n) *", "* q * ds # # a += delta_1 *", "0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def plot_matrix_primal_hybrid_full(a_form,", "A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1],", "* (p - lambda_h) * (q - mu_h) * ds", "= 1 / h delta_4 = 1 / h #", "dx a += delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) *", "based a += (avg(eta_p) / h_avg) * (jump(u, n) *", "as in DG a = delta_0 * inner(u + grad(p),", "* dx a += eta_p * div(u) * div(v) *", "\"\"\"Provides a plot of a condensed hybrid-mixed matrix for single", "** The terms below are based on ASGS Badia-Codina (2010),", "/ h beta = beta_0 # Stabilization parameters delta_0 =", "imposed boundary conditions a += dot(v, n) * p *", "dot(u, n)(\"+\") * dS a += beta(\"+\") * (lambda_h(\"+\") -", "* p_exact * dot(v, n) * ds # Flux Least-squares", "= DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter s = Constant(-1.0)", "for current_solver in solvers_options: # Setting the output file name", "1 condition_number = calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a, assembled_form=Smat,", "dot(jump(p, n), jump(q, n)) * dS # a += p", "plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs): \"\"\"Provides a plot of", "* dx + jump(u_hat, n) * q(\"+\") * dS L", "delta_3 * p * q * ds # may decrease", "beta_avg = beta_0 / h(\"+\") # Stabilizing parameter # delta_0", "= \"HDiv Trace\" V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous:", "L = -delta_1 * dot(u_projected, n) * q * ds", "SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values =", "LARGE_NUMBER = Constant(1e0) delta = h * h # delta", "Badia-Codina paper # eta_u = 1 # Nitsche's penalizing term", "CellDiameter(mesh) h_avg = avg(h) # Classical term a = dot(grad(p),", "* ds # ) # maybe this is not a", "B in the Badia-Codina paper # eta_p = 1 #", "terms a += 0.5 * inner(u + grad(p), grad(q) -", "shape=size) Mnp.eliminate_zeros() Mnp = Mnp.toarray() # Eliminate rows and columns", "space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family = 'DQ'", "n) - dot(u_projected, n))) * ds a += beta *", "W = U * V * T # Trial and", "list(), \"nnz\": list(), \"dofs\": list(), \"h\": list(), \"Condition Number\": list(),", "of a condensed hybrid-mixed matrix for single scale problems.\"\"\" fig,", "stabilizing terms # a += 0.5 * inner(u + grad(p),", "np.delete(Mnp, idx, axis=1) Am = np.ma.masked_values(Mnp, 0, rtol=1e-13) # Plot", "return result def solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False ): # Function", "\"CG\", degree) # Trial and test functions u = TrialFunction(V)", "classical form a = (dot(u, v) - div(v) * p)", "dS a += (beta / h_avg) * (p(\"+\") - lambda_h(\"+\"))", "= beta_0 # Stabilization parameters delta_0 = Constant(-1) delta_1 =", "+= delta_2 * div(u) * div(v) * dx a +=", "else: raise RuntimeError(\"SLEPc SVD has not converged.\") singular_values = np.array(singular_values_list)", "to cut off imaginary part in complex number. :return: Filtered", "'DG' trace_family = \"HDiv Trace\" V = FunctionSpace(mesh, pressure_family, degree)", "terms a = (dot(u, v) - div(v) * p +", "u, p, lambda_h = split(solution) p, lambda_h = TrialFunctions(W) q,", "* lambda_h * ds # ### # a += (", "grad(p), v + grad(q)) * dx a += delta_2 *", "inner(grad(u), grad(v)) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat", "a += s * dot(p * n, grad(q)) * ds", "ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\")", "V = FunctionSpace(mesh, \"CG\", degree) # Trial and test functions", "Tensor(a) A = _A.blocks S = A[2, 2] - A[2,", "result def solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False ): # Function space", "-grad(p) u_hat = u + beta * (p - lambda_h)", "Least-squares as in DG a = delta_0 * inner(u +", "Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle size = petsc_mat.getSize()", "* ds # How to set this bc?? # a", "h # delta = Constant(1) # delta = h delta_0", "delta_1 = delta delta_2 = delta delta_3 = delta delta_4", "my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form, result.bcs,", "assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result", "0].handle.getSize() f1_size = assembled_form.M[1, 1].handle.getSize() size = petsc_mat.getSize() Mnp =", "q * dot(u, n) * ds # ** The terms", "= Constant(-0.5) * h * h delta_2 = Constant(0.5) *", "mesh = UnitSquareMesh(N, N, quadrilateral=True) # result = solve_poisson_lsh(mesh, degree=1)", "ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return", "idx = np.argwhere(np.all(Mnp[..., :] == 0, axis=0)) Mnp = np.delete(Mnp,", "n), jump(q, n)) * dS # Volumetric stabilizing terms #", ") return result def solve_poisson_vms(mesh, degree=1): # Function space declaration", "plot of a matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat", "= assembled_form.M[1, 1].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size)", "import * import numpy as np import matplotlib.pyplot as plt", "assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size =", "div(v) * dx # a += 0.5 * inner(curl(u), curl(v))", "from hybridization # a += mu_h * (lambda_h - p_boundaries)", "pd from tqdm import tqdm import os matplotlib.use('Agg') @attr.s class", "\"HDiv Trace\" V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement", "mu_h) * ds # a += delta_5 * (dot(u, n)(\"+\")", "and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def plot_matrix_mixed(assembled_form, **kwargs):", "= split(solution) p, lambda_h = TrialFunctions(W) q, mu_h = TestFunctions(W)", "list(), \"Number of Elements\": list(), \"Degree\": list(), \"Symmetric\": list(), \"nnz\":", "- avg(q) * jump(u, n) * dS # Edge stabilizing", "\"Tri\" pbar = tqdm(range(min_degree, max_degree)) for degree in pbar: for", "u + beta * (p - lambda_h) * n v_hat", "** a += eta_u * avg(delta_3) * (jump(u, n) *", "(p- p_boundaries) * q * ds # is this necessary?", "A[:2, 2] Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle is_symmetric", "beta(\"+\") * dot(jump(p, n), jump(q, n)) * dS # Weak", "ds # a += mu_h * lambda_h * ds #", ":param imag_threshold: Threshold to cut off imaginary part in complex", "use_quads else \"DG\" V = FunctionSpace(mesh, primal_family, degree) if is_multiplier_continuous:", "functions p = TrialFunction(V) q = TestFunction(V) # Mesh entities", "* ds # ### # a += ( # (mu_h", "= 'DQ' if use_quads else 'DG' velocity_family = 'DQ' if", "plot = plt.spy(Am, **kwargs) # Remove axis ticks and values", "required method for condition number estimation is currently unavailable.\") return", "W.dim() num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors)", "= Constant(-1) # Classical volumetric terms a = inner(grad(p), grad(q))", "hybrid-mixed matrix.\"\"\" fig, ax = plt.subplots(1, 1) assembled_form = assemble(a_form,", "Mnp.nnz number_of_dofs = V.dim() num_of_factors = int(number_of_dofs) - 1 condition_number", "# Weakly imposed BC a += lambda_h * dot(v, n)", "= {degree} - N = {n}\") mesh = UnitSquareMesh(n, n,", "eta_p * div(u) * div(v) * dx # Weakly imposed", "Badia-Codina paper # eta_u = h_avg / L0 # method", "* dx L = f * q * dx #", "Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") #", "dx a += eta_p * inner(curl(u), curl(v)) * dx #", "(1) s = Constant(-1) # Classical volumetric terms a =", "* f * div(v) * dx # a += 0.5", "nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_cgls(mesh, degree=1): # Function", "= _A.blocks S = A[1, 1] - A[1, :1] *", "n)) * dS # Weak boundary conditions a += s", "# Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family", "# \"dgls\": solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm, # \"ls\": solve_poisson_ls, #", "* div(u)) * dx # Stabilizing terms a += 0.5", "0, axis=0)) Mnp = np.delete(Mnp, idx, axis=1) Am = np.ma.masked_values(Mnp,", "# a += -dot(vel_projected, n) * v * ds #", "* L0 # method D in the Badia-Codina paper eta_u", "results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True) df_cond_number", "petsc_mat = Smat.M.handle size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size)", "solvers_options: # Setting the output file name name = f\"{current_solver}\"", "if use_quads: hdiv_family = 'RTCF' pressure_family = 'DQ' else: hdiv_family", "# DG terms a += jump(v, n) * avg(p) *", "DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0) beta", "Stabilizing terms a += -0.5 * inner((u + grad(p)), v", "h * h * f * div(v) * dx #", "# \"ls\": solve_poisson_ls, # \"dls\": solve_poisson_dls, \"lsh\": solve_poisson_lsh, # \"vms\":", "solve_poisson_hdg, # \"cgh\": solve_poisson_cgh, # \"ldgc\": solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg,", "\"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG' V =", "{name} - degree = {degree} - N = {n}\") mesh", "+= 0.5 * inner(curl(u), curl(v)) * dx # L +=", "= solver(mesh, degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min() if not quadrilateral else", "-> np.ndarray: \"\"\"Utility function to filter real part in a", "Mixed classical terms a = (dot(u, v) - div(v) *", "petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size = petsc_mat.getSize() Mnp", "0, rtol=1e-13) # Plot the matrix plot = ax.matshow(Am, **kwargs)", "Elements\": list(), \"Degree\": list(), \"Symmetric\": list(), \"nnz\": list(), \"dofs\": list(),", "# Classical volumetric terms a = inner(grad(p), grad(q)) * dx", "dx # L = delta_2 * f * div(v) *", "'DG' velocity_family = 'DQ' if use_quads else 'DG' U =", "function to filter real part in a numpy array. :param", "* div(u) * div(v) * dx a += delta_3 *", "* h # method B in the Badia-Codina paper #", "FunctionSpace(mesh, pressure_family, degree) W = U * V # Trial", "* n, q * n) * ds # may decrease", "dot(jump(p, n), jump(q, n)) * dS # ** Mesh independent", ":param array: Array with real and complex numbers. :param imag_threshold:", "matplotlib.use('Agg') @attr.s class ConditionNumberResult(object): form = attr.ib() assembled_form = attr.ib()", "a += delta_2 * div(u) * div(v) * dx a", "* p * ds - q * dot(u, n) *", "n) * q * ds # a += delta_1(\"+\") *", "(dot(v, n)(\"+\") - dot(v_hat, n)(\"+\")) * dS # a +=", "- p_boundaries) * ds # ) # maybe this is", "* dS # Volumetric stabilizing terms # a += 0.5", "- A[1, :1] * A[:1, :1].inv * A[:1, 1] Smat", "= beta_0 / h beta_avg = beta_0 / h(\"+\") #", "h_avg / L0 # method B in the Badia-Codina paper", "* lambda_h(\"+\") * jump(v, n=n) * dS # a +=", "dot(v_hat, n)(\"+\")) * dS # a += delta_5 * (dot(u,", "**kwargs) # Below there is the spy alternative # plot", "* q * ds # a += delta_1(\"+\") * lambda_h(\"+\")", "based a += eta_u * inner(u + grad(p), grad(q) -", "if use_quads else 'DG' trace_family = \"HDiv Trace\" V =", "idx] - A[idx, :idx] * A[:idx, :idx].inv * A[:idx, idx]", "p_exact, \"on_boundary\") # Hybridization parameter s = Constant(-1.0) beta =", "curl(v)) * dx # Weakly imposed boundary conditions a +=", "# a += dot(jump(p, n), jump(q, n)) * dS #", "num_of_factors) result = ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz,", "s = Constant(-1.0) beta = Constant(32.0) h = CellDiameter(mesh) h_avg", "if use_quads else 'DG' V = FunctionSpace(mesh, pressure_family, degree) #", "* dot(jump(p, n), jump(q, n)) * dS # Weak boundary", "plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form,", "Mesh entities h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh) #", "* f * div(v) * dx # Hybridization terms a", "axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5,", "def solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration", "* dx # Hybridization terms a += lambda_h(\"+\") * dot(v,", "L = delta_2 * f * div(v) * dx #", "= delta # Numerical flux trace u_hat = u +", "= solve_poisson_lsh(mesh, degree=1) # print(f'Is symmetric? {result.is_operator_symmetric}') # print(f'nnz: {result.nnz}')", "* dS # ** Mesh independent terms # a +=", "dx # Edge stabilizing terms # ** Badia-Codina based (better", "dS a += eta_u_bc * delta_3 * p * q", "# \"cg\": solve_poisson_cg, # \"cgls\": solve_poisson_cgls, # \"dgls\": solve_poisson_dgls, #", "FunctionSpace(mesh, C0TraceElement) else: trace_family = \"HDiv Trace\" T = FunctionSpace(mesh,", "k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" ) else: M = Mnp.toarray()", "n) * q * ds F = a - L", "* q * ds A = assemble(a, mat_type=\"aij\") petsc_mat =", "div(v) * p + q * div(u)) * dx #", "\"HDiv Trace\" T = FunctionSpace(mesh, trace_family, degree) W = V", "= Constant(0.5) * h * h # Mixed classical terms", "p_boundaries = Constant(0.0) bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization", "cell size and mesh dependent stabilization h_avg = (h(\"+\") +", "# L = delta_2 * f * div(v) * dx", "= UnitSquareMesh(n, n, quadrilateral=quadrilateral) result = solver(mesh, degree=degree) current_cell_size =", "flux trace u_hat = u + beta * (p -", "Constant(1) # Least-squares terms a = delta_1 * inner(u +", "* A[:2, :2].inv * A[:2, 2] Smat = assemble(S, bcs=bc_multiplier)", "* A[:2, 2] Smat = assemble(S, bcs=bcs) petsc_mat = Smat.M.handle", "* dS # a += delta_4 * (p - lambda_h)", "unsymmetric # a += delta_1 * jump(u_hat, n=n) * q(\"+\")", "plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of a full hybrid-mixed", "NIPG (1) s = Constant(-1) # Classical volumetric terms a", "# N = 5 # mesh = UnitSquareMesh(N, N, quadrilateral=True)", "* h * h * f * div(v) * dx", "# # These terms below are unsymmetric # a +=", "attr.ib() condition_number = attr.ib() sparse_operator = attr.ib() number_of_dofs = attr.ib()", "a = inner(grad(p), grad(q)) * dx L = f *", "* dot(jump(p, n), avg(grad(q))) * dS - dot(avg(grad(p)), jump(q, n))", "= DirichletBC(W[0], sigma_e, \"on_boundary\") # Mixed classical terms a =", "avg(grad(q))) * dS - dot(avg(grad(p)), jump(q, n)) * dS #", "penalizing term beta_0 = Constant(1.0) beta = beta_0 / h", "n)(\"+\") * dS a += beta(\"+\") * (lambda_h(\"+\") - p(\"+\"))", "decrease convergente rates a += eta_u_bc * delta_4 * dot(u,", "dot(u_projected, n) * q * ds # a += delta_1(\"+\")", "h_avg # method B in the Badia-Codina paper eta_p =", "u + beta * (p - lambda_h) * n #", "* p - q * div(u)) * dx # Stabilizing", "Classical volumetric terms a = inner(grad(p), grad(q)) * dx L", "* dx # Stabilizing terms a += -0.5 * inner((u", "v, q = TestFunctions(W) # Mesh entities n = FacetNormal(mesh)", "in range(num_converged_values): singular_value = S.getValue(i) singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc SVD", "* dot(v, n) * ds # Mass balance least-square a", "use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family = 'DQ' if use_quads", "paper eta_u = 1 # eta_u_bc = h / L0", "dot(v, n) * ds # Mass balance least-square a +=", "# Trial and test functions p = TrialFunction(V) q =", "ax.set_yticklabels([]) return plot def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a plot of", "n=n) * dS # a += delta_1 * lambda_h *", "(lambda_h - p_boundaries) * ds # ) # maybe this", "h) * dot(u, n) * dot(v, n) * ds a", "plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of a", "L = delta_1 * p_exact * dot(v, n) * ds", "n, q * n) * ds A = assemble(a, mat_type=\"aij\")", "terms # a += 0.5 * inner(u + grad(p), grad(q)", "+ beta * (p - lambda_h) * n v_hat =", "* div(v) * dx # a += 0.5 * inner(curl(u),", "# Plot the matrix plot = ax.matshow(Am, **kwargs) # Below", "+ q * div(u)) * dx # Stabilizing terms a", "Trace\" U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family,", "= FunctionSpace(mesh, trace_family, degree) W = V * T #", "delta_1 * dot(u, n) * q * ds # #", "exact_solution.rename(\"Exact pressure\", \"label\") # Forcing function f_expression = div(-grad(p_exact)) f", "return result def solve_poisson_cgls(mesh, degree=1): # Function space declaration pressure_family", "+= dot(jump(p, n), jump(q, n)) * dS # a +=", "B in the Badia-Codina paper eta_u_bc = 1 # Least-Squares", "based on Badia-Codina stabilized dG method # L0 = 1", "* n, grad(q)) * ds - dot(grad(p), q * n)", "* dS # Weakly imposed BC a += dot(u_hat, n)", "= A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize() Mnp =", "p(\"+\")) * (mu_h(\"+\") - q(\"+\")) * dS # Weakly imposed", "- mu_h(\"+\")) * dS # a += delta_4 * (p", "int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult(", "* h delta_3 = Constant(0.5) * h * h #", "a += beta * (lambda_h - p_boundaries) * mu_h *", "condition_number = singular_values.max() / singular_values.min() else: raise NotImplementedError(\"The required method", "S = A[2, 2] - A[2, :2] * A[:2, :2].inv", "h # beta = beta_0 # Numerical flux trace u_hat", "method D in the Badia-Codina paper # eta_u = h_avg", "delta_2 * f * div(v) * dx # Hybridization terms", "f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Edge stabilizing parameter", "= 1 eta_p = L0 * h # method B", "**kwargs ): results_dict = { \"Element\": list(), \"Number of Elements\":", "bcs=bcs, mat_type=\"aij\") petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() f1_size", "* A[:2, :2].inv * A[:2, 2] Smat = assemble(S, bcs=bcs)", "(q - mu_h) * ds # a += delta_5 *", "np.array(singular_values_list) singular_values = singular_values[singular_values > zero_tol] condition_number = singular_values.max() /", "q * div(u)) * dx # DG terms a +=", "# ) # # These terms below are unsymmetric #", "n)) * dS # Volumetric stabilizing terms # a +=", "declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family = 'DQ' if", "def solve_poisson_cg(mesh, degree=1, use_quads=False): # Function space declaration V =", "= FunctionSpace(mesh, pressure_family, degree) W = U * V #", "/ h delta_5 = delta # Numerical flux trace u_hat", "name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs # bcs = DirichletBC(W[0],", "q * ds A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle", "method D in the Badia-Codina paper eta_u = h /", "div(v) * p - q * div(u)) * dx #", "* dot(u, n) * q * ds # # L", "solve_poisson_sipg, } degree = 1 last_degree = 1 for current_solver", "Badia-Codina based (better results) ** a += eta_u * avg(delta_3)", "= Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs bcs =", "and its kwargs solver = solvers_options[current_solver] # Performing the convergence", "term. Choose if the method is SIPG (-1) or NIPG", "pressure\", \"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet", "= assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size", "for degree in pbar: for n in numel_xy: pbar.set_description(f\"Processing {name}", "def solve_poisson_vms(mesh, degree=1): # Function space declaration pressure_family = 'CG'", "- lambda_h(\"+\")) * dS a += -dot(grad(p), n)(\"+\") * (q(\"+\")", "inner(curl(u), curl(v)) * dx # ** Badia-Codina based a +=", "terms # ** Badia-Codina based a += (avg(eta_p) / h_avg)", "based (better results) ** a += eta_u * avg(delta_3) *", "\"DQ\" if use_quads else \"DG\" V = FunctionSpace(mesh, primal_family, degree)", "* lambda_h * dot(v, n) * ds # # L", "v) - div(v) * p) * dx a += delta_1(\"+\")", ") return result def solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False ): #", "zero entries Mnp = Mnp[~(Mnp==0).all(1)] idx = np.argwhere(np.all(Mnp[..., :] ==", "+= dot(u_hat, n) * q * ds F = a", "condition_number def solve_poisson_cg(mesh, degree=1, use_quads=False): # Function space declaration V", "in the Badia-Codina paper # eta_u = 1 # Nitsche's", "degree in pbar: for n in numel_xy: pbar.set_description(f\"Processing {name} -", "- degree = {degree} - N = {n}\") mesh =", "h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh) # Exact solution", "fig, ax = plt.subplots(1, 1) assembled_form = assemble(a_form, bcs=bcs, mat_type=\"aij\")", "= beta_0 / h # beta = beta_0 # Numerical", "beta0 = Constant(1e1) beta = beta0 / h # Symmetry", "= Tensor(a_form) A = _A.blocks S = A[1, 1] -", "# Stabilizing terms a += delta_1 * inner(u + grad(p),", "delta_1 * div(u) * div(v) * dx a += delta_2", "= 1 last_degree = 1 for current_solver in solvers_options: #", "- 0.5, color=\"k\") ax.axvline(x=f0_size[0] + f1_size[0] - 0.5, color=\"k\") return", "'CG' velocity_family = 'CG' U = VectorFunctionSpace(mesh, velocity_family, degree) V", "lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) * dS # a +=", "functions # solution = Function(W) # u, p, lambda_h =", "= Mnp.shape[0] num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat,", "= Constant(1.0) beta = beta_0 / h beta_avg = beta_0", "a += delta_3 * inner(curl(u), curl(v)) * dx A =", "return result def solve_poisson_ls(mesh, degree=1): # Function space declaration pressure_family", "u = -grad(p) u_hat = u + beta * (p", "= DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0)", "(inner(u, v) - q * div(u) - p * div(v)", "pressure_family = 'DQ' if use_quads else 'DG' trace_family = \"HDiv", "div(u)) * dx # Stabilizing terms a += 0.5 *", "+= delta_1 * inner(u + grad(p), v + grad(q)) *", "Hybridization parameter beta_0 = Constant(1.0e-18) # beta = beta_0 /", "Constant(1) # delta_3 = Constant(1) # delta_4 = Constant(1) #", "unavailable.\") return condition_number def solve_poisson_cg(mesh, degree=1, use_quads=False): # Function space", "# eta_p = L0 * h_avg # method B in", "= Constant(-1) delta_1 = Constant(-0.5) * h * h delta_2", "ds # How to set this bc?? # a +=", "* div(u) * div(v) * dx a += eta_p *", "FacetNormal(mesh) h = CellDiameter(mesh) x, y = SpatialCoordinate(mesh) # Exact", "SLEPc import pandas as pd from tqdm import tqdm import", "ds # # a += delta_1 * dot(u, n) *", "p_boundaries) * q * ds # is this necessary? L", "bcs=[], **kwargs): \"\"\"Provides a plot of a condensed hybrid-mixed matrix", "* div(u) * div(v) * dx a += 0.5 *", "= {n}\") mesh = UnitSquareMesh(n, n, quadrilateral=quadrilateral) result = solver(mesh,", "columns filled with zero entries Mnp = Mnp[~(Mnp==0).all(1)] idx =", "else: M = Mnp.toarray() singular_values = svd(M, compute_uv=False, check_finite=False) singular_values", "HDG classical form a = (dot(u, v) - div(v) *", "use_quads else 'DG' trace_family = \"HDiv Trace\" V = FunctionSpace(mesh,", "* (q(\"+\") - mu_h(\"+\")) * dS # a += delta_4", "grad(q)) * ds - dot(grad(p), q * n) * ds", "Below there is the spy alternative # plot = plt.spy(Am,", "lambda_h(\"+\") * jump(v, n=n) * dS # a += delta_1", ":2].inv * A[:2, 2] Smat = assemble(S, bcs=bc_multiplier) petsc_mat =", "pandas as pd from tqdm import tqdm import os matplotlib.use('Agg')", "* dx # a += 0.5 * div(u) * div(v)", "* dot(grad(q), n)(\"+\") * (p(\"+\") - lambda_h(\"+\")) * dS a", "# Edge stabilizing terms # ** Badia-Codina based (better results)", "assembled_form.M[1, 1].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "in the Badia-Codina paper # eta_u = h_avg / L0", "= assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() f1_size = assembled_form.M[1, 1].handle.getSize()", "terms a += lambda_h(\"+\") * dot(v, n)(\"+\") * dS +", "imag_threshold: Threshold to cut off imaginary part in complex number.", "pi * y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") #", "* x) * sin(2 * pi * y) exact_solution =", "delta_0 = delta delta_1 = delta delta_2 = delta delta_3", "= Constant(-1.0) beta = Constant(32.0) h = CellDiameter(mesh) h_avg =", "V.dim() num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors)", "h beta = beta_0 # Stabilization parameters delta_0 = Constant(-1)", "a += dot(jump(p, n), jump(q, n)) * dS # a", "curl(v)) * dx # L += 0.5 * h *", "in the Badia-Codina paper eta_u = 1 # eta_u_bc =", "n)(\"+\") - dot(u_hat, n)(\"+\")) * (dot(v, n)(\"+\") - dot(v_hat, n)(\"+\"))", "number_of_dofs = V.dim() num_of_factors = int(number_of_dofs) - 1 condition_number =", "Mnp.shape[0] num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors)", "ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs):", "Dirichlet BCs p_boundaries = Constant(0.0) bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\")", "= Function(V).interpolate(f_expression) # Edge stabilizing parameter beta0 = Constant(1e1) beta", "result def solve_poisson_ldgc( mesh, degree=1, is_multiplier_continuous=True ): # Function space", "solve_poisson_vms(mesh, degree=1): # Function space declaration pressure_family = 'CG' velocity_family", "n) * ds # Flux Least-squares as in DG a", "# HDG classical form a = (dot(u, v) - div(v)", "pi * x) * sin(2 * pi * y) exact_solution", "* ds a += beta * p * q *", "dx # a += 0.5 * inner(curl(u), curl(v)) * dx", "result = ConditionNumberResult( form=a, assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric", "= 1 # Least-Squares weights delta = Constant(1.0) # delta", "* dot(v, n) * ds a += (eta_u / h)", "+= mu_h * (lambda_h - p_boundaries) * ds # a", "* ds # may decrease convergente rates (Nitsche) A =", "Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = W.dim() num_of_factors = int(number_of_dofs)", "n) * ds a += (eta_u / h) * dot(p", "grad(q)) * dx L = f * q * dx", "h # Symmetry term. Choose if the method is SIPG", "import svd from scipy.sparse.linalg import svds from scipy.sparse import csr_matrix", "= tqdm(range(min_degree, max_degree)) for degree in pbar: for n in", "* dS # a += dot(jump(p, n), jump(q, n)) *", "a += delta_1 * div(u) * div(v) * dx a", "+= p * q * ds A = assemble(a, mat_type=\"aij\")", "= np.argwhere(np.all(Mnp[..., :] == 0, axis=0)) Mnp = np.delete(Mnp, idx,", "solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False ): # Function space declaration use_quads", "/ h_avg) * (jump(u, n) * jump(v, n)) * dS", "backend == \"slepc\": S = SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors)", "dx # Weakly imposed boundary conditions a += dot(v, n)", "Badia-Codina paper # eta_p = 1 # eta_p = L0", "1) petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size =", "lambda_h = split(solution) p, lambda_h = TrialFunctions(W) q, mu_h =", "curl(v)) * dx L += delta_2 * f * div(v)", "from slepc4py import SLEPc import pandas as pd from tqdm", "q * n) * ds A = assemble(a, mat_type=\"aij\") petsc_mat", "Choose if the method is SIPG (-1) or NIPG (1)", "degree) W = V * T # Trial and test", "n # Flux least-squares # a = ( # (inner(u,", "# ** Mesh independent ** # a += jump(u, n)", "= Constant(1) # LARGE_NUMBER = Constant(1e0) delta = h *", "= attr.ib() assembled_form = attr.ib() condition_number = attr.ib() sparse_operator =", "* q * dx # Transmission condition a += jump(u_hat,", "assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result", "sin(2 * pi * y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\",", "terms below are unsymmetric # a += delta_1 * jump(u_hat,", "shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = V.dim() num_of_factors =", "ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def filter_real_part_in_array(array:", ") return result def solve_poisson_dvms(mesh, degree=1): # Function space declaration", "delta_1 = Constant(1) delta_2 = Constant(1) delta_3 = Constant(1) #", "f = Function(V).interpolate(f_expression) # Edge stabilizing parameter beta0 = Constant(1e1)", "ax.axvline(x=f0_size[0] - 0.5, color=\"k\") return plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs):", "Stabilization parameters delta_1 = Constant(1) delta_2 = Constant(1) delta_3 =", "delta_5 = delta # Numerical flux trace u_hat = u", "max_degree)) for degree in pbar: for n in numel_xy: pbar.set_description(f\"Processing", "assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() f1_size = assembled_form.M[1, 1].handle.getSize() size", "Filtered array with only real numbers. \"\"\" real_part_array = array.real[abs(array.imag)", "maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" ) else: M = Mnp.toarray() singular_values =", "dx # ** Badia-Codina based a += -eta_u * inner(u", "- q * div(u)) * dx # Stabilizing terms a", "* dot(p * n, q * n) * ds A", "# Jump stabilizing parameters based on Badia-Codina stabilized dG method", "1] - A[1, :1] * A[:1, :1].inv * A[:1, 1]", "L a_form = lhs(F) _A = Tensor(a_form) A = _A.blocks", "+= mu_h * lambda_h * ds # ### # a", "based on Badia-Codina stabilized dG method L0 = 1 eta_p", "delta_3 * inner(curl(u), curl(v)) * dx A = assemble(a, bcs=bcs,", "rows and columns filled with zero entries Mnp = Mnp[~(Mnp==0).all(1)]", "os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\"", "ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def filter_real_part_in_array(array: np.ndarray, imag_threshold: float", "h * inner(curl(u), curl(v)) * dx # L += 0.5", "+= (p_boundaries * dot(v, n) + mu_h * (dot(u, n)", "* delta_3 * p * q * ds # may", "+= s * dot(jump(p, n), avg(grad(q))) * dS - dot(avg(grad(p)),", "and complex numbers. :param imag_threshold: Threshold to cut off imaginary", "-dot(grad(p), n)(\"+\") * (q(\"+\") - mu_h(\"+\")) * dS a +=", "use_quads else 'DG' V = FunctionSpace(mesh, pressure_family, degree) # Trial", "lambda_h) * (q - mu_h) * ds # a +=", "HDG classical form a = -dot(u, grad(q)) * dx +", "A[:1, 1] Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric", "lhs(F) _A = Tensor(a_form) A = _A.blocks S = A[1,", "assemble(S, bcs=bcs) petsc_mat = Smat.M.handle size = petsc_mat.getSize() Mnp =", "# Least-squares terms a = delta_0 * inner(u + grad(p),", "dS # Volumetric stabilizing terms # a += 0.5 *", "Mnp = Mnp.toarray() # Eliminate rows and columns filled with", "Volumetric stabilizing terms # a += 0.5 * h *", "sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Forcing function f_expression", "{n}\") mesh = UnitSquareMesh(n, n, quadrilateral=quadrilateral) result = solver(mesh, degree=degree)", "== \"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG' V", "Performing the convergence study hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree + last_degree,", "dG method L0 = 1 eta_p = L0 * h", "dot(v_hat, n)) * ds # Weakly imposed BC from hybridization", "if use_quads else 'DG' trace_family = \"HDiv Trace\" U =", "- 1 condition_number = calculate_condition_number(petsc_mat, num_of_factors) result = ConditionNumberResult( form=a,", "# # plot_matrix(result.assembled_form, cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form, cmap=my_cmap) # plt.tight_layout()", "compute_uv=False, check_finite=False) singular_values = singular_values[singular_values > zero_tol] condition_number = singular_values.max()", "rates # ** Classical Nitsche # a += beta *", "curl(v)) * dx # Edge stabilizing terms # ** Badia-Codina", "with only real numbers. \"\"\" real_part_array = array.real[abs(array.imag) < 1e-5]", "not quadrilateral else 1 / n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n", "L += 0.5 * f * div(v) * dx #", "= attr.ib() sparse_operator = attr.ib() number_of_dofs = attr.ib() nnz =", "+= delta_1 * lambda_h * dot(v, n) * ds #", "# matplotlib.use('TkAgg') # import copy # my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) #", "plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap) # #", "/ singular_values.min() else: raise NotImplementedError(\"The required method for condition number", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def solve_poisson_hdg( mesh,", "Elements\"].append(n * n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number)", "delta_2 = Constant(1) delta_3 = Constant(1) # Least-squares terms a", "avg(p) * dS - avg(q) * jump(u, n) * dS", "+ last_degree, quadrilateral=True, name=name ) # N = 5 #", "+= s * dot(grad(q), n)(\"+\") * (p(\"+\") - lambda_h(\"+\")) *", "n results_dict[\"Element\"].append(element_kind) results_dict[\"Number of Elements\"].append(n * n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz)", "f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs p_boundaries", "delta_3 = 1 / h delta_4 = 1 / h", "Function(W) # u, p, lambda_h = split(solution) p, lambda_h =", "* q * ds # may decrease convergente rates a", "dx + jump(u_hat, n) * q(\"+\") * dS L =", "= 1 # Nitsche's penalizing term beta_0 = Constant(1.0) beta", "n)(\"+\") * (q(\"+\") - mu_h(\"+\")) * dS a += (beta", "current_cell_size = mesh.cell_sizes.dat.data_ro.min() if not quadrilateral else 1 / n", "dS # a += delta_1(\"+\") * dot(u_hat, n) * q", "div(v) * dx a += 0.5 * inner(curl(u), curl(v)) *", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_cgh(", "imposed BC a += (p_boundaries * dot(v, n) + mu_h", "values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def filter_real_part_in_array(array: np.ndarray, imag_threshold:", "= div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # BCs u_projected = sigma_e", "div(v) * dx # a += -0.5 * inner(u +", "Badia-Codina stabilized dG method L0 = 1 eta_p = L0", "* (mu_h(\"+\") - q(\"+\")) * dS # Weakly imposed BC", "csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = Mnp.shape[0] num_of_factors", "solve_poisson_sipg(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "= (dot(u, v) - div(v) * p - q *", "the original paper # a += dot(jump(p, n), jump(q, n))", "BC from hybridization # a += mu_h * (lambda_h -", "csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp = Mnp.toarray() # Eliminate rows and", "dS # a += delta_5 * (dot(u, n) - dot(u_hat,", "numel_xy: pbar.set_description(f\"Processing {name} - degree = {degree} - N =", "split(solution) p, lambda_h = TrialFunctions(W) q, mu_h = TestFunctions(W) #", "V = FunctionSpace(mesh, pressure_family, degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\",", "= Constant(1.0e-18) # beta = beta_0 / h beta =", "(dot(u, v) - div(v) * p + delta_0 * q", "* dS a += (avg(eta_u) / h_avg) * dot(jump(p, n),", "solve_poisson_cgls, # \"dgls\": solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm, # \"ls\": solve_poisson_ls,", "grad(q)) * dx # a += 0.5 * h *", "may decrease convergente rates # ** Classical Nitsche # a", "= ConditionNumberResult( form=a, assembled_form=Smat, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs", "'DQ' if use_quads else 'DG' trace_family = \"HDiv Trace\" V", "'RTCF' pressure_family = 'DQ' else: hdiv_family = 'RT' pressure_family =", "# Stabilizing parameter # delta_0 = Constant(1) # delta_1 =", "q) * (lambda_h - p_boundaries) * ds # ) #", "/ h_avg) * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\"))", "inner(u + grad(p), grad(q) - v) * dx a +=", "# my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form,", "degree) if is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement =", "n)(\"+\") - dot(v_hat, n)(\"+\")) * dS # a += delta_5", "+ grad(p), v + grad(q)) * dx a += delta_1", "the matrix plot = ax.matshow(Am, **kwargs) # Remove axis ticks", "dx # L += 0.5 * h * h *", "# a += -0.5 * inner(u + grad(p), v +", "solve_poisson_lsh, # \"vms\": solve_poisson_vms, # \"dvms\": solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT,", "lambda_h = TrialFunctions(W) q, mu_h = TestFunctions(W) # Mesh entities", "= S.getValue(i) singular_values_list.append(singular_value) else: raise RuntimeError(\"SLEPc SVD has not converged.\")", "dx # a += 0.5 * h * h *", "div(v) * dx # ** Badia-Codina based a += eta_u", "use_quads else 'DG' velocity_family = 'DQ' if use_quads else 'DG'", "* dx + lambda_h(\"+\") * jump(v, n) * dS a", "v * ds # How to set this bc?? #", "a += ( # (mu_h - q) * (lambda_h -", "# delta = Constant(1) # delta = h delta_0 =", "Constant(1.0) beta = beta_0 / h # Mixed classical terms", "VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree) W =", "= h / L0 # method B in the Badia-Codina", "a += s * dot(grad(q), n)(\"+\") * (p(\"+\") - lambda_h(\"+\"))", "last_degree, quadrilateral=True, name=name ) # N = 5 # mesh", "Constant(1e0) delta = h * h # delta = Constant(1)", "n) * ds A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle", "return result def solve_poisson_hdg( mesh, degree=1, is_multiplier_continuous=False ): # Function", "ds # ** The terms below are based on ASGS", "dx # ** Badia-Codina based a += eta_u * inner(u", "# delta_5 = Constant(1) # LARGE_NUMBER = Constant(1e0) delta =", "hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree + last_degree, quadrilateral=True, name=name ) #", "* q * ds F = a - L a_form", "mu_h * (dot(u, n) - dot(u_projected, n))) * ds a", "- A[idx, :idx] * A[:idx, :idx].inv * A[:idx, idx] Smat", "div(v) * dx # a += 0.5 * div(u) *", "v_hat = v + beta * (q - mu_h) *", "petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs", "plot def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a plot of a mixed", "= W.dim() num_of_factors = int(number_of_dofs) - 1 condition_number = calculate_condition_number(petsc_mat,", "== \"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG' trace_family", "a += beta(\"+\") * (lambda_h(\"+\") - p(\"+\")) * (mu_h(\"+\") -", "BC, but this necessary _A = Tensor(a) A = _A.blocks", "S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK) S.setDimensions(nsv=num_of_factors) S.setTolerances(max_it=5000) S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values = S.getConverged()", "# Dirichlet BCs # bcs = DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\")", "cmap=my_cmap) # # plot_matrix_mixed(result.assembled_form, cmap=my_cmap) # plt.tight_layout() # plt.savefig(\"sparse_pattern.png\") #", "first-order terms as stabilizing terms a += delta_1 * (dot(u,", "singular_values.max() / singular_values.min() elif backend == \"slepc\": S = SLEPc.SVD()", "L = f * q * dx # DG edge", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dgls(mesh,", "\"quadrilateral\" primal_family = \"DQ\" if use_quads else \"DG\" V =", "grad(p)), v + grad(q)) * dx # a += 0.5", "* q * dx # Hybridization terms a += s", "* div(u) * div(v) * dx # a += 0.5", "@attr.s class ConditionNumberResult(object): form = attr.ib() assembled_form = attr.ib() condition_number", "= str(mesh.ufl_cell()) == \"quadrilateral\" pressure_family = 'DQ' if use_quads else", "Constant(1) # LARGE_NUMBER = Constant(1e0) delta = h * h", "TestFunction(V) # Mesh entities n = FacetNormal(mesh) h = CellDiameter(mesh)", "# import copy # my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") #", "lambda_h * dot(v, n) * ds # # L =", "nnz = Mnp.nnz number_of_dofs = W.dim() num_of_factors = int(number_of_dofs) -", "* div(v) * dx # L = delta_2 * f", "= TestFunction(V) # Dirichlet BCs bcs = DirichletBC(V, 0.0, \"on_boundary\")", "\"cg\": solve_poisson_cg, # \"cgls\": solve_poisson_cgls, # \"dgls\": solve_poisson_dgls, # \"sdhm\":", "q * div(u) - p * div(v) + inner(grad(p), grad(q)))", "Am = np.ma.masked_values(Mnp, 0, rtol=1e-13) # Plot the matrix plot", "= Constant(1.0) beta = beta_0 / h # Mixed classical", "2.0 # Jump stabilizing parameters based on Badia-Codina stabilized dG", "ds # a += delta_5 * (dot(u, n)(\"+\") - dot(u_hat,", "based a += -eta_u * inner(u + grad(p), v +", "* ds # may decrease convergente rates # ** The", "These terms below are unsymmetric # a += delta_1 *", "* div(v) + inner(grad(p), grad(q))) # * delta_1 # *", "Mesh independent terms # a += jump(u, n) * jump(v,", "maybe this is not a good way to impose BC,", "* dot(p * n, grad(q)) * ds - dot(grad(p), q", "not considered in the original paper # a += dot(jump(p,", "q * n) * ds # may decrease convergente rates", "if use_quads else 'DG' velocity_family = 'DQ' if use_quads else", "jump(v, n) * dS a += -dot(u, grad(q)) * dx", "# may decrease convergente rates a += eta_u_bc * delta_4", "matrix # matplotlib.use('TkAgg') # import copy # my_cmap = copy.copy(plt.cm.get_cmap(\"winter\"))", "Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Forcing function f_expression = div(-grad(p_exact))", "# Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" primal_family", "- lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) * dS # Boundary", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False ):", "= UnitSquareMesh(N, N, quadrilateral=True) # result = solve_poisson_lsh(mesh, degree=1) #", "from tqdm import tqdm import os matplotlib.use('Agg') @attr.s class ConditionNumberResult(object):", "attr.ib() number_of_dofs = attr.ib() nnz = attr.ib() is_operator_symmetric = attr.ib()", "Smat = assemble(S, bcs=bc_multiplier) petsc_mat = Smat.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8)", "file name name = f\"{current_solver}\" # Selecting the solver and", "# ** Badia-Codina based a += eta_u * inner(u +", "solver, min_degree=degree, max_degree=degree + last_degree, quadrilateral=True, name=name ) # N", "q * dx # Transmission condition a += jump(u_hat, n)", "hdiv_family = 'RTCF' pressure_family = 'DQ' else: hdiv_family = 'RT'", "* q * ds # may decrease convergente rates #", "Badia-Codina (2010), it is not a classical Nitsche's method a", "color=\"k\") return plot def plot_matrix_primal_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot", "method B in the Badia-Codina paper eta_p = 1 #", "grad(q)) * dx # Classical mixed Darcy eq. first-order terms", "* (p - lambda_h) * n # HDG classical form", "jump(v, n)) * dS a += (avg(eta_u) / h_avg) *", "C0TraceElement = LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: trace_family =", "BC a += (p_boundaries * dot(v, n) + mu_h *", "* h * h delta_3 = Constant(0.5) * h *", "values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) return plot def plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides", "\"dvms\": solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg, # \"cgh\":", "= \"HDiv Trace\" U = VectorFunctionSpace(mesh, velocity_family, degree) V =", "n) * ds # # L = delta_1 * p_exact", "* n) results_dict[\"Degree\"].append(degree) results_dict[\"Symmetric\"].append(result.is_operator_symmetric) results_dict[\"nnz\"].append(result.nnz) results_dict[\"dofs\"].append(result.number_of_dofs) results_dict[\"h\"].append(current_cell_size) results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\"", "= ( # (inner(u, v) - q * div(u) -", "plot = ax.matshow(Am, **kwargs) # Remove axis ticks and values", "# beta = beta_0 # Numerical flux trace u =", "attr.ib() nnz = attr.ib() is_operator_symmetric = attr.ib() bcs = attr.ib(default=list())", "= ax.matshow(Am, **kwargs) # Remove axis ticks and values ax.tick_params(length=0)", "LagrangeElement[\"facet\"] T = FunctionSpace(mesh, C0TraceElement) else: T = FunctionSpace(mesh, trace_family,", "Hybridization parameter s = Constant(-1.0) beta = Constant(32.0) h =", "1 eta_p = L0 * h # method B in", "n) * ds # ** The terms below are based", "* n # Flux least-squares # a = ( #", "* p + q * div(u)) * dx # Stabilizing", "n)) * dS a += eta_u_bc * delta_3 * p", "delta_2 * f * div(v) * dx # Irrotational least-squares", "dot(v, n) * ds # # L = delta_1 *", "terms a += -0.5 * inner((u + grad(p)), v +", "result = solver(mesh, degree=degree) current_cell_size = mesh.cell_sizes.dat.data_ro.min() if not quadrilateral", "grad(q)) * dx a += delta_2 * div(u) * div(v)", "\"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e-18) # beta =", "grad(q)) * dx + jump(u_hat, n) * q(\"+\") * dS", "= Constant(1) # delta = h delta_0 = delta delta_1", "a += delta_5 * (dot(u, n) - dot(u_hat, n)) *", "plt import matplotlib from scipy.linalg import svd from scipy.sparse.linalg import", "terms a = delta_0 * inner(u + grad(p), v +", "== \"scipy\": size = A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros()", "bc?? # a += (beta / h) * (p- p_boundaries)", "+= eta_u * avg(delta_3) * (jump(u, n) * jump(v, n))", "hdiv_family = 'RT' pressure_family = 'DG' U = FunctionSpace(mesh, hdiv_family,", "* dS # not considered in the original paper #", "a = dot(grad(p), grad(q)) * dx L = f *", "result def solve_poisson_ls(mesh, degree=1): # Function space declaration pressure_family =", "idx = trace_index S = A[idx, idx] - A[idx, :idx]", "necessary _A = Tensor(a) A = _A.blocks S = A[2,", "grad(q))) # * delta_1 # * dx # ) #", "= list() if num_converged_values > 0: for i in range(num_converged_values):", "\"Element\": list(), \"Number of Elements\": list(), \"Degree\": list(), \"Symmetric\": list(),", "* (lambda_h - p_boundaries) * ds # a += mu_h", "= Function(V).interpolate(f_expression) # BCs u_projected = sigma_e p_boundaries = p_exact", "* dx # ** Badia-Codina based a += -eta_u *", "n)(\"+\")) * dS # a += delta_5 * (dot(u, n)", ") return result def solve_poisson_sdhm( mesh, degree=1, is_multiplier_continuous=False ): #", "+ grad(p), v + grad(q)) * dx a += eta_p", "use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" primal_family = \"DQ\" if use_quads", "currently unavailable.\") return condition_number def solve_poisson_cg(mesh, degree=1, use_quads=False): # Function", "number estimation is currently unavailable.\") return condition_number def solve_poisson_cg(mesh, degree=1,", "paper # eta_u = h_avg / L0 # method B", "velocity_family = 'DQ' if use_quads else 'DG' trace_family = \"HDiv", "= 'DQ' if use_quads else 'DG' trace_family = \"HDiv Trace\"", "* dx # Stabilizing terms a += delta_1 * inner(u", "condition a += jump(u_hat, n) * mu_h(\"+\") * dS #", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_ls(mesh, degree=1):", "dS - avg(q) * jump(u, n) * dS # Edge", "(dot(v, n) - dot(v_hat, n)) * ds # Weakly imposed", "Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] -", "# method B in the Badia-Codina paper eta_p = 1", "* mu_h(\"+\") * dS # Weakly imposed BC a +=", "A[idx, idx] - A[idx, :idx] * A[:idx, :idx].inv * A[:idx,", "dS - dot(avg(grad(p)), jump(q, n)) * dS # Edge stabilizing", "Function(W) # u, p, lambda_h = split(solution) u, p, lambda_h", "L0 * L0 # method D in the Badia-Codina paper", "{degree} - N = {n}\") mesh = UnitSquareMesh(n, n, quadrilateral=quadrilateral)", "= delta_1 * p_exact * dot(v, n) * ds #", "TrialFunctions(W) v, q = TestFunctions(W) # Mesh entities x, y", "avg(delta_4) * dot(jump(p, n), jump(q, n)) * dS a +=", "is_operator_symmetric=is_symmetric ) return result def solve_poisson_dls(mesh, degree=1): # Function space", "* ds # is this necessary? L += s *", "delta_1 = Constant(1) # delta_2 = Constant(1) # delta_3 =", "* dS # a += delta_1(\"+\") * dot(u_hat, n) *", "BCs bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter beta_0", "0.5 * h * h * inner(curl(u), curl(v)) * dx", "n) - dot(u_hat, n)) * (dot(v, n) - dot(v_hat, n))", "Stabilizing terms a += 0.5 * inner(u + grad(p), grad(q)", "== 0, axis=0)) Mnp = np.delete(Mnp, idx, axis=1) Am =", "+= delta_5 * (dot(u, n) - dot(u_hat, n)) * (dot(v,", "terms a += jump(v, n) * avg(p) * dS -", "= TrialFunctions(W) v, q, mu_h = TestFunctions(W) # Mesh entities", "BCs u_projected = sigma_e p_boundaries = p_exact bcs = DirichletBC(W.sub(2),", "stabilizing terms # a += 0.5 * h * h", "* avg(delta_3) * (jump(u, n) * jump(v, n)) * dS", "terms a += beta(\"+\") * dot(jump(p, n), jump(q, n)) *", "+= 0.5 * h * h * f * div(v)", "+= dot(v, n) * p * ds - q *", "\"nnz\": list(), \"dofs\": list(), \"h\": list(), \"Condition Number\": list(), }", "= delta delta_1 = delta delta_2 = delta delta_3 =", "number. :return: Filtered array with only real numbers. \"\"\" real_part_array", "+= -dot(vel_projected, n) * v * ds # How to", "v, q = TestFunctions(W) # Mesh entities x, y =", "beta(\"+\") * (lambda_h(\"+\") - p(\"+\")) * (mu_h(\"+\") - q(\"+\")) *", "print(f'nnz: {result.nnz}') # print(f'DoFs: {result.number_of_dofs}') # print(f'Condition Number: {result.condition_number}') #", "- lambda_h) * (q - mu_h) * ds # a", "* pi * y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\")", "= h_avg / L0 # method B in the Badia-Codina", "- q * dot(u, n) * ds a += beta", "Constant(0.0) bc_multiplier = DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter s", "solve_poisson_dls(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "bool = False, zero_tol: float = 1e-5 ): backend =", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_dvms(mesh, degree=1):", "condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sipg(mesh,", "p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e-18) # beta", "# a += delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) *", "# \"ldgc\": solve_poisson_ldgc, # \"sipg\": solve_poisson_sipg, } degree = 1", "stabilized dG method L0 = 1 eta_p = L0 *", "ds a += dot(u_hat, n) * q * ds F", "lambda_h) * n # HDG classical form a = (dot(u,", "(lambda_h(\"+\") - p(\"+\")) * (mu_h(\"+\") - q(\"+\")) * dS #", "Edge stabilizing parameter beta0 = Constant(1e1) beta = beta0 /", "= f * q * dx # Transmission condition a", "* dot(u_hat, n) * q * ds # # a", "* h * inner(curl(u), curl(v)) * dx # L +=", "# plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) #", "(avg(eta_p) / h_avg) * (jump(u, n) * jump(v, n)) *", "a = ( # (inner(u, v) - q * div(u)", "beta_0 # Stabilization parameters delta_0 = Constant(-1) delta_1 = Constant(-0.5)", "SVD has not converged.\") singular_values = np.array(singular_values_list) singular_values = singular_values[singular_values", "= TrialFunction(V) v = TestFunction(V) # Dirichlet BCs bcs =", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bcs ) return result def solve_poisson_hdg(", "solver=\"lobpcg\" ) else: M = Mnp.toarray() singular_values = svd(M, compute_uv=False,", "# a += 0.5 * h * h * inner(curl(u),", "name=name ) # N = 5 # mesh = UnitSquareMesh(N,", "* (dot(v, n)(\"+\") - dot(v_hat, n)(\"+\")) * dS # a", "degree) # Trial and test functions p = TrialFunction(V) q", "- dot(avg(grad(p)), jump(q, n)) * dS # Edge stabilizing terms", "* (q(\"+\") - mu_h(\"+\")) * dS a += (beta /", "p_exact = sin(2 * pi * x) * sin(2 *", "v, q = TestFunctions(W) # Mesh entities h = CellDiameter(mesh)", "+= eta_p * div(u) * div(v) * dx # Weakly", "dS a += delta_1 * lambda_h * dot(v, n) *", "# Variational form a = inner(grad(u), grad(v)) * dx A", "- p(\"+\")) * (mu_h(\"+\") - q(\"+\")) * dS # Weakly", "= Function(W) # u, p, lambda_h = split(solution) p, lambda_h", "f * div(v) * dx # a += 0.5 *", "dot(u, n) * dot(v, n) * ds # ** Mesh", "velocity_family = 'DQ' if use_quads else 'DG' U = VectorFunctionSpace(mesh,", "import svds from scipy.sparse import csr_matrix from slepc4py import SLEPc", "not a good way to impose BC, but this necessary", "n) * p_boundaries * ds F = a - L", "degree=1, use_quads=False): # Function space declaration V = FunctionSpace(mesh, \"CG\",", "dot(u, n) * dot(v, n) * ds a += (eta_u", "* div(v) * dx # Hybridization terms a += lambda_h(\"+\")", "return result def solve_poisson_cgh( mesh, degree=1, is_multiplier_continuous=False ): # Function", "S.setWhichSingularTriplets(SLEPc.SVD.Which.LARGEST) S.solve() num_converged_values = S.getConverged() singular_values_list = list() if num_converged_values", "* dx # L += 0.5 * f * div(v)", "grad(q) - v) * dx a += eta_p * div(u)", "* dS a += eta_p * avg(delta_4) * dot(jump(p, n),", "* n v_hat = v + beta * (q -", "_A = Tensor(a_form) A = _A.blocks idx = trace_index S", "- div(v) * p - q * div(u)) * dx", "Dirichlet BCs bcs = DirichletBC(V, 0.0, \"on_boundary\") # Variational form", "plot_matrix_mixed(assembled_form, **kwargs): \"\"\"Provides a plot of a mixed matrix.\"\"\" fig,", "(-1) or NIPG (1) s = Constant(-1) # Classical volumetric", "classical form a = -dot(u, grad(q)) * dx + jump(u_hat,", "- 0.5, color=\"k\") return plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs):", "1) _A = Tensor(a_form) A = _A.blocks idx = trace_index", "s * dot(jump(p, n), avg(grad(q))) * dS - dot(avg(grad(p)), jump(q,", "# Below there is the spy alternative # plot =", "= Tensor(a) A = _A.blocks S = A[2, 2] -", "* import numpy as np import matplotlib.pyplot as plt import", "mu_h = TestFunctions(W) # Mesh entities n = FacetNormal(mesh) h", "q * div(u)) * dx # Stabilizing terms a +=", "= beta_0 # Numerical flux trace u_hat = u +", "# Irrotational least-squares a += delta_3 * inner(curl(u), curl(v)) *", "trace_index S = A[idx, idx] - A[idx, :idx] * A[:idx,", "div(v) * dx a += eta_p * inner(curl(u), curl(v)) *", "/ h delta_4 = 1 / h # Least-squares terms", "color=\"k\") return plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs): \"\"\"Provides a", "FunctionSpace(mesh, C0TraceElement) else: T = FunctionSpace(mesh, trace_family, degree) W =", "* ds F = a - L a_form = lhs(F)", "q = TestFunctions(W) # Mesh entities x, y = SpatialCoordinate(mesh)", "results_dict[\"Condition Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results", "= (h(\"+\") + h(\"-\")) / 2.0 # Jump stabilizing parameters", "is_multiplier_continuous: LagrangeElement = FiniteElement(\"Lagrange\", mesh.ufl_cell(), degree) C0TraceElement = LagrangeElement[\"facet\"] T", "singular_values = np.array(singular_values_list) singular_values = singular_values[singular_values > zero_tol] condition_number =", "= False, zero_tol: float = 1e-5 ): backend = backend.lower()", "\"quadrilateral\" pressure_family = 'DQ' if use_quads else 'DG' velocity_family =", "Volumetric stabilizing terms # a += 0.5 * inner(u +", "Mnp.eliminate_zeros() if use_sparse: singular_values = svds( A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000,", "-0.5 * inner(u + grad(p), v + grad(q)) * dx", "# method D in the Badia-Codina paper # eta_u =", "u, p, lambda_h = split(solution) u, p, lambda_h = TrialFunctions(W)", "lambda_h * dot(v, n) * ds a += dot(u_hat, n)", "dot(jump(p, n), avg(grad(q))) * dS - dot(avg(grad(p)), jump(q, n)) *", "in complex number. :return: Filtered array with only real numbers.", "result def solve_poisson_vms(mesh, degree=1): # Function space declaration pressure_family =", "# may decrease convergente rates (Nitsche) A = assemble(a, mat_type=\"aij\")", "dx a += delta_3 * inner(curl(u), curl(v)) * dx L", "fig, ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle f0_size =", "+ q * div(u)) * dx A = assemble(a, bcs=bcs,", "Dirichlet BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Mixed classical", "beta_0 / h(\"+\") # Stabilizing parameter # delta_0 = Constant(1)", "\"quadrilateral\" if use_quads: hdiv_family = 'RTCF' pressure_family = 'DQ' else:", "* dS # ** Mesh independent (original) # a +=", "+ grad(p), v + grad(q)) * dx # Classical mixed", "Badia-Codina paper eta_u = h / L0 # method B", "* inner(u + grad(p), v + grad(q)) * dx a", "nnz=nnz, is_operator_symmetric=is_symmetric, bcs=bc_multiplier ) return result def solve_poisson_cgh( mesh, degree=1,", "+= delta_1 * dot(u, n) * q * ds #", "axis=1) Am = np.ma.masked_values(Mnp, 0, rtol=1e-13) # Plot the matrix", "a = delta_1 * inner(u + grad(p), v + grad(q))", "- 0.5, color=\"k\") ax.axhline(y=f0_size[0] + f1_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0]", "(original) # a += jump(u, n) * jump(v, n) *", "n) * q(\"+\") * dS L = f * q", "terms # ** Badia-Codina based (better results) ** a +=", "in a numpy array. :param array: Array with real and", "/ L0 # method B in the Badia-Codina paper eta_u", "* dx # L += 0.5 * h * h", "Weak boundary conditions a += s * dot(p * n,", "% name, exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" %", "L0 = 1 eta_p = L0 * h # method", "eta_u * inner(u + grad(p), grad(q) - v) * dx", "assembled_form=A, condition_number=condition_number, sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def", "S.solve() num_converged_values = S.getConverged() singular_values_list = list() if num_converged_values >", "- 0.5, color=\"k\") return plot def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides", "0].handle.getSize() size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() Mnp", "jump(q, n)) * dS a += eta_u_bc * delta_3 *", "\"dofs\": list(), \"h\": list(), \"Condition Number\": list(), } element_kind =", "# L += 0.5 * h * h * f", "= f * q * dx # Hybridization terms a", "delta_2 = delta delta_3 = 1 / h delta_4 =", "): backend = backend.lower() if backend == \"scipy\": size =", "s = Constant(-1) # Classical volumetric terms a = inner(grad(p),", "dx L = f * q * dx # DG", "\"on_boundary\", method=\"geometric\") # Average cell size and mesh dependent stabilization", "lambda_h * dot(v, n) * ds # Mass balance least-square", "* avg(delta_4) * dot(jump(p, n), jump(q, n)) * dS a", "dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric", "ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0] - 0.5, color=\"k\") ax.axhline(y=f0_size[0]", "jump(q, n)) * dS # ** Mesh independent terms #", "* q(\"+\") * dS L = f * q *", "ds # Mass balance least-square a += delta_2 * div(u)", ":] == 0, axis=0)) Mnp = np.delete(Mnp, idx, axis=1) Am", "# # plot_matrix_mixed(result.assembled_form, cmap=my_cmap) # plt.tight_layout() # plt.savefig(\"sparse_pattern.png\") # plt.show()", "} degree = 1 last_degree = 1 for current_solver in", "- dot(v_hat, n)(\"+\")) * dS # a += delta_5 *", "imposed BC a += dot(u_hat, n) * q * ds", "* div(u) * div(v) * dx # L = delta_2", "a += (beta / h_avg) * (p(\"+\") - lambda_h(\"+\")) *", "= Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") # Forcing function f_expression =", "A[1, :1] * A[:1, :1].inv * A[:1, 1] Smat =", "ds # is this necessary? L += s * dot(grad(q),", "p * q * ds # may decrease convergente rates", "(Nitsche) A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric =", "# # plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap) # plot_matrix_hybrid_multiplier(result.form, trace_index=2, bcs=result.bcs, cmap=my_cmap)", "* dx # DG edge terms a += s *", "def plot_matrix_mixed_hybrid_full(a_form, bcs=[], **kwargs): \"\"\"Provides a plot of a full", "> zero_tol] condition_number = singular_values.max() / singular_values.min() else: raise NotImplementedError(\"The", "tqdm(range(min_degree, max_degree)) for degree in pbar: for n in numel_xy:", "solvers_options[current_solver] # Performing the convergence study hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree", "method=\"geometric\") # Average cell size and mesh dependent stabilization h_avg", "# Dirichlet BCs bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Stabilization", "# a += 0.5 * h * h * div(u)", "+ grad(q)) * dx a += delta_2 * div(u) *", "ax.matshow(Am, **kwargs) # Remove axis ticks and values ax.tick_params(length=0) ax.set_xticklabels([])", "h delta_4 = 1 / h # Least-squares terms a", "is currently unavailable.\") return condition_number def solve_poisson_cg(mesh, degree=1, use_quads=False): #", "# Dirichlet BCs bcs = DirichletBC(V, 0.0, \"on_boundary\") # Variational", "div(v) * dx # Weakly imposed boundary conditions a +=", "= sin(2 * pi * x) * sin(2 * pi", "Badia-Codina paper eta_u_bc = 1 # Least-Squares weights delta =", "dS # a += delta_1 * lambda_h * dot(v, n)", "n), jump(q, n)) * dS a += eta_u_bc * delta_3", "beta_0 = Constant(1.0e0) beta = beta_0 / h # beta", "* h * h delta_2 = Constant(0.5) * h *", "DirichletBC(W.sub(2), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e0) beta", "0.5 * div(u) * div(v) * dx a += 0.5", "A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" ) else: M =", "use_sparse: bool = False, zero_tol: float = 1e-5 ): backend", "* dS a += -dot(u, grad(q)) * dx + jump(u_hat,", "num_of_factors, backend: str = \"scipy\", use_sparse: bool = False, zero_tol:", "name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs bcs = DirichletBC(W[0], sigma_e,", "results_dict = { \"Element\": list(), \"Number of Elements\": list(), \"Degree\":", "dot(v, n) * ds a += (eta_u / h) *", "dot(v, n) * ds # ** Mesh independent ** #", "sparse_operator=Mnp, number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_sipg(mesh, degree=1):", "a += lambda_h * dot(v, n) * ds a +=", "{result.nnz}') # print(f'DoFs: {result.number_of_dofs}') # print(f'Condition Number: {result.condition_number}') # #", "(p(\"+\") - lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) * dS #", "quadrilateral=True, name=name ) # N = 5 # mesh =", "A[:idx, :idx].inv * A[:idx, idx] Smat = assemble(S, bcs=bcs) petsc_mat", "* div(v) * dx a += delta_3 * inner(curl(u), curl(v))", "grad(p), v + grad(q)) * dx a += delta_1 *", "solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm, # \"ls\": solve_poisson_ls, # \"dls\": solve_poisson_dls,", "SpatialCoordinate(mesh) # Exact solution p_exact = sin(2 * pi *", "zero_tol] condition_number = singular_values.max() / singular_values.min() else: raise NotImplementedError(\"The required", "y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") # Forcing function", "A = assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8)", "- div(v) * p + delta_0 * q * div(u))", "\"DG\" V = FunctionSpace(mesh, primal_family, degree) if is_multiplier_continuous: LagrangeElement =", "- mu_h(\"+\")) * dS a += (beta / h_avg) *", "Selecting the solver and its kwargs solver = solvers_options[current_solver] #", "* dot(v, n) * ds # ** Mesh independent **", "f1_size[0] - 0.5, color=\"k\") return plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[],", "a += delta_1 * dot(u, n) * q * ds", "pressure_family = 'DQ' if use_quads else 'DG' V = FunctionSpace(mesh,", "** # a += jump(u, n) * jump(v, n) *", "h # method B in the Badia-Codina paper # eta_p", "* jump(v, n)) * dS a += (avg(eta_u) / h_avg)", "= csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() nnz = Mnp.nnz number_of_dofs = W.dim()", "'DG' U = VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family,", "ds # may decrease convergente rates # ** Classical Nitsche", "method L0 = 1 eta_p = L0 * h #", "L += 0.5 * f * div(v) * dx A", "delta_1 = Constant(-0.5) * h * h delta_2 = Constant(0.5)", "= assemble(a, mat_type=\"aij\") petsc_mat = A.M.handle is_symmetric = petsc_mat.isSymmetric(tol=1e-8) size", "* dot(jump(p, n), jump(q, n)) * dS a += eta_u_bc", "h_avg = avg(h) # Classical term a = dot(grad(p), grad(q))", "0: for i in range(num_converged_values): singular_value = S.getValue(i) singular_values_list.append(singular_value) else:", "if num_converged_values > 0: for i in range(num_converged_values): singular_value =", "n)) * dS # ** Mesh independent (original) # a", "* dot(u_projected, n) * q * ds # a +=", "Badia-Codina paper # eta_p = L0 * L0 # method", "jump(v, n) * avg(p) * dS - avg(q) * jump(u,", "div(u)) * dx # Stabilizing terms a += -0.5 *", "= mesh.cell_sizes.dat.data_ro.min() if not quadrilateral else 1 / n results_dict[\"Element\"].append(element_kind)", "* (dot(u, n)(\"+\") - dot(u_hat, n)(\"+\")) * (dot(v, n)(\"+\") -", "div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # BCs u_projected = sigma_e p_boundaries", "\"label\") # Forcing function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression)", "== \"quadrilateral\" if use_quads: hdiv_family = 'RTCF' pressure_family = 'DQ'", "h_avg) * (p(\"+\") - lambda_h(\"+\")) * (q(\"+\") - mu_h(\"+\")) *", "dS # ** Mesh independent (original) # a += jump(u,", "delta = Constant(1) # delta = h delta_0 = delta", "name = f\"{current_solver}\" # Selecting the solver and its kwargs", "a += (avg(eta_u) / h_avg) * dot(jump(p, n), jump(q, n))", "div(u) * div(v) * dx a += delta_3 * inner(curl(u),", "n) * dS # not considered in the original paper", "v) - div(v) * p + delta_0 * q *", "f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet BCs bc_multiplier", "dx # Classical mixed Darcy eq. first-order terms as stabilizing", "grad(p), v + grad(q)) * dx a += eta_p *", "dx # ) # # These terms below are unsymmetric", "0.5 * h * h * div(u) * div(v) *", "degree=1): # Function space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\"", "= FunctionSpace(mesh, hdiv_family, degree + 1) V = FunctionSpace(mesh, pressure_family,", "s * dot(grad(q), n)(\"+\") * (p(\"+\") - lambda_h(\"+\")) * dS", "* div(v) * dx # Irrotational least-squares a += delta_3", "# # L = -delta_1 * dot(u_projected, n) * q", "ds - dot(grad(p), q * n) * ds a +=", "is_multiplier_continuous=True ): # Function space declaration use_quads = str(mesh.ufl_cell()) ==", "- lambda_h) * n # HDG classical form a =", "name, exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results = \"./cond_number_results/results_%s/cond_numbers.csv\" % name", "solution = Function(W) # u, p, lambda_h = split(solution) u,", "condition number estimation is currently unavailable.\") return condition_number def solve_poisson_cg(mesh,", "solve_poisson_cg, # \"cgls\": solve_poisson_cgls, # \"dgls\": solve_poisson_dgls, # \"sdhm\": solve_poisson_sdhm,", "n), avg(grad(q))) * dS - dot(avg(grad(p)), jump(q, n)) * dS", "# Dirichlet BCs p_boundaries = Constant(0.0) bc_multiplier = DirichletBC(W.sub(1), p_exact,", "matplotlib.use('TkAgg') # import copy # my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\")", "is_symmetric = petsc_mat.isSymmetric(tol=1e-12) size = petsc_mat.getSize() Mnp = csr_matrix(petsc_mat.getValuesCSR()[::-1], shape=size)", "Plot the matrix plot = ax.matshow(Am, **kwargs) # Remove axis", "Forcing function f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # Dirichlet", "q(\"+\") * dS # a += delta_1(\"+\") * dot(u_hat, n)", "bcs = DirichletBC(W[0], sigma_e, \"on_boundary\") # Stabilization parameters delta_1 =", "TestFunctions(W) # Mesh entities n = FacetNormal(mesh) h = CellDiameter(mesh)", "\"Condition Number\": list(), } element_kind = \"Quad\" if quadrilateral else", "* dS # Boundary terms # a += -dot(vel_projected, n)", "= attr.ib() bcs = attr.ib(default=list()) def plot_matrix(assembled_form, **kwargs): \"\"\"Provides a", "* y) exact_solution = Function(V).interpolate(p_exact) exact_solution.rename(\"Exact pressure\", \"label\") sigma_e =", "'DG' V = FunctionSpace(mesh, pressure_family, degree) # Trial and test", "Number\"].append(result.condition_number) os.makedirs(\"./cond_number_results/results_%s\" % name, exist_ok=True) df_cond_number = pd.DataFrame(data=results_dict) path_to_save_results =", "pressure\", \"label\") sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Forcing", "* dx # a += -0.5 * inner(u + grad(p),", "dot(u_hat, n) * q * ds # # a +=", "grad(p), v + grad(q)) * dx # Classical mixed Darcy", "matrix.\"\"\" fig, ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle f0_size", ") return result def solve_poisson_ls(mesh, degree=1): # Function space declaration", "A = _A.blocks S = A[1, 1] - A[1, :1]", "a += eta_p * inner(curl(u), curl(v)) * dx # Weakly", "declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" if use_quads: hdiv_family =", "L0 # method D in the Badia-Codina paper # eta_u", "eta_u_bc = 1 # Least-Squares weights delta = Constant(1.0) #", "= Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # BCs bcs = DirichletBC(W.sub(2),", "study hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree + last_degree, quadrilateral=True, name=name )", "a += beta * p * q * ds #", "a += mu_h(\"+\") * jump(u_hat, n=n) * dS a +=", "numel_xy=(5, 10, 15, 20, 25), quadrilateral=True, name=\"\", **kwargs ): results_dict", "solve_poisson_vms, # \"dvms\": solve_poisson_dvms, # \"mixed_RT\": solve_poisson_mixed_RT, # \"hdg\": solve_poisson_hdg,", "# a += delta_4 * (p - lambda_h) * (q", "div(v) * dx a += 0.5 * div(u) * div(v)", "f_expression = div(-grad(p_exact)) f = Function(V).interpolate(f_expression) # BCs u_projected =", "a += beta * p * q * ds A", "\"scipy\": size = A.getSize() Mnp = csr_matrix(A.getValuesCSR()[::-1], shape=size) Mnp.eliminate_zeros() if", "# Performing the convergence study hp_refinement_cond_number_calculation( solver, min_degree=degree, max_degree=degree +", "Mnp.toarray() singular_values = svd(M, compute_uv=False, check_finite=False) singular_values = singular_values[singular_values >", "- mu_h) * n # Flux least-squares # a =", "Hybridization terms a += mu_h(\"+\") * jump(u_hat, n=n) * dS", "1e-5] return real_part_array def calculate_condition_number( A, num_of_factors, backend: str =", "f = Function(V).interpolate(f_expression) # Dirichlet BCs p_boundaries = Constant(0.0) bc_multiplier", "# Flux least-squares # a = ( # (inner(u, v)", "Constant(0.5) * h * h # Mixed classical terms a", "delta_5 * (dot(u, n)(\"+\") - dot(u_hat, n)(\"+\")) * (dot(v, n)(\"+\")", "* dot(jump(p, n), jump(q, n)) * dS # ** Mesh", "# bcs = DirichletBC(W[0], sigma_e, \"on_boundary\", method=\"geometric\") # Average cell", "axis=0)) Mnp = np.delete(Mnp, idx, axis=1) Am = np.ma.masked_values(Mnp, 0,", "- L a_form = lhs(F) _A = Tensor(a_form) A =", "DirichletBC(W.sub(1), p_exact, \"on_boundary\") # Hybridization parameter beta_0 = Constant(1.0e0) beta", "space declaration use_quads = str(mesh.ufl_cell()) == \"quadrilateral\" primal_family = \"DQ\"", "trace_family, degree) W = V * T # Trial and", "sigma_e, \"on_boundary\", method=\"geometric\") # Average cell size and mesh dependent", ") return result def solve_poisson_sipg(mesh, degree=1): # Function space declaration", "(beta / h) * (p- p_boundaries) * q * ds", "this necessary _A = Tensor(a) A = _A.blocks S =", "+= delta_1(\"+\") * lambda_h(\"+\") * jump(v, n=n) * dS #", "# (mu_h - q) * (lambda_h - p_boundaries) * ds", "solve_poisson_cg(mesh, degree=1, use_quads=False): # Function space declaration V = FunctionSpace(mesh,", "name=\"\", **kwargs ): results_dict = { \"Element\": list(), \"Number of", "scale problems.\"\"\" fig, ax = plt.subplots(1, 1) _A = Tensor(a_form)", "convergente rates a += eta_u_bc * delta_4 * dot(u, n)", "Mesh entities n = FacetNormal(mesh) h = CellDiameter(mesh) x, y", "\"Number of Elements\": list(), \"Degree\": list(), \"Symmetric\": list(), \"nnz\": list(),", "result def solve_poisson_lsh( mesh, degree=1, is_multiplier_continuous=False ): # Function space", "FunctionSpace(mesh, pressure_family, degree) # Trial and test functions p =", "# # plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap) # # plot_matrix_mixed_hybrid_full(result.form, result.bcs, cmap=my_cmap)", "elif backend == \"slepc\": S = SLEPc.SVD() S.create() S.setOperator(A) S.setType(SLEPc.SVD.Type.LAPACK)", "h beta_avg = beta_0 / h(\"+\") # Stabilizing parameter #", "* dS - avg(q) * jump(u, n) * dS #", "ax = plt.subplots(1, 1) petsc_mat = assembled_form.M.handle size = petsc_mat.getSize()", "shape=size) Mnp.eliminate_zeros() if use_sparse: singular_values = svds( A=Mnp, k=num_of_factors, which=\"LM\",", "q * dot(u, n) * ds a += beta *", "div(v) * dx A = assemble(a, bcs=bcs, mat_type=\"aij\") petsc_mat =", "(mu_h(\"+\") - q(\"+\")) * dS # Weakly imposed BC a", "* jump(u, n) * dS # Edge stabilizing terms #", "T # Trial and test functions # solution = Function(W)", "(p_boundaries * dot(v, n) + mu_h * (dot(u, n) -", "as np import matplotlib.pyplot as plt import matplotlib from scipy.linalg", "q * dx # Hybridization terms a += s *", "* (dot(v, n) - dot(v_hat, n)) * ds # Weakly", "delta_4 = LARGE_NUMBER / h delta_5 = delta # Numerical", "# Edge stabilizing terms # ** Badia-Codina based a +=", "# Least-Squares weights delta = Constant(1.0) # delta = h", "if use_sparse: singular_values = svds( A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False,", "Constant(1) # delta = h delta_0 = delta delta_1 =", "(better results) ** a += eta_u * avg(delta_3) * (jump(u,", "number_of_dofs=number_of_dofs, nnz=nnz, is_operator_symmetric=is_symmetric ) return result def solve_poisson_mixed_RT(mesh, degree=1): #", ") return result def solve_poisson_cgls(mesh, degree=1): # Function space declaration", "+= eta_p * inner(curl(u), curl(v)) * dx # Weakly imposed", "beta = beta_0 / h # Mixed classical terms a", "plt.subplots(1, 1) petsc_mat = assembled_form.M.handle f0_size = assembled_form.M[0, 0].handle.getSize() size", "= Constant(32.0) h = CellDiameter(mesh) h_avg = avg(h) # Classical", "a plot of a full hybrid-mixed matrix.\"\"\" fig, ax =", "problems.\"\"\" fig, ax = plt.subplots(1, 1) _A = Tensor(a_form) A", "TestFunction(V) # Dirichlet BCs bcs = DirichletBC(V, 0.0, \"on_boundary\") #", "= VectorFunctionSpace(mesh, velocity_family, degree) V = FunctionSpace(mesh, pressure_family, degree) W", "delta_4 * (p - lambda_h) * (q - mu_h) *", "def solve_poisson_cgls(mesh, degree=1): # Function space declaration pressure_family = 'CG'", "list(), \"Condition Number\": list(), } element_kind = \"Quad\" if quadrilateral", "def solve_poisson_sipg(mesh, degree=1): # Function space declaration use_quads = str(mesh.ufl_cell())", "* jump(v, n=n) * dS # a += delta_1 *", "0.5, color=\"k\") return plot def plot_matrix_hybrid_multiplier(a_form, trace_index=2, bcs=[], **kwargs): \"\"\"Provides", "# Stabilizing terms a += 0.5 * inner(u + grad(p),", "independent terms # a += jump(u, n) * jump(v, n)", "functions u = TrialFunction(V) v = TestFunction(V) # Dirichlet BCs", "estimation is currently unavailable.\") return condition_number def solve_poisson_cg(mesh, degree=1, use_quads=False):", "* ds # may decrease convergente rates a += eta_u_bc", "= -dot(u, grad(q)) * dx + jump(u_hat, n) * q(\"+\")", "# u, p, lambda_h = split(solution) p, lambda_h = TrialFunctions(W)", "+= beta * p * q * ds A =", "# beta = beta_0 / h beta = beta_0 #", "singular_values = svds( A=Mnp, k=num_of_factors, which=\"LM\", maxiter=5000, return_singular_vectors=False, solver=\"lobpcg\" )", "sigma_e = Function(U, name='Exact velocity') sigma_e.project(-grad(p_exact)) # Dirichlet BCs #", "delta = h delta_0 = delta delta_1 = delta delta_2", "# \"sipg\": solve_poisson_sipg, } degree = 1 last_degree = 1", "# Hybridization parameter beta_0 = Constant(1.0e0) beta = beta_0 /", "split(solution) u, p, lambda_h = TrialFunctions(W) v, q, mu_h =", "u = TrialFunction(V) v = TestFunction(V) # Dirichlet BCs bcs", "my_cmap = copy.copy(plt.cm.get_cmap(\"winter\")) # my_cmap.set_bad(color=\"lightgray\") # # plot_matrix_primal_hybrid_full(result.form, result.bcs, cmap=my_cmap)", "a += -0.5 * inner(u + grad(p), v + grad(q))", "# L0 = 1 # eta_p = L0 * h_avg", ") # maybe this is not a good way to", "the resulting matrix # matplotlib.use('TkAgg') # import copy # my_cmap", "Tensor(a_form) A = _A.blocks S = A[2, 2] - A[2,", "and values ax.tick_params(length=0) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.axhline(y=f0_size[0] - 0.5, color=\"k\") ax.axvline(x=f0_size[0]", "# maybe this is not a good way to impose" ]
[ "In [4]: d, l = load_deap(path, 0) In [5]: hoc(d,", "int, optional Order, by default 10 Return ---------- nzc: Solved", "[14]: statistics_feature(d).shape Out[14]: (40, 32, 7) \"\"\" # Power power", "= f.reshape((*f.shape[:-2])) return f def calc_L(X, k, m): \"\"\" Return", "than box counting The higuchi method is used here because", "k): \"\"\" Return <L(k)> as the average value over k", "@File :_time_domain_features.py @Time :2021/04/16 20:02:55 @Author :wlgls @Version :1.0 '''", "is solved, which is used to describe the shape information", "---------- In [13]: d.shape, l.shape Out[13]: ((40, 32, 8064), (40,", "return ).shape Out[8]: (40, 32, 1) \"\"\" calc_L_average_series = np.frompyfunc(lambda", "of 2nd difference mean diff_2nd = np.mean(np.abs(data[..., 2:] - data[...,", "to describe the shape information of EEG time series data.", "on. Sevcik method: fast calculation and robust analysis of noise", "of Lm(k). \"\"\" calc_L_series = np.frompyfunc(lambda m: calc_L(X, k, m),", "f = np.stack((activity, mobility, complexity), axis=-1) if combined: f =", "as np def statistics(data, combined=True): \"\"\"Statistical features, include Power, Mean,", "\"\"\" calc_L_average_series = np.frompyfunc(lambda k: calc_L_average(data, k), 1, 1) k", "np.max(x) miny = np.expand_dims(np.min(data, axis=-1), axis=-1) maxy = np.expand_dims(np.max(data, axis=-1),", "= np.diff(data, n=1, axis=-1) # print(diff_1st.shape) diff_2nd = data[..., 2:]", "theoretical value than box counting The Sevick method is used", "# print(FD.shape) if combined: f = f.reshape((*f.shape[:-2])) return f def", "\"\"\" # Power power = np.mean(data**2, axis=-1) # Mean ave", "the absolute values of 2nd difference mean diff_2nd = np.mean(np.abs(data[...,", "ave = np.mean(data, axis=-1)[..., np.newaxis] diff_1st = np.diff(data, n=1, axis=-1)", "return f def higher_order_crossing(data, k=10, combined=True): \"\"\"Solving the feature of", "features, include activity, mobility, complexity Parameters ---------- data array data,", "= diff_2nd / std # Features.append(np.concatenate((Power, Mean, Std, diff_1st, normal_diff_1st,", "n_channels, n_features) Example ---------- In [7]: d.shape, l.shape Out[7]: ((40,", "method: fast calculation and robust analysis of noise Higuchi: closer", "axis=-1)**2 + np.diff(x_)**2), axis=-1), axis=-1) f = 1 + np.log(L)", "n = np.floor((N-m)/k).astype(np.int64) norm = (N-1) / (n*k) ss =", "1, 1) k = np.arange(1, k_max+1) L = calc_L_average_series(k) L", "1)) In [8]: sevcik_fd(d).shape Out[8]: (40, 32, 1) \"\"\" points", "= (N-1) / (n*k) ss = np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1)", "Return <L(k)> as the average value over k sets of", "Deviation std = np.std(data, axis=-1) # the mean of the", "Normalized 2nd difference. Parameters ---------- data array data, for DEAP", "= X.shape[-1] n = np.floor((N-m)/k).astype(np.int64) norm = (N-1) / (n*k)", "((40, 32, 8064), (40, 1)) In [16]: hjorth_features(d).shape Out[16]: (40,", "Lm def calc_L_average(X, k): \"\"\" Return <L(k)> as the average", "data, for DEAP dataset, It's shape may be (n_trials, n_channels,", "mean of the absolute values of Normalized 1st difference normal_diff_1st", "2:] - data[..., :-2] # Activity activity = np.mean((data-ave)**2, axis=-1)", "of 1st differece mean diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) #", "curr_diff = np.diff(data, n=i) x_t = curr_diff >= 0 x_t", "\"\"\" N = X.shape[-1] n = np.floor((N-m)/k).astype(np.int64) norm = (N-1)", "f.shape is (n_trials, n_channels, n_features) Example ---------- In [13]: d.shape,", "describe the shape information of EEG time series data. It", "1) fd[ind[0], ind[1if combined: f = f return ], ind[2]]", "f def hjorth(data, combined=True): \"\"\"Solving Hjorth features, include activity, mobility,", "((40, 32, 8064), (40, 1)) In [8]: sevcik_fd(d).shape Out[8]: (40,", "= np.sqrt(varsdiff/varfdiff) / mobility f = np.stack((activity, mobility, complexity), axis=-1)", "[16]: hjorth_features(d).shape Out[16]: (40, 32, 3) \"\"\" data = np.array(data)", "diff_1st / std # the mean of the absolute values", "2nd difference normal_diff_2nd = diff_2nd / std # Features.append(np.concatenate((Power, Mean,", "std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1) if combined: f =", "feature of hoc. Hoc is a high order zero crossing", "[6]: hoc(d, k=5).shape Out[6]: (40, 32, 5) \"\"\" nzc =", "fast calculation and robust analysis of noise Higuchi: closer to", "k: calc_L_average(data, k), 1, 1) k = np.arange(1, k_max+1) L", "(n_trials, n_channels, points), the f.shape is (n_trials, n_channels, n_features) Example", "np.array(data) ave = np.mean(data, axis=-1)[..., np.newaxis] diff_1st = np.diff(data, n=1,", "(n_trials, n_channels, n_features) Example ---------- In [15]: d.shape, l.shape Out[15]:", "= calc_L_average_series(k) L = np.stack(L, axis=-1) fd = np.zeros(data.shape[:-1]) for", "absolute values of Normalized 1st difference normal_diff_1st = diff_1st /", "difference normal_diff_1st = diff_1st / std # the mean of", "L = calc_L_average_series(k) L = np.stack(L, axis=-1) fd = np.zeros(data.shape[:-1])", "N = X.shape[-1] n = np.floor((N-m)/k).astype(np.int64) norm = (N-1) /", "np.diff(data, n=i) x_t = curr_diff >= 0 x_t = np.diff(x_t)", "= np.var(diff_2nd, axis=-1) complexity = np.sqrt(varsdiff/varfdiff) / mobility f =", "mean diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) # the mean of", "L_average = np.average(calc_L_series(np.arange(1, k+1))) return L_average def higuchi_fd(data, k_max, combined=True):", "points) k : int, optional Order, by default 10 Return", "complexity = np.sqrt(varsdiff/varfdiff) / mobility f = np.stack((activity, mobility, complexity),", "y_ = (data-miny) / (maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 +", "to judge the electrooculogram and EEG.The calculation methods include Sevcik,", ":-2] # Activity activity = np.mean((data-ave)**2, axis=-1) # print(Activity.shape) #", "(n_trials, n_channels, points) k : int, optional Order, by default", "In [14]: statistics_feature(d).shape Out[14]: (40, 32, 7) \"\"\" # Power", "be (n_trials, n_channels, points) k : int, optional Order, by", "axis=-1), axis=-1) maxy = np.expand_dims(np.max(data, axis=-1), axis=-1) y_ = (data-miny)", "def statistics(data, combined=True): \"\"\"Statistical features, include Power, Mean, Std, 1st", "fractal Brownian motion, box counting, Higuchi and so on. Sevcik", "# the mean of the absolute values of Normalized 2nd", "32, 8064), (40, 1)) In [16]: hjorth_features(d).shape Out[16]: (40, 32,", "is used to describe the shape information of EEG time", "shape is similar to the shape of your input data.", "Parameters ---------- data : array data, for DEAP dataset, It's", "= np.expand_dims(np.min(data, axis=-1), axis=-1) maxy = np.expand_dims(np.max(data, axis=-1), axis=-1) y_", "---------- data array data, for DEAP dataset, It's shape may", "the absolute values of 1st differece mean diff_1st = np.mean(np.abs(np.diff(data,n=1,", "std = np.std(data, axis=-1) # the mean of the absolute", "if combined: f = f.reshape((*f.shape[:-2])) return f def hjorth(data, combined=True):", "points), the f.shape is (n_trials, n_channels, n_features) Example ---------- In", "(40, 1)) In [16]: hjorth_features(d).shape Out[16]: (40, 32, 3) \"\"\"", "f def calc_L(X, k, m): \"\"\" Return Lm(k) as the", "(40, 1)) In [8]: higuchi_fd(dif combined: f = f return", "calc_L_average_series(k) L = np.stack(L, axis=-1) fd = np.zeros(data.shape[:-1]) for ind", "k=5).shape Out[6]: (40, 32, 5) \"\"\" nzc = [] for", "x_t = np.diff(x_t) x_t = np.abs(x_t) count = np.count_nonzero(x_t, axis=-1)", "= np.diff(x_t) x_t = np.abs(x_t) count = np.count_nonzero(x_t, axis=-1) nzc.append(count)", "return f def calc_L(X, k, m): \"\"\" Return Lm(k) as", "your input data. e.g. for input.shape is (n_trials, n_channels, points),", "@Time :2021/04/16 20:02:55 @Author :wlgls @Version :1.0 ''' import numpy", "x_t = np.abs(x_t) count = np.count_nonzero(x_t, axis=-1) nzc.append(count) f =", "Normalized 1st difference, 2nd difference, Normalized 2nd difference. Parameters ----------", "axis=-1) # print(varfdiff.shape) mobility = np.sqrt(varfdiff / activity) # Complexity", "- data[..., :-2] # Activity activity = np.mean((data-ave)**2, axis=-1) #", "Higuchi: closer to the theoretical value than box counting The", "import numpy as np def statistics(data, combined=True): \"\"\"Statistical features, include", "D f = np.expand_dims(fd, axis=-1) if combined: f = f.reshape((*f.shape[:-2]))", "0) In [5]: hoc(d, k=10).shape Out[5]: (40, 32, 10) In", "= np.stack((power, ave, std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1) if", "zero crossing quantity. Parameters ---------- data : array data, for", "f def sevcik_fd(data, combined=True): \"\"\"Fractal dimension feature is solved, which", "of noise Higuchi: closer to the theoretical value than box", "calc_L_average(X, k): \"\"\" Return <L(k)> as the average value over", "= np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2), axis=-1), axis=-1) f = 1", "Activity activity = np.mean((data-ave)**2, axis=-1) # print(Activity.shape) # Mobility varfdiff", "np.mean(data, axis=-1) # Standard Deviation std = np.std(data, axis=-1) #", "k=10).shape Out[5]: (40, 32, 10) In [6]: hoc(d, k=5).shape Out[6]:", "1) L_average = np.average(calc_L_series(np.arange(1, k+1))) return L_average def higuchi_fd(data, k_max,", "counting The Sevick method is used here because it is", "= - D f = np.expand_dims(fd, axis=-1) if combined: f", "np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2), axis=-1), axis=-1) f = 1 +", "3) \"\"\" data = np.array(data) ave = np.mean(data, axis=-1)[..., np.newaxis]", "as the length of the curve. \"\"\" N = X.shape[-1]", "and so on. Sevcik method: fast calculation and robust analysis", "Hjorth features, include activity, mobility, complexity Parameters ---------- data array", "= np.var(diff_1st, axis=-1) # print(varfdiff.shape) mobility = np.sqrt(varfdiff / activity)", "1) k = np.arange(1, k_max+1) L = calc_L_average_series(k) L =", "count = np.count_nonzero(x_t, axis=-1) nzc.append(count) f = np.stack(nzc, axis=-1) if", "def higuchi_fd(data, k_max, combined=True): \"\"\"Fractal dimension feature is solved, which", "= np.diff(data, n=i) x_t = curr_diff >= 0 x_t =", "32, 5) \"\"\" nzc = [] for i in range(k):", "nzc.append(count) f = np.stack(nzc, axis=-1) if combined: f = f.reshape((*f.shape[:-2]))", "np.mean((data-ave)**2, axis=-1) # print(Activity.shape) # Mobility varfdiff = np.var(diff_1st, axis=-1)", "np.mean(data, axis=-1)[..., np.newaxis] diff_1st = np.diff(data, n=1, axis=-1) # print(diff_1st.shape)", "---------- In [7]: d.shape, l.shape Out[7]: ((40, 32, 8064), (40,", "axis=-1) complexity = np.sqrt(varsdiff/varfdiff) / mobility f = np.stack((activity, mobility,", "as the average value over k sets of Lm(k). \"\"\"", "k return Lm def calc_L_average(X, k): \"\"\" Return <L(k)> as", "points = data.shape[-1] x = np.arange(1, points+1) x_ = x", "hoc. Hoc is a high order zero crossing quantity. Parameters", "miny = np.expand_dims(np.min(data, axis=-1), axis=-1) maxy = np.expand_dims(np.max(data, axis=-1), axis=-1)", "diff_2nd = np.mean(np.abs(data[..., 2:] - data[..., :-2]), axis=-1) # the", "def calc_L(X, k, m): \"\"\" Return Lm(k) as the length", "= np.std(data, axis=-1) # the mean of the absolute values", "to the shape of your input data. e.g. for input.shape", "0]): tmp = L[ind[0], ind[1], ind[2]] D, _= np.polyfit(np.log2(k), np.log2(tmp),", "np.floor((N-m)/k).astype(np.int64) norm = (N-1) / (n*k) ss = np.sum(np.abs(np.diff(X[..., m::k],", "k sets of Lm(k). \"\"\" calc_L_series = np.frompyfunc(lambda m: calc_L(X,", "], ind[2]] = - D f = np.expand_dims(fd, axis=-1) if", "value over k sets of Lm(k). \"\"\" calc_L_series = np.frompyfunc(lambda", "by default 10 Return ---------- nzc: Solved feature, It's shape", "1 + np.log(L) / np.log(2 * (points-1)) # print(FD.shape) if", "diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) # the mean of the", "feature is solved, which is used to describe the shape", "feature, It's shape is similar to the shape of your", "activity = np.mean((data-ave)**2, axis=-1) # print(Activity.shape) # Mobility varfdiff =", "= np.sqrt(varfdiff / activity) # Complexity varsdiff = np.var(diff_2nd, axis=-1)", "Parameters ---------- Parameters ---------- data array data, for DEAP dataset,", "Standard Deviation std = np.std(data, axis=-1) # the mean of", "_= np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0], ind[1if combined: f = f", "+ np.log(L) / np.log(2 * (points-1)) # print(FD.shape) if combined:", "n=1, axis=-1) # print(diff_1st.shape) diff_2nd = data[..., 2:] - data[...,", "axis=-1) # print(Activity.shape) # Mobility varfdiff = np.var(diff_1st, axis=-1) #", "n_channels, points) Return ---------- f: Solved feature, It's shape is", "= load_deap(path, 0) In [5]: hoc(d, k=10).shape Out[5]: (40, 32,", "the absolute values of Normalized 1st difference normal_diff_1st = diff_1st", "fd = np.zeros(data.shape[:-1]) for ind in np.argwhere(L[..., 0]): tmp =", "input data. e.g. for input.shape is (n_trials, n_channels, points), the", "is used here because it is easier to implement Parameters", "= (data-miny) / (maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2),", "Out[16]: (40, 32, 3) \"\"\" data = np.array(data) ave =", "ind[1], ind[2]] D, _= np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0], ind[1if combined:", "It's shape may be (n_trials, n_channels, points) Return ---------- f:", "diff_2nd, normal_diff_2nd), axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f", "combined: f = f.reshape((*f.shape[:-2])) return f def calc_L(X, k, m):", "It's shape is similar to the shape of your input", "the curve. \"\"\" N = X.shape[-1] n = np.floor((N-m)/k).astype(np.int64) norm", "combined: f = f.reshape((*f.shape[:-2])) return f def higher_order_crossing(data, k=10, combined=True):", "hjorth(data, combined=True): \"\"\"Solving Hjorth features, include activity, mobility, complexity Parameters", ">= 0 x_t = np.diff(x_t) x_t = np.abs(x_t) count =", "Example ---------- In [15]: d.shape, l.shape Out[15]: ((40, 32, 8064),", "In [6]: hoc(d, k=5).shape Out[6]: (40, 32, 5) \"\"\" nzc", "the f.shape is (n_trials, n_channels, n_features) Example ---------- In [7]:", "+ np.diff(x_)**2), axis=-1), axis=-1) f = 1 + np.log(L) /", "= np.mean((data-ave)**2, axis=-1) # print(Activity.shape) # Mobility varfdiff = np.var(diff_1st,", "= np.mean(np.abs(data[..., 2:] - data[..., :-2]), axis=-1) # the mean", "/ np.max(x) miny = np.expand_dims(np.min(data, axis=-1), axis=-1) maxy = np.expand_dims(np.max(data,", "Lm(k). \"\"\" calc_L_series = np.frompyfunc(lambda m: calc_L(X, k, m), 1,", "and EEG.The calculation methods include Sevcik, fractal Brownian motion, box", "[15]: d.shape, l.shape Out[15]: ((40, 32, 8064), (40, 1)) In", "= f return ).shape Out[8]: (40, 32, 1) \"\"\" calc_L_average_series", "power = np.mean(data**2, axis=-1) # Mean ave = np.mean(data, axis=-1)", "optional Order, by default 10 Return ---------- nzc: Solved feature,", "ind[2]] D, _= np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0], ind[1if combined: f", "closer to the theoretical value than box counting The higuchi", "information of EEG time series data. It seems that this", "may be (n_trials, n_channels, points) Return ---------- f: Solved feature,", "diff_2nd = data[..., 2:] - data[..., :-2] # Activity activity", "the average value over k sets of Lm(k). \"\"\" calc_L_series", "np.expand_dims(np.max(data, axis=-1), axis=-1) y_ = (data-miny) / (maxy-miny) L =", "difference. Parameters ---------- data array data, for DEAP dataset, It's", "@Author :wlgls @Version :1.0 ''' import numpy as np def", "DEAP dataset, It's shape may be (n_trials, n_channels, points) k", "complexity Parameters ---------- data array data, for DEAP dataset, It's", "if combined: f = f.reshape((*f.shape[:-2])) return f def higher_order_crossing(data, k=10,", "np.arange(1, k_max+1) L = calc_L_average_series(k) L = np.stack(L, axis=-1) fd", "used to judge the electrooculogram and EEG.The calculation methods include", "In [16]: hjorth_features(d).shape Out[16]: (40, 32, 3) \"\"\" data =", "activity, mobility, complexity Parameters ---------- data array data, for DEAP", "Example ---------- In [4]: d, l = load_deap(path, 0) In", "ss = np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1) Lm = (ss*norm) /", "np.newaxis] diff_1st = np.diff(data, n=1, axis=-1) # print(diff_1st.shape) diff_2nd =", "noise Higuchi: closer to the theoretical value than box counting", "Return ---------- f: Solved feature, It's shape is similar to", "values of 2nd difference mean diff_2nd = np.mean(np.abs(data[..., 2:] -", "---------- In [4]: d, l = load_deap(path, 0) In [5]:", "Out[13]: ((40, 32, 8064), (40, 1)) In [14]: statistics_feature(d).shape Out[14]:", "k_max, combined=True): \"\"\"Fractal dimension feature is solved, which is used", "std # Features.append(np.concatenate((Power, Mean, Std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2))", "n_channels, points) k : int, optional Order, by default 10", "Features.append(np.concatenate((Power, Mean, Std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2)) f =", "# the mean of the absolute values of Normalized 1st", "the absolute values of Normalized 2nd difference normal_diff_2nd = diff_2nd", "diff_2nd / std # Features.append(np.concatenate((Power, Mean, Std, diff_1st, normal_diff_1st, diff_2nd,", "Out[8]: (40, 32, 1) \"\"\" calc_L_average_series = np.frompyfunc(lambda k: calc_L_average(data,", "l.shape Out[13]: ((40, 32, 8064), (40, 1)) In [14]: statistics_feature(d).shape", "/ std # the mean of the absolute values of", "k+1))) return L_average def higuchi_fd(data, k_max, combined=True): \"\"\"Fractal dimension feature", "f: Solved feature, It's shape is similar to the shape", "\"\"\" Return <L(k)> as the average value over k sets", "0 x_t = np.diff(x_t) x_t = np.abs(x_t) count = np.count_nonzero(x_t,", "k), 1, 1) k = np.arange(1, k_max+1) L = calc_L_average_series(k)", "1st differece, Normalized 1st difference, 2nd difference, Normalized 2nd difference.", "# Complexity varsdiff = np.var(diff_2nd, axis=-1) complexity = np.sqrt(varsdiff/varfdiff) /", "ind[2]] = - D f = np.expand_dims(fd, axis=-1) if combined:", "k, m), 1, 1) L_average = np.average(calc_L_series(np.arange(1, k+1))) return L_average", "electrooculogram and EEG.The calculation methods include Sevcik, fractal Brownian motion,", "for ind in np.argwhere(L[..., 0]): tmp = L[ind[0], ind[1], ind[2]]", "(40, 32, 1) \"\"\" points = data.shape[-1] x = np.arange(1,", "e.g. for input.shape is (n_trials, n_channels, points), the f.shape is", "n_features) Example ---------- In [15]: d.shape, l.shape Out[15]: ((40, 32,", "higuchi method is used here because it is easier to", "\"\"\"Statistical features, include Power, Mean, Std, 1st differece, Normalized 1st", "(40, 32, 1) \"\"\" calc_L_average_series = np.frompyfunc(lambda k: calc_L_average(data, k),", "32, 7) \"\"\" # Power power = np.mean(data**2, axis=-1) #", "k : int, optional Order, by default 10 Return ----------", "shape of your input data. e.g. for input.shape is (n_trials,", "In [13]: d.shape, l.shape Out[13]: ((40, 32, 8064), (40, 1))", "EEG time series data. It seems that this feature can", "Complexity varsdiff = np.var(diff_2nd, axis=-1) complexity = np.sqrt(varsdiff/varfdiff) / mobility", "/ std # Features.append(np.concatenate((Power, Mean, Std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd),", "---------- f: Solved feature, It's shape is similar to the", "= np.abs(x_t) count = np.count_nonzero(x_t, axis=-1) nzc.append(count) f = np.stack(nzc,", "activity) # Complexity varsdiff = np.var(diff_2nd, axis=-1) complexity = np.sqrt(varsdiff/varfdiff)", "10) In [6]: hoc(d, k=5).shape Out[6]: (40, 32, 5) \"\"\"", "# Standard Deviation std = np.std(data, axis=-1) # the mean", "Power, Mean, Std, 1st differece, Normalized 1st difference, 2nd difference,", "of your input data. e.g. for input.shape is (n_trials, n_channels,", "the shape information of EEG time series data. It seems", "Lm = (ss*norm) / k return Lm def calc_L_average(X, k):", "of Normalized 1st difference normal_diff_1st = diff_1st / std #", "Out[7]: ((40, 32, 8064), (40, 1)) In [8]: higuchi_fd(dif combined:", "= L[ind[0], ind[1], ind[2]] D, _= np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0],", "difference, Normalized 2nd difference. Parameters ---------- data array data, for", "axis=-1) # the mean of the absolute values of 1st", "the mean of the absolute values of 1st differece mean", "utf-8 -*- ''' @File :_time_domain_features.py @Time :2021/04/16 20:02:55 @Author :wlgls", "the f.shape is (n_trials, n_channels, n_features) Example ---------- In [13]:", "data[..., :-2]), axis=-1) # the mean of the absolute values", "the electrooculogram and EEG.The calculation methods include Sevcik, fractal Brownian", "of Normalized 2nd difference normal_diff_2nd = diff_2nd / std #", "l = load_deap(path, 0) In [5]: hoc(d, k=10).shape Out[5]: (40,", "data : array data, for DEAP dataset, It's shape may", "normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return", "n_channels, n_features) Example ---------- In [15]: d.shape, l.shape Out[15]: ((40,", "= np.array(data) ave = np.mean(data, axis=-1)[..., np.newaxis] diff_1st = np.diff(data,", "1st difference, 2nd difference, Normalized 2nd difference. Parameters ---------- data", "absolute values of 1st differece mean diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)),", "np.frompyfunc(lambda m: calc_L(X, k, m), 1, 1) L_average = np.average(calc_L_series(np.arange(1,", "\"\"\" nzc = [] for i in range(k): curr_diff =", "ave, std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1) if combined: f", "m: calc_L(X, k, m), 1, 1) L_average = np.average(calc_L_series(np.arange(1, k+1)))", "complexity), axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f def", "32, 1) \"\"\" calc_L_average_series = np.frompyfunc(lambda k: calc_L_average(data, k), 1,", "difference, 2nd difference, Normalized 2nd difference. Parameters ---------- data array", "((40, 32, 8064), (40, 1)) In [14]: statistics_feature(d).shape Out[14]: (40,", "dimension feature is solved, which is used to describe the", "higuchi_fd(data, k_max, combined=True): \"\"\"Fractal dimension feature is solved, which is", "mean of the absolute values of 2nd difference mean diff_2nd", "f.reshape((*f.shape[:-2])) return f def hjorth(data, combined=True): \"\"\"Solving Hjorth features, include", "data = np.array(data) ave = np.mean(data, axis=-1)[..., np.newaxis] diff_1st =", "Std, 1st differece, Normalized 1st difference, 2nd difference, Normalized 2nd", "include activity, mobility, complexity Parameters ---------- data array data, for", "time series data. It seems that this feature can be", "- data[..., :-2]), axis=-1) # the mean of the absolute", "32, 3) \"\"\" data = np.array(data) ave = np.mean(data, axis=-1)[...,", "if combined: f = f.reshape((*f.shape[:-2])) return f def sevcik_fd(data, combined=True):", "mobility = np.sqrt(varfdiff / activity) # Complexity varsdiff = np.var(diff_2nd,", "Order, by default 10 Return ---------- nzc: Solved feature, It's", "np.count_nonzero(x_t, axis=-1) nzc.append(count) f = np.stack(nzc, axis=-1) if combined: f", "= f.reshape((*f.shape[:-2])) return f def higher_order_crossing(data, k=10, combined=True): \"\"\"Solving the", "/ (n*k) ss = np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1) Lm =", "Mean ave = np.mean(data, axis=-1) # Standard Deviation std =", "# print(Activity.shape) # Mobility varfdiff = np.var(diff_1st, axis=-1) # print(varfdiff.shape)", "\"\"\" calc_L_series = np.frompyfunc(lambda m: calc_L(X, k, m), 1, 1)", "20:02:55 @Author :wlgls @Version :1.0 ''' import numpy as np", "the shape of your input data. e.g. for input.shape is", "to the theoretical value than box counting The Sevick method", "k = np.arange(1, k_max+1) L = calc_L_average_series(k) L = np.stack(L,", "quantity. Parameters ---------- data : array data, for DEAP dataset,", "2:] - data[..., :-2]), axis=-1) # the mean of the", "def hjorth(data, combined=True): \"\"\"Solving Hjorth features, include activity, mobility, complexity", "used here because it is easier to implement Parameters ----------", "Out[8]: (40, 32, 1) \"\"\" points = data.shape[-1] x =", "X.shape[-1] n = np.floor((N-m)/k).astype(np.int64) norm = (N-1) / (n*k) ss", "(n_trials, n_channels, n_features) Example ---------- In [13]: d.shape, l.shape Out[13]:", "data array data, for DEAP dataset, It's shape may be", ":2021/04/16 20:02:55 @Author :wlgls @Version :1.0 ''' import numpy as", "(N-1) / (n*k) ss = np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1) Lm", "absolute values of 2nd difference mean diff_2nd = np.mean(np.abs(data[..., 2:]", "combined=True): \"\"\"Solving the feature of hoc. Hoc is a high", "differece, Normalized 1st difference, 2nd difference, Normalized 2nd difference. Parameters", "values of Normalized 2nd difference normal_diff_2nd = diff_2nd / std", "def sevcik_fd(data, combined=True): \"\"\"Fractal dimension feature is solved, which is", "(data-miny) / (maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2), axis=-1),", "differece mean diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) # the mean", "range(k): curr_diff = np.diff(data, n=i) x_t = curr_diff >= 0", "Example ---------- In [13]: d.shape, l.shape Out[13]: ((40, 32, 8064),", "Std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2)) f = np.stack((power, ave,", "np.zeros(data.shape[:-1]) for ind in np.argwhere(L[..., 0]): tmp = L[ind[0], ind[1],", "varsdiff = np.var(diff_2nd, axis=-1) complexity = np.sqrt(varsdiff/varfdiff) / mobility f", "[7]: d.shape, l.shape Out[7]: ((40, 32, 8064), (40, 1)) In", "In [5]: hoc(d, k=10).shape Out[5]: (40, 32, 10) In [6]:", "np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0], ind[1if combined: f = f return", "n_features) Example ---------- In [7]: d.shape, l.shape Out[7]: ((40, 32,", "= np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1) Lm = (ss*norm) / k", "---------- data : array data, for DEAP dataset, It's shape", "(n_trials, n_channels, points) Return ---------- f: Solved feature, It's shape", "(40, 32, 3) \"\"\" data = np.array(data) ave = np.mean(data,", "k, m): \"\"\" Return Lm(k) as the length of the", "L = np.stack(L, axis=-1) fd = np.zeros(data.shape[:-1]) for ind in", "of hoc. Hoc is a high order zero crossing quantity.", "the f.shape is (n_trials, n_channels, n_features) Example ---------- In [15]:", "varfdiff = np.var(diff_1st, axis=-1) # print(varfdiff.shape) mobility = np.sqrt(varfdiff /", "Sevick method is used here because it is easier to", "np.std(data, axis=-1) # the mean of the absolute values of", "which is used to describe the shape information of EEG", ").shape Out[8]: (40, 32, 1) \"\"\" calc_L_average_series = np.frompyfunc(lambda k:", "np.stack((power, ave, std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1) if combined:", "axis=-1) Lm = (ss*norm) / k return Lm def calc_L_average(X,", "ave = np.mean(data, axis=-1) # Standard Deviation std = np.std(data,", "print(varfdiff.shape) mobility = np.sqrt(varfdiff / activity) # Complexity varsdiff =", "1)) In [16]: hjorth_features(d).shape Out[16]: (40, 32, 3) \"\"\" data", "np.argwhere(L[..., 0]): tmp = L[ind[0], ind[1], ind[2]] D, _= np.polyfit(np.log2(k),", "crossing quantity. Parameters ---------- data : array data, for DEAP", "values of Normalized 1st difference normal_diff_1st = diff_1st / std", "hoc(d, k=10).shape Out[5]: (40, 32, 10) In [6]: hoc(d, k=5).shape", "= np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) # the mean of the absolute", "= np.expand_dims(np.max(data, axis=-1), axis=-1) y_ = (data-miny) / (maxy-miny) L", "x / np.max(x) miny = np.expand_dims(np.min(data, axis=-1), axis=-1) maxy =", "np.average(calc_L_series(np.arange(1, k+1))) return L_average def higuchi_fd(data, k_max, combined=True): \"\"\"Fractal dimension", "value than box counting The Sevick method is used here", "the length of the curve. \"\"\" N = X.shape[-1] n", "array data, for DEAP dataset, It's shape may be (n_trials,", "(40, 32, 7) \"\"\" # Power power = np.mean(data**2, axis=-1)", "to implement Parameters ---------- Parameters ---------- data array data, for", "normal_diff_1st = diff_1st / std # the mean of the", "= np.mean(data, axis=-1) # Standard Deviation std = np.std(data, axis=-1)", "np.log(L) / np.log(2 * (points-1)) # print(FD.shape) if combined: f", "axis=-1) # Standard Deviation std = np.std(data, axis=-1) # the", "f.reshape((*f.shape[:-2])) return f def higher_order_crossing(data, k=10, combined=True): \"\"\"Solving the feature", "8064), (40, 1)) In [8]: higuchi_fd(dif combined: f = f", "implement Parameters ---------- Parameters ---------- data array data, for DEAP", "= np.average(calc_L_series(np.arange(1, k+1))) return L_average def higuchi_fd(data, k_max, combined=True): \"\"\"Fractal", "= diff_1st / std # the mean of the absolute", "= data[..., 2:] - data[..., :-2] # Activity activity =", "of the absolute values of 2nd difference mean diff_2nd =", "is (n_trials, n_channels, n_features) Example ---------- In [4]: d, l", "average value over k sets of Lm(k). \"\"\" calc_L_series =", "f return ).shape Out[8]: (40, 32, 1) \"\"\" calc_L_average_series =", "\"\"\"Fractal dimension feature is solved, which is used to describe", "be used to judge the electrooculogram and EEG.The calculation methods", "# the mean of the absolute values of 2nd difference", "(40, 32, 10) In [6]: hoc(d, k=5).shape Out[6]: (40, 32,", "is easier to implement Parameters ---------- Parameters ---------- data array", "input.shape is (n_trials, n_channels, points), the f.shape is (n_trials, n_channels,", "f = np.stack(nzc, axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return", "combined: f = f.reshape((*f.shape[:-2])) return f def hjorth(data, combined=True): \"\"\"Solving", "# print(diff_1st.shape) diff_2nd = data[..., 2:] - data[..., :-2] #", "= (ss*norm) / k return Lm def calc_L_average(X, k): \"\"\"", "the mean of the absolute values of Normalized 1st difference", "for i in range(k): curr_diff = np.diff(data, n=i) x_t =", "# print(varfdiff.shape) mobility = np.sqrt(varfdiff / activity) # Complexity varsdiff", "combined=True): \"\"\"Solving Hjorth features, include activity, mobility, complexity Parameters ----------", "\"\"\"Solving Hjorth features, include activity, mobility, complexity Parameters ---------- data", "np.diff(x_)**2), axis=-1), axis=-1) f = 1 + np.log(L) / np.log(2", "the f.shape is (n_trials, n_channels, n_features) Example ---------- In [4]:", "box counting, Higuchi and so on. Sevcik method: fast calculation", "length of the curve. \"\"\" N = X.shape[-1] n =", "(40, 1)) In [8]: sevcik_fd(d).shape Out[8]: (40, 32, 1) \"\"\"", "32, 8064), (40, 1)) In [14]: statistics_feature(d).shape Out[14]: (40, 32,", "hjorth_features(d).shape Out[16]: (40, 32, 3) \"\"\" data = np.array(data) ave", "axis=-1) maxy = np.expand_dims(np.max(data, axis=-1), axis=-1) y_ = (data-miny) /", "np.stack((activity, mobility, complexity), axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return", "methods include Sevcik, fractal Brownian motion, box counting, Higuchi and", "in range(k): curr_diff = np.diff(data, n=i) x_t = curr_diff >=", "np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1) Lm = (ss*norm) / k return", "[5]: hoc(d, k=10).shape Out[5]: (40, 32, 10) In [6]: hoc(d,", "1)) In [14]: statistics_feature(d).shape Out[14]: (40, 32, 7) \"\"\" #", "sets of Lm(k). \"\"\" calc_L_series = np.frompyfunc(lambda m: calc_L(X, k,", "n_features) Example ---------- In [4]: d, l = load_deap(path, 0)", "ind in np.argwhere(L[..., 0]): tmp = L[ind[0], ind[1], ind[2]] D,", "# Power power = np.mean(data**2, axis=-1) # Mean ave =", "series data. It seems that this feature can be used", "counting The higuchi method is used here because it is", "calculation methods include Sevcik, fractal Brownian motion, box counting, Higuchi", "In [8]: higuchi_fd(dif combined: f = f return ).shape Out[8]:", "of the curve. \"\"\" N = X.shape[-1] n = np.floor((N-m)/k).astype(np.int64)", "calc_L_average_series = np.frompyfunc(lambda k: calc_L_average(data, k), 1, 1) k =", "(maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2), axis=-1), axis=-1) f", "= np.stack(nzc, axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f", "= np.floor((N-m)/k).astype(np.int64) norm = (N-1) / (n*k) ss = np.sum(np.abs(np.diff(X[...,", "include Power, Mean, Std, 1st differece, Normalized 1st difference, 2nd", "mobility f = np.stack((activity, mobility, complexity), axis=-1) if combined: f", "combined: f = f return ).shape Out[8]: (40, 32, 1)", "= np.frompyfunc(lambda k: calc_L_average(data, k), 1, 1) k = np.arange(1,", "d, l = load_deap(path, 0) In [5]: hoc(d, k=10).shape Out[5]:", "f = f.reshape((*f.shape[:-2])) return f def sevcik_fd(data, combined=True): \"\"\"Fractal dimension", "f = f.reshape((*f.shape[:-2])) return f def higher_order_crossing(data, k=10, combined=True): \"\"\"Solving", "@Version :1.0 ''' import numpy as np def statistics(data, combined=True):", "(40, 1)) In [14]: statistics_feature(d).shape Out[14]: (40, 32, 7) \"\"\"", "32, 8064), (40, 1)) In [8]: higuchi_fd(dif combined: f =", "normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2)) f = np.stack((power, ave, std, diff_1st,", "axis=-1) # Mean ave = np.mean(data, axis=-1) # Standard Deviation", "easier to implement Parameters ---------- Parameters ---------- data array data,", "return ], ind[2]] = - D f = np.expand_dims(fd, axis=-1)", "Solved feature, It's shape is similar to the shape of", "Sevcik, fractal Brownian motion, box counting, Higuchi and so on.", "default 10 Return ---------- nzc: Solved feature, It's shape is", "= np.stack((activity, mobility, complexity), axis=-1) if combined: f = f.reshape((*f.shape[:-2]))", "calc_L(X, k, m), 1, 1) L_average = np.average(calc_L_series(np.arange(1, k+1))) return", "= np.mean(data**2, axis=-1) # Mean ave = np.mean(data, axis=-1) #", "f = f.reshape((*f.shape[:-2])) return f def hjorth(data, combined=True): \"\"\"Solving Hjorth", "7) \"\"\" # Power power = np.mean(data**2, axis=-1) # Mean", "---------- nzc: Solved feature, It's shape is similar to the", "motion, box counting, Higuchi and so on. Sevcik method: fast", "combined: f = f.reshape((*f.shape[:-2])) return f def sevcik_fd(data, combined=True): \"\"\"Fractal", "2nd difference, Normalized 2nd difference. Parameters ---------- data array data,", "used to describe the shape information of EEG time series", "np.diff(data, n=1, axis=-1) # print(diff_1st.shape) diff_2nd = data[..., 2:] -", "of the absolute values of 1st differece mean diff_1st =", "8064), (40, 1)) In [8]: sevcik_fd(d).shape Out[8]: (40, 32, 1)", "f def higher_order_crossing(data, k=10, combined=True): \"\"\"Solving the feature of hoc.", "- D f = np.expand_dims(fd, axis=-1) if combined: f =", "(n_trials, n_channels, n_features) Example ---------- In [7]: d.shape, l.shape Out[7]:", "Return Lm(k) as the length of the curve. \"\"\" N", "(points-1)) # print(FD.shape) if combined: f = f.reshape((*f.shape[:-2])) return f", "f.shape is (n_trials, n_channels, n_features) Example ---------- In [7]: d.shape,", "# Mobility varfdiff = np.var(diff_1st, axis=-1) # print(varfdiff.shape) mobility =", "= f.reshape((*f.shape[:-2])) return f def sevcik_fd(data, combined=True): \"\"\"Fractal dimension feature", "[4]: d, l = load_deap(path, 0) In [5]: hoc(d, k=10).shape", "that this feature can be used to judge the electrooculogram", "n_channels, points), the f.shape is (n_trials, n_channels, n_features) Example ----------", "Parameters ---------- data array data, for DEAP dataset, It's shape", "n_channels, n_features) Example ---------- In [13]: d.shape, l.shape Out[13]: ((40,", "axis=-1) # print(diff_1st.shape) diff_2nd = data[..., 2:] - data[..., :-2]", "\"\"\" Return Lm(k) as the length of the curve. \"\"\"", "= np.expand_dims(fd, axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f", "values of 1st differece mean diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1)", "axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f def hjorth(data,", "The Sevick method is used here because it is easier", "higuchi_fd(dif combined: f = f return ).shape Out[8]: (40, 32,", "np.diff(x_t) x_t = np.abs(x_t) count = np.count_nonzero(x_t, axis=-1) nzc.append(count) f", "\"\"\" data = np.array(data) ave = np.mean(data, axis=-1)[..., np.newaxis] diff_1st", "box counting The higuchi method is used here because it", "np.mean(np.abs(data[..., 2:] - data[..., :-2]), axis=-1) # the mean of", "to the theoretical value than box counting The higuchi method", "-*- encoding: utf-8 -*- ''' @File :_time_domain_features.py @Time :2021/04/16 20:02:55", "f.shape is (n_trials, n_channels, n_features) Example ---------- In [15]: d.shape,", "data. e.g. for input.shape is (n_trials, n_channels, points), the f.shape", "m): \"\"\" Return Lm(k) as the length of the curve.", "x = np.arange(1, points+1) x_ = x / np.max(x) miny", "---------- In [15]: d.shape, l.shape Out[15]: ((40, 32, 8064), (40,", "d.shape, l.shape Out[7]: ((40, 32, 8064), (40, 1)) In [8]:", "return f def hjorth(data, combined=True): \"\"\"Solving Hjorth features, include activity,", "high order zero crossing quantity. Parameters ---------- data : array", "Mobility varfdiff = np.var(diff_1st, axis=-1) # print(varfdiff.shape) mobility = np.sqrt(varfdiff", "= f.reshape((*f.shape[:-2])) return f def hjorth(data, combined=True): \"\"\"Solving Hjorth features,", "axis=-1) fd = np.zeros(data.shape[:-1]) for ind in np.argwhere(L[..., 0]): tmp", "counting, Higuchi and so on. Sevcik method: fast calculation and", "32, 8064), (40, 1)) In [8]: sevcik_fd(d).shape Out[8]: (40, 32,", "1, 1) L_average = np.average(calc_L_series(np.arange(1, k+1))) return L_average def higuchi_fd(data,", "similar to the shape of your input data. e.g. for", "D, _= np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0], ind[1if combined: f =", "(n_trials, n_channels, n_features) Example ---------- In [4]: d, l =", "((40, 32, 8064), (40, 1)) In [8]: higuchi_fd(dif combined: f", "ind[1if combined: f = f return ], ind[2]] = -", "np.abs(x_t) count = np.count_nonzero(x_t, axis=-1) nzc.append(count) f = np.stack(nzc, axis=-1)", "value than box counting The higuchi method is used here", "axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f def higher_order_crossing(data,", "<L(k)> as the average value over k sets of Lm(k).", "x_t = curr_diff >= 0 x_t = np.diff(x_t) x_t =", "= np.frompyfunc(lambda m: calc_L(X, k, m), 1, 1) L_average =", "It's shape may be (n_trials, n_channels, points) k : int,", "(40, 32, 5) \"\"\" nzc = [] for i in", "= np.arange(1, points+1) x_ = x / np.max(x) miny =", "in np.argwhere(L[..., 0]): tmp = L[ind[0], ind[1], ind[2]] D, _=", "= np.zeros(data.shape[:-1]) for ind in np.argwhere(L[..., 0]): tmp = L[ind[0],", "f = np.stack((power, ave, std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1)", "[] for i in range(k): curr_diff = np.diff(data, n=i) x_t", "the mean of the absolute values of Normalized 2nd difference", "calculation and robust analysis of noise Higuchi: closer to the", "Brownian motion, box counting, Higuchi and so on. Sevcik method:", ": int, optional Order, by default 10 Return ---------- nzc:", "= data.shape[-1] x = np.arange(1, points+1) x_ = x /", "print(FD.shape) if combined: f = f.reshape((*f.shape[:-2])) return f def calc_L(X,", "the theoretical value than box counting The higuchi method is", "seems that this feature can be used to judge the", "combined=True): \"\"\"Fractal dimension feature is solved, which is used to", "data[..., 2:] - data[..., :-2] # Activity activity = np.mean((data-ave)**2,", "np.var(diff_1st, axis=-1) # print(varfdiff.shape) mobility = np.sqrt(varfdiff / activity) #", "return f def sevcik_fd(data, combined=True): \"\"\"Fractal dimension feature is solved,", "/ np.log(2 * (points-1)) # print(FD.shape) if combined: f =", "L_average def higuchi_fd(data, k_max, combined=True): \"\"\"Fractal dimension feature is solved,", "is (n_trials, n_channels, n_features) Example ---------- In [7]: d.shape, l.shape", "axis=-1) f = 1 + np.log(L) / np.log(2 * (points-1))", "feature can be used to judge the electrooculogram and EEG.The", "diff_1st = np.diff(data, n=1, axis=-1) # print(diff_1st.shape) diff_2nd = data[...,", "return Lm def calc_L_average(X, k): \"\"\" Return <L(k)> as the", "is similar to the shape of your input data. e.g.", "x_ = x / np.max(x) miny = np.expand_dims(np.min(data, axis=-1), axis=-1)", "= np.arange(1, k_max+1) L = calc_L_average_series(k) L = np.stack(L, axis=-1)", "np.log2(tmp), 1) fd[ind[0], ind[1if combined: f = f return ],", "dataset, It's shape may be (n_trials, n_channels, points) k :", "is a high order zero crossing quantity. Parameters ---------- data", "absolute values of Normalized 2nd difference normal_diff_2nd = diff_2nd /", "n_channels, n_features) Example ---------- In [4]: d, l = load_deap(path,", "EEG.The calculation methods include Sevcik, fractal Brownian motion, box counting,", "f return ], ind[2]] = - D f = np.expand_dims(fd,", "-*- ''' @File :_time_domain_features.py @Time :2021/04/16 20:02:55 @Author :wlgls @Version", "of the absolute values of Normalized 1st difference normal_diff_1st =", "m::k], n=1)), axis=-1) Lm = (ss*norm) / k return Lm", "k=10, combined=True): \"\"\"Solving the feature of hoc. Hoc is a", "data. It seems that this feature can be used to", "n=i) x_t = curr_diff >= 0 x_t = np.diff(x_t) x_t", "judge the electrooculogram and EEG.The calculation methods include Sevcik, fractal", "Sevcik method: fast calculation and robust analysis of noise Higuchi:", "theoretical value than box counting The higuchi method is used", "is (n_trials, n_channels, points), the f.shape is (n_trials, n_channels, n_features)", "---------- Parameters ---------- data array data, for DEAP dataset, It's", "Out[6]: (40, 32, 5) \"\"\" nzc = [] for i", "Higuchi and so on. Sevcik method: fast calculation and robust", "l.shape Out[15]: ((40, 32, 8064), (40, 1)) In [16]: hjorth_features(d).shape", "points+1) x_ = x / np.max(x) miny = np.expand_dims(np.min(data, axis=-1),", "np.arange(1, points+1) x_ = x / np.max(x) miny = np.expand_dims(np.min(data,", "print(diff_1st.shape) diff_2nd = data[..., 2:] - data[..., :-2] # Activity", "32, 1) \"\"\" points = data.shape[-1] x = np.arange(1, points+1)", "Hoc is a high order zero crossing quantity. Parameters ----------", "sevcik_fd(data, combined=True): \"\"\"Fractal dimension feature is solved, which is used", "n_features) Example ---------- In [13]: d.shape, l.shape Out[13]: ((40, 32,", "nzc: Solved feature, It's shape is similar to the shape", "box counting The Sevick method is used here because it", "order zero crossing quantity. Parameters ---------- data : array data,", "because it is easier to implement Parameters ---------- Parameters ----------", "normal_diff_2nd), axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f def", ":_time_domain_features.py @Time :2021/04/16 20:02:55 @Author :wlgls @Version :1.0 ''' import", ":-2]), axis=-1) # the mean of the absolute values of", "d.shape, l.shape Out[13]: ((40, 32, 8064), (40, 1)) In [14]:", "8064), (40, 1)) In [14]: statistics_feature(d).shape Out[14]: (40, 32, 7)", "np.sqrt(varsdiff/varfdiff) / mobility f = np.stack((activity, mobility, complexity), axis=-1) if", "include Sevcik, fractal Brownian motion, box counting, Higuchi and so", "can be used to judge the electrooculogram and EEG.The calculation", "axis=-1), axis=-1) y_ = (data-miny) / (maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_,", "return L_average def higuchi_fd(data, k_max, combined=True): \"\"\"Fractal dimension feature is", "axis=-1) # the mean of the absolute values of Normalized", "= f return ], ind[2]] = - D f =", "load_deap(path, 0) In [5]: hoc(d, k=10).shape Out[5]: (40, 32, 10)", "def higher_order_crossing(data, k=10, combined=True): \"\"\"Solving the feature of hoc. Hoc", "[13]: d.shape, l.shape Out[13]: ((40, 32, 8064), (40, 1)) In", "for input.shape is (n_trials, n_channels, points), the f.shape is (n_trials,", "# the mean of the absolute values of 1st differece", "axis=-1) y_ = (data-miny) / (maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2", "statistics(data, combined=True): \"\"\"Statistical features, include Power, Mean, Std, 1st differece,", "is (n_trials, n_channels, n_features) Example ---------- In [13]: d.shape, l.shape", "= x / np.max(x) miny = np.expand_dims(np.min(data, axis=-1), axis=-1) maxy", "[8]: sevcik_fd(d).shape Out[8]: (40, 32, 1) \"\"\" points = data.shape[-1]", ": array data, for DEAP dataset, It's shape may be", "The higuchi method is used here because it is easier", "features, include Power, Mean, Std, 1st differece, Normalized 1st difference,", "n=1)), axis=-1) Lm = (ss*norm) / k return Lm def", "k_max+1) L = calc_L_average_series(k) L = np.stack(L, axis=-1) fd =", "of EEG time series data. It seems that this feature", "5) \"\"\" nzc = [] for i in range(k): curr_diff", "maxy = np.expand_dims(np.max(data, axis=-1), axis=-1) y_ = (data-miny) / (maxy-miny)", "f = f return ).shape Out[8]: (40, 32, 1) \"\"\"", "In [7]: d.shape, l.shape Out[7]: ((40, 32, 8064), (40, 1))", "combined: f = f return ], ind[2]] = - D", "is (n_trials, n_channels, n_features) Example ---------- In [15]: d.shape, l.shape", "calc_L_average(data, k), 1, 1) k = np.arange(1, k_max+1) L =", "''' @File :_time_domain_features.py @Time :2021/04/16 20:02:55 @Author :wlgls @Version :1.0", "statistics_feature(d).shape Out[14]: (40, 32, 7) \"\"\" # Power power =", "print(Activity.shape) # Mobility varfdiff = np.var(diff_1st, axis=-1) # print(varfdiff.shape) mobility", "1) \"\"\" points = data.shape[-1] x = np.arange(1, points+1) x_", "np.stack(L, axis=-1) fd = np.zeros(data.shape[:-1]) for ind in np.argwhere(L[..., 0]):", "f.reshape((*f.shape[:-2])) return f def calc_L(X, k, m): \"\"\" Return Lm(k)", "the mean of the absolute values of 2nd difference mean", "np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) # the mean of the absolute values", "Normalized 2nd difference normal_diff_2nd = diff_2nd / std # Features.append(np.concatenate((Power,", "mobility, complexity), axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f", "Out[5]: (40, 32, 10) In [6]: hoc(d, k=5).shape Out[6]: (40,", "mobility, complexity Parameters ---------- data array data, for DEAP dataset,", "d.shape, l.shape Out[15]: ((40, 32, 8064), (40, 1)) In [16]:", "f = 1 + np.log(L) / np.log(2 * (points-1)) #", "np.frompyfunc(lambda k: calc_L_average(data, k), 1, 1) k = np.arange(1, k_max+1)", "mean of the absolute values of Normalized 2nd difference normal_diff_2nd", "= np.mean(data, axis=-1)[..., np.newaxis] diff_1st = np.diff(data, n=1, axis=-1) #", "32, 10) In [6]: hoc(d, k=5).shape Out[6]: (40, 32, 5)", "than box counting The Sevick method is used here because", "= curr_diff >= 0 x_t = np.diff(x_t) x_t = np.abs(x_t)", "normal_diff_2nd), axis=2)) f = np.stack((power, ave, std, diff_1st, normal_diff_1st, diff_2nd,", "/ k return Lm def calc_L_average(X, k): \"\"\" Return <L(k)>", "DEAP dataset, It's shape may be (n_trials, n_channels, points) Return", "(n*k) ss = np.sum(np.abs(np.diff(X[..., m::k], n=1)), axis=-1) Lm = (ss*norm)", "In [8]: sevcik_fd(d).shape Out[8]: (40, 32, 1) \"\"\" points =", "encoding: utf-8 -*- ''' @File :_time_domain_features.py @Time :2021/04/16 20:02:55 @Author", "curve. \"\"\" N = X.shape[-1] n = np.floor((N-m)/k).astype(np.int64) norm =", "np def statistics(data, combined=True): \"\"\"Statistical features, include Power, Mean, Std,", "dataset, It's shape may be (n_trials, n_channels, points) Return ----------", "f = np.expand_dims(fd, axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return", "/ activity) # Complexity varsdiff = np.var(diff_2nd, axis=-1) complexity =", "may be (n_trials, n_channels, points) k : int, optional Order,", "Out[14]: (40, 32, 7) \"\"\" # Power power = np.mean(data**2,", "data.shape[-1] x = np.arange(1, points+1) x_ = x / np.max(x)", "f = f.reshape((*f.shape[:-2])) return f def calc_L(X, k, m): \"\"\"", "np.mean(data**2, axis=-1) # Mean ave = np.mean(data, axis=-1) # Standard", "robust analysis of noise Higuchi: closer to the theoretical value", "axis=-1) nzc.append(count) f = np.stack(nzc, axis=-1) if combined: f =", "i in range(k): curr_diff = np.diff(data, n=i) x_t = curr_diff", "def calc_L_average(X, k): \"\"\" Return <L(k)> as the average value", "np.expand_dims(np.min(data, axis=-1), axis=-1) maxy = np.expand_dims(np.max(data, axis=-1), axis=-1) y_ =", "it is easier to implement Parameters ---------- Parameters ---------- data", "\"\"\" points = data.shape[-1] x = np.arange(1, points+1) x_ =", "Normalized 1st difference normal_diff_1st = diff_1st / std # the", "Power power = np.mean(data**2, axis=-1) # Mean ave = np.mean(data,", "f.shape is (n_trials, n_channels, n_features) Example ---------- In [4]: d,", "normal_diff_2nd = diff_2nd / std # Features.append(np.concatenate((Power, Mean, Std, diff_1st,", "combined=True): \"\"\"Statistical features, include Power, Mean, Std, 1st differece, Normalized", "It seems that this feature can be used to judge", "the theoretical value than box counting The Sevick method is", "diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=-1) if combined: f = f.reshape((*f.shape[:-2]))", "L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2), axis=-1), axis=-1) f =", "axis=-1), axis=-1) f = 1 + np.log(L) / np.log(2 *", "Example ---------- In [7]: d.shape, l.shape Out[7]: ((40, 32, 8064),", "f.reshape((*f.shape[:-2])) return f def sevcik_fd(data, combined=True): \"\"\"Fractal dimension feature is", "Mean, Std, 1st differece, Normalized 1st difference, 2nd difference, Normalized", "curr_diff >= 0 x_t = np.diff(x_t) x_t = np.abs(x_t) count", "= 1 + np.log(L) / np.log(2 * (points-1)) # print(FD.shape)", "Return ---------- nzc: Solved feature, It's shape is similar to", ":wlgls @Version :1.0 ''' import numpy as np def statistics(data,", ":1.0 ''' import numpy as np def statistics(data, combined=True): \"\"\"Statistical", "higher_order_crossing(data, k=10, combined=True): \"\"\"Solving the feature of hoc. Hoc is", "1st differece mean diff_1st = np.mean(np.abs(np.diff(data,n=1, axis=-1)), axis=-1) # the", "* (points-1)) # print(FD.shape) if combined: f = f.reshape((*f.shape[:-2])) return", "for DEAP dataset, It's shape may be (n_trials, n_channels, points)", "shape may be (n_trials, n_channels, points) k : int, optional", "of the absolute values of Normalized 2nd difference normal_diff_2nd =", "Mean, Std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2)) f = np.stack((power,", "In [15]: d.shape, l.shape Out[15]: ((40, 32, 8064), (40, 1))", "axis=2)) f = np.stack((power, ave, std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd),", "8064), (40, 1)) In [16]: hjorth_features(d).shape Out[16]: (40, 32, 3)", "calc_L_series = np.frompyfunc(lambda m: calc_L(X, k, m), 1, 1) L_average", "a high order zero crossing quantity. Parameters ---------- data :", "Out[7]: ((40, 32, 8064), (40, 1)) In [8]: sevcik_fd(d).shape Out[8]:", "/ (maxy-miny) L = np.expand_dims(np.sum(np.sqrt(np.diff(y_, axis=-1)**2 + np.diff(x_)**2), axis=-1), axis=-1)", "# Activity activity = np.mean((data-ave)**2, axis=-1) # print(Activity.shape) # Mobility", "np.log(2 * (points-1)) # print(FD.shape) if combined: f = f.reshape((*f.shape[:-2]))", "l.shape Out[7]: ((40, 32, 8064), (40, 1)) In [8]: sevcik_fd(d).shape", "(ss*norm) / k return Lm def calc_L_average(X, k): \"\"\" Return", "''' import numpy as np def statistics(data, combined=True): \"\"\"Statistical features,", "points) Return ---------- f: Solved feature, It's shape is similar", "mean diff_2nd = np.mean(np.abs(data[..., 2:] - data[..., :-2]), axis=-1) #", "difference mean diff_2nd = np.mean(np.abs(data[..., 2:] - data[..., :-2]), axis=-1)", "fd[ind[0], ind[1if combined: f = f return ], ind[2]] =", "[8]: higuchi_fd(dif combined: f = f return ).shape Out[8]: (40,", "= np.stack(L, axis=-1) fd = np.zeros(data.shape[:-1]) for ind in np.argwhere(L[...,", "sevcik_fd(d).shape Out[8]: (40, 32, 1) \"\"\" points = data.shape[-1] x", "shape may be (n_trials, n_channels, points) Return ---------- f: Solved", "the feature of hoc. Hoc is a high order zero", "method is used here because it is easier to implement", "closer to the theoretical value than box counting The Sevick", "Out[15]: ((40, 32, 8064), (40, 1)) In [16]: hjorth_features(d).shape Out[16]:", "1)) In [8]: higuchi_fd(dif combined: f = f return ).shape", "axis=-1)[..., np.newaxis] diff_1st = np.diff(data, n=1, axis=-1) # print(diff_1st.shape) diff_2nd", "# -*- encoding: utf-8 -*- ''' @File :_time_domain_features.py @Time :2021/04/16", "axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f def sevcik_fd(data,", "/ mobility f = np.stack((activity, mobility, complexity), axis=-1) if combined:", "# Mean ave = np.mean(data, axis=-1) # Standard Deviation std", "mean of the absolute values of 1st differece mean diff_1st", "l.shape Out[7]: ((40, 32, 8064), (40, 1)) In [8]: higuchi_fd(dif", "shape information of EEG time series data. It seems that", "data[..., :-2] # Activity activity = np.mean((data-ave)**2, axis=-1) # print(Activity.shape)", "np.var(diff_2nd, axis=-1) complexity = np.sqrt(varsdiff/varfdiff) / mobility f = np.stack((activity,", "2nd difference. Parameters ---------- data array data, for DEAP dataset,", "axis=-1)), axis=-1) # the mean of the absolute values of", "= [] for i in range(k): curr_diff = np.diff(data, n=i)", "calc_L(X, k, m): \"\"\" Return Lm(k) as the length of", "and robust analysis of noise Higuchi: closer to the theoretical", "diff_2nd, normal_diff_2nd), axis=2)) f = np.stack((power, ave, std, diff_1st, normal_diff_1st,", "here because it is easier to implement Parameters ---------- Parameters", "numpy as np def statistics(data, combined=True): \"\"\"Statistical features, include Power,", "10 Return ---------- nzc: Solved feature, It's shape is similar", "diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2)) f = np.stack((power, ave, std,", "1) \"\"\" calc_L_average_series = np.frompyfunc(lambda k: calc_L_average(data, k), 1, 1)", "over k sets of Lm(k). \"\"\" calc_L_series = np.frompyfunc(lambda m:", "\"\"\"Solving the feature of hoc. Hoc is a high order", "so on. Sevcik method: fast calculation and robust analysis of", "hoc(d, k=5).shape Out[6]: (40, 32, 5) \"\"\" nzc = []", "L[ind[0], ind[1], ind[2]] D, _= np.polyfit(np.log2(k), np.log2(tmp), 1) fd[ind[0], ind[1if", "Lm(k) as the length of the curve. \"\"\" N =", "analysis of noise Higuchi: closer to the theoretical value than", "difference normal_diff_2nd = diff_2nd / std # Features.append(np.concatenate((Power, Mean, Std,", "1st difference normal_diff_1st = diff_1st / std # the mean", "# Features.append(np.concatenate((Power, Mean, Std, diff_1st, normal_diff_1st, diff_2nd, normal_diff_2nd), axis=2)) f", "np.sqrt(varfdiff / activity) # Complexity varsdiff = np.var(diff_2nd, axis=-1) complexity", "np.stack(nzc, axis=-1) if combined: f = f.reshape((*f.shape[:-2])) return f def", "norm = (N-1) / (n*k) ss = np.sum(np.abs(np.diff(X[..., m::k], n=1)),", "be (n_trials, n_channels, points) Return ---------- f: Solved feature, It's", "tmp = L[ind[0], ind[1], ind[2]] D, _= np.polyfit(np.log2(k), np.log2(tmp), 1)", "m), 1, 1) L_average = np.average(calc_L_series(np.arange(1, k+1))) return L_average def", "<reponame>Wlgls/pyDEAP<gh_stars>0 # -*- encoding: utf-8 -*- ''' @File :_time_domain_features.py @Time", "std # the mean of the absolute values of 2nd", "nzc = [] for i in range(k): curr_diff = np.diff(data,", "= np.count_nonzero(x_t, axis=-1) nzc.append(count) f = np.stack(nzc, axis=-1) if combined:", "f = f return ], ind[2]] = - D f", "this feature can be used to judge the electrooculogram and", "2nd difference mean diff_2nd = np.mean(np.abs(data[..., 2:] - data[..., :-2]),", "if combined: f = f.reshape((*f.shape[:-2])) return f def calc_L(X, k,", "solved, which is used to describe the shape information of" ]