repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.directory_cloud
python
def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000): '''Creates a word cloud using files from a directory. The color of the words correspond to the amount of documents the word occurs in.''' worddict = assign_fonts(tuplecount(read_dir(directory)),max_text_size,min_text_size,self.exclude_words) sorted_worddict = list(reversed(sorted(worddict.keys(), key=lambda x: worddict[x]))) colordict = assign_colors(dir_freq(directory)) num_words = 0 for word in sorted_worddict: self.render_word(word,worddict[word],colordict[word]) if self.width < self.word_size[0]: #If the word is bigger than the surface, expand the surface. self.expand(self.word_size[0]-self.width,0) elif self.height < self.word_size[1]: self.expand(0,self.word_size[1]-self.height) position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] #the initial position is determined loopcount = 0 while self.collides(position,self.word_size): if loopcount > max_count: #If it can't find a position for the word, create a bigger cloud. self.expand(expand_width,expand_height) loopcount = 0 position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount += 1 self.plot_word(position) num_words += 1
Creates a word cloud using files from a directory. The color of the words correspond to the amount of documents the word occurs in.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L60-L85
[ "def tuplecount(text):\n '''Changes a dictionary into a list of tuples.'''\n worddict = wordcount(text)\n countlist = []\n for key in worddict.keys():\n countlist.append((key,worddict[key]))\n countlist = list(reversed(sorted(countlist,key = lambda x: x[1])))\n return countlist\n", "def dir_freq(directory):\n '''Returns a list of tuples of (word,# of directories it occurs)'''\n content = dir_list(directory)\n i = 0\n freqdict = {}\n for filename in content:\n filewords = eliminate_repeats(read_file(directory + '/' + filename))\n for word in filewords:\n if freqdict.has_key(word):\n freqdict[word] += 1\n else:\n freqdict[word] = 1\n tupleize = []\n for key in freqdict.keys():\n wordtuple = (key,freqdict[key])\n tupleize.append(wordtuple)\n return tupleize\n", "def read_dir(directory):\n '''Returns the text of all files in a directory.'''\n content = dir_list(directory)\n text = ''\n for filename in content:\n text += read_file(directory + '/' + filename)\n text += ' '\n return text\n", "def assign_colors(dir_counts):\n '''Defines the color of a word in the cloud.\n Counts is a list of tuples in the form (word,occurences)\n The more files a word occurs in, the more red it appears in the cloud.'''\n frequencies = map(lambda x: x[1],dir_counts)\n words = map(lambda x: x[0],dir_counts)\n maxoccur = max(frequencies)\n minoccur = min(frequencies)\n colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies)\n color_dict = dict(zip(words,colors))\n return color_dict\n", "def assign_fonts(counts,maxsize,minsize,exclude_words):\n '''Defines the font size of a word in the cloud.\n Counts is a list of tuples in the form (word,count)'''\n valid_counts = []\n if exclude_words:\n for i in counts:\n if i[1] != 1:\n valid_counts.append(i)\n else:\n valid_counts = counts\n frequencies = map(lambda x: x[1],valid_counts)\n words = map(lambda x: x[0],valid_counts)\n maxcount = max(frequencies)\n font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies)\n size_dict = dict(zip(words, font_sizes))\n return size_dict\n", "def render_word(self,word,size,color):\n '''Creates a surface that contains a word.'''\n pygame.font.init()\n font = pygame.font.Font(None,size)\n self.rendered_word = font.render(word,0,color)\n self.word_size = font.size(word)\n", "def collides(self,position,size):\n '''Returns True if the word collides with another plotted word.'''\n word_rect = pygame.Rect(position,self.word_size)\n if word_rect.collidelistall(self.used_pos) == []:\n return False\n else:\n return True\n", "def expand(self,delta_width,delta_height):\n '''Makes the cloud surface bigger. Maintains all word positions.'''\n temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height))\n (self.width,self.height) = (self.width + delta_width, self.height + delta_height)\n temp_surface.blit(self.cloud,(0,0))\n self.cloud = temp_surface\n" ]
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surface that contains a word.''' pygame.font.init() font = pygame.font.Font(None,size) self.rendered_word = font.render(word,0,color) self.word_size = font.size(word) def plot_word(self,position): '''Blits a rendered word on to the main display surface''' posrectangle = pygame.Rect(position,self.word_size) self.used_pos.append(posrectangle) self.cloud.blit(self.rendered_word,position) def collides(self,position,size): '''Returns True if the word collides with another plotted word.''' word_rect = pygame.Rect(position,self.word_size) if word_rect.collidelistall(self.used_pos) == []: return False else: return True def expand(self,delta_width,delta_height): '''Makes the cloud surface bigger. Maintains all word positions.''' temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height)) (self.width,self.height) = (self.width + delta_width, self.height + delta_height) temp_surface.blit(self.cloud,(0,0)) self.cloud = temp_surface def smart_cloud(self,input,max_text_size=72,min_text_size=12,exclude_words = True): '''Creates a word cloud using the input. Input can be a file, directory, or text. Set exclude_words to true if you want to eliminate words that only occur once.''' self.exclude_words = exclude_words if isdir(input): self.directory_cloud(input,max_text_size,min_text_size) elif isfile(input): text = read_file(input) self.text_cloud(text,max_text_size,min_text_size) elif isinstance(input, basestring): self.text_cloud(input,max_text_size,min_text_size) else: print 'Input type not supported.' print 'Supported types: String, Directory, .txt file' def text_cloud(self,text,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000): '''Creates a word cloud using plain text.''' worddict = assign_fonts(tuplecount(text),max_text_size,min_text_size,self.exclude_words) sorted_worddict = list(reversed(sorted(worddict.keys(), key=lambda x: worddict[x]))) for word in sorted_worddict: self.render_word(word,worddict[word],(randint(0,255),randint(0,255),randint(0,255))) if self.width < self.word_size[0]: #If the word is bigger than the surface, expand the surface. self.expand(self.word_size[0]-self.width,0) elif self.height < self.word_size[1]: self.expand(0,self.word_size[1]-self.height) position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount = 0 while self.collides(position,self.word_size): if loopcount > max_count: #If it can't find a position for the word, expand the cloud. self.expand(expand_width,expand_height) loopcount = 0 position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount += 1 self.plot_word(position) def display(self): '''Displays the word cloud to the screen.''' pygame.init() self.display = pygame.display.set_mode((self.width,self.height)) self.display.blit(self.cloud,(0,0)) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return def save(self,filename): '''Saves the cloud to a file.''' pygame.image.save(self.cloud,filename)
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.text_cloud
python
def text_cloud(self,text,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000): '''Creates a word cloud using plain text.''' worddict = assign_fonts(tuplecount(text),max_text_size,min_text_size,self.exclude_words) sorted_worddict = list(reversed(sorted(worddict.keys(), key=lambda x: worddict[x]))) for word in sorted_worddict: self.render_word(word,worddict[word],(randint(0,255),randint(0,255),randint(0,255))) if self.width < self.word_size[0]: #If the word is bigger than the surface, expand the surface. self.expand(self.word_size[0]-self.width,0) elif self.height < self.word_size[1]: self.expand(0,self.word_size[1]-self.height) position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount = 0 while self.collides(position,self.word_size): if loopcount > max_count: #If it can't find a position for the word, expand the cloud. self.expand(expand_width,expand_height) loopcount = 0 position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount += 1 self.plot_word(position)
Creates a word cloud using plain text.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L87-L107
[ "def tuplecount(text):\n '''Changes a dictionary into a list of tuples.'''\n worddict = wordcount(text)\n countlist = []\n for key in worddict.keys():\n countlist.append((key,worddict[key]))\n countlist = list(reversed(sorted(countlist,key = lambda x: x[1])))\n return countlist\n", "def assign_fonts(counts,maxsize,minsize,exclude_words):\n '''Defines the font size of a word in the cloud.\n Counts is a list of tuples in the form (word,count)'''\n valid_counts = []\n if exclude_words:\n for i in counts:\n if i[1] != 1:\n valid_counts.append(i)\n else:\n valid_counts = counts\n frequencies = map(lambda x: x[1],valid_counts)\n words = map(lambda x: x[0],valid_counts)\n maxcount = max(frequencies)\n font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies)\n size_dict = dict(zip(words, font_sizes))\n return size_dict\n", "def render_word(self,word,size,color):\n '''Creates a surface that contains a word.'''\n pygame.font.init()\n font = pygame.font.Font(None,size)\n self.rendered_word = font.render(word,0,color)\n self.word_size = font.size(word)\n", "def collides(self,position,size):\n '''Returns True if the word collides with another plotted word.'''\n word_rect = pygame.Rect(position,self.word_size)\n if word_rect.collidelistall(self.used_pos) == []:\n return False\n else:\n return True\n", "def expand(self,delta_width,delta_height):\n '''Makes the cloud surface bigger. Maintains all word positions.'''\n temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height))\n (self.width,self.height) = (self.width + delta_width, self.height + delta_height)\n temp_surface.blit(self.cloud,(0,0))\n self.cloud = temp_surface\n" ]
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surface that contains a word.''' pygame.font.init() font = pygame.font.Font(None,size) self.rendered_word = font.render(word,0,color) self.word_size = font.size(word) def plot_word(self,position): '''Blits a rendered word on to the main display surface''' posrectangle = pygame.Rect(position,self.word_size) self.used_pos.append(posrectangle) self.cloud.blit(self.rendered_word,position) def collides(self,position,size): '''Returns True if the word collides with another plotted word.''' word_rect = pygame.Rect(position,self.word_size) if word_rect.collidelistall(self.used_pos) == []: return False else: return True def expand(self,delta_width,delta_height): '''Makes the cloud surface bigger. Maintains all word positions.''' temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height)) (self.width,self.height) = (self.width + delta_width, self.height + delta_height) temp_surface.blit(self.cloud,(0,0)) self.cloud = temp_surface def smart_cloud(self,input,max_text_size=72,min_text_size=12,exclude_words = True): '''Creates a word cloud using the input. Input can be a file, directory, or text. Set exclude_words to true if you want to eliminate words that only occur once.''' self.exclude_words = exclude_words if isdir(input): self.directory_cloud(input,max_text_size,min_text_size) elif isfile(input): text = read_file(input) self.text_cloud(text,max_text_size,min_text_size) elif isinstance(input, basestring): self.text_cloud(input,max_text_size,min_text_size) else: print 'Input type not supported.' print 'Supported types: String, Directory, .txt file' def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000): '''Creates a word cloud using files from a directory. The color of the words correspond to the amount of documents the word occurs in.''' worddict = assign_fonts(tuplecount(read_dir(directory)),max_text_size,min_text_size,self.exclude_words) sorted_worddict = list(reversed(sorted(worddict.keys(), key=lambda x: worddict[x]))) colordict = assign_colors(dir_freq(directory)) num_words = 0 for word in sorted_worddict: self.render_word(word,worddict[word],colordict[word]) if self.width < self.word_size[0]: #If the word is bigger than the surface, expand the surface. self.expand(self.word_size[0]-self.width,0) elif self.height < self.word_size[1]: self.expand(0,self.word_size[1]-self.height) position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] #the initial position is determined loopcount = 0 while self.collides(position,self.word_size): if loopcount > max_count: #If it can't find a position for the word, create a bigger cloud. self.expand(expand_width,expand_height) loopcount = 0 position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount += 1 self.plot_word(position) num_words += 1 def display(self): '''Displays the word cloud to the screen.''' pygame.init() self.display = pygame.display.set_mode((self.width,self.height)) self.display.blit(self.cloud,(0,0)) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return def save(self,filename): '''Saves the cloud to a file.''' pygame.image.save(self.cloud,filename)
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.display
python
def display(self): '''Displays the word cloud to the screen.''' pygame.init() self.display = pygame.display.set_mode((self.width,self.height)) self.display.blit(self.cloud,(0,0)) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return
Displays the word cloud to the screen.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L109-L119
null
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surface that contains a word.''' pygame.font.init() font = pygame.font.Font(None,size) self.rendered_word = font.render(word,0,color) self.word_size = font.size(word) def plot_word(self,position): '''Blits a rendered word on to the main display surface''' posrectangle = pygame.Rect(position,self.word_size) self.used_pos.append(posrectangle) self.cloud.blit(self.rendered_word,position) def collides(self,position,size): '''Returns True if the word collides with another plotted word.''' word_rect = pygame.Rect(position,self.word_size) if word_rect.collidelistall(self.used_pos) == []: return False else: return True def expand(self,delta_width,delta_height): '''Makes the cloud surface bigger. Maintains all word positions.''' temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height)) (self.width,self.height) = (self.width + delta_width, self.height + delta_height) temp_surface.blit(self.cloud,(0,0)) self.cloud = temp_surface def smart_cloud(self,input,max_text_size=72,min_text_size=12,exclude_words = True): '''Creates a word cloud using the input. Input can be a file, directory, or text. Set exclude_words to true if you want to eliminate words that only occur once.''' self.exclude_words = exclude_words if isdir(input): self.directory_cloud(input,max_text_size,min_text_size) elif isfile(input): text = read_file(input) self.text_cloud(text,max_text_size,min_text_size) elif isinstance(input, basestring): self.text_cloud(input,max_text_size,min_text_size) else: print 'Input type not supported.' print 'Supported types: String, Directory, .txt file' def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000): '''Creates a word cloud using files from a directory. The color of the words correspond to the amount of documents the word occurs in.''' worddict = assign_fonts(tuplecount(read_dir(directory)),max_text_size,min_text_size,self.exclude_words) sorted_worddict = list(reversed(sorted(worddict.keys(), key=lambda x: worddict[x]))) colordict = assign_colors(dir_freq(directory)) num_words = 0 for word in sorted_worddict: self.render_word(word,worddict[word],colordict[word]) if self.width < self.word_size[0]: #If the word is bigger than the surface, expand the surface. self.expand(self.word_size[0]-self.width,0) elif self.height < self.word_size[1]: self.expand(0,self.word_size[1]-self.height) position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] #the initial position is determined loopcount = 0 while self.collides(position,self.word_size): if loopcount > max_count: #If it can't find a position for the word, create a bigger cloud. self.expand(expand_width,expand_height) loopcount = 0 position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount += 1 self.plot_word(position) num_words += 1 def text_cloud(self,text,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000): '''Creates a word cloud using plain text.''' worddict = assign_fonts(tuplecount(text),max_text_size,min_text_size,self.exclude_words) sorted_worddict = list(reversed(sorted(worddict.keys(), key=lambda x: worddict[x]))) for word in sorted_worddict: self.render_word(word,worddict[word],(randint(0,255),randint(0,255),randint(0,255))) if self.width < self.word_size[0]: #If the word is bigger than the surface, expand the surface. self.expand(self.word_size[0]-self.width,0) elif self.height < self.word_size[1]: self.expand(0,self.word_size[1]-self.height) position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount = 0 while self.collides(position,self.word_size): if loopcount > max_count: #If it can't find a position for the word, expand the cloud. self.expand(expand_width,expand_height) loopcount = 0 position = [randint(0,self.width-self.word_size[0]),randint(0,self.height-self.word_size[1])] loopcount += 1 self.plot_word(position) def save(self,filename): '''Saves the cloud to a file.''' pygame.image.save(self.cloud,filename)
NickMonzillo/SmartCloud
SmartCloud/utils.py
dir_freq
python
def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize
Returns a list of tuples of (word,# of directories it occurs)
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L3-L19
[ "def read_file(filename):\n '''Reads in a .txt file.'''\n with open(filename,'r') as f:\n content = f.read()\n return content\n", "def dir_list(directory):\n '''Returns the list of all files in the directory.'''\n try:\n content = listdir(directory)\n return content\n except WindowsError as winErr:\n print(\"Directory error: \" + str((winErr)))\n", "def eliminate_repeats(text):\n '''Returns a list of words that occur in the text. Eliminates stopwords.'''\n\n bannedwords = read_file('stopwords.txt')\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n words = text.split()\n standardwords = []\n for word in words:\n newstr = ''\n for char in word:\n if char in alphabet or char in alphabet.upper():\n newstr += char\n if newstr not in standardwords and newstr != '' and newstr not in bannedwords:\n standardwords.append(newstr)\n\n return map(lambda x: x.lower(),standardwords)\n" ]
from os import listdir from wordplay import eliminate_repeats, read_file def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr))) def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
NickMonzillo/SmartCloud
SmartCloud/utils.py
dir_list
python
def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr)))
Returns the list of all files in the directory.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L21-L27
null
from os import listdir from wordplay import eliminate_repeats, read_file def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
NickMonzillo/SmartCloud
SmartCloud/utils.py
read_dir
python
def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text
Returns the text of all files in a directory.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L29-L36
[ "def read_file(filename):\n '''Reads in a .txt file.'''\n with open(filename,'r') as f:\n content = f.read()\n return content\n", "def dir_list(directory):\n '''Returns the list of all files in the directory.'''\n try:\n content = listdir(directory)\n return content\n except WindowsError as winErr:\n print(\"Directory error: \" + str((winErr)))\n" ]
from os import listdir from wordplay import eliminate_repeats, read_file def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr))) def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
NickMonzillo/SmartCloud
SmartCloud/utils.py
assign_colors
python
def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict
Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L38-L48
null
from os import listdir from wordplay import eliminate_repeats, read_file def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr))) def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
NickMonzillo/SmartCloud
SmartCloud/utils.py
colorize
python
def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color
A formula for determining colors.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L50-L58
null
from os import listdir from wordplay import eliminate_repeats, read_file def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr))) def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
NickMonzillo/SmartCloud
SmartCloud/utils.py
assign_fonts
python
def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict
Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L60-L75
null
from os import listdir from wordplay import eliminate_repeats, read_file def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr))) def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
NickMonzillo/SmartCloud
SmartCloud/utils.py
fontsize
python
def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
A formula for determining font sizes.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L77-L82
null
from os import listdir from wordplay import eliminate_repeats, read_file def dir_freq(directory): '''Returns a list of tuples of (word,# of directories it occurs)''' content = dir_list(directory) i = 0 freqdict = {} for filename in content: filewords = eliminate_repeats(read_file(directory + '/' + filename)) for word in filewords: if freqdict.has_key(word): freqdict[word] += 1 else: freqdict[word] = 1 tupleize = [] for key in freqdict.keys(): wordtuple = (key,freqdict[key]) tupleize.append(wordtuple) return tupleize def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr))) def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text def assign_colors(dir_counts): '''Defines the color of a word in the cloud. Counts is a list of tuples in the form (word,occurences) The more files a word occurs in, the more red it appears in the cloud.''' frequencies = map(lambda x: x[1],dir_counts) words = map(lambda x: x[0],dir_counts) maxoccur = max(frequencies) minoccur = min(frequencies) colors = map(lambda x: colorize(x,maxoccur,minoccur),frequencies) color_dict = dict(zip(words,colors)) return color_dict def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255)) return color def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: valid_counts = counts frequencies = map(lambda x: x[1],valid_counts) words = map(lambda x: x[0],valid_counts) maxcount = max(frequencies) font_sizes = map(lambda x:fontsize(x,maxsize,minsize,maxcount),frequencies) size_dict = dict(zip(words, font_sizes)) return size_dict
ONSdigital/sdc-rabbit
sdc/rabbit/publishers.py
Publisher._connect
python
def _connect(self): logger.info("Connecting to rabbit") for url in self._urls: try: self._connection = pika.BlockingConnection(pika.URLParameters(url)) self._channel = self._connection.channel() self._declare() if self._confirm_delivery: self._channel.confirm_delivery() logger.info("Enabled delivery confirmation") logger.debug("Connected to rabbit") return True except pika.exceptions.AMQPConnectionError: logger.exception("Unable to connect to rabbit") continue except Exception: logger.exception("Unexpected exception connecting to rabbit") continue raise pika.exceptions.AMQPConnectionError
Connect to a RabbitMQ instance :returns: Boolean corresponding to success of connection :rtype: bool
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L38-L65
[ "def _declare(self):\n raise NotImplementedError('_declare not implemented')\n", "def _declare(self):\n self._channel.exchange_declare(exchange=self._exchange,\n exchange_type=self._exchange_type,\n durable=self._durable_exchange,\n arguments=self._arguments)\n", "def _declare(self):\n self._channel.queue_declare(queue=self._queue,\n durable=self._durable_queue,\n arguments=self._arguments)\n" ]
class Publisher(object): """Base class for publishers to RabbitMQ.""" def __init__(self, urls, **kwargs): """Create a new instance of a Publisher class :param urls: List of RabbitMQ cluster URLs :param confirm_delivery: Delivery confirmations toggle :param **kwargs: Custom key/value pairs passed to the arguments parameter of pika's channel.exchange_declare method :returns: Object of type Publisher :rtype: ExchangePublisher """ self._urls = urls self._arguments = kwargs self._connection = None self._channel = None self._confirm_delivery = False if 'confirm_delivery' in kwargs: self._confirm_delivery = True self._arguments.pop('confirm_delivery', None) def _declare(self): raise NotImplementedError('_declare not implemented') def _disconnect(self): """ Cleanly close a RabbitMQ connection. :returns: None """ try: self._connection.close() logger.debug("Disconnected from rabbit") except Exception: logger.exception("Unable to close connection") def _do_publish(self, message, mandatory=False, immediate=False, content_type=None, headers=None): raise NotImplementedError('_do_publish not implemented') def publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False): """ Publish a response message to a RabbitMQ instance. :param message: Response message :param content_type: Pika BasicProperties content_type value :param headers: Message header properties :param mandatory: The mandatory flag :param immediate: The immediate flag :returns: Boolean corresponding to the success of publishing :rtype: bool """ logger.debug("Publishing message") try: self._connect() return self._do_publish(mandatory=mandatory, immediate=immediate, content_type=content_type, headers=headers, message=message) except pika.exceptions.AMQPConnectionError: logger.error("AMQPConnectionError occurred. Message not published.") raise PublishMessageError except NackError: # raised when a message published in publisher-acknowledgments mode # is returned via `Basic.Return` followed by `Basic.Ack`. logger.error("NackError occurred. Message not published.") raise PublishMessageError except UnroutableError: # raised when a message published in publisher-acknowledgments # mode is returned via `Basic.Return` followed by `Basic.Ack`. logger.error("UnroutableError occurred. Message not published.") raise PublishMessageError except Exception: logger.exception("Unknown exception occurred. Message not published.") raise PublishMessageError
ONSdigital/sdc-rabbit
sdc/rabbit/publishers.py
Publisher._disconnect
python
def _disconnect(self): try: self._connection.close() logger.debug("Disconnected from rabbit") except Exception: logger.exception("Unable to close connection")
Cleanly close a RabbitMQ connection. :returns: None
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L67-L78
null
class Publisher(object): """Base class for publishers to RabbitMQ.""" def __init__(self, urls, **kwargs): """Create a new instance of a Publisher class :param urls: List of RabbitMQ cluster URLs :param confirm_delivery: Delivery confirmations toggle :param **kwargs: Custom key/value pairs passed to the arguments parameter of pika's channel.exchange_declare method :returns: Object of type Publisher :rtype: ExchangePublisher """ self._urls = urls self._arguments = kwargs self._connection = None self._channel = None self._confirm_delivery = False if 'confirm_delivery' in kwargs: self._confirm_delivery = True self._arguments.pop('confirm_delivery', None) def _declare(self): raise NotImplementedError('_declare not implemented') def _connect(self): """ Connect to a RabbitMQ instance :returns: Boolean corresponding to success of connection :rtype: bool """ logger.info("Connecting to rabbit") for url in self._urls: try: self._connection = pika.BlockingConnection(pika.URLParameters(url)) self._channel = self._connection.channel() self._declare() if self._confirm_delivery: self._channel.confirm_delivery() logger.info("Enabled delivery confirmation") logger.debug("Connected to rabbit") return True except pika.exceptions.AMQPConnectionError: logger.exception("Unable to connect to rabbit") continue except Exception: logger.exception("Unexpected exception connecting to rabbit") continue raise pika.exceptions.AMQPConnectionError def _do_publish(self, message, mandatory=False, immediate=False, content_type=None, headers=None): raise NotImplementedError('_do_publish not implemented') def publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False): """ Publish a response message to a RabbitMQ instance. :param message: Response message :param content_type: Pika BasicProperties content_type value :param headers: Message header properties :param mandatory: The mandatory flag :param immediate: The immediate flag :returns: Boolean corresponding to the success of publishing :rtype: bool """ logger.debug("Publishing message") try: self._connect() return self._do_publish(mandatory=mandatory, immediate=immediate, content_type=content_type, headers=headers, message=message) except pika.exceptions.AMQPConnectionError: logger.error("AMQPConnectionError occurred. Message not published.") raise PublishMessageError except NackError: # raised when a message published in publisher-acknowledgments mode # is returned via `Basic.Return` followed by `Basic.Ack`. logger.error("NackError occurred. Message not published.") raise PublishMessageError except UnroutableError: # raised when a message published in publisher-acknowledgments # mode is returned via `Basic.Return` followed by `Basic.Ack`. logger.error("UnroutableError occurred. Message not published.") raise PublishMessageError except Exception: logger.exception("Unknown exception occurred. Message not published.") raise PublishMessageError
ONSdigital/sdc-rabbit
sdc/rabbit/publishers.py
Publisher.publish_message
python
def publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False): logger.debug("Publishing message") try: self._connect() return self._do_publish(mandatory=mandatory, immediate=immediate, content_type=content_type, headers=headers, message=message) except pika.exceptions.AMQPConnectionError: logger.error("AMQPConnectionError occurred. Message not published.") raise PublishMessageError except NackError: # raised when a message published in publisher-acknowledgments mode # is returned via `Basic.Return` followed by `Basic.Ack`. logger.error("NackError occurred. Message not published.") raise PublishMessageError except UnroutableError: # raised when a message published in publisher-acknowledgments # mode is returned via `Basic.Return` followed by `Basic.Ack`. logger.error("UnroutableError occurred. Message not published.") raise PublishMessageError except Exception: logger.exception("Unknown exception occurred. Message not published.") raise PublishMessageError
Publish a response message to a RabbitMQ instance. :param message: Response message :param content_type: Pika BasicProperties content_type value :param headers: Message header properties :param mandatory: The mandatory flag :param immediate: The immediate flag :returns: Boolean corresponding to the success of publishing :rtype: bool
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L83-L120
[ "def _connect(self):\n \"\"\"\n Connect to a RabbitMQ instance\n\n :returns: Boolean corresponding to success of connection\n :rtype: bool\n\n \"\"\"\n logger.info(\"Connecting to rabbit\")\n for url in self._urls:\n try:\n self._connection = pika.BlockingConnection(pika.URLParameters(url))\n self._channel = self._connection.channel()\n self._declare()\n if self._confirm_delivery:\n self._channel.confirm_delivery()\n logger.info(\"Enabled delivery confirmation\")\n logger.debug(\"Connected to rabbit\")\n return True\n\n except pika.exceptions.AMQPConnectionError:\n logger.exception(\"Unable to connect to rabbit\")\n continue\n except Exception:\n logger.exception(\"Unexpected exception connecting to rabbit\")\n continue\n\n raise pika.exceptions.AMQPConnectionError\n", "def _do_publish(self, message, mandatory=False, immediate=False, content_type=None, headers=None):\n raise NotImplementedError('_do_publish not implemented')\n" ]
class Publisher(object): """Base class for publishers to RabbitMQ.""" def __init__(self, urls, **kwargs): """Create a new instance of a Publisher class :param urls: List of RabbitMQ cluster URLs :param confirm_delivery: Delivery confirmations toggle :param **kwargs: Custom key/value pairs passed to the arguments parameter of pika's channel.exchange_declare method :returns: Object of type Publisher :rtype: ExchangePublisher """ self._urls = urls self._arguments = kwargs self._connection = None self._channel = None self._confirm_delivery = False if 'confirm_delivery' in kwargs: self._confirm_delivery = True self._arguments.pop('confirm_delivery', None) def _declare(self): raise NotImplementedError('_declare not implemented') def _connect(self): """ Connect to a RabbitMQ instance :returns: Boolean corresponding to success of connection :rtype: bool """ logger.info("Connecting to rabbit") for url in self._urls: try: self._connection = pika.BlockingConnection(pika.URLParameters(url)) self._channel = self._connection.channel() self._declare() if self._confirm_delivery: self._channel.confirm_delivery() logger.info("Enabled delivery confirmation") logger.debug("Connected to rabbit") return True except pika.exceptions.AMQPConnectionError: logger.exception("Unable to connect to rabbit") continue except Exception: logger.exception("Unexpected exception connecting to rabbit") continue raise pika.exceptions.AMQPConnectionError def _disconnect(self): """ Cleanly close a RabbitMQ connection. :returns: None """ try: self._connection.close() logger.debug("Disconnected from rabbit") except Exception: logger.exception("Unable to close connection") def _do_publish(self, message, mandatory=False, immediate=False, content_type=None, headers=None): raise NotImplementedError('_do_publish not implemented')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.connect
python
def connect(self): count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue
This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L58-L88
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.on_channel_open
python
def on_channel_open(self, channel): logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange)
This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L172-L184
[ "def add_on_channel_close_callback(self):\n \"\"\"This method tells pika to call the on_channel_closed method if\n RabbitMQ unexpectedly closes the channel.\n\n \"\"\"\n logger.info('Adding channel close callback')\n self._channel.add_on_close_callback(self.on_channel_closed)\n", "def setup_exchange(self, exchange_name):\n \"\"\"Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC\n command. When it is complete, the on_exchange_declareok method will\n be invoked by pika.\n\n :param str|unicode exchange_name: The name of the exchange to declare\n\n \"\"\"\n logger.info('Declaring exchange', name=exchange_name)\n self._channel.exchange_declare(self.on_exchange_declareok,\n exchange_name,\n self._exchange_type)\n" ]
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.setup_exchange
python
def setup_exchange(self, exchange_name): logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type)
Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L186-L197
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.setup_queue
python
def setup_queue(self, queue_name): logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue )
Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare.
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L209-L220
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.on_queue_declareok
python
def on_queue_declareok(self, method_frame): logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange)
Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L222-L233
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.on_consumer_cancelled
python
def on_consumer_cancelled(self, method_frame): msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close()
Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L244-L254
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.acknowledge_message
python
def acknowledge_message(self, delivery_tag, **kwargs): logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag)
Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L256-L264
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.nack_message
python
def nack_message(self, delivery_tag, **kwargs): logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag)
Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L266-L273
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.reject_message
python
def reject_message(self, delivery_tag, requeue=False, **kwargs): logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue)
Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L275-L282
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.on_message
python
def on_message(self, unused_channel, basic_deliver, properties, body): logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag)
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L284-L304
[ "def acknowledge_message(self, delivery_tag, **kwargs):\n \"\"\"Acknowledge the message delivery from RabbitMQ by sending a\n Basic.Ack RPC method for the delivery tag.\n\n :param int delivery_tag: The delivery tag from the Basic.Deliver frame\n\n \"\"\"\n logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs)\n self._channel.basic_ack(delivery_tag)\n" ]
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.stop_consuming
python
def stop_consuming(self): if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command.
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L318-L325
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.open_channel
python
def open_channel(self): logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open)
Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika.
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L362-L369
null
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start() def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.run
python
def run(self): logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start()
Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate.
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L371-L378
[ "def connect(self):\n \"\"\"This method connects to RabbitMQ using a SelectConnection object,\n returning the connection handle.\n\n When the connection is established, the on_connection_open method\n will be invoked by pika.\n\n :rtype: pika.SelectConnection\n\n \"\"\"\n\n count = 1\n no_of_servers = len(self._rabbit_urls)\n\n while True:\n server_choice = (count % no_of_servers) - 1\n\n self._url = self._rabbit_urls[server_choice]\n\n try:\n logger.info('Connecting', attempt=count)\n return pika.SelectConnection(pika.URLParameters(self._url),\n self.on_connection_open,\n stop_ioloop_on_close=False)\n except pika.exceptions.AMQPConnectionError:\n logger.exception(\"Connection error\")\n count += 1\n logger.error(\"Connection sleep\", no_of_seconds=count)\n time.sleep(count)\n\n continue\n" ]
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def stop(self): """Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed. """ logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.stop
python
def stop(self): logger.info('Stopping') self._closing = True self.stop_consuming() logger.info('Stopped')
Cleanly shutdown the connection to RabbitMQ by stopping the consumer with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok will be invoked by pika, which will then closing the channel and connection. The IOLoop is started again because this method is invoked when CTRL-C is pressed raising a KeyboardInterrupt exception. This exception stops the IOLoop which needs to be running for pika to communicate with RabbitMQ. All of the commands issued prior to starting the IOLoop will be buffered but not processed.
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L380-L394
[ "def stop_consuming(self):\n \"\"\"Tell RabbitMQ that you would like to stop consuming by sending the\n Basic.Cancel RPC command.\n\n \"\"\"\n if self._channel:\n logger.info('Sending a Basic.Cancel RPC command to RabbitMQ')\n self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)\n" ]
class AsyncConsumer: """This is an example consumer that will handle unexpected interactions with RabbitMQ such as channel and connection closures. If RabbitMQ closes the connection, it will reopen it. You should look at the output, as there are limited reasons why the connection may be closed, which usually are tied to permission related issues or socket timeouts. If the channel is closed, it will indicate a problem with one of the commands that were issued and that should surface in the output as well. """ def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls): """Create a new instance of the AsyncConsumer class. :param durable_queue: Boolean specifying whether queue is durable :param exchange: RabbitMQ exchange name :param exchange_type: RabbitMQ exchange type :param rabbit_queue: RabbitMQ queue name :param rabbit_urls: List of rabbit urls :returns Object of type AsyncConsumer :rtype AsyncConsumer """ self._exchange = exchange self._exchange_type = exchange_type self._durable_queue = durable_queue self._queue = rabbit_queue self._rabbit_urls = rabbit_urls self._connection = None self._channel = None self._closing = False self._consumer_tag = None self._url = None def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 no_of_servers = len(self._rabbit_urls) while True: server_choice = (count % no_of_servers) - 1 self._url = self._rabbit_urls[server_choice] try: logger.info('Connecting', attempt=count) return pika.SelectConnection(pika.URLParameters(self._url), self.on_connection_open, stop_ioloop_on_close=False) except pika.exceptions.AMQPConnectionError: logger.exception("Connection error") count += 1 logger.error("Connection sleep", no_of_seconds=count) time.sleep(count) continue def close_connection(self): """This method closes the connection to RabbitMQ.""" logger.info('Closing connection') self._connection.close() def add_on_connection_close_callback(self): """This method adds an on close callback that will be invoked by pika when RabbitMQ closes the connection to the publisher unexpectedly. """ logger.info('Adding connection close callback') self._connection.add_on_close_callback(self.on_connection_closed) def on_connection_closed(self, connection, reply_code, reply_text): """This method is invoked by pika when the connection to RabbitMQ is closed unexpectedly. Since it is unexpected, we will reconnect to RabbitMQ if it disconnects. :param pika.connection.Connection connection: The closed connection obj :param int reply_code: The server provided reply_code if given :param str reply_text: The server provided reply_text if given """ self._channel = None if self._closing: self._connection.ioloop.stop() else: logger.warning('Connection closed, reopening in 5 seconds', reply_code=reply_code, reply_text=reply_text) self._connection.add_timeout(5, self.reconnect) def on_connection_open(self, unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :type unused_connection: pika.SelectConnection """ logger.info('Connection opened') self.add_on_connection_close_callback() self.open_channel() def reconnect(self): """Will be invoked by the IOLoop timer if the connection is closed. See the on_connection_closed method. """ if not self._closing: # Create a new connection # The ioloop may be stopped in self._connection._handle_ioloop_stop() # depending on the value of 'stop_ioloop_on_close' self._connection = self.connect() def add_on_channel_close_callback(self): """This method tells pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed) def on_channel_closed(self, channel, reply_code, reply_text): """Invoked by pika when RabbitMQ unexpectedly closes the channel. Channels are usually closed if you attempt to do something that violates the protocol, such as re-declare an exchange or queue with different parameters. In this case, we'll close the connection to shutdown the object. :param pika.channel.Channel: The closed channel :param int reply_code: The numeric reason the channel was closed :param str reply_text: The text reason the channel was closed """ logger.warning('Channel was closed', channel=channel, reply_code=reply_code, reply_text=reply_text) self._connection.close() def on_channel_open(self, channel): """This method is invoked by pika when the channel has been opened. The channel object is passed in so we can make use of it. Since the channel is now open, we'll declare the exchange to use. :param pika.channel.Channel channel: The channel object """ logger.info('Channel opened', channel=channel) self._channel = channel self.add_on_channel_close_callback() self.setup_exchange(self._exchange) def setup_exchange(self, exchange_name): """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare """ logger.info('Declaring exchange', name=exchange_name) self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) def on_exchange_declareok(self, unused_frame): """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC command. :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame """ logger.info('Exchange declared') self.setup_queue(self._queue) def setup_queue(self, queue_name): """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare. """ logger.info('Declaring queue', name=queue_name) self._channel.queue_declare( self.on_queue_declareok, queue_name, durable=self._durable_queue ) def on_queue_declareok(self, method_frame): """Method invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete, the on_bindok method will be invoked by pika. :param pika.frame.Method method_frame: The Queue.DeclareOk frame """ logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue) self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) def add_on_cancel_callback(self): """Add a callback that will be invoked if RabbitMQ cancels the consumer for some reason. If RabbitMQ does cancel the consumer, on_consumer_cancelled will be invoked by pika. """ logger.info('Adding consumer cancellation callback') self._channel.add_on_cancel_callback(self.on_consumer_cancelled) def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close() def acknowledge_message(self, delivery_tag, **kwargs): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_ack(delivery_tag) def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag) def reject_message(self, delivery_tag, requeue=False, **kwargs): """Reject the message delivery from RabbitMQ by sending a Basic.Reject RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_reject(delivery_tag, requeue=requeue) def on_message(self, unused_channel, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties and the body is the message that was sent. :param pika.channel.Channel unused_channel: The channel object :param pika.Spec.Basic.Deliver: basic_deliver method :param pika.Spec.BasicProperties: properties :param str|unicode body: The message body """ logger.info( 'Received message', delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, msg=body, ) self.acknowledge_message(basic_deliver.delivery_tag) def on_cancelok(self, unused_frame): """This method is invoked by pika when RabbitMQ acknowledges the cancellation of a consumer. At this point we will close the channel. This will invoke the on_channel_closed method once the channel has been closed, which will in-turn close the connection. :param pika.frame.Method unused_frame: The Basic.CancelOk frame """ logger.info('RabbitMQ acknowledged the cancellation of the consumer') self.close_channel() def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) def start_consuming(self): """This method sets up the consumer by first calling add_on_cancel_callback so that the object is notified if RabbitMQ cancels the consumer. It then issues the Basic.Consume RPC command which returns the consumer tag that is used to uniquely identify the consumer with RabbitMQ. We keep the value to use it when we want to cancel consuming. The on_message method is passed in as a callback pika will invoke when a message is fully received. """ logger.info('Issuing consumer related RPC commands') self.add_on_cancel_callback() self._channel.basic_qos(prefetch_count=1) self._consumer_tag = self._channel.basic_consume(self.on_message, self._queue) def on_bindok(self, unused_frame): """Invoked by pika when the Queue.Bind method has completed. At this point we will start consuming messages by calling start_consuming which will invoke the needed RPC commands to start the process. :param pika.frame.Method unused_frame: The Queue.BindOk response frame """ logger.info('Queue bound') self.start_consuming() def close_channel(self): """Call to close the channel with RabbitMQ cleanly by issuing the Channel.Close RPC command. """ logger.info('Closing the channel') self._channel.close() def open_channel(self): """Open a new channel with RabbitMQ by issuing the Channel.Open RPC command. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.info('Creating a new channel') self._connection.channel(on_open_callback=self.on_channel_open) def run(self): """Run the example consumer by connecting to RabbitMQ and then starting the IOLoop to block and allow the SelectConnection to operate. """ logger.debug('Running rabbit consumer') self._connection = self.connect() self._connection.ioloop.start()
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
MessageConsumer.tx_id
python
def tx_id(properties): tx_id = properties.headers['tx_id'] logger.info("Retrieved tx_id from message properties: tx_id={}".format(tx_id)) return tx_id
Gets the tx_id for a message from a rabbit queue, using the message properties. Will raise KeyError if tx_id is missing from message headers. : param properties: Message properties : returns: tx_id of survey response : rtype: str
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L444-L457
null
class MessageConsumer(TornadoConsumer): """This is a queue consumer that handles messages from RabbitMQ message queues. On receipt of a message it takes a number of params from the message properties, processes the message, and (if successful) positively acknowledges the publishing queue. If a message is not successfuly processed, it can be either negatively acknowledged, rejected or quarantined, depending on the type of excpetion raised. """ @staticmethod def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls, quarantine_publisher, process, check_tx_id=True): """Create a new instance of the SDXConsumer class : param durable_queue: Boolean specifying whether queue is durable : param exchange: RabbitMQ exchange name : param exchange_type: RabbitMQ exchange type : param rabbit_queue: RabbitMQ queue name : param rabbit_urls: List of rabbit urls : param quarantine_publisher: Object of type sdc.rabbit.QueuePublisher. Will publish quarantined messages to the named queue. : param process: Function or method to use for processsing message. Will be passed the body of the message as a string decoded using UTF - 8. Should raise sdc.rabbit.DecryptError, sdc.rabbit.BadMessageError or sdc.rabbit.RetryableError on failure, depending on the failure mode. : returns: Object of type SDXConsumer : rtype: SDXConsumer """ self.process = process if not callable(process): msg = 'process callback is not callable' raise AttributeError(msg.format(process)) self.quarantine_publisher = quarantine_publisher self.check_tx_id = check_tx_id super().__init__(durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls) def on_message(self, unused_channel, basic_deliver, properties, body): """Called on receipt of a message from a queue. Processes the message using the self._process method or function and positively acknowledges the queue if successful. If processing is not succesful, the message can either be rejected, quarantined or negatively acknowledged, depending on the failure mode. : param basic_deliver: AMQP basic.deliver method : param properties: Message properties : param body: Message body : returns: None """ if self.check_tx_id: try: tx_id = self.tx_id(properties) logger.info('Received message', queue=self._queue, delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, tx_id=tx_id) except KeyError as e: self.reject_message(basic_deliver.delivery_tag) logger.error("Bad message properties - no tx_id", action="rejected", exception=str(e)) return None except TypeError as e: self.reject_message(basic_deliver.delivery_tag) logger.error("Bad message properties - no headers", action="rejected", exception=str(e)) return None else: logger.debug("check_tx_id is False. Not checking tx_id for message.", delivery_tag=basic_deliver.delivery_tag) tx_id = None try: try: self.process(body.decode("utf-8"), tx_id) except TypeError: logger.error('Incorrect call to process method') raise QuarantinableError self.acknowledge_message(basic_deliver.delivery_tag, tx_id=tx_id) except (QuarantinableError, BadMessageError) as e: # Throw it into the quarantine queue to be dealt with try: self.quarantine_publisher.publish_message(body, headers={'tx_id': tx_id}) self.reject_message(basic_deliver.delivery_tag, tx_id=tx_id) logger.error("Quarantinable error occured", action="quarantined", exception=str(e), tx_id=tx_id) except PublishMessageError: logger.error("Unable to publish message to quarantine queue. Rejecting message and requeuing.") self.reject_message(basic_deliver.delivery_tag, requeue=True, tx_id=tx_id) except RetryableError as e: self.nack_message(basic_deliver.delivery_tag, tx_id=tx_id) logger.error("Failed to process", action="nack", exception=str(e), tx_id=tx_id) except Exception as e: self.nack_message(basic_deliver.delivery_tag, tx_id=tx_id) logger.exception("Unexpected exception occurred") logger.error("Failed to process", action="nack", exception=str(e), tx_id=tx_id)
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
MessageConsumer.on_message
python
def on_message(self, unused_channel, basic_deliver, properties, body): if self.check_tx_id: try: tx_id = self.tx_id(properties) logger.info('Received message', queue=self._queue, delivery_tag=basic_deliver.delivery_tag, app_id=properties.app_id, tx_id=tx_id) except KeyError as e: self.reject_message(basic_deliver.delivery_tag) logger.error("Bad message properties - no tx_id", action="rejected", exception=str(e)) return None except TypeError as e: self.reject_message(basic_deliver.delivery_tag) logger.error("Bad message properties - no headers", action="rejected", exception=str(e)) return None else: logger.debug("check_tx_id is False. Not checking tx_id for message.", delivery_tag=basic_deliver.delivery_tag) tx_id = None try: try: self.process(body.decode("utf-8"), tx_id) except TypeError: logger.error('Incorrect call to process method') raise QuarantinableError self.acknowledge_message(basic_deliver.delivery_tag, tx_id=tx_id) except (QuarantinableError, BadMessageError) as e: # Throw it into the quarantine queue to be dealt with try: self.quarantine_publisher.publish_message(body, headers={'tx_id': tx_id}) self.reject_message(basic_deliver.delivery_tag, tx_id=tx_id) logger.error("Quarantinable error occured", action="quarantined", exception=str(e), tx_id=tx_id) except PublishMessageError: logger.error("Unable to publish message to quarantine queue. Rejecting message and requeuing.") self.reject_message(basic_deliver.delivery_tag, requeue=True, tx_id=tx_id) except RetryableError as e: self.nack_message(basic_deliver.delivery_tag, tx_id=tx_id) logger.error("Failed to process", action="nack", exception=str(e), tx_id=tx_id) except Exception as e: self.nack_message(basic_deliver.delivery_tag, tx_id=tx_id) logger.exception("Unexpected exception occurred") logger.error("Failed to process", action="nack", exception=str(e), tx_id=tx_id)
Called on receipt of a message from a queue. Processes the message using the self._process method or function and positively acknowledges the queue if successful. If processing is not succesful, the message can either be rejected, quarantined or negatively acknowledged, depending on the failure mode. : param basic_deliver: AMQP basic.deliver method : param properties: Message properties : param body: Message body : returns: None
train
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L500-L580
[ "def acknowledge_message(self, delivery_tag, **kwargs):\n \"\"\"Acknowledge the message delivery from RabbitMQ by sending a\n Basic.Ack RPC method for the delivery tag.\n\n :param int delivery_tag: The delivery tag from the Basic.Deliver frame\n\n \"\"\"\n logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs)\n self._channel.basic_ack(delivery_tag)\n", "def nack_message(self, delivery_tag, **kwargs):\n \"\"\"Negative acknowledge a message\n\n :param int delivery_tag: The deliver tag from the Basic.Deliver frame\n\n \"\"\"\n logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs)\n self._channel.basic_nack(delivery_tag)\n", "def reject_message(self, delivery_tag, requeue=False, **kwargs):\n \"\"\"Reject the message delivery from RabbitMQ by sending a\n Basic.Reject RPC method for the delivery tag.\n :param int delivery_tag: The delivery tag from the Basic.Deliver frame\n\n \"\"\"\n logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs)\n self._channel.basic_reject(delivery_tag, requeue=requeue)\n", "def tx_id(properties):\n \"\"\"\n Gets the tx_id for a message from a rabbit queue, using the\n message properties. Will raise KeyError if tx_id is missing from message\n headers.\n\n : param properties: Message properties\n\n : returns: tx_id of survey response\n : rtype: str\n \"\"\"\n tx_id = properties.headers['tx_id']\n logger.info(\"Retrieved tx_id from message properties: tx_id={}\".format(tx_id))\n return tx_id\n" ]
class MessageConsumer(TornadoConsumer): """This is a queue consumer that handles messages from RabbitMQ message queues. On receipt of a message it takes a number of params from the message properties, processes the message, and (if successful) positively acknowledges the publishing queue. If a message is not successfuly processed, it can be either negatively acknowledged, rejected or quarantined, depending on the type of excpetion raised. """ @staticmethod def tx_id(properties): """ Gets the tx_id for a message from a rabbit queue, using the message properties. Will raise KeyError if tx_id is missing from message headers. : param properties: Message properties : returns: tx_id of survey response : rtype: str """ tx_id = properties.headers['tx_id'] logger.info("Retrieved tx_id from message properties: tx_id={}".format(tx_id)) return tx_id def __init__(self, durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls, quarantine_publisher, process, check_tx_id=True): """Create a new instance of the SDXConsumer class : param durable_queue: Boolean specifying whether queue is durable : param exchange: RabbitMQ exchange name : param exchange_type: RabbitMQ exchange type : param rabbit_queue: RabbitMQ queue name : param rabbit_urls: List of rabbit urls : param quarantine_publisher: Object of type sdc.rabbit.QueuePublisher. Will publish quarantined messages to the named queue. : param process: Function or method to use for processsing message. Will be passed the body of the message as a string decoded using UTF - 8. Should raise sdc.rabbit.DecryptError, sdc.rabbit.BadMessageError or sdc.rabbit.RetryableError on failure, depending on the failure mode. : returns: Object of type SDXConsumer : rtype: SDXConsumer """ self.process = process if not callable(process): msg = 'process callback is not callable' raise AttributeError(msg.format(process)) self.quarantine_publisher = quarantine_publisher self.check_tx_id = check_tx_id super().__init__(durable_queue, exchange, exchange_type, rabbit_queue, rabbit_urls)
erikvw/django-collect-offline-files
django_collect_offline_files/file_queues/file_queue_handlers.py
RegexFileQueueHandlerIncoming.process
python
def process(self, event): logger.info(f"{self}: put {event.src_path}") self.queue.put(os.path.basename(event.src_path))
Put and process tasks in queue.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/file_queue_handlers.py#L26-L30
null
class RegexFileQueueHandlerIncoming(RegexMatchingEventHandler): def __init__(self, queue=None, regexes=None, **kwargs): super().__init__(regexes=regexes) self.queue = queue def __repr__(self, queue=None, regexes=None, **kwargs): return f"{self.__class__.__name__}({self.queue})" def __str__(self): return str(self.queue) def on_created(self, event): self.process(event)
erikvw/django-collect-offline-files
django_collect_offline_files/confirmation.py
Confirmation.confirm
python
def confirm(self, batch_id=None, filename=None): if batch_id or filename: export_history = self.history_model.objects.using(self.using).filter( Q(batch_id=batch_id) | Q(filename=filename), sent=True, confirmation_code__isnull=True, ) else: export_history = self.history_model.objects.using(self.using).filter( sent=True, confirmation_code__isnull=True ) if export_history.count() == 0: raise ConfirmationError( "Nothing to do. No history of sent and unconfirmed files" ) else: confirmation_code = ConfirmationCode() export_history.update( confirmation_code=confirmation_code.identifier, confirmation_datetime=get_utcnow(), ) return confirmation_code.identifier
Flags the batch as confirmed by updating confirmation_datetime on the history model for this batch.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/confirmation.py#L24-L48
null
class Confirmation: """A class to manage confirmation of sent / transferred transaction files. """ def __init__(self, history_model=None, using=None, **kwargs): self.history_model = history_model self.using = using
erikvw/django-collect-offline-files
django_collect_offline_files/file_queues/base_file_queue.py
BaseFileQueue.reload
python
def reload(self, regexes=None, **kwargs): combined = re.compile("(" + ")|(".join(regexes) + ")", re.I) pending_files = os.listdir(self.src_path) or [] pending_files.sort() for filename in pending_files: if re.match(combined, filename): self.put(os.path.join(self.src_path, filename))
Reloads /path/to/filenames into the queue that match the regexes.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/base_file_queue.py#L34-L43
null
class BaseFileQueue(Queue): file_archiver_cls = FileArchiver def __init__(self, src_path=None, dst_path=None, **kwargs): super().__init__(maxsize=kwargs.get("maxsize", 0)) self.src_path = src_path self.dst_path = dst_path try: self.file_archiver = self.file_archiver_cls( src_path=src_path, dst_path=dst_path, **kwargs ) except FileArchiverError as e: raise TransactionsFileQueueError(e) from e def __repr__(self): return f"{self.__class__.__name__}({self.src_path}, {self.dst_path})" def __str__(self): return self.__class__.__name__ def next_task(self, item, **kwargs): pass def archive(self, filename=None): try: self.file_archiver.archive(filename) except FileArchiverError as e: raise TransactionsFileQueueError(e) from e
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_file_sender.py
TransactionFileSender.send
python
def send(self, filenames=None): try: with self.ssh_client.connect() as ssh_conn: with self.sftp_client.connect(ssh_conn) as sftp_conn: for filename in filenames: sftp_conn.copy(filename=filename) self.archive(filename=filename) if self.update_history_model: self.update_history(filename=filename) except SSHClientError as e: raise TransactionFileSenderError(e) from e except SFTPClientError as e: raise TransactionFileSenderError(e) from e return filenames
Sends the file to the remote host and archives the sent file locally.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_file_sender.py#L39-L55
[ "def update_history(self, filename=None):\n try:\n obj = self.history_model.objects.using(self.using).get(filename=filename)\n except self.history_model.DoesNotExist as e:\n raise TransactionFileSenderError(\n f\"History does not exist for file '{filename}'. Got {e}\"\n ) from e\n else:\n obj.sent = True\n obj.sent_datetime = get_utcnow()\n obj.save()\n", "def archive(self, filename):\n self.file_archiver.archive(filename=filename)\n" ]
class TransactionFileSender: def __init__( self, remote_host=None, username=None, src_path=None, dst_tmp=None, dst_path=None, archive_path=None, history_model=None, using=None, update_history_model=None, **kwargs, ): self.using = using self.update_history_model = ( True if update_history_model is None else update_history_model ) self.file_archiver = FileArchiver(src_path=src_path, dst_path=archive_path) self.history_model = history_model self.ssh_client = SSHClient( username=username, remote_host=remote_host, **kwargs ) self.sftp_client = SFTPClient( src_path=src_path, dst_tmp=dst_tmp, dst_path=dst_path, **kwargs ) def update_history(self, filename=None): try: obj = self.history_model.objects.using(self.using).get(filename=filename) except self.history_model.DoesNotExist as e: raise TransactionFileSenderError( f"History does not exist for file '{filename}'. Got {e}" ) from e else: obj.sent = True obj.sent_datetime = get_utcnow() obj.save() def archive(self, filename): self.file_archiver.archive(filename=filename)
erikvw/django-collect-offline-files
django_collect_offline_files/sftp_client.py
SFTPClient.copy
python
def copy(self, filename=None): dst = os.path.join(self.dst_path, filename) src = os.path.join(self.src_path, filename) dst_tmp = os.path.join(self.dst_tmp, filename) self.put(src=src, dst=dst_tmp, callback=self.update_progress, confirm=True) self.rename(src=dst_tmp, dst=dst)
Puts on destination as a temp file, renames on the destination.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/sftp_client.py#L38-L46
null
class SFTPClient(ClosingContextManager): """Wraps open_sftp with folder defaults for copy. Copy is two steps; put then rename. """ def __init__( self, src_path=None, dst_path=None, dst_tmp=None, verbose=None, **kwargs ): self.src_path = src_path self.dst_tmp = dst_tmp self.dst_path = dst_path self._sftp_client = None self.verbose = verbose self.progress = 0 def connect(self, ssh_conn=None): self._sftp_client = ssh_conn.open_sftp() return self def close(self): self._sftp_client.close() def put(self, src=None, dst=None, callback=None, confirm=None): if not os.path.exists(src): raise SFTPClientError(f"Source file does not exist. Got '{src}'") self.progress = 0 try: self._sftp_client.put(src, dst, callback=callback, confirm=confirm) except IOError as e: raise SFTPClientError(f"IOError. Failed to copy {src}.") from e if self.verbose: logger.info(f"Copied {src} to {dst}") sys.stdout.write("\n") def rename(self, src=None, dst=None): try: self._sftp_client.rename(src, dst) except IOError as e: raise SFTPClientError(f"IOError. Failed to rename {src} to {dst}.") from e def update_progress(self, sent_bytes, total_bytes): self.progress = (sent_bytes / total_bytes) * 100 if self.verbose: sys.stdout.write(f"Progress {self.progress}% \r")
erikvw/django-collect-offline-files
django_collect_offline_files/file_queues/process_queue.py
process_queue
python
def process_queue(queue=None, **kwargs): while True: item = queue.get() if item is None: queue.task_done() logger.info(f"{queue}: exiting process queue.") break filename = os.path.basename(item) try: queue.next_task(item, **kwargs) except Exception as e: queue.task_done() logger.warn(f"{queue}: item={filename}. {e}\n") logger.exception(e) sys.stdout.write( style.ERROR( f"{queue}. item={filename}. {e}. Exception has been logged.\n" ) ) sys.stdout.flush() break else: logger.info(f"{queue}: Successfully processed {filename}.\n") queue.task_done()
Loops and waits on queue calling queue's `next_task` method. If an exception occurs, log the error, log the exception, and break.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/process_queue.py#L11-L39
[ "def next_task(self, item, raise_exceptions=None, **kwargs):\n \"\"\"Deserializes all transactions for this batch and\n archives the file.\n \"\"\"\n filename = os.path.basename(item)\n batch = self.get_batch(filename)\n tx_deserializer = self.tx_deserializer_cls(\n allow_self=self.allow_self, override_role=self.override_role\n )\n try:\n tx_deserializer.deserialize_transactions(\n transactions=batch.saved_transactions\n )\n except (DeserializationError, TransactionDeserializerError) as e:\n raise TransactionsFileQueueError(e) from e\n else:\n batch.close()\n self.archive(filename)\n", "def next_task(self, item, **kwargs):\n \"\"\"Calls import_batch for the next filename in the queue\n and \"archives\" the file.\n\n The archive folder is typically the folder for the deserializer queue.\n \"\"\"\n filename = os.path.basename(item)\n try:\n self.tx_importer.import_batch(filename=filename)\n except TransactionImporterError as e:\n raise TransactionsFileQueueError(e) from e\n else:\n self.archive(filename)\n" ]
import os import logging import sys from django.core.management.color import color_style logger = logging.getLogger("django_collect_offline_files") style = color_style()
erikvw/django-collect-offline-files
django_collect_offline_files/file_queues/incoming_transactions_file_queue.py
IncomingTransactionsFileQueue.next_task
python
def next_task(self, item, **kwargs): filename = os.path.basename(item) try: self.tx_importer.import_batch(filename=filename) except TransactionImporterError as e: raise TransactionsFileQueueError(e) from e else: self.archive(filename)
Calls import_batch for the next filename in the queue and "archives" the file. The archive folder is typically the folder for the deserializer queue.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/incoming_transactions_file_queue.py#L17-L29
[ "def archive(self, filename=None):\n try:\n self.file_archiver.archive(filename)\n except FileArchiverError as e:\n raise TransactionsFileQueueError(e) from e\n" ]
class IncomingTransactionsFileQueue(BaseFileQueue): tx_importer_cls = TransactionImporter def __init__(self, src_path=None, raise_exceptions=None, **kwargs): super().__init__(src_path=src_path, **kwargs) self.tx_importer = self.tx_importer_cls(import_path=src_path, **kwargs) self.raise_exceptions = raise_exceptions
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
JSONLoadFile.read
python
def read(self): p = os.path.join(self.path, self.name) try: with open(p) as f: json_text = f.read() except FileNotFoundError as e: raise JSONFileError(e) from e try: json.loads(json_text) except (json.JSONDecodeError, TypeError) as e: raise JSONFileError(f"{e} Got {p}") from e return json_text
Returns the file contents as validated JSON text.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L62-L75
null
class JSONLoadFile: def __init__(self, name=None, path=None, **kwargs): self._deserialized_objects = None self.deserialize = deserialize self.name = name self.path = path def __str__(self): return os.path.join(self.path, self.name) def __repr__(self): return f"{self.__class__.__name__}(name={self.name})" @property def deserialized_objects(self): """Returns a generator of deserialized objects. """ if not self._deserialized_objects: json_text = self.read() self._deserialized_objects = self.deserialize(json_text=json_text) return self._deserialized_objects
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
JSONLoadFile.deserialized_objects
python
def deserialized_objects(self): if not self._deserialized_objects: json_text = self.read() self._deserialized_objects = self.deserialize(json_text=json_text) return self._deserialized_objects
Returns a generator of deserialized objects.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L78-L84
[ "def read(self):\n \"\"\"Returns the file contents as validated JSON text.\n \"\"\"\n p = os.path.join(self.path, self.name)\n try:\n with open(p) as f:\n json_text = f.read()\n except FileNotFoundError as e:\n raise JSONFileError(e) from e\n try:\n json.loads(json_text)\n except (json.JSONDecodeError, TypeError) as e:\n raise JSONFileError(f\"{e} Got {p}\") from e\n return json_text\n" ]
class JSONLoadFile: def __init__(self, name=None, path=None, **kwargs): self._deserialized_objects = None self.deserialize = deserialize self.name = name self.path = path def __str__(self): return os.path.join(self.path, self.name) def __repr__(self): return f"{self.__class__.__name__}(name={self.name})" def read(self): """Returns the file contents as validated JSON text. """ p = os.path.join(self.path, self.name) try: with open(p) as f: json_text = f.read() except FileNotFoundError as e: raise JSONFileError(e) from e try: json.loads(json_text) except (json.JSONDecodeError, TypeError) as e: raise JSONFileError(f"{e} Got {p}") from e return json_text @property
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
BatchHistory.exists
python
def exists(self, batch_id=None): try: self.model.objects.get(batch_id=batch_id) except self.model.DoesNotExist: return False return True
Returns True if batch_id exists in the history.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L91-L98
null
class BatchHistory: def __init__(self, model=None): self.model = model or ImportedTransactionFileHistory def close(self, batch_id): obj = self.model.objects.get(batch_id=batch_id) obj.consumed = True obj.consumed_datetime = get_utcnow() obj.save() def update( self, filename=None, batch_id=None, prev_batch_id=None, producer=None, count=None, ): """Creates an history model instance. """ # TODO: refactor model enforce unique batch_id # TODO: refactor model to not allow NULLs if not filename: raise BatchHistoryError("Invalid filename. Got None") if not batch_id: raise BatchHistoryError("Invalid batch_id. Got None") if not prev_batch_id: raise BatchHistoryError("Invalid prev_batch_id. Got None") if not producer: raise BatchHistoryError("Invalid producer. Got None") if self.exists(batch_id=batch_id): raise IntegrityError("Duplicate batch_id") try: obj = self.model.objects.get(batch_id=batch_id) except self.model.DoesNotExist: obj = self.model( filename=filename, batch_id=batch_id, prev_batch_id=prev_batch_id, producer=producer, total=count, ) obj.transaction_file.name = filename obj.save() return obj
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
BatchHistory.update
python
def update( self, filename=None, batch_id=None, prev_batch_id=None, producer=None, count=None, ): # TODO: refactor model enforce unique batch_id # TODO: refactor model to not allow NULLs if not filename: raise BatchHistoryError("Invalid filename. Got None") if not batch_id: raise BatchHistoryError("Invalid batch_id. Got None") if not prev_batch_id: raise BatchHistoryError("Invalid prev_batch_id. Got None") if not producer: raise BatchHistoryError("Invalid producer. Got None") if self.exists(batch_id=batch_id): raise IntegrityError("Duplicate batch_id") try: obj = self.model.objects.get(batch_id=batch_id) except self.model.DoesNotExist: obj = self.model( filename=filename, batch_id=batch_id, prev_batch_id=prev_batch_id, producer=producer, total=count, ) obj.transaction_file.name = filename obj.save() return obj
Creates an history model instance.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L106-L140
[ "def exists(self, batch_id=None):\n \"\"\"Returns True if batch_id exists in the history.\n \"\"\"\n try:\n self.model.objects.get(batch_id=batch_id)\n except self.model.DoesNotExist:\n return False\n return True\n" ]
class BatchHistory: def __init__(self, model=None): self.model = model or ImportedTransactionFileHistory def exists(self, batch_id=None): """Returns True if batch_id exists in the history. """ try: self.model.objects.get(batch_id=batch_id) except self.model.DoesNotExist: return False return True def close(self, batch_id): obj = self.model.objects.get(batch_id=batch_id) obj.consumed = True obj.consumed_datetime = get_utcnow() obj.save()
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
ImportBatch.populate
python
def populate(self, deserialized_txs=None, filename=None, retry=None): if not deserialized_txs: raise BatchError("Failed to populate batch. There are no objects to add.") self.filename = filename if not self.filename: raise BatchError("Invalid filename. Got None") try: for deserialized_tx in deserialized_txs: self.peek(deserialized_tx) self.objects.append(deserialized_tx.object) break for deserialized_tx in deserialized_txs: self.objects.append(deserialized_tx.object) except DeserializationError as e: raise BatchDeserializationError(e) from e except JSONFileError as e: raise BatchDeserializationError(e) from e
Populates the batch with unsaved model instances from a generator of deserialized objects.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L160-L179
[ "def peek(self, deserialized_tx):\n \"\"\"Peeks into first tx and sets self attrs or raise.\n \"\"\"\n self.batch_id = deserialized_tx.object.batch_id\n self.prev_batch_id = deserialized_tx.object.prev_batch_id\n self.producer = deserialized_tx.object.producer\n if self.batch_history.exists(batch_id=self.batch_id):\n raise BatchAlreadyProcessed(\n f\"Batch {self.batch_id} has already been processed\"\n )\n if self.prev_batch_id != self.batch_id:\n if not self.batch_history.exists(batch_id=self.prev_batch_id):\n raise InvalidBatchSequence(\n f\"Invalid import sequence. History does not exist for prev_batch_id. \"\n f\"Got file='{self.filename}', prev_batch_id=\"\n f\"{self.prev_batch_id}, batch_id={self.batch_id}.\"\n )\n" ]
class ImportBatch: def __init__(self, **kwargs): self._valid_sequence = None self.filename = None self.batch_id = None self.prev_batch_id = None self.producer = None self.objects = [] self.batch_history = BatchHistory() self.model = IncomingTransaction def __str__(self): return f"Batch(batch_id={self.batch_id}, filename={self.filename})" def __repr__(self): return f"Batch(batch_id={self.batch_id}, filename={self.filename})" def peek(self, deserialized_tx): """Peeks into first tx and sets self attrs or raise. """ self.batch_id = deserialized_tx.object.batch_id self.prev_batch_id = deserialized_tx.object.prev_batch_id self.producer = deserialized_tx.object.producer if self.batch_history.exists(batch_id=self.batch_id): raise BatchAlreadyProcessed( f"Batch {self.batch_id} has already been processed" ) if self.prev_batch_id != self.batch_id: if not self.batch_history.exists(batch_id=self.prev_batch_id): raise InvalidBatchSequence( f"Invalid import sequence. History does not exist for prev_batch_id. " f"Got file='{self.filename}', prev_batch_id=" f"{self.prev_batch_id}, batch_id={self.batch_id}." ) def save(self): """Saves all model instances in the batch as model. """ saved = 0 if not self.objects: raise BatchError("Save failed. Batch is empty") for deserialized_tx in self.objects: try: self.model.objects.get(pk=deserialized_tx.pk) except self.model.DoesNotExist: data = {} for field in self.model._meta.get_fields(): try: data.update({field.name: getattr(deserialized_tx, field.name)}) except AttributeError: pass self.model.objects.create(**data) saved += 1 return saved def update_history(self): if not self.objects: raise BatchIsEmpty("Update history failed. Batch is empty") if self.objects_unsaved: raise BatchUnsaved("Update history failed. Batch has unsaved objects") self.batch_history.update( filename=self.filename, batch_id=self.batch_id, prev_batch_id=self.prev_batch_id, producer=self.producer, count=self.saved_transactions.count(), ) @property def saved_transactions(self): """Returns the count of saved model instances for this batch. """ return self.model.objects.filter(batch_id=self.batch_id) @property def count(self): """Returns the number of objects in the batch. """ return len(self.objects) @property def objects_unsaved(self): """Returns True if any batch objects have not been saved. """ return self.count > self.saved_transactions.count() def close(self): self.batch_history.close(self.batch_id)
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
ImportBatch.peek
python
def peek(self, deserialized_tx): self.batch_id = deserialized_tx.object.batch_id self.prev_batch_id = deserialized_tx.object.prev_batch_id self.producer = deserialized_tx.object.producer if self.batch_history.exists(batch_id=self.batch_id): raise BatchAlreadyProcessed( f"Batch {self.batch_id} has already been processed" ) if self.prev_batch_id != self.batch_id: if not self.batch_history.exists(batch_id=self.prev_batch_id): raise InvalidBatchSequence( f"Invalid import sequence. History does not exist for prev_batch_id. " f"Got file='{self.filename}', prev_batch_id=" f"{self.prev_batch_id}, batch_id={self.batch_id}." )
Peeks into first tx and sets self attrs or raise.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L181-L197
null
class ImportBatch: def __init__(self, **kwargs): self._valid_sequence = None self.filename = None self.batch_id = None self.prev_batch_id = None self.producer = None self.objects = [] self.batch_history = BatchHistory() self.model = IncomingTransaction def __str__(self): return f"Batch(batch_id={self.batch_id}, filename={self.filename})" def __repr__(self): return f"Batch(batch_id={self.batch_id}, filename={self.filename})" def populate(self, deserialized_txs=None, filename=None, retry=None): """Populates the batch with unsaved model instances from a generator of deserialized objects. """ if not deserialized_txs: raise BatchError("Failed to populate batch. There are no objects to add.") self.filename = filename if not self.filename: raise BatchError("Invalid filename. Got None") try: for deserialized_tx in deserialized_txs: self.peek(deserialized_tx) self.objects.append(deserialized_tx.object) break for deserialized_tx in deserialized_txs: self.objects.append(deserialized_tx.object) except DeserializationError as e: raise BatchDeserializationError(e) from e except JSONFileError as e: raise BatchDeserializationError(e) from e def save(self): """Saves all model instances in the batch as model. """ saved = 0 if not self.objects: raise BatchError("Save failed. Batch is empty") for deserialized_tx in self.objects: try: self.model.objects.get(pk=deserialized_tx.pk) except self.model.DoesNotExist: data = {} for field in self.model._meta.get_fields(): try: data.update({field.name: getattr(deserialized_tx, field.name)}) except AttributeError: pass self.model.objects.create(**data) saved += 1 return saved def update_history(self): if not self.objects: raise BatchIsEmpty("Update history failed. Batch is empty") if self.objects_unsaved: raise BatchUnsaved("Update history failed. Batch has unsaved objects") self.batch_history.update( filename=self.filename, batch_id=self.batch_id, prev_batch_id=self.prev_batch_id, producer=self.producer, count=self.saved_transactions.count(), ) @property def saved_transactions(self): """Returns the count of saved model instances for this batch. """ return self.model.objects.filter(batch_id=self.batch_id) @property def count(self): """Returns the number of objects in the batch. """ return len(self.objects) @property def objects_unsaved(self): """Returns True if any batch objects have not been saved. """ return self.count > self.saved_transactions.count() def close(self): self.batch_history.close(self.batch_id)
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
ImportBatch.save
python
def save(self): saved = 0 if not self.objects: raise BatchError("Save failed. Batch is empty") for deserialized_tx in self.objects: try: self.model.objects.get(pk=deserialized_tx.pk) except self.model.DoesNotExist: data = {} for field in self.model._meta.get_fields(): try: data.update({field.name: getattr(deserialized_tx, field.name)}) except AttributeError: pass self.model.objects.create(**data) saved += 1 return saved
Saves all model instances in the batch as model.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L199-L217
null
class ImportBatch: def __init__(self, **kwargs): self._valid_sequence = None self.filename = None self.batch_id = None self.prev_batch_id = None self.producer = None self.objects = [] self.batch_history = BatchHistory() self.model = IncomingTransaction def __str__(self): return f"Batch(batch_id={self.batch_id}, filename={self.filename})" def __repr__(self): return f"Batch(batch_id={self.batch_id}, filename={self.filename})" def populate(self, deserialized_txs=None, filename=None, retry=None): """Populates the batch with unsaved model instances from a generator of deserialized objects. """ if not deserialized_txs: raise BatchError("Failed to populate batch. There are no objects to add.") self.filename = filename if not self.filename: raise BatchError("Invalid filename. Got None") try: for deserialized_tx in deserialized_txs: self.peek(deserialized_tx) self.objects.append(deserialized_tx.object) break for deserialized_tx in deserialized_txs: self.objects.append(deserialized_tx.object) except DeserializationError as e: raise BatchDeserializationError(e) from e except JSONFileError as e: raise BatchDeserializationError(e) from e def peek(self, deserialized_tx): """Peeks into first tx and sets self attrs or raise. """ self.batch_id = deserialized_tx.object.batch_id self.prev_batch_id = deserialized_tx.object.prev_batch_id self.producer = deserialized_tx.object.producer if self.batch_history.exists(batch_id=self.batch_id): raise BatchAlreadyProcessed( f"Batch {self.batch_id} has already been processed" ) if self.prev_batch_id != self.batch_id: if not self.batch_history.exists(batch_id=self.prev_batch_id): raise InvalidBatchSequence( f"Invalid import sequence. History does not exist for prev_batch_id. " f"Got file='{self.filename}', prev_batch_id=" f"{self.prev_batch_id}, batch_id={self.batch_id}." ) def update_history(self): if not self.objects: raise BatchIsEmpty("Update history failed. Batch is empty") if self.objects_unsaved: raise BatchUnsaved("Update history failed. Batch has unsaved objects") self.batch_history.update( filename=self.filename, batch_id=self.batch_id, prev_batch_id=self.prev_batch_id, producer=self.producer, count=self.saved_transactions.count(), ) @property def saved_transactions(self): """Returns the count of saved model instances for this batch. """ return self.model.objects.filter(batch_id=self.batch_id) @property def count(self): """Returns the number of objects in the batch. """ return len(self.objects) @property def objects_unsaved(self): """Returns True if any batch objects have not been saved. """ return self.count > self.saved_transactions.count() def close(self): self.batch_history.close(self.batch_id)
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_importer.py
TransactionImporter.import_batch
python
def import_batch(self, filename): batch = self.batch_cls() json_file = self.json_file_cls(name=filename, path=self.path) try: deserialized_txs = json_file.deserialized_objects except JSONFileError as e: raise TransactionImporterError(e) from e try: batch.populate(deserialized_txs=deserialized_txs, filename=json_file.name) except ( BatchDeserializationError, InvalidBatchSequence, BatchAlreadyProcessed, ) as e: raise TransactionImporterError(e) from e batch.save() batch.update_history() return batch
Imports the batch of outgoing transactions into model IncomingTransaction.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L264-L284
null
class TransactionImporter: """Imports transactions from a file as incoming transaction. """ batch_cls = ImportBatch json_file_cls = JSONLoadFile def __init__(self, import_path=None, **kwargs): self.path = import_path
erikvw/django-collect-offline-files
django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py
DeserializeTransactionsFileQueue.next_task
python
def next_task(self, item, raise_exceptions=None, **kwargs): filename = os.path.basename(item) batch = self.get_batch(filename) tx_deserializer = self.tx_deserializer_cls( allow_self=self.allow_self, override_role=self.override_role ) try: tx_deserializer.deserialize_transactions( transactions=batch.saved_transactions ) except (DeserializationError, TransactionDeserializerError) as e: raise TransactionsFileQueueError(e) from e else: batch.close() self.archive(filename)
Deserializes all transactions for this batch and archives the file.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py#L25-L42
[ "def archive(self, filename=None):\n try:\n self.file_archiver.archive(filename)\n except FileArchiverError as e:\n raise TransactionsFileQueueError(e) from e\n", "def get_batch(self, filename=None):\n \"\"\"Returns a batch instance given the filename.\n \"\"\"\n try:\n history = self.history_model.objects.get(filename=filename)\n except self.history_model.DoesNotExist as e:\n raise TransactionsFileQueueError(\n f\"Batch history not found for '{filename}'.\"\n ) from e\n if history.consumed:\n raise TransactionsFileQueueError(\n f\"Batch closed for '{filename}'. Got consumed=True\"\n )\n batch = self.batch_cls()\n batch.batch_id = history.batch_id\n batch.filename = history.filename\n return batch\n" ]
class DeserializeTransactionsFileQueue(BaseFileQueue): batch_cls = TransactionImporterBatch tx_deserializer_cls = TransactionDeserializer def __init__( self, history_model=None, allow_self=None, override_role=None, **kwargs ): super().__init__(**kwargs) self.history_model = history_model self.allow_self = allow_self self.override_role = override_role def get_batch(self, filename=None): """Returns a batch instance given the filename. """ try: history = self.history_model.objects.get(filename=filename) except self.history_model.DoesNotExist as e: raise TransactionsFileQueueError( f"Batch history not found for '{filename}'." ) from e if history.consumed: raise TransactionsFileQueueError( f"Batch closed for '{filename}'. Got consumed=True" ) batch = self.batch_cls() batch.batch_id = history.batch_id batch.filename = history.filename return batch
erikvw/django-collect-offline-files
django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py
DeserializeTransactionsFileQueue.get_batch
python
def get_batch(self, filename=None): try: history = self.history_model.objects.get(filename=filename) except self.history_model.DoesNotExist as e: raise TransactionsFileQueueError( f"Batch history not found for '{filename}'." ) from e if history.consumed: raise TransactionsFileQueueError( f"Batch closed for '{filename}'. Got consumed=True" ) batch = self.batch_cls() batch.batch_id = history.batch_id batch.filename = history.filename return batch
Returns a batch instance given the filename.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py#L44-L60
null
class DeserializeTransactionsFileQueue(BaseFileQueue): batch_cls = TransactionImporterBatch tx_deserializer_cls = TransactionDeserializer def __init__( self, history_model=None, allow_self=None, override_role=None, **kwargs ): super().__init__(**kwargs) self.history_model = history_model self.allow_self = allow_self self.override_role = override_role def next_task(self, item, raise_exceptions=None, **kwargs): """Deserializes all transactions for this batch and archives the file. """ filename = os.path.basename(item) batch = self.get_batch(filename) tx_deserializer = self.tx_deserializer_cls( allow_self=self.allow_self, override_role=self.override_role ) try: tx_deserializer.deserialize_transactions( transactions=batch.saved_transactions ) except (DeserializationError, TransactionDeserializerError) as e: raise TransactionsFileQueueError(e) from e else: batch.close() self.archive(filename)
erikvw/django-collect-offline-files
django_collect_offline_files/transaction/transaction_exporter.py
TransactionExporter.export_batch
python
def export_batch(self): batch = self.batch_cls( model=self.model, history_model=self.history_model, using=self.using ) if batch.items: try: json_file = self.json_file_cls(batch=batch, path=self.path) json_file.write() except JSONDumpFileError as e: raise TransactionExporterError(e) batch.close() return batch return None
Returns a batch instance after exporting a batch of txs.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_exporter.py#L179-L193
null
class TransactionExporter: """Export pending OutgoingTransactions to a file in JSON format and update the export `History` model. """ batch_cls = ExportBatch json_file_cls = JSONDumpFile model = OutgoingTransaction history_model = ExportedTransactionFileHistory def __init__(self, export_path=None, using=None, **kwargs): self.path = export_path self.serialize = serialize self.using = using
erikvw/django-collect-offline-files
django_collect_offline_files/apps.py
AppConfig.make_required_folders
python
def make_required_folders(self): for folder in [ self.pending_folder, self.usb_incoming_folder, self.outgoing_folder, self.incoming_folder, self.archive_folder, self.tmp_folder, self.log_folder, ]: if not os.path.exists(folder): os.makedirs(folder)
Makes all folders declared in the config if they do not exist.
train
https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/apps.py#L31-L45
null
class AppConfig(DjangoAppConfig): name = "django_collect_offline_files" verbose_name = "File support for data synchronization" django_collect_offline_files_using = True user = settings.DJANGO_COLLECT_OFFLINE_FILES_USER remote_host = settings.DJANGO_COLLECT_OFFLINE_FILES_REMOTE_HOST usb_volume = settings.DJANGO_COLLECT_OFFLINE_FILES_USB_VOLUME tmp_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "tmp") pending_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "pending") usb_incoming_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "usb") outgoing_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "outgoing") incoming_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "incoming") archive_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "archive") log_folder = os.path.join(settings.MEDIA_ROOT, "transactions", "log") def ready(self): sys.stdout.write(f"Loading {self.verbose_name} ...\n") self.make_required_folders() sys.stdout.write(f"Done loading {self.verbose_name}.\n")
GGiecold/Concurrent_AP
Concurrent_AP.py
chunk_generator
python
def chunk_generator(N, n): chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N))
Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L118-L139
[ "def get_chunk_size(N, n):\n \"\"\"Given a two-dimensional array with a dimension of size 'N', \n determine the number of rows or columns that can fit into memory.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of size 'N' times 'chunk_size' that can fit in memory.\n\n Returns\n -------\n chunk_size : int\n The size of the dimension orthogonal to the one of size 'N'. \n \"\"\"\n\n mem_free = memory()['free']\n if mem_free > 60000000:\n chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 40000000:\n chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 14000000:\n chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 8000000:\n chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 2000000:\n chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 1000000:\n chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N))\n return chunk_size\n else:\n print(\"\\nERROR: Concurrent_AP: get_chunk_size: this machine does not \"\n \"have enough free memory.\\n\")\n sys.exit(1)\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
parse_options
python
def parse_options(): parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0]
Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L142-L229
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
check_HDF5_arrays
python
def check_HDF5_arrays(hdf5_file, N, convergence_iter): Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release()
Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L232-L276
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
get_sum
python
def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp
Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L433-L471
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
terminate_processes
python
def terminate_processes(pid_list): for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate()
Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L522-L534
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
compute_similarities
python
def compute_similarities(hdf5_file, data, N_processes): slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect()
Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L537-L562
[ "def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n Returns\n -------\n Slice objects of the type 'slice(start, stop)' are generated, representing\n the set of indices specified by 'range(start, stop)'. \n \"\"\"\n\n chunk_size = get_chunk_size(N, n)\n\n for start in range(0, N, chunk_size):\n yield slice(start, min(start + chunk_size, N))\n", "def terminate_processes(pid_list):\n \"\"\"Terminate a list of processes by sending to each of them a SIGTERM signal, \n pre-emptively checking if its PID might have been reused.\n\n Parameters\n ----------\n pid_list : list\n A list of process identifiers identifying active processes.\n \"\"\"\n\n for proc in psutil.process_iter():\n if proc.pid in pid_list:\n proc.terminate()\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
add_preference
python
def add_preference(hdf5_file, preference): Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release()
Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L565-L578
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
add_fluctuations
python
def add_fluctuations(hdf5_file, N_columns, N_processes): random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect()
This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L581-L608
[ "def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n Returns\n -------\n Slice objects of the type 'slice(start, stop)' are generated, representing\n the set of indices specified by 'range(start, stop)'. \n \"\"\"\n\n chunk_size = get_chunk_size(N, n)\n\n for start in range(0, N, chunk_size):\n yield slice(start, min(start + chunk_size, N))\n", "def terminate_processes(pid_list):\n \"\"\"Terminate a list of processes by sending to each of them a SIGTERM signal, \n pre-emptively checking if its PID might have been reused.\n\n Parameters\n ----------\n pid_list : list\n A list of process identifiers identifying active processes.\n \"\"\"\n\n for proc in psutil.process_iter():\n if proc.pid in pid_list:\n proc.terminate()\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
compute_responsibilities
python
def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list)
Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L611-L634
[ "def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n Returns\n -------\n Slice objects of the type 'slice(start, stop)' are generated, representing\n the set of indices specified by 'range(start, stop)'. \n \"\"\"\n\n chunk_size = get_chunk_size(N, n)\n\n for start in range(0, N, chunk_size):\n yield slice(start, min(start + chunk_size, N))\n", "def terminate_processes(pid_list):\n \"\"\"Terminate a list of processes by sending to each of them a SIGTERM signal, \n pre-emptively checking if its PID might have been reused.\n\n Parameters\n ----------\n pid_list : list\n A list of process identifiers identifying active processes.\n \"\"\"\n\n for proc in psutil.process_iter():\n if proc.pid in pid_list:\n proc.terminate()\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
rows_sum_init
python
def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args)
Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L637-L647
[ "def to_numpy_array(multiprocessing_array, shape, dtype):\n \"\"\"Convert a share multiprocessing array to a numpy array.\n No data copying involved.\n \"\"\"\n\n return np.frombuffer(multiprocessing_array.get_obj(),\n dtype = dtype).reshape(shape)\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
to_numpy_array
python
def to_numpy_array(multiprocessing_array, shape, dtype): return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape)
Convert a share multiprocessing array to a numpy array. No data copying involved.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L655-L661
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
compute_rows_sum
python
def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum
Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L664-L709
[ "def get_chunk_size(N, n):\n \"\"\"Given a two-dimensional array with a dimension of size 'N', \n determine the number of rows or columns that can fit into memory.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of size 'N' times 'chunk_size' that can fit in memory.\n\n Returns\n -------\n chunk_size : int\n The size of the dimension orthogonal to the one of size 'N'. \n \"\"\"\n\n mem_free = memory()['free']\n if mem_free > 60000000:\n chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 40000000:\n chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 14000000:\n chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 8000000:\n chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 2000000:\n chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N))\n return chunk_size\n elif mem_free > 1000000:\n chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N))\n return chunk_size\n else:\n print(\"\\nERROR: Concurrent_AP: get_chunk_size: this machine does not \"\n \"have enough free memory.\\n\")\n sys.exit(1)\n", "def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n Returns\n -------\n Slice objects of the type 'slice(start, stop)' are generated, representing\n the set of indices specified by 'range(start, stop)'. \n \"\"\"\n\n chunk_size = get_chunk_size(N, n)\n\n for start in range(0, N, chunk_size):\n yield slice(start, min(start + chunk_size, N))\n", "def to_numpy_array(multiprocessing_array, shape, dtype):\n \"\"\"Convert a share multiprocessing array to a numpy array.\n No data copying involved.\n \"\"\"\n\n return np.frombuffer(multiprocessing_array.get_obj(),\n dtype = dtype).reshape(shape)\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
compute_availabilities
python
def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect()
Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L712-L754
[ "def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n Returns\n -------\n Slice objects of the type 'slice(start, stop)' are generated, representing\n the set of indices specified by 'range(start, stop)'. \n \"\"\"\n\n chunk_size = get_chunk_size(N, n)\n\n for start in range(0, N, chunk_size):\n yield slice(start, min(start + chunk_size, N))\n", "def terminate_processes(pid_list):\n \"\"\"Terminate a list of processes by sending to each of them a SIGTERM signal, \n pre-emptively checking if its PID might have been reused.\n\n Parameters\n ----------\n pid_list : list\n A list of process identifiers identifying active processes.\n \"\"\"\n\n for proc in psutil.process_iter():\n if proc.pid in pid_list:\n proc.terminate()\n" ]
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
check_convergence
python
def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False
If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L757-L790
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
cluster_labels_A
python
def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s
One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L827-L843
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
cluster_labels_B
python
def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s
Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L846-L862
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
get_cluster_labels
python
def get_cluster_labels(hdf5_file, N_processes): with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels
Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L884-L990
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
output_clusters
python
def output_clusters(labels, cluster_centers_indices): here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t')
Write in tab-separated files the vectors of cluster identities and of indices of cluster centers.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L993-L1020
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
GGiecold/Concurrent_AP
Concurrent_AP.py
set_preference
python
def set_preference(data, chunk_size): N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference
Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling.
train
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L1023-L1080
null
#!/usr/bin/env python # Concurrent_AP/Concurrent_AP.py # Author: Gregory Giecold for the GC Yuan Lab # Affiliation: Harvard University # Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu """Concurrent_AP is a scalable and concurrent programming implementation of Affinity Propagation clustering. Affinity Propagation is a clustering algorithm based on passing messages between data-points. Storing and updating matrices of 'affinities', 'responsibilities' and 'similarities' between samples can be memory-intensive. We address this issue through the use of an HDF5 data structure, allowing Affinity Propagation clustering of arbitrarily large data-sets, where other Python implementations would return a MemoryError on most machines. We also significantly speed up the computations by splitting them up across subprocesses, thereby taking full advantage of the resources of multi-core processors and bypassing the Global Interpreter Lock of the standard Python interpreter, CPython. Reference --------- Brendan J. Frey and Delbert Dueck., "Clustering by Passing Messages Between Data Points". In: Science, Vol. 315, no. 5814, pp. 972-976. 2007 """ from abc import ABCMeta, abstractmethod from contextlib import closing from ctypes import c_double, c_int import gc import multiprocessing import numpy as np import optparse import os import psutil from sklearn.metrics.pairwise import euclidean_distances import sys import tables from tempfile import NamedTemporaryFile import time import warnings np.seterr(invalid = 'ignore') warnings.filterwarnings('ignore', category = DeprecationWarning) __all__ = [] def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memory of the system. """ mem_info = dict() for k, v in psutil.virtual_memory().__dict__.items(): mem_info[k] = int(v) return mem_info def get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of size 'N' times 'chunk_size' that can fit in memory. Returns ------- chunk_size : int The size of the dimension orthogonal to the one of size 'N'. """ mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: chunk_size = int(((mem_free - 2000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 8000000: chunk_size = int(((mem_free - 1400000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 2000000: chunk_size = int(((mem_free - 900000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 1000000: chunk_size = int(((mem_free - 400000) * 1000) / (4 * n * N)) return chunk_size else: print("\nERROR: Concurrent_AP: get_chunk_size: this machine does not " "have enough free memory.\n") sys.exit(1) def chunk_generator(N, n): """Returns a generator of slice objects. Parameters ---------- N : int The size of one of the dimensions of a two-dimensional array. n : int The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into memory. Returns ------- Slice objects of the type 'slice(start, stop)' are generated, representing the set of indices specified by 'range(start, stop)'. """ chunk_size = get_chunk_size(N, n) for start in range(0, N, chunk_size): yield slice(start, min(start + chunk_size, N)) def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering. """ parser = optparse.OptionParser( usage = "Usage: %prog [options] file_name\n\n" "file_name denotes the path where the data to be " "processed by affinity propagation clustering is stored" ) parser.add_option('-m', '--multiprocessing', dest = 'count', default = multiprocessing.cpu_count(), type = 'int', help = ("The number of processes to use (1..20) " "[default %default]")) parser.add_option('-f', '--file', dest = 'hdf5_file', default = None, type = 'str', help = ("File name or file handle of the HDF5 " "data structure holding the matrices involved in " "affinity propagation clustering " "[default %default]")) parser.add_option('-s', '--similarities', dest = 'similarities', default = False, action = 'store_true', help = ("Specifies if a matrix of similarities " "has already been computed; only makes sense " "with -f or --file in effect [default %default]")) parser.add_option('-i', '--iterations', dest = 'max_iter', default = 200, type = 'int', help = ("The maximum number of message passing " "iterations undergone before affinity " "propagation returns, having reached " "convergence or not [default %default]")) parser.add_option('-c', '--convergence', dest = 'convergence_iter', default = 15, type = 'int', help = ("Specifies the number of consecutive " "iterations without change in the number " "of clusters that signals convergence " "[default %default]") ) parser.add_option('-p', '--preference', dest = 'preference', default = None, type = 'float', help = ("The preference parameter of affinity " "propagation [default %default]")) parser.add_option('-d', '--damping', dest = 'damping', default = 0.5, type = 'float', help = ("The damping parameter of affinity " "propagation; must be within 0.5 and 1.0 " "[default %default]")) parser.add_option('-v', '--verbose', dest = 'verbose', default = False, action = 'store_true', help = ("Turns on the display of messaging regarding " "the status of the various stages of affinity " "propagation clustering currently ongoing " "on the user-specified data-set " "[default %default]")) opts, args = parser.parse_args() if len(args) == 0: parser.error('A data file must be specified') if opts.similarities and (opts.hdf5_file is None): parser.error("Option -s is conditional on -f") if not (1 <= opts.count <= 20): parser.error("The number of processes must range " "from 1 to 20, inclusive") if opts.max_iter <= 0: parser.error("The number of iterations must be " "a non-negative integer") if opts.convergence_iter >= opts.max_iter: parser.error("The number of iterations signalling convergence " "cannot exceed the maximum number of iterations possibly " "required") if not (0.5 <= opts.damping <= 1.0): parser.error("The damping parameter is restricted to values " "between 0.5 and 1.0") return opts, args[0] def check_HDF5_arrays(hdf5_file, N, convergence_iter): """Check that the HDF5 data structure of file handle 'hdf5_file' has all the required nodes organizing the various two-dimensional arrays required for Affinity Propagation clustering ('Responsibility' matrix, 'Availability', etc.). Parameters ---------- hdf5_file : string or file handle Name of the Hierarchical Data Format under consideration. N : int The number of samples in the data-set that will undergo Affinity Propagation clustering. convergence_iter : int Number of iterations with no change in the number of estimated clusters that stops the convergence. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: if not hasattr(fileh.root, 'aff_prop_group'): fileh.create_group(fileh.root, "aff_prop_group") atom = tables.Float32Atom() filters = None #filters = tables.Filters(5, 'blosc') for feature in ('availabilities', 'responsibilities', 'similarities', 'temporaries'): if not hasattr(fileh.root.aff_prop_group, feature): fileh.create_carray(fileh.root.aff_prop_group, feature, atom, (N, N), "Matrix of {0} for affinity " "propagation clustering".format(feature), filters = filters) if not hasattr(fileh.root.aff_prop_group, 'parallel_updates'): fileh.create_carray(fileh.root.aff_prop_group, 'parallel_updates', atom, (N, convergence_iter), "Matrix of parallel updates for affinity propagation " "clustering", filters = filters) Worker.hdf5_lock.release() class Worker(multiprocessing.Process, metaclass=ABCMeta): """Abstract Base Class whose methods are meant to be overriden by the various classes of processes designed to handle the various stages of Affinity Propagation clustering. """ hdf5_lock = multiprocessing.Lock() @abstractmethod def __init__(self, hdf5_file, path, slice_queue): multiprocessing.Process.__init__(self) self.hdf5_file = hdf5_file self.path = path self.slice_queue = slice_queue def run(self): while True: try: slc = self.slice_queue.get() self.process(slc) finally: self.slice_queue.task_done() @abstractmethod def process(self, slc): raise NotImplementedError() class Similarities_worker(Worker): """Class of worker processes handling the computation of a similarities matrix of pairwise distances between samples. """ def __init__(self, hdf5_file, path, array, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.array = array def process(self, rows_slice): tmp = self.array[rows_slice, ...] result = - euclidean_distances(tmp, self.array, squared = True) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = result del tmp class Fluctuations_worker(Worker): """Class of worker processes adding small random fluctuations to the array specified by the node accessed via 'path' in 'hdf5_file'. """ def __init__(self, hdf5_file, path, random_state, N, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.random_state = random_state self.N = N def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) X = hdf5_array[rows_slice, ...] eensy = np.finfo(np.float32).eps weensy = np.finfo(np.float32).tiny * 100 tmp = self.random_state.randn(rows_slice.stop - rows_slice.start, self.N) X += (eensy * X + weensy) * tmp with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(self.path) hdf5_array[rows_slice, ...] = X del X class Responsibilities_worker(Worker): """Class of worker processes that are tasked with computing and updating the responsibility matrix. """ def __init__(self, hdf5_file, path, N, damping, slice_queue): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping def process(self, rows_slice): Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') S = fileh.get_node(self.path + '/similarities') T = fileh.get_node(self.path + '/temporaries') s = S[rows_slice, ...] a = A[rows_slice, ...] Worker.hdf5_lock.release() ind = np.arange(0, rows_slice.stop - rows_slice.start) tmp = a + s I = tmp.argmax(axis = 1) Y = tmp[ind, I] tmp[ind, I] = - np.inf Y_2 = tmp.max(axis = 1) # tmp = R_new np.subtract(s, Y[:, None], tmp) tmp[ind, I] = s[ind, I] - Y_2 with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') r = R[rows_slice, ...] # damping r = r * self.damping + tmp * (1 - self.damping) # tmp = R_p tmp = np.where(r >= 0, r, 0) tmp[ind, rows_slice.start + ind] = r[ind, rows_slice.start + ind] Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: R = fileh.get_node(self.path + '/responsibilities') T = fileh.get_node(self.path + '/temporaries') R[rows_slice, ...] = r T[rows_slice, ...] = tmp Worker.hdf5_lock.release() del a, r, s, tmp class Rows_worker(Worker): """The processes instantiated from this class compute the sums of row entries in an array accessed at node 'path' from the hierarchidal data format at 'hdf5_file'. Those sums are stored in the shared multiprocessing.Array data structure 'g_rows_sum'. """ def __init__(self, hdf5_file, path, N, slice_queue, g_rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.g_rows_sum = g_rows_sum def process(self, rows_slice): get_sum(self.hdf5_file, self.path, self.g_rows_sum, out_lock, rows_slice) def get_sum(hdf5_file, path, array_out, out_lock, rows_slice): """Access an array at node 'path' of the 'hdf5_file', compute the sums along a slice of rows specified by 'rows_slice' and add the resulting vector to 'array_out'. Parameters ---------- hdf5_file : string or file handle The location of the HDF5 data structure containing the matrices of availabitilites, responsibilities and similarities among others. path : string Specify the node where the matrix whose row-sums are to be computed is located within the given hierarchical data format. array_out : multiprocessing.Array object This ctypes array is allocated from shared memory and used by various processes to store the outcome of their computations. out_lock : multiprocessing.Lock object Synchronize access to the values stored in 'array_out'. rows_slice : slice object Specifies a range of rows indices. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) tmp = hdf5_array[rows_slice, ...] Worker.hdf5_lock.release() szum = np.sum(tmp, axis = 0) with out_lock: array_out += szum del tmp class Availabilities_worker(Worker): """Class of processes working on the computation and update of the availability matrix for Affinity Propagation Clustering. """ def __init__(self, hdf5_file, path, N, damping, slice_queue, rows_sum): super(self.__class__, self).__init__(hdf5_file, path, slice_queue) self.N = N self.damping = damping self.rows_sum = rows_sum def process(self, rows_slice): with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: T = fileh.get_node(self.path + '/temporaries') tmp = T[rows_slice, ...] ind = np.arange(0, rows_slice.stop - rows_slice.start) # tmp = - A_new tmp -= self.rows_sum diag_A = tmp[ind, rows_slice.start + ind].copy() np.clip(tmp, 0, np.inf, tmp) tmp[ind, rows_slice.start + ind] = diag_A Worker.hdf5_lock.acquire() with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') a = A[rows_slice, ...] Worker.hdf5_lock.release() # yet more damping a = a * self.damping - tmp * (1 - self.damping) with Worker.hdf5_lock: with tables.open_file(self.hdf5_file, 'r+') as fileh: A = fileh.get_node(self.path + '/availabilities') T = fileh.get_node(self.path + '/temporaries') A[rows_slice, ...] = a T[rows_slice, ...] = tmp del a, tmp def terminate_processes(pid_list): """Terminate a list of processes by sending to each of them a SIGTERM signal, pre-emptively checking if its PID might have been reused. Parameters ---------- pid_list : list A list of process identifiers identifying active processes. """ for proc in psutil.process_iter(): if proc.pid in pid_list: proc.terminate() def compute_similarities(hdf5_file, data, N_processes): """Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'. This computation is to be done in parallel by 'N_processes' distinct processes. Those processes (which are instances of the class 'Similarities_worker') are prevented from simultaneously accessing the HDF5 data structure at 'hdf5_file' through the use of a multiprocessing.Lock object. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities', data, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(data.shape[0], 2 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def add_preference(hdf5_file, preference): """Assign the value 'preference' to the diagonal entries of the matrix of similarities stored in the HDF5 data structure at 'hdf5_file'. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities diag_ind = np.diag_indices(S.nrows) S[diag_ind] = preference Worker.hdf5_lock.release() def add_fluctuations(hdf5_file, N_columns, N_processes): """This procedure organizes the addition of small fluctuations on top of a matrix of similarities at 'hdf5_file' across 'N_processes' different processes. Each of those processes is an instance of the class 'Fluctuations_Worker' defined elsewhere in this module. """ random_state = np.random.RandomState(0) slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Fluctuations_worker(hdf5_file, '/aff_prop_group/similarities', random_state, N_columns, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 4 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def compute_responsibilities(hdf5_file, N_columns, damping, N_processes): """Organize the computation and update of the responsibility matrix for Affinity Propagation clustering with 'damping' as the eponymous damping parameter. Each of the processes concurrently involved in this task is an instance of the class 'Responsibilities_worker' defined above. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Responsibilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) def rows_sum_init(hdf5_file, path, out_lock, *numpy_args): """Create global variables sharing the same object as the one pointed by 'hdf5_file', 'path' and 'out_lock'. Also Create a NumPy array copy of a multiprocessing.Array ctypes array specified by '*numpy_args'. """ global g_hdf5_file, g_path, g_out, g_out_lock g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock g_out = to_numpy_array(*numpy_args) def multiprocessing_get_sum(columns_slice): get_sum(g_hdf5_file, g_path, g_out, g_out_lock, columns_slice) def to_numpy_array(multiprocessing_array, shape, dtype): """Convert a share multiprocessing array to a numpy array. No data copying involved. """ return np.frombuffer(multiprocessing_array.get_obj(), dtype = dtype).reshape(shape) def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'): """Parallel computation of the sums across the rows of two-dimensional array accessible at the node specified by 'path' in the 'hdf5_file' hierarchical data format. """ assert isinstance(method, str), "parameter 'method' must consist in a string of characters" assert method in ('Ordinary', 'Pool'), "parameter 'method' must be set to either of 'Ordinary' or 'Pool'" if method == 'Ordinary': rows_sum = np.zeros(N_columns, dtype = float) chunk_size = get_chunk_size(N_columns, 2) with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: hdf5_array = fileh.get_node(path) N_rows = hdf5_array.nrows assert N_columns == N_rows for i in range(0, N_columns, chunk_size): slc = slice(i, min(i+chunk_size, N_columns)) tmp = hdf5_array[:, slc] rows_sum[slc] = tmp[:].sum(axis = 0) else: rows_sum_array = multiprocessing.Array(c_double, N_columns, lock = True) chunk_size = get_chunk_size(N_columns, 2 * N_processes) numpy_args = rows_sum_array, N_columns, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = rows_sum_init, initargs = (hdf5_file, path, rows_sum_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_get_sum, chunk_generator(N_columns, 2 * N_processes), chunk_size) pool.close() pool.join() rows_sum = to_numpy_array(*numpy_args) gc.collect() return rows_sum def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum): """Coordinates the computation and update of the availability matrix for Affinity Propagation clustering. Parameters ---------- hdf5_file : string or file handle Specify access to the hierarchical data format used throughout all the iterations of message-passing between data-points involved in Affinity Propagation clustering. N_columns : int The number of samples in the data-set subjected to Affinity Propagation clustering. damping : float The damping parameter of Affinity Propagation clustering, typically set to 0.5. N_processes : int The number of subprocesses involved in the parallel computation and update of the matrix of availabitilies. rows_sum : array of shape (N_columns,) A vector containing, for each column entry of the similarities matrix, the sum of its rows entries. """ slice_queue = multiprocessing.JoinableQueue() pid_list = [] for i in range(N_processes): worker = Availabilities_worker(hdf5_file, '/aff_prop_group', N_columns, damping, slice_queue, rows_sum) worker.daemon = True worker.start() pid_list.append(worker.pid) for rows_slice in chunk_generator(N_columns, 8 * N_processes): slice_queue.put(rows_slice) slice_queue.join() slice_queue.close() terminate_processes(pid_list) gc.collect() def check_convergence(hdf5_file, iteration, convergence_iter, max_iter): """If the estimated number of clusters has not changed for 'convergence_iter' consecutive iterations in a total of 'max_iter' rounds of message-passing, the procedure herewith returns 'True'. Otherwise, returns 'False'. Parameter 'iteration' identifies the run of message-passing that has just completed. """ Worker.hdf5_lock.acquire() with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities P = fileh.root.aff_prop_group.parallel_updates N = A.nrows diag_ind = np.diag_indices(N) E = (A[diag_ind] + R[diag_ind]) > 0 P[:, iteration % convergence_iter] = E e_mat = P[:] K = E.sum(axis = 0) Worker.hdf5_lock.release() if iteration >= convergence_iter: se = e_mat.sum(axis = 1) unconverged = (np.sum((se == convergence_iter) + (se == 0)) != N) if (not unconverged and (K > 0)) or (iteration == max_iter): return True return False def cluster_labels_init(hdf5_file, I, c_array_lock, *numpy_args): global g_hdf5_file, g_I, g_c_array_lock, g_c g_hdf5_file, g_I, g_c_array_lock = hdf5_file, I, c_array_lock g_c = to_numpy_array(*numpy_args) def cluster_labels_init_B(hdf5_file, I, ii, iix, s_reduced_array_lock, *numpy_args): global g_hdf5_file, g_I, g_ii, g_iix, g_s_reduced_array_lock, g_s_reduced g_hdf5_file, g_I, g_ii, g_iix = hdf5_file, I, ii, iix g_s_reduced_array_lock = s_reduced_array_lock g_s_reduced = to_numpy_array(*numpy_args) def multiprocessing_cluster_labels_A(rows_slice): cluster_labels_A(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def multiprocessing_cluster_labels_B(rows_slice): cluster_labels_B(g_hdf5_file, g_s_reduced, g_s_reduced_array_lock, g_I, g_ii, g_iix, rows_slice) def multiprocessing_cluster_labels_C(rows_slice): cluster_labels_C(g_hdf5_file, g_c, g_c_array_lock, g_I, rows_slice) def cluster_labels_A(hdf5_file, c, lock, I, rows_slice): """One of the task to be performed by a pool of subprocesses, as the first step in identifying the cluster labels and indices of the cluster centers for Affinity Propagation clustering. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = np.argmax(s[:, I], axis = 1) with lock: c[rows_slice] = s[:] del s def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice): """Second task to be performed by a pool of subprocesses before the cluster labels and cluster center indices can be identified. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, ii] s = s[iix[rows_slice]] with lock: s_reduced += s[:].sum(axis = 0) del s def cluster_labels_C(hdf5_file, c, lock, I, rows_slice): """Third and final task to be executed by a pool of subprocesses, as part of the goal of finding the cluster to which each data-point has been assigned by Affinity Propagation clustering on a given data-set. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: S = fileh.root.aff_prop_group.similarities s = S[rows_slice, ...] s = s[:, I] with lock: c[rows_slice] = np.argmax(s[:], axis = 1) del s def get_cluster_labels(hdf5_file, N_processes): """ Returns ------- cluster_centers_indices : array of shape (n_clusters,) Indices of cluster centers labels : array of shape (n_samples,) Specify the label of the cluster to which each point has been assigned. """ with Worker.hdf5_lock: with tables.open_file(hdf5_file, 'r+') as fileh: A = fileh.root.aff_prop_group.availabilities R = fileh.root.aff_prop_group.responsibilities N = A.nrows diag_ind = np.diag_indices(N) a = A[diag_ind] r = R[diag_ind] I = np.where(np.add(a[:], r[:]) > 0)[0] K = I.size if K == 0: labels = np.empty((N, 1)) labels.fill(np.nan) cluster_centers_indices = None else: c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_A, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() gc.collect() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) # determine the exemplars of clusters, applying some # cosmetics to our results before returning them for k in range(K): ii = np.where(c == k)[0] iix = np.full(N, False, dtype = bool) iix[ii] = True s_reduced_array = multiprocessing.Array(c_double, ii.size, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = s_reduced_array, ii.size, np.float64 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init_B, initargs = (hdf5_file, I, ii, iix, s_reduced_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_B, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() s_reduced = to_numpy_array(*numpy_args) j = np.argmax(s_reduced) I[k] = ii[j] gc.collect() c_array = multiprocessing.Array(c_int, N, lock = True) chunk_size = get_chunk_size(N, 3 * N_processes) numpy_args = c_array, N, np.int32 with closing(multiprocessing.Pool(N_processes, initializer = cluster_labels_init, initargs = (hdf5_file, I, c_array.get_lock()) + numpy_args)) as pool: pool.map_async(multiprocessing_cluster_labels_C, chunk_generator(N, 3 * N_processes), chunk_size) pool.close() pool.join() c = to_numpy_array(*numpy_args) c[I] = np.arange(K) labels = I[c] gc.collect() cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) return cluster_centers_indices, labels def output_clusters(labels, cluster_centers_indices): """Write in tab-separated files the vectors of cluster identities and of indices of cluster centers. """ here = os.getcwd() try: output_directory = os.path.join(here, 'concurrent_AP_output') os.makedirs(output_directory) except OSError: if not os.path.isdir(output_directory): print("ERROR: concurrent_AP: output_clusters: cannot create a directory " "for storage of the results of Affinity Propagation clustering " "in your current working directory") sys.exit(1) if any(np.isnan(labels)): fmt = '%.1f' else: fmt = '%d' with open(os.path.join(output_directory, 'labels.tsv'), 'w') as fh: np.savetxt(fh, labels, fmt = fmt, delimiter = '\t') if cluster_centers_indices is not None: with open(os.path.join(output_directory, 'cluster_centers_indices.tsv'), 'w') as fh: np.savetxt(fh, cluster_centers_indices, fmt = '%.1f', delimiter = '\t') def set_preference(data, chunk_size): """Return the median of the distribution of pairwise L2 Euclidean distances between samples (the rows of 'data') as the default preference parameter for Affinity Propagation clustering. Parameters ---------- data : array of shape (N_samples, N_features) The data-set submitted for Affinity Propagation clustering. chunk_size : int The size of random subsamples from the data-set whose similarity matrix is computed. The resulting median of the distribution of pairwise distances between the data-points selected as part of a given subsample is stored into a list of medians. Returns ------- preference : float The preference parameter for Affinity Propagation clustering is computed as the median of the list of median pairwise distances between the data-points selected as part of each of 15 rounds of random subsampling. """ N_samples, N_features = data.shape rng = np.arange(0, N_samples, dtype = int) medians = [] for i in range(15): selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False) samples = data[selected_samples, :] S = - euclidean_distances(samples, data, squared = True) n = chunk_size * N_samples - (chunk_size * (chunk_size + 1) / 2) rows = np.zeros(0, dtype = int) for i in range(chunk_size): rows = np.append(rows, np.full(N_samples - i, i, dtype = int)) cols = np.zeros(0, dtype = int) for i in range(chunk_size): cols = np.append(cols, np.delete(rng, selected_samples[:i+1])) triu_indices = tuple((rows, cols)) preference = np.median(S, overwrite_input = True) medians.append(preference) del S if i % 4 == 3: gc.collect() preference = np.median(medians) return preference def main(): opts, args = parse_options() with open(args, 'r') as fh: data = np.loadtxt(fh, dtype = float, delimiter = '\t') N = data.shape[0] fh = None try: if opts.hdf5_file is None: fh = NamedTemporaryFile('w', delete = True, dir = './', suffix = '.h5') hdf5_file = fh.name else: hdf5_file = opts.hdf5_file fh = open(opts.hdf5_file, 'r+') check_HDF5_arrays(hdf5_file, N, opts.convergence_iter) # compute the matrix of pairwise squared Euclidean distances # between all sampled cells and store it in a # HDF5 data structure on disk if not opts.similarities: sim_start = time.time() compute_similarities(hdf5_file, data, opts.count) sim_end = time.time() if opts.verbose: delta = sim_end - sim_start print(("INFO: concurrent_AP: the computation of the matrix of pairwise " "similarities took {} seconds".format(round(delta, 4)))) if opts.preference is None: # The preference is set to the median of all the entries # of the similarities matrix computed at the previous step chunk_size = get_chunk_size(N, 4) if chunk_size < N: preference = set_preference(data, chunk_size) else: S = - euclidean_distances(data, data, squared = True) preference = np.median(S[np.triu_indices(N, k = 1)], overwrite_input = True) del S gc.collect() else: preference = opts.preference add_preference(hdf5_file, preference) add_fluctuations(hdf5_file, N, opts.count) for iteration in range(opts.max_iter): iteration_start = time.time() compute_responsibilities(hdf5_file, N, opts.damping, opts.count) rows_sum = compute_rows_sum(hdf5_file, '/aff_prop_group/temporaries', N, opts.count, method = 'Pool') compute_availabilities(hdf5_file, N, opts.damping, opts.count, rows_sum) # have we reached convergence? convergence_flag = check_convergence(hdf5_file, iteration, opts.convergence_iter, opts.max_iter) iteration_end = time.time() if opts.verbose: delta = iteration_end - iteration_start print(("INFO: iteration # {0} took {1} " "seconds".format(iteration + 1, round(delta, 4)))) if convergence_flag: break print('DONE WITH ALL ITERATIONS') cc_start = time.time() cluster_centers_indices, labels = get_cluster_labels(hdf5_file, opts.count) cc_end = time.time() if opts.verbose: delta = cc_end - cc_start print(("INFO: the procedure 'get_cluster_labels' " "completed in {} seconds".format(round(delta, 4)))) except EnvironmentError as err: print(('ERROR: Affinity_propagation: {0}'.format(err))) finally: if fh is not None: fh.close() output_clusters(labels, cluster_centers_indices) if __name__ == '__main__': main()
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_primary_zone
python
def create_primary_zone(self, account_name, zone_name): zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L29-L40
[ "def post(self, uri, json=None):\n if json is not None:\n return self._do_call(uri, \"POST\", body=json)\n else:\n return self._do_call(uri, \"POST\")\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_primary_zone_by_upload
python
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files)
Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L43-L57
[ "def post_multi_part(self, uri, files):\n #use empty string for content type so we don't set it\n return self._do_call(uri, \"POST\", files=files, content_type=\"\")\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_primary_zone_by_axfr
python
def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L60-L81
null
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_secondary_zone
python
def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data))
Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L84-L107
null
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.get_zones_of_account
python
def get_zones_of_account(self, account_name, q=None, **kwargs): uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L130-L155
[ "def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n", "def get(self, uri, params=None):\n if params is None:\n params = {}\n return self._do_call(uri, \"GET\", params=params)\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.get_zones
python
def get_zones(self, q=None, **kwargs): uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L158-L180
[ "def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n", "def get(self, uri, params=None):\n if params is None:\n params = {}\n return self._do_call(uri, \"GET\", params=params)\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.edit_secondary_name_server
python
def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data))
Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L203-L225
null
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.get_rrsets
python
def get_rrsets(self, zone_name, q=None, **kwargs): uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L229-L251
[ "def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n", "def get(self, uri, params=None):\n if params is None:\n params = {}\n return self._do_call(uri, \"GET\", params=params)\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.get_rrsets_by_type
python
def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L255-L279
[ "def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n", "def get(self, uri, params=None):\n if params is None:\n params = {}\n return self._do_call(uri, \"GET\", params=params)\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.get_rrsets_by_type_owner
python
def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params)
Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L283-L308
[ "def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n", "def get(self, uri, params=None):\n if params is None:\n params = {}\n return self._do_call(uri, \"GET\", params=params)\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_rrset
python
def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset))
Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings.
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L311-L330
[ "def post(self, uri, json=None):\n if json is not None:\n return self._do_call(uri, \"POST\", body=json)\n else:\n return self._do_call(uri, \"POST\")\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.edit_rrset
python
def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset))
Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L333-L356
[ "def put(self, uri, json):\n return self._do_call(uri, \"PUT\", body=json)\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.edit_rrset_rdata
python
def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset))
Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L359-L383
null
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.delete_rrset
python
def delete_rrset(self, zone_name, rtype, owner_name): return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name)
Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.)
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L386-L398
[ "def delete(self, uri):\n return self._do_call(uri, \"DELETE\")\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_web_forward
python
def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward))
Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L413-L428
null
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_sb_pool
python
def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0)
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L551-L571
[ "def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/SBPool.jsonschema\"}\n for p in pool_info:\n profile[p] = pool_info[p]\n profile[\"backupRecords\"] = backup_record_list\n profile[\"rdataInfo\"] = rdata_info_list\n rrset = {\"ttl\": ttl, \"rdata\": rdata, \"profile\": profile}\n return rrset\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.edit_sb_pool
python
def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0)
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L575-L592
[ "def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/SBPool.jsonschema\"}\n for p in pool_info:\n profile[p] = pool_info[p]\n profile[\"backupRecords\"] = backup_record_list\n profile[\"rdataInfo\"] = rdata_info_list\n rrset = {\"ttl\": ttl, \"rdata\": rdata, \"profile\": profile}\n return rrset\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.create_tc_pool
python
def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0)
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L661-L681
[ "def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/TCPool.jsonschema\"}\n for p in pool_info:\n profile[p] = pool_info[p]\n profile[\"backupRecord\"] = backup_record\n profile[\"rdataInfo\"] = rdata_info_list\n rrset = {\"ttl\": ttl, \"rdata\": rdata, \"profile\": profile}\n return rrset\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } # Update an SB Pool def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
ultradns/python_rest_api_client
ultra_rest_client/ultra_rest_client.py
RestApiClient.edit_tc_pool
python
def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset))
Updates an existing TC Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record: dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0)
train
https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L685-L702
[ "def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/TCPool.jsonschema\"}\n for p in pool_info:\n profile[p] = pool_info[p]\n profile[\"backupRecord\"] = backup_record\n profile[\"rdataInfo\"] = rdata_info_list\n rrset = {\"ttl\": ttl, \"rdata\": rdata, \"profile\": profile}\n return rrset\n" ]
class RestApiClient: def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"): """Initialize a Rest API Client. Arguments: username -- The username of the user password -- The password of the user Keyword Arguments: use_http -- For internal testing purposes only, lets developers use http instead of https. host -- Allows you to point to a server other than the production server. """ self.rest_api_connection = RestApiConnection(use_http, host) self.rest_api_connection.auth(username, password) # Zones # create a primary zone def create_primary_zone(self, account_name, zone_name): """Creates a new primary zone. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "NEW"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create primary zone by file upload def create_primary_zone_by_upload(self, account_name, zone_name, bind_file): """Creates a new primary zone by uploading a bind file Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. bind_file -- The file to upload. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} primary_zone_info = {"forceImport": True, "createType": "UPLOAD"} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} files = {'zone': ('', json.dumps(zone_data), 'application/json'), 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')} return self.rest_api_connection.post_multi_part("/v1/zones", files) # create a primary zone using axfr def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new primary zone by zone transferring off a master. Arguments: account_name -- The name of the account that will contain this zone. zone_name -- The name of the zone. It must be unique. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} primary_zone_info = {"forceImport": True, "createType": "TRANSFER", "nameServer": name_server_info} zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # create a secondary zone def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arguments: tsig_key -- For TSIG-enabled zones: The transaction signature key. NOTE: Requires key_value. key_value -- TSIG key secret. """ zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"} if tsig_key is not None and key_value is not None: name_server_info = {"ip": master, "tsigKey": tsig_key, "tsigKeyValue": key_value} else: name_server_info = {"ip": master} name_server_ip_1 = {"nameServerIp1": name_server_info} name_server_ip_list = {"nameServerIpList": name_server_ip_1} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"properties": zone_properties, "secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.post("/v1/zones", json.dumps(zone_data)) # force zone axfr def force_axfr(self, zone_name): """Force a secondary zone transfer. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/transfer") # convert secondary def convert_zone(self, zone_name): """Convert a secondary zone to primary. This cannot be reversed. Arguments: zone_name -- The zone name. The trailing dot is optional. """ return self.rest_api_connection.post("/v1/zones/" + zone_name + "/convert") # list zones for account def get_zones_of_account(self, account_name, q=None, **kwargs): """Returns a list of zones for the specified account. Arguments: account_name -- The name of the account. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/accounts/" + account_name + "/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list zones for all user accounts def get_zones(self, q=None, **kwargs): """Returns a list of zones across all of the user's accounts. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: name - substring match of the zone name zone_type - one of: PRIMARY SECONDARY ALIAS sort -- The sort column used to order the list. Valid values for the sort field are: NAME ACCOUNT_NAME RECORD_COUNT ZONE_TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # get zone metadata def get_zone_metadata(self, zone_name): """Returns the metadata for the specified zone. Arguments: zone_name -- The name of the zone being returned. """ return self.rest_api_connection.get("/v1/zones/" + zone_name) # delete a zone def delete_zone(self, zone_name): """Deletes the specified zone. Arguments: zone_name -- The name of the zone being deleted. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name) # update secondary zone name servers (PATCH) def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None): """Edit the axfr name servers of a secondary zone. Arguments: zone_name -- The name of the secondary zone being edited. primary -- The primary name server value. Keyword Arguments: backup -- The backup name server if any. second_backup -- The second backup name server. """ name_server_info = {} if primary is not None: name_server_info['nameServerIp1'] = {'ip':primary} if backup is not None: name_server_info['nameServerIp2'] = {'ip':backup} if second_backup is not None: name_server_info['nameServerIp3'] = {'ip':second_backup} name_server_ip_list = {"nameServerIpList": name_server_info} secondary_zone_info = {"primaryNameServers": name_server_ip_list} zone_data = {"secondaryCreateInfo": secondary_zone_info} return self.rest_api_connection.patch("/v1/zones/" + zone_name, json.dumps(zone_data)) # RRSets # list rrsets for a zone def get_rrsets(self, zone_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone. Arguments: zone_name -- The name of the zone. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets" params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset owner - substring match of the owner name value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: OWNER TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # list rrsets by type and owner for a zone # q The query used to construct the list. Query operators are ttl, owner, and value def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs): """Returns the list of RRSets in the specified zone of the specified type. Arguments: zone_name -- The name of the zone. rtype -- The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) Keyword Arguments: q -- The search parameters, in a dict. Valid keys are: ttl - must match the TTL for the rrset value - substring match of the first BIND field value sort -- The sort column used to order the list. Valid values for the sort field are: TTL TYPE reverse -- Whether the list is ascending(False) or descending(True) offset -- The position in the list for the first returned element(0 based) limit -- The maximum number of rows to be returned. """ uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name params = build_params(q, kwargs) return self.rest_api_connection.get(uri, params) # create an rrset def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata): """Creates a new RRSet in the specified zone. Arguments: zone_name -- The zone that will contain the new RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The TTL value for the RRSet. rdata -- The BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) # edit an rrset (PUT) def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None): """Updates an existing RRSet in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"ttl": ttl, "rdata": rdata} if profile: rrset["profile"] = profile uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return self.rest_api_connection.put(uri, json.dumps(rrset)) # edit an rrset's rdata (PATCH) def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None): """Updates an existing RRSet's Rdata in the specified zone. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) rdata -- The updated BIND data for the RRSet as a string. If there is a single resource record in the RRSet, you can pass in the single string. If there are multiple resource records in this RRSet, pass in a list of strings. profile -- The profile info if this is updating a resource pool """ if type(rdata) is not list: rdata = [rdata] rrset = {"rdata": rdata} method = "patch" if profile: rrset["profile"] = profile method = "put" uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name return getattr(self.rest_api_connection, method)(uri,json.dumps(rrset)) # delete an rrset def delete_rrset(self, zone_name, rtype, owner_name): """Deletes an RRSet. Arguments: zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional. rtype -- The type of the RRSet. This can be numeric (1) or if a well-known name is defined for the type (A), you can use it instead. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) # Web Forwards # get web forwards def get_web_forwards(self, zone_name): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone for which to return a list of current web forwards. The response will include the system-generated guid for each object. """ return self.rest_api_connection.get("/v1/zones/" + zone_name + "/webforwards") # create web forward def create_web_forward(self, zone_name, request_to, redirect_to, forward_type): """Create a web forward record. Arguments: zone_name -- The zone in which the web forward is to be created. request_to -- The URL to be redirected. You may use http:// and ftp://. forward_type -- The type of forward. Valid options include: Framed HTTP_301_REDIRECT HTTP_302_REDIRECT HTTP_303_REDIRECT HTTP_307_REDIRECT """ web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type} return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) # delete web forward def delete_web_forward(self, zone_name, guid): """Return all web forwards for a specific zone. Arguments: zone_name -- The zone containing the web forward to be deleted. guid -- The system-generated unique id for the web forward. """ return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/webforwards/" + guid) # Accounts # get account details for user def get_account_details(self): """Returns a list of all accounts of which the current user is a member.""" return self.rest_api_connection.get("/v1/accounts") # Version # get version def version(self): """Returns the version of the REST API server.""" return self.rest_api_connection.get("/v1/version") # Status # get status def status(self): """Returns the status of the REST API server.""" return self.rest_api_connection.get("/v1/status") # Tasks def get_all_tasks(self): return self.rest_api_connection.get("/v1/tasks") def get_task(self, task_id): return self.rest_api_connection.get("/v1/tasks/"+task_id) def clear_task(self, task_id): return self.rest_api_connection.delete("/v1/tasks/"+task_id) # Batch def batch(self, batch_list): """Sends multiple requests as a single transaction. Arguments: batch_list -- a list of request objects. Each request must have: method -- valid values are POST, PATCH, PUT, GET, DELETE uri -- The path for the request If the request should have a body, there is a third field: body (only if required) - The body of the request """ return self.rest_api_connection.post("/v1/batch", json.dumps(batch_list)) # Create an SB Pool # Sample JSON for an SB pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/SBPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "order": "ROUND_ROBIN", # "maxActive": 1, # "maxServed": 0, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1 # } # ], # "backupRecords": [ # { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # ] # } # } def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/SBPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecords"] = backup_record_list profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Creates a new SB Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record_list -- list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list): """Updates an existing SB Pool in the specified zone. :param zone_name: The zone that contains the RRSet. The trailing dot is optional. :param owner_name: The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) :param ttl: The updated TTL value for the RRSet. :param pool_info: dict of information about the pool :param rdata_info: dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records :param backup_record_list: list of dicts of information about the backup (all-fail) records in the pool. There are two key/value in each dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl) return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl): rdata = [] rdata_info_list = [] for rr in rdata_info: rdata.append(rr) rdata_info_list.append(rdata_info[rr]) profile = {"@context": "http://schemas.ultradns.com/TCPool.jsonschema"} for p in pool_info: profile[p] = pool_info[p] profile["backupRecord"] = backup_record profile["rdataInfo"] = rdata_info_list rrset = {"ttl": ttl, "rdata": rdata, "profile": profile} return rrset # Create a TC Pool # Sample JSON for a TC pool -- see the REST API docs for their descriptions # { # "ttl": 120, # "rdata": [ # "4.5.6.7", "199.7.167.22", "1.2.3.4", "5.6.7.8" # ], # "profile": { # "@context": "http://schemas.ultradns.com/TCPool.jsonschema", # "description": "description", # "runProbes": true, # "actOnProbes": true, # "maxToLB": 1, # "rdataInfo": [ # { # "state": "ACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 0, # "threshold": 1, # "weight": 2 # }, # { # "state": "ACTIVE", # "runProbes": true, # "priority": 1, # "failoverDelay": 1, # "threshold": 1, # "weight": 4 # }, # { # "state": "INACTIVE", # "runProbes": true, # "priority": 2, # "failoverDelay": 3, # "threshold": 1, # "weight": 8 # } # ], # "backupRecord": { # "rdata":"1.2.2.2", # "failoverDelay": 1 # } # } # } def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record): """Creates a new TC Pool. Arguments: zone_name -- The zone that contains the RRSet. The trailing dot is optional. owner_name -- The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute (foo.zonename.com.) ttl -- The updated TTL value for the RRSet. pool_info -- dict of information about the pool rdata_info -- dict of information about the records in the pool. The keys in the dict are the A and CNAME records that make up the pool. The values are the rdataInfo for each of the records backup_record -- dict of information about the backup (all-fail) records in the pool. There are two key/value in the dict: rdata - the A or CNAME for the backup record failoverDelay - the time to wait to fail over (optional, defaults to 0) """ rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl) return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) # Update an SB Pool
pudo/jsonmapping
jsonmapping/transforms.py
transliterate
python
def transliterate(text): text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text
Utility to properly transliterate text.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L11-L15
null
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """ for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """ for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])] def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func def hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """ for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest() def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """ categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/transforms.py
slugify
python
def slugify(mapping, bind, values): for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value
Transform all values into URL-capable slugs.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L26-L32
[ "def transliterate(text):\n \"\"\" Utility to properly transliterate text. \"\"\"\n text = unidecode(six.text_type(text))\n text = text.replace('@', 'a')\n return text\n" ]
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def transliterate(text): """ Utility to properly transliterate text. """ text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """ for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])] def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func def hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """ for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest() def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """ categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/transforms.py
latinize
python
def latinize(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v
Transliterate a given string into the latin alphabet.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L35-L40
[ "def transliterate(text):\n \"\"\" Utility to properly transliterate text. \"\"\"\n text = unidecode(six.text_type(text))\n text = text.replace('@', 'a')\n return text\n" ]
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def transliterate(text): """ Utility to properly transliterate text. """ text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """ for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])] def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func def hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """ for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest() def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """ categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/transforms.py
join
python
def join(mapping, bind, values): return [' '.join([six.text_type(v) for v in values if v is not None])]
Merge all the strings. Put space between them.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L43-L45
null
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def transliterate(text): """ Utility to properly transliterate text. """ text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """ for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """ for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func def hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """ for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest() def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """ categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/transforms.py
str_func
python
def str_func(name): def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func
Apply functions like upper(), lower() and strip().
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L48-L55
null
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def transliterate(text): """ Utility to properly transliterate text. """ text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """ for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """ for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])] def hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """ for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest() def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """ categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/transforms.py
hash
python
def hash(mapping, bind, values): for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest()
Generate a sha1 for each of the given values.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L58-L65
null
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def transliterate(text): """ Utility to properly transliterate text. """ text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """ for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """ for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])] def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func def clean(mapping, bind, values): """ Perform several types of string cleaning for titles etc.. """ categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/transforms.py
clean
python
def clean(mapping, bind, values): categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) yield value
Perform several types of string cleaning for titles etc..
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L68-L76
null
import re import six from hashlib import sha1 from unidecode import unidecode import normality COLLAPSE = re.compile(r'\s+') def transliterate(text): """ Utility to properly transliterate text. """ text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text def coalesce(mapping, bind, values): """ Given a list of values, return the first non-null value. """ for value in values: if value is not None: return [value] return [] def slugify(mapping, bind, values): """ Transform all values into URL-capable slugs. """ for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value def latinize(mapping, bind, values): """ Transliterate a given string into the latin alphabet. """ for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])] def str_func(name): """ Apply functions like upper(), lower() and strip(). """ def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func def hash(mapping, bind, values): """ Generate a sha1 for each of the given values. """ for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest() TRANSFORMS = { 'coalesce': coalesce, 'slugify': slugify, 'clean': clean, 'latinize': latinize, 'join': join, 'upper': str_func('upper'), 'lower': str_func('lower'), 'strip': str_func('strip'), 'hash': hash }
pudo/jsonmapping
jsonmapping/value.py
extract_value
python
def extract_value(mapping, bind, data): columns = mapping.get('columns', [mapping.get('column')]) values = [data.get(c) for c in columns] for transform in mapping.get('transforms', []): # any added transforms must also be added to the schema. values = list(TRANSFORMS[transform](mapping, bind, values)) format_str = mapping.get('format') value = values[0] if len(values) else None if not is_empty(format_str): value = format_str % tuple('' if v is None else v for v in values) empty = is_empty(value) if empty: value = mapping.get('default') or bind.schema.get('default') return empty, convert_value(bind, value)
Given a mapping and JSON schema spec, extract a value from ``data`` and apply certain transformations to normalize the value.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L7-L25
[ "def convert_value(bind, value):\n \"\"\" Type casting. \"\"\"\n type_name = get_type(bind)\n try:\n return typecast.cast(type_name, value)\n except typecast.ConverterError:\n return value\n", "def is_empty(value):\n if value is None:\n return True\n if isinstance(value, six.string_types):\n return len(value.strip()) < 1\n return False\n" ]
import six import typecast from jsonmapping.transforms import TRANSFORMS def get_type(bind): """ Detect the ideal type for the data, either using the explicit type definition or the format (for date, date-time, not supported by JSON). """ types = bind.types + [bind.schema.get('format')] for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean', 'number', 'string'): if type_name in types: return type_name return 'string' def convert_value(bind, value): """ Type casting. """ type_name = get_type(bind) try: return typecast.cast(type_name, value) except typecast.ConverterError: return value def is_empty(value): if value is None: return True if isinstance(value, six.string_types): return len(value.strip()) < 1 return False
pudo/jsonmapping
jsonmapping/value.py
get_type
python
def get_type(bind): types = bind.types + [bind.schema.get('format')] for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean', 'number', 'string'): if type_name in types: return type_name return 'string'
Detect the ideal type for the data, either using the explicit type definition or the format (for date, date-time, not supported by JSON).
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L28-L36
null
import six import typecast from jsonmapping.transforms import TRANSFORMS def extract_value(mapping, bind, data): """ Given a mapping and JSON schema spec, extract a value from ``data`` and apply certain transformations to normalize the value. """ columns = mapping.get('columns', [mapping.get('column')]) values = [data.get(c) for c in columns] for transform in mapping.get('transforms', []): # any added transforms must also be added to the schema. values = list(TRANSFORMS[transform](mapping, bind, values)) format_str = mapping.get('format') value = values[0] if len(values) else None if not is_empty(format_str): value = format_str % tuple('' if v is None else v for v in values) empty = is_empty(value) if empty: value = mapping.get('default') or bind.schema.get('default') return empty, convert_value(bind, value) def convert_value(bind, value): """ Type casting. """ type_name = get_type(bind) try: return typecast.cast(type_name, value) except typecast.ConverterError: return value def is_empty(value): if value is None: return True if isinstance(value, six.string_types): return len(value.strip()) < 1 return False
pudo/jsonmapping
jsonmapping/value.py
convert_value
python
def convert_value(bind, value): type_name = get_type(bind) try: return typecast.cast(type_name, value) except typecast.ConverterError: return value
Type casting.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L39-L45
[ "def get_type(bind):\n \"\"\" Detect the ideal type for the data, either using the explicit type\n definition or the format (for date, date-time, not supported by JSON). \"\"\"\n types = bind.types + [bind.schema.get('format')]\n for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean',\n 'number', 'string'):\n if type_name in types:\n return type_name\n return 'string'\n" ]
import six import typecast from jsonmapping.transforms import TRANSFORMS def extract_value(mapping, bind, data): """ Given a mapping and JSON schema spec, extract a value from ``data`` and apply certain transformations to normalize the value. """ columns = mapping.get('columns', [mapping.get('column')]) values = [data.get(c) for c in columns] for transform in mapping.get('transforms', []): # any added transforms must also be added to the schema. values = list(TRANSFORMS[transform](mapping, bind, values)) format_str = mapping.get('format') value = values[0] if len(values) else None if not is_empty(format_str): value = format_str % tuple('' if v is None else v for v in values) empty = is_empty(value) if empty: value = mapping.get('default') or bind.schema.get('default') return empty, convert_value(bind, value) def get_type(bind): """ Detect the ideal type for the data, either using the explicit type definition or the format (for date, date-time, not supported by JSON). """ types = bind.types + [bind.schema.get('format')] for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean', 'number', 'string'): if type_name in types: return type_name return 'string' def is_empty(value): if value is None: return True if isinstance(value, six.string_types): return len(value.strip()) < 1 return False
pudo/jsonmapping
jsonmapping/elastic.py
generate_schema_mapping
python
def generate_schema_mapping(resolver, schema_uri, depth=1): visitor = SchemaVisitor({'$ref': schema_uri}, resolver) return _generate_schema_mapping(visitor, set(), depth)
Try and recursively iterate a JSON schema and to generate an ES mapping that encasulates it.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/elastic.py#L6-L10
[ "def _generate_schema_mapping(visitor, path, depth):\n if visitor.is_object:\n mapping = {\n 'type': 'nested',\n '_id': {'path': 'id'},\n 'properties': {\n '$schema': {'type': 'string', 'index': 'not_analyzed'},\n 'id': {'type': 'string', 'index': 'not_analyzed'}\n }\n }\n if not visitor.parent:\n mapping['type'] = 'object'\n if visitor.path in path or not depth:\n return mapping\n sub_path = path.union([visitor.path])\n for prop in visitor.properties:\n prop_mapping = _generate_schema_mapping(prop, sub_path, depth - 1)\n mapping['properties'][prop.name] = prop_mapping\n return mapping\n elif visitor.is_array:\n return _generate_schema_mapping(visitor.items, path, depth - 1)\n else:\n return _generator_field_mapping(visitor)\n" ]
""" These are utility functions used by the OCCRP datamapper to generate a matching ElasticSearch schema, given a JSON Schema descriptor. """ from jsonmapping.visitor import SchemaVisitor def _generator_field_mapping(visitor): type_name = 'string' if 'number' in visitor.types: type_name = 'float' if 'integer' in visitor.types: type_name = 'long' if 'boolean' in visitor.types: type_name = 'boolean' mapping = {'type': type_name, 'index': 'not_analyzed'} format_ = visitor.schema.get('format') if format_ and format_ in ('date-time', 'datetime', 'date'): mapping['type'] = 'date' mapping['format'] = 'dateOptionalTime' return mapping def _generate_schema_mapping(visitor, path, depth): if visitor.is_object: mapping = { 'type': 'nested', '_id': {'path': 'id'}, 'properties': { '$schema': {'type': 'string', 'index': 'not_analyzed'}, 'id': {'type': 'string', 'index': 'not_analyzed'} } } if not visitor.parent: mapping['type'] = 'object' if visitor.path in path or not depth: return mapping sub_path = path.union([visitor.path]) for prop in visitor.properties: prop_mapping = _generate_schema_mapping(prop, sub_path, depth - 1) mapping['properties'][prop.name] = prop_mapping return mapping elif visitor.is_array: return _generate_schema_mapping(visitor.items, path, depth - 1) else: return _generator_field_mapping(visitor)
pudo/jsonmapping
jsonmapping/util.py
validate_mapping
python
def validate_mapping(mapping): file_path = os.path.join(os.path.dirname(__file__), 'schemas', 'mapping.json') with open(file_path, 'r') as fh: validator = Draft4Validator(json.load(fh)) validator.validate(mapping) return mapping
Validate a mapping configuration file against the relevant schema.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/util.py#L7-L14
null
import os import json from jsonschema import Draft4Validator
pudo/jsonmapping
jsonmapping/mapper.py
Mapper.apply
python
def apply(self, data): if self.visitor.is_object: obj = {} if self.visitor.parent is None: obj['$schema'] = self.visitor.path obj_empty = True for child in self.children: empty, value = child.apply(data) if empty and child.optional: continue obj_empty = False if not empty else obj_empty if child.visitor.name in obj and child.visitor.is_array: obj[child.visitor.name].extend(value) else: obj[child.visitor.name] = value return obj_empty, obj elif self.visitor.is_array: empty, value = self.children.apply(data) return empty, [value] elif self.visitor.is_value: return extract_value(self.mapping, self.visitor, data)
Apply the given mapping to ``data``, recursively. The return type is a tuple of a boolean and the resulting data element. The boolean indicates whether any values were mapped in the child nodes of the mapping. It is used to skip optional branches of the object graph.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/mapper.py#L52-L79
[ "def extract_value(mapping, bind, data):\n \"\"\" Given a mapping and JSON schema spec, extract a value from ``data``\n and apply certain transformations to normalize the value. \"\"\"\n columns = mapping.get('columns', [mapping.get('column')])\n values = [data.get(c) for c in columns]\n\n for transform in mapping.get('transforms', []):\n # any added transforms must also be added to the schema.\n values = list(TRANSFORMS[transform](mapping, bind, values))\n\n format_str = mapping.get('format')\n value = values[0] if len(values) else None\n if not is_empty(format_str):\n value = format_str % tuple('' if v is None else v for v in values)\n\n empty = is_empty(value)\n if empty:\n value = mapping.get('default') or bind.schema.get('default')\n return empty, convert_value(bind, value)\n" ]
class Mapper(object): """ Given a JSON-specified mapping, this class will recursively transform a flat data structure (e.g. a CSV file or database table) into a nested JSON structure as specified by the JSON schema associated with the given mapping. """ def __init__(self, mapping, resolver, visitor=None, scope=None): self.mapping = mapping.copy() if '$ref' in self.mapping: with resolver.in_scope(scope): uri, data = resolver.resolve(self.mapping.pop('$ref')) self.mapping.update(data) if visitor is None: schema = self.mapping.get('schema') visitor = SchemaVisitor(schema, resolver, scope=scope) self.visitor = visitor if self.visitor.parent is None: validate_mapping(self.mapping) is not None @property def optional(self): """ If optional, the object will be skipped if no values exist in source data to fill it up. """ return self.mapping.get('optional', False) @property def children(self): if not hasattr(self, '_children'): if self.visitor.is_array: self._children = Mapper(self.mapping, self.visitor.resolver, visitor=self.visitor.items) elif self.visitor.is_object: self._children = [] for name, mappings in self.mapping.get('mapping', {}).items(): if hasattr(mappings, 'items'): mappings = [mappings] for mapping in mappings: for prop in self.visitor.properties: if prop.match(name): mapper = Mapper(mapping, self.visitor.resolver, visitor=prop) self._children.append(mapper) else: self._children = None return self._children @classmethod def apply_iter(cls, rows, mapping, resolver, scope=None): """ Given an iterable ``rows`` that yield data records, and a ``mapping`` which is to be applied to them, return a tuple of ``data`` (the generated object graph) and ``err``, a validation exception if the resulting data did not match the expected schema. """ mapper = cls(mapping, resolver, scope=scope) for row in rows: _, data = mapper.apply(row) yield data
pudo/jsonmapping
jsonmapping/mapper.py
Mapper.apply_iter
python
def apply_iter(cls, rows, mapping, resolver, scope=None): mapper = cls(mapping, resolver, scope=scope) for row in rows: _, data = mapper.apply(row) yield data
Given an iterable ``rows`` that yield data records, and a ``mapping`` which is to be applied to them, return a tuple of ``data`` (the generated object graph) and ``err``, a validation exception if the resulting data did not match the expected schema.
train
https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/mapper.py#L82-L90
[ "def apply(self, data):\n \"\"\" Apply the given mapping to ``data``, recursively. The return type\n is a tuple of a boolean and the resulting data element. The boolean\n indicates whether any values were mapped in the child nodes of the\n mapping. It is used to skip optional branches of the object graph. \"\"\"\n if self.visitor.is_object:\n obj = {}\n if self.visitor.parent is None:\n obj['$schema'] = self.visitor.path\n obj_empty = True\n for child in self.children:\n empty, value = child.apply(data)\n if empty and child.optional:\n continue\n obj_empty = False if not empty else obj_empty\n\n if child.visitor.name in obj and child.visitor.is_array:\n obj[child.visitor.name].extend(value)\n else:\n obj[child.visitor.name] = value\n return obj_empty, obj\n\n elif self.visitor.is_array:\n empty, value = self.children.apply(data)\n return empty, [value]\n\n elif self.visitor.is_value:\n return extract_value(self.mapping, self.visitor, data)\n" ]
class Mapper(object): """ Given a JSON-specified mapping, this class will recursively transform a flat data structure (e.g. a CSV file or database table) into a nested JSON structure as specified by the JSON schema associated with the given mapping. """ def __init__(self, mapping, resolver, visitor=None, scope=None): self.mapping = mapping.copy() if '$ref' in self.mapping: with resolver.in_scope(scope): uri, data = resolver.resolve(self.mapping.pop('$ref')) self.mapping.update(data) if visitor is None: schema = self.mapping.get('schema') visitor = SchemaVisitor(schema, resolver, scope=scope) self.visitor = visitor if self.visitor.parent is None: validate_mapping(self.mapping) is not None @property def optional(self): """ If optional, the object will be skipped if no values exist in source data to fill it up. """ return self.mapping.get('optional', False) @property def children(self): if not hasattr(self, '_children'): if self.visitor.is_array: self._children = Mapper(self.mapping, self.visitor.resolver, visitor=self.visitor.items) elif self.visitor.is_object: self._children = [] for name, mappings in self.mapping.get('mapping', {}).items(): if hasattr(mappings, 'items'): mappings = [mappings] for mapping in mappings: for prop in self.visitor.properties: if prop.match(name): mapper = Mapper(mapping, self.visitor.resolver, visitor=prop) self._children.append(mapper) else: self._children = None return self._children def apply(self, data): """ Apply the given mapping to ``data``, recursively. The return type is a tuple of a boolean and the resulting data element. The boolean indicates whether any values were mapped in the child nodes of the mapping. It is used to skip optional branches of the object graph. """ if self.visitor.is_object: obj = {} if self.visitor.parent is None: obj['$schema'] = self.visitor.path obj_empty = True for child in self.children: empty, value = child.apply(data) if empty and child.optional: continue obj_empty = False if not empty else obj_empty if child.visitor.name in obj and child.visitor.is_array: obj[child.visitor.name].extend(value) else: obj[child.visitor.name] = value return obj_empty, obj elif self.visitor.is_array: empty, value = self.children.apply(data) return empty, [value] elif self.visitor.is_value: return extract_value(self.mapping, self.visitor, data) @classmethod