signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def __init__(self, word, format, type, index_in_timed_response = None): | self.type = type<EOL>self.format = format<EOL>self.phonetic_representation = None<EOL>self.index_in_timed_response = index_in_timed_response<EOL>if self.format == "<STR_LIT>":<EOL><INDENT>self.text = word.string.lower()<EOL>self.original_text = [word.string.lower()] <EOL>self.start_time = word.start<EOL>self.end_time = word.end<EOL>self.duration = word.duration<EOL><DEDENT>elif self.format == "<STR_LIT>":<EOL><INDENT>self.text = word.lower()<EOL>self.original_text = [word.lower()] <EOL>self.start_time = None<EOL>self.end_time = None<EOL>self.duration = None<EOL><DEDENT> | Initialization of Unit object.
:param word: Original word that the Unit represents.
:type word: If format is "TextGrid", this must be a TextGrid.Word object.
If format is "csv", this must be a string.
:param str format: 'TextGrid' or 'csv'
:param str type: 'SEMANTIC' or 'PHONETIC
:param int index_in_timed_response: Index in the raw response input.
Used to find phone-level information later if necessary.
:rtype : Unit object | f13479:c2:m0 |
def __str__(self): | return self.text<EOL> | Enables the str() function. Returns the simplest textual representation of the Unit. | f13479:c2:m1 |
def __init__(self,response_type,<EOL>letter_or_category,<EOL>quiet = False,<EOL>cmudict = None, <EOL>english_words = None, <EOL>lemmas = None, <EOL>names = None, <EOL>permissible_words = None): | self.type = response_type<EOL>self.letter_or_category = letter_or_category<EOL>self.quiet = quiet<EOL>self.cmudict = cmudict<EOL>self.english_words = english_words<EOL>self.lemmas = lemmas<EOL>self.names = names<EOL>self.permissible_words = permissible_words<EOL>self.unit_list = []<EOL>self.timing_included = None<EOL>self.iterator_index = <NUM_LIT:0><EOL> | Initializes a ParsedResponse object.
:param str response_type: 'PHONETIC' or 'SEMANTIC - used for determining whether
lemmatization/tokenization should be done during initialization
:param str letter_or_category: letter (for type='PHONETIC') or string (for type='SEMANTIC')
required for determining which Units in the list are appropriate responses
to the current fluencyt ask
:param bool quiet: If True, suppresses output to screen.
:param dict cmudict: Dictionary of phonetic representations of words. Used for phonetic clustering.
:param list english_words: Big list of English words. Used to determine whether responses
in the phonetic clustering response are in English.
:param set lemmas: Set of available lemmas, i.e. words in their simplest version (non-plural)
:param list names: List of tokenized responses, i.e. compound words.
:param list permissible_words: List of legal words of the relevant dimension | f13479:c3:m0 |
def __iter__(self): | return iter(self.unit_list)<EOL> | Makes the object iterable, iterates over the list of units in the ParsedResponse. | f13479:c3:m1 |
def __len__(self): | return len(self.unit_list)<EOL> | Implements len(), returns length of the list of units in the ParsedResponse. | f13479:c3:m2 |
def __getitem__(self,i): | return self.unit_list[i]<EOL> | Implements e.g. parsed_response[i] to return the ith Unit in the ParsedResponse. | f13479:c3:m3 |
def create_from_csv(self,token_list): | self.timing_included = False<EOL>for entry in token_list:<EOL><INDENT>self.unit_list.append(Unit(entry, format = "<STR_LIT>", type = self.type))<EOL><DEDENT>if self.type == "<STR_LIT>":<EOL><INDENT>self.lemmatize()<EOL>self.tokenize()<EOL><DEDENT> | Fills the ParsedResponse object with a list of words/tokens originally from a .csv file.
:param list token_list: List of strings corresponding to words in the subject response.
Modifies:
- self.timing_included: csv files do not include timing information
- self.unit_list: fills it with Unit objects derived from the token_list argument.
If the type is 'SEMANTIC', the words in these units are automatically lemmatized and
made into compound words where appropriate. | f13479:c3:m4 |
def create_from_textgrid(self,word_list): | self.timing_included = True<EOL>for i, entry in enumerate(word_list):<EOL><INDENT>self.unit_list.append(Unit(entry, format="<STR_LIT>",<EOL>type=self.type,<EOL>index_in_timed_response=i))<EOL><DEDENT>if self.type == "<STR_LIT>":<EOL><INDENT>self.lemmatize()<EOL>self.tokenize()<EOL><DEDENT> | Fills the ParsedResponse object with a list of TextGrid.Word objects originally from a .TextGrid file.
:param list word_list: List of TextGrid.Word objects corresponding to words/tokens in the subject response.
Modifies:
- self.timing_included: TextGrid files include timing information
- self.unit_list: fills it with Unit objects derived from the word_list argument.
If the type is 'SEMANTIC', the words in these units are automatically lemmatized and
made into compound words where appropriate. | f13479:c3:m5 |
def lemmatize(self): | for unit in self.unit_list:<EOL><INDENT>if lemmatizer.lemmatize(unit.text) in self.lemmas:<EOL><INDENT>unit.text = lemmatizer.lemmatize(unit.text)<EOL><DEDENT><DEDENT> | Lemmatize all Units in self.unit_list.
Modifies:
- self.unit_list: converts the .text property into its lemmatized form.
This method lemmatizes all inflected variants of permissible words to
those words' respective canonical forms. This is done to ensure that
each instance of a permissible word will correspond to a term vector with
which semantic relatedness to other words' term vectors can be computed.
(Term vectors were derived from a corpus in which inflected words were
similarly lemmatized, meaning that , e.g., 'dogs' will not have a term
vector to use for semantic relatedness computation.) | f13479:c3:m6 |
def tokenize(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL><DEDENT>compound_word_dict = {}<EOL>for compound_length in range(<NUM_LIT:5>,<NUM_LIT:1>,-<NUM_LIT:1>):<EOL><INDENT>compound_word_dict[compound_length] = [name for name in self.names if len(name.split()) == compound_length]<EOL><DEDENT>current_index = <NUM_LIT:0><EOL>finished = False<EOL>while not finished:<EOL><INDENT>for compound_length in range(<NUM_LIT:5>,<NUM_LIT:1>,-<NUM_LIT:1>): <EOL><INDENT>if current_index + compound_length - <NUM_LIT:1> < len(self.unit_list): <EOL><INDENT>compound_word = "<STR_LIT>"<EOL>for word in self.unit_list[current_index:current_index + compound_length]:<EOL><INDENT>compound_word += "<STR_LIT:U+0020>" + word.text<EOL><DEDENT>compound_word = compound_word.strip() <EOL>if compound_word in compound_word_dict[compound_length]:<EOL><INDENT>self.make_compound_word(start_index = current_index, how_many = compound_length)<EOL>current_index += <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT><DEDENT>else: <EOL><INDENT>current_index += <NUM_LIT:1><EOL>if current_index >= len(self.unit_list): <EOL><INDENT>finished = True<EOL><DEDENT><DEDENT><DEDENT> | Tokenizes all multiword names in the list of Units.
Modifies:
- (indirectly) self.unit_list, by combining words into compound words.
This is done because many names may be composed of multiple words, e.g.,
'grizzly bear'. In order to count the number of permissible words
generated, and also to compute semantic relatedness between these
multiword names and other names, multiword names must each be reduced to
a respective single token. | f13479:c3:m7 |
def make_compound_word(self, start_index, how_many): | if not self.quiet:<EOL><INDENT>compound_word = "<STR_LIT>"<EOL>for word in self.unit_list[start_index:start_index + how_many]:<EOL><INDENT>compound_word += "<STR_LIT:U+0020>" + word.text<EOL><DEDENT>print(compound_word.strip(), "<STR_LIT>","<STR_LIT:_>".join(compound_word.split()))<EOL><DEDENT>for other_unit in range(<NUM_LIT:1>, how_many):<EOL><INDENT>self.unit_list[start_index].original_text.append(self.unit_list[start_index + other_unit].text)<EOL>self.unit_list[start_index].text += "<STR_LIT:_>" + self.unit_list[start_index + other_unit].text<EOL><DEDENT>self.unit_list[start_index].end_time = self.unit_list[start_index + how_many - <NUM_LIT:1>].end_time<EOL>self.unit_list = self.unit_list[:start_index + <NUM_LIT:1>] + self.unit_list[start_index + how_many:]<EOL> | Combines two Units in self.unit_list to make a compound word token.
:param int start_index: Index of first Unit in self.unit_list to be combined
:param int how_many: Index of how many Units in self.unit_list to be combined.
Modifies:
- self.unit_list: Modifies the Unit corresponding to the first word
in the compound word. Changes the .text property to include .text
properties from subsequent Units, separted by underscores. Modifies
the .original_text property to record each componentword separately.
Modifies the .end_time property to be the .end_time of the final unit
in the compound word. Finally, after extracting the text and timing
information, it removes all units in the compound word except for the
first.
.. note: This method is only used with semantic processing, so we don't need to worry
about the phonetic representation of Units. | f13479:c3:m8 |
def remove_unit(self, index): | if not self.quiet:<EOL><INDENT>print("<STR_LIT>", self.unit_list[index].text)<EOL><DEDENT>self.unit_list.pop(index)<EOL> | Removes the unit at the given index in self.unit_list. Does not modify any other units. | f13479:c3:m9 |
def combine_same_stem_units(self, index): | if not self.quiet:<EOL><INDENT>combined_word = "<STR_LIT>"<EOL>for word in self.unit_list[index:index + <NUM_LIT:2>]:<EOL><INDENT>for original_word in word.original_text:<EOL><INDENT>combined_word += "<STR_LIT:U+0020>" + original_word<EOL><DEDENT><DEDENT>print(combined_word.strip(), "<STR_LIT>","<STR_LIT:/>".join(combined_word.split()))<EOL><DEDENT>self.unit_list[index].original_text.append(self.unit_list[index + <NUM_LIT:1>].text)<EOL>self.unit_list[index].end_time = self.unit_list[index + <NUM_LIT:1>].end_time<EOL>self.unit_list.pop(index + <NUM_LIT:1>)<EOL> | Combines adjacent words with the same stem into a single unit.
:param int index: Index of Unit in self.unit_list to be combined with the
subsequent Unit.
Modifies:
- self.unit_list: Modifies the .original_text property of the Unit
corresponding to the index. Changes the .end_time property to be the
.end_time of the next Unit, as Units with the same stem are considered
as single Unit inc lustering. Finally, after extracting the text and timing
information, it removes the unit at index+1. | f13479:c3:m10 |
def display(self): | table_list = []<EOL>table_list.append(("<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>", "<STR_LIT>"))<EOL>for unit in self.unit_list:<EOL><INDENT>table_list.append((unit.text,<EOL>"<STR_LIT:/>".join(unit.original_text),<EOL>unit.start_time,<EOL>unit.end_time,<EOL>unit.phonetic_representation))<EOL><DEDENT>print_table(table_list)<EOL> | Pretty-prints the ParsedResponse to the screen. | f13479:c3:m11 |
def generate_phonetic_representation(self, word): | with NamedTemporaryFile() as temp_file:<EOL><INDENT>temp_file.write(word)<EOL>t2pargs = [os.path.abspath(os.path.join(os.path.dirname(__file__),'<STR_LIT>')),<EOL>'<STR_LIT>', os.path.join(data_path, '<STR_LIT>'),<EOL>temp_file.name]<EOL>temp_file.seek(<NUM_LIT:0>)<EOL>output, error = subprocess.Popen(<EOL>t2pargs, stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE<EOL>).communicate()<EOL>output = output.split()<EOL>phonetic_representation = output[<NUM_LIT:1>:]<EOL><DEDENT>return phonetic_representation<EOL> | Returns a generated phonetic representation for a word.
:param str word: a word to be phoneticized.
:return: A list of phonemes representing the phoneticized word.
This method is used for words for which there is no pronunication
entry in the CMU dictionary. The function generates a
pronunication for the word in the standard CMU format. This can then
be converted to a compact phonetic representation using
modify_phonetic_representation(). | f13479:c3:m12 |
def modify_phonetic_representation(self, phonetic_representation): | for i in range(len(phonetic_representation)):<EOL><INDENT>phonetic_representation[i] = re.sub('<STR_LIT>', '<STR_LIT>', phonetic_representation[i])<EOL><DEDENT>multis = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>singles = ['<STR_LIT:a>', '<STR_LIT:b>', '<STR_LIT:c>', '<STR_LIT:d>', '<STR_LIT:e>', '<STR_LIT:f>', '<STR_LIT:g>', '<STR_LIT:h>', '<STR_LIT:i>', '<STR_LIT>', '<STR_LIT:k>', '<STR_LIT:l>',<EOL>'<STR_LIT:m>', '<STR_LIT:n>', '<STR_LIT:o>', '<STR_LIT:p>', '<STR_LIT:q>', '<STR_LIT:r>', '<STR_LIT:s>', '<STR_LIT:t>', '<STR_LIT:u>', '<STR_LIT:v>', '<STR_LIT:w>']<EOL>for i in range(len(phonetic_representation)):<EOL><INDENT>if phonetic_representation[i] in multis:<EOL><INDENT>phonetic_representation[i] = singles[multis.index(phonetic_representation[i])]<EOL><DEDENT><DEDENT>phonetic_representation = '<STR_LIT>'.join(phonetic_representation)<EOL>return phonetic_representation<EOL> | Returns a compact phonetic representation given a CMUdict-formatted representation.
:param list phonetic_representation: a phonetic representation in standard
CMUdict formatting, i.e. a list of phonemes like ['HH', 'EH0', 'L', 'OW1']
:returns: A string representing a custom phonetic representation, where each phoneme is
mapped to a single ascii character.
Changing the phonetic representation from a list to a string is useful for calculating phonetic
simlarity scores. | f13479:c3:m13 |
def clean(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print(self.display())<EOL><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL><DEDENT>current_index = <NUM_LIT:0><EOL>while current_index < len(self.unit_list):<EOL><INDENT>word = self.unit_list[current_index].text<EOL>if self.type == "<STR_LIT>":<EOL><INDENT>test = (word.startswith(self.letter_or_category) and <EOL>not word.endswith('<STR_LIT:->') and <EOL>'<STR_LIT:_>' not in word and <EOL>word.lower() in self.english_words) <EOL><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>test = word in self.permissible_words<EOL><DEDENT>if not test: <EOL><INDENT>self.remove_unit(index = current_index)<EOL><DEDENT>else: <EOL><INDENT>current_index += <NUM_LIT:1><EOL><DEDENT><DEDENT>current_index = <NUM_LIT:0><EOL>finished = False<EOL>while current_index < len(self.unit_list) - <NUM_LIT:1>:<EOL><INDENT>if stemmer.stem(self.unit_list[current_index].text) ==stemmer.stem(self.unit_list[current_index + <NUM_LIT:1>].text):<EOL><INDENT>self.combine_same_stem_units(index = current_index)<EOL><DEDENT>else: <EOL><INDENT>current_index += <NUM_LIT:1><EOL><DEDENT><DEDENT>if self.type == "<STR_LIT>":<EOL><INDENT>for unit in self.unit_list:<EOL><INDENT>word = unit.text<EOL>if word in self.cmudict:<EOL><INDENT>phonetic_representation = self.cmudict[word]<EOL><DEDENT>if word not in self.cmudict:<EOL><INDENT>phonetic_representation = self.generate_phonetic_representation(word)<EOL>phonetic_representation = self.modify_phonetic_representation(phonetic_representation)<EOL><DEDENT>unit.phonetic_representation = phonetic_representation<EOL><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>print(self.display())<EOL><DEDENT> | Removes any Units that are not applicable given the current semantic or phonetic category.
Modifies:
- self.unit_list: Removes Units from this list that do not fit into the clustering category.
it does by by either combining units to make compound words, combining units with the
same stem, or eliminating units altogether if they do not conform to the category.
If the type is phonetic, this method also generates phonetic clusters for all Unit
objects in self.unit_list.
This method performs three main tasks:
1. Removes words that do not conform to the clustering category (i.e. start with the
wrong letter, or are not an animal).
2. Combine adjacent words with the same stem into a single unit. The NLTK Porter Stemmer
is used for determining whether stems are the same.
http://www.nltk.org/_modules/nltk/stem/porter.html
3. In the case of PHONETIC clustering, compute the phonetic representation of each unit. | f13479:c3:m14 |
def __init__(self,<EOL>response_category,<EOL>response_file_path,<EOL>target_file_path=None,<EOL>collection_types=["<STR_LIT>", "<STR_LIT>"],<EOL>similarity_measures=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"], <EOL>clustering_parameter=<NUM_LIT>, <EOL>quiet=False,<EOL>similarity_file = None,<EOL>threshold = None): | self.valid_semantic_categories = ['<STR_LIT>', '<STR_LIT>']<EOL>self.valid_phonetic_categories = ['<STR_LIT:a>', '<STR_LIT:f>', '<STR_LIT:s>', '<STR_LIT:p>']<EOL>self.valid_semantic_measures = ['<STR_LIT>']<EOL>self.valid_phonemic_measures = ['<STR_LIT>', '<STR_LIT>']<EOL>self.vowels = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>self.continuants = ['<STR_LIT>', '<STR_LIT:F>', '<STR_LIT:L>', '<STR_LIT:M>', '<STR_LIT:N>', '<STR_LIT>', '<STR_LIT:R>', '<STR_LIT:S>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']<EOL>self.same_word_similarity = <NUM_LIT><EOL>self.quiet = quiet<EOL>self.target_file = target_file_path<EOL>self.response_format = os.path.splitext(response_file_path)[<NUM_LIT:1>][<NUM_LIT:1>:]<EOL>self.response_category = response_category<EOL>self.collection_types = collection_types<EOL>if self.response_category in self.valid_phonetic_categories:<EOL><INDENT>self.type = "<STR_LIT>"<EOL>self.letter = response_category<EOL>self.similarity_measures = [m for m in similarity_measures if m in self.valid_phonemic_measures]<EOL><DEDENT>elif response_category in self.valid_semantic_categories:<EOL><INDENT>self.type = "<STR_LIT>"<EOL>self.category = response_category<EOL>self.clustering_parameter = int(clustering_parameter)<EOL>self.similarity_measures = [m for m in similarity_measures if m in self.valid_semantic_measures]<EOL><DEDENT>else:<EOL><INDENT>raise VFClustException('<STR_LIT>' + response_category)<EOL><DEDENT>self.measures = defaultdict(int)<EOL>if self.response_format not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise VFClustException('<STR_LIT>' +<EOL>'<STR_LIT>' +<EOL>'<STR_LIT>' + self.response_format)<EOL><DEDENT>if self.response_format == '<STR_LIT>':<EOL><INDENT>self.raw_response = open(response_file_path, '<STR_LIT:r>').readlines()[<NUM_LIT:0>].lower()<EOL>self.raw_response = self.raw_response.strip('<STR_LIT:\n>')<EOL>self.raw_response = self.raw_response.split('<STR_LIT:U+002C>')<EOL>self.measures['<STR_LIT>'] = self.raw_response[<NUM_LIT:0>]<EOL>del self.raw_response[<NUM_LIT:0>]<EOL>self.raw_response = [re.sub('<STR_LIT:U+0020>', '<STR_LIT>', word) for word in<EOL>self.raw_response]<EOL><DEDENT>if self.response_format == '<STR_LIT>':<EOL><INDENT>self.full_timed_response = TextGrid(response_file_path).parse_words()<EOL>self.measures['<STR_LIT>'] = os.path.basename(response_file_path)[:-<NUM_LIT:9>]<EOL><DEDENT>if not self.quiet: print()<EOL>if threshold:<EOL><INDENT>self.custom_threshold = threshold<EOL><DEDENT>else:<EOL><INDENT>self.custom_threshold = None<EOL><DEDENT>if self.type == "<STR_LIT>":<EOL><INDENT>self.names = None<EOL>self.lemmas = None<EOL>self.permissible_words = None<EOL>self.cmudict = pickle.load(open(os.path.join(data_path, '<STR_LIT>'), '<STR_LIT:rb>'))<EOL>self.english_words = open(os.path.join(data_path,os.path.join('<STR_LIT>','<STR_LIT>')),'<STR_LIT:r>').read().split()<EOL><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>self.cmudict = None<EOL>self.english_words = None<EOL>if self.category == '<STR_LIT>':<EOL><INDENT>if not self.quiet:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>self.names = pickle.load(open(os.path.join(data_path, self.category + '<STR_LIT>'), '<STR_LIT:rb>'))<EOL>if not self.quiet:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>with open(os.path.join(data_path, self.category + '<STR_LIT>'), '<STR_LIT:rb>') as infile:<EOL><INDENT>self.permissible_words = pickle.load(infile)<EOL><DEDENT><DEDENT>elif self.category == '<STR_LIT>':<EOL><INDENT>self.similarity_measures = ["<STR_LIT>"] <EOL>self.custom_similarity_file = open(similarity_file, '<STR_LIT:r>').readlines()<EOL>self.custom_similarity_scores = {}<EOL>for entry in self.custom_similarity_file:<EOL><INDENT>temp = entry.split("<STR_LIT:U+002C>")<EOL>words_split = temp[<NUM_LIT:0>].split("<STR_LIT:U+0020>")<EOL>self.custom_similarity_scores[(words_split[<NUM_LIT:0>],words_split[<NUM_LIT:1>])] = float(temp[<NUM_LIT:1>])<EOL><DEDENT>self.permissible_words = []<EOL>for w1, w2 in self.custom_similarity_scores:<EOL><INDENT>self.permissible_words.append(w1)<EOL>self.permissible_words.append(w2)<EOL><DEDENT>self.permissible_words = list(set(self.permissible_words))<EOL>self.names = self.permissible_words[:] <EOL><DEDENT>self.lemmas = []<EOL>for w in self.permissible_words:<EOL><INDENT>self.lemmas.append(lemmatizer.lemmatize(w))<EOL><DEDENT>self.lemmas = set(self.lemmas)<EOL><DEDENT>if "<STR_LIT>" in self.similarity_measures:<EOL><INDENT>self.load_lsa_information()<EOL><DEDENT>self.parsed_response = ParsedResponse(self.type,<EOL>quiet = self.quiet,<EOL>letter_or_category=response_category,<EOL>cmudict = self.cmudict,<EOL>english_words = self.english_words,<EOL>lemmas = self.lemmas,<EOL>names = self.names,<EOL>permissible_words = self.permissible_words)<EOL>if self.response_format == "<STR_LIT>":<EOL><INDENT>self.parsed_response.create_from_csv(self.raw_response)<EOL><DEDENT>elif self.response_format == "<STR_LIT>":<EOL><INDENT>self.parsed_response.create_from_textgrid(self.full_timed_response)<EOL><DEDENT>self.get_raw_counts() <EOL>self.parsed_response.clean() <EOL>for similarity_measure in self.similarity_measures:<EOL><INDENT>self.current_similarity_measure = similarity_measure<EOL>self.similarity_threshold = None<EOL>self.similarity_scores = []<EOL>if not self.quiet:<EOL><INDENT>print()<EOL>print()<EOL>print("<STR_LIT>" +"<STR_LIT>" +"<STR_LIT>" +"<STR_LIT:U+0020>" + similarity_measure + "<STR_LIT:\n>" +"<STR_LIT>" +"<STR_LIT>")<EOL>self.get_similarity_measures() <EOL><DEDENT>for collection_type in self.collection_types:<EOL><INDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print()<EOL>print("<STR_LIT>" +"<STR_LIT>" +"<STR_LIT>" +"<STR_LIT:U+0020>" + collection_type + "<STR_LIT:\n>" +"<STR_LIT>" +"<STR_LIT>")<EOL><DEDENT>self.current_collection_type = collection_type<EOL>self.collection_indices = []<EOL>self.collection_list = []<EOL>self.collection_sizes = []<EOL>self.collection_sizes_no_singletons = []<EOL>self.get_collections()<EOL>self.get_collection_measures()<EOL><DEDENT><DEDENT>self.print_output()<EOL> | Initialize for VFClust analysis of a verbal phonetic or semantic fluency test response.
response_file_path -- filepath for a comma-separated string comprising a
file ID and the words, pauses, etc., produced during the
attempt. Or, if the response format is a TextGrid file,
the filepath for that file.
Field 1 in the response file should hold some sort of file ID,
e.g., a filename or subject ID. Subsequent fields must each hold
a single word or filled pause, etc., that was produced during
the attempt.
target_file_path -- file to which VF-Clust CSV output will be written.
collection_types -- list of "cluster" or "chain" - what the measures should be calculated over
similarity_measures -- list of types of similarity measures to use between words
- at this point "phone" and "biphone" are supported
:param str response_category: a letter in the case of phonetic clustering, or a word category
(e.g. animals) in for phonetic clustering.
:param str response_file_path: file path of the subject response to be clustered.
:param target_file_path: (optional) directory in which the the .csv output file to be produced.
:param list collection_types: (optional) list of collection types to be used in clustering.
A "chain" is list of response tokens in which every token is related to the tokens adjacent
to it. A "cluster" is a list of response tokens in which every token is related to every
token in the cluster.
:param similarity_measures: (optional) a list of similarity measures to be used. By default, "lsa"
(Linear Semantic Analysis) is used for SEMANTIC clustering, and "phone" and "biphone" are used
for PHONETIC clustering.
:param clustering_parameter: (optional) parameters to be used in clustering
:param bool quiet: (optional) If set to True, suppresses output to screen.
:param similarity_file (optional): When doing semantic processing, this is the path of
a file containing custom term similarity scores that will be used for clustering.
If a custom file is used, the default LSA-based clustering will not be performed.
:param threshold (opitonal): When doing semantic processing, this threshold is used
in conjunction with a custom similarity file. The value is used as a semantic
similarity cutoff in clustering. This argument is required if a custom similarity
file is specified.
The initialization of a VFClustEngine object performs the following:
- parse input arguments
- loads relevant data from the supporting data directory to be used in
clustering, i.e. permissible words, LSA feature vectors, a dictionary of
English words, etc
- parses the subject response, generating a parsed_response object
- performs clustering
- produces a .csv file with clustering results.
The self.measures dictionary is used to hold all measures derived from the analysis. The
acutal collections produced are printed to screen, but only the measures derived from
clustering are output to the .csv file.
Methods are organized into two categories:
- load_ methods, in which data is loaded from disk
- get_ methods, which print processing information to screen, perform preprocessing and call related
clustering methods. These are called from __init__
- compute_ methods, which compute cluster-specific measures. These are called from get_ methdos.
.. note:: Both clusters and chains are implemented as collection types. Because there is more than one type,
the word "collection" is used throughout to refer to both clusters and chains. However, "clustering"
is still used to mean the process of discovering these groups.
.. note:: At this point, the only category of semantic clustering available is "animals." | f13479:c4:m0 |
def load_lsa_information(self): | if not (<NUM_LIT> < int(self.clustering_parameter) < <NUM_LIT>):<EOL><INDENT>raise Exception('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT>if not self.quiet:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>with open(os.path.join(data_path, self.category + '<STR_LIT:_>' +<EOL>os.path.join('<STR_LIT>',<EOL>'<STR_LIT>' +<EOL>str(self.clustering_parameter) + '<STR_LIT>')),<EOL>'<STR_LIT:rb>') as infile:<EOL><INDENT>self.term_vectors = pickle.load(infile)<EOL><DEDENT> | Loads a dictionary from disk that maps permissible words to their LSA term vectors. | f13479:c4:m1 |
def get_similarity_measures(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>", self.current_similarity_measure, "<STR_LIT>")<EOL><DEDENT>self.compute_similarity_scores()<EOL> | Helper function for computing similarity measures. | f13479:c4:m2 |
def get_collections(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>" + self.current_collection_type + "<STR_LIT>")<EOL><DEDENT>self.compute_collections()<EOL>if not self.quiet:<EOL><INDENT>print(self.current_similarity_measure, self.current_collection_type, "<STR_LIT>")<EOL>table_contents = [("<STR_LIT>","<STR_LIT>","<STR_LIT>")]<EOL>for (i, j, k) in zip(self.collection_indices,self.collection_sizes,self.collection_list):<EOL><INDENT>table_contents.append(([unit.text for unit in k], i, j))<EOL><DEDENT>print_table(table_contents)<EOL><DEDENT> | Helper function for determining what the clusters/chains/other collections are. | f13479:c4:m3 |
def get_collection_measures(self): | if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>", self.current_collection_type, "<STR_LIT>")<EOL><DEDENT>self.compute_collection_measures() <EOL>self.compute_collection_measures(no_singletons = True) <EOL>self.compute_pairwise_similarity_score()<EOL>if not self.quiet:<EOL><INDENT>collection_measures = [x for x in self.measuresif x.startswith("<STR_LIT>")<EOL>and self.current_collection_type in x<EOL>and self.current_similarity_measure in x]<EOL>collection_measures.sort()<EOL>print_table([(k, str(self.measures[k])) for k in collection_measures])<EOL><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL><DEDENT>self.compute_duration_measures()<EOL> | Helper function for calculating measurements derived from clusters/chains/collections | f13479:c4:m4 |
def get_raw_counts(self): | <EOL>words = []<EOL>labels = []<EOL>words_said = set()<EOL>for unit in self.parsed_response:<EOL><INDENT>word = unit.text<EOL>test = False<EOL>if self.type == "<STR_LIT>":<EOL><INDENT>test = (word.startswith(self.letter) and<EOL>"<STR_LIT>" not in word and "<STR_LIT>" not in word and "<STR_LIT:!>" not in word and <EOL>"<STR_LIT>" not in word and <EOL>not word.endswith('<STR_LIT:->') and <EOL>word.lower() in self.english_words) <EOL><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>test = (word in self.permissible_words)<EOL><DEDENT>if test:<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>if any(word == w for w in words_said):<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>labels.append('<STR_LIT>')<EOL><DEDENT>elif any(stemmer.stem(word) == stemmer.stem(w) for w in words_said):<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>labels.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>labels.append('<STR_LIT>')<EOL><DEDENT>words_said.add(word)<EOL>words.append(word)<EOL><DEDENT>elif word.lower().startswith('<STR_LIT>'):<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>words.append(word)<EOL>labels.append('<STR_LIT>')<EOL><DEDENT>elif word.endswith('<STR_LIT:->'):<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>words.append(word)<EOL>labels.append('<STR_LIT>')<EOL><DEDENT>elif word.lower().startswith('<STR_LIT>'):<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>words.append(word)<EOL>labels.append('<STR_LIT>')<EOL><DEDENT>elif word.lower() not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>self.measures['<STR_LIT>'] += <NUM_LIT:1><EOL>words.append(word)<EOL>labels.append('<STR_LIT>')<EOL><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>print_table([(word,label) for word,label in zip(words,labels)])<EOL><DEDENT>self.measures['<STR_LIT>'] =self.measures['<STR_LIT>'] -self.measures['<STR_LIT>'] -self.measures['<STR_LIT>']<EOL>if not self.quiet:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>collection_measures = [x for x in self.measures if x.startswith("<STR_LIT>")]<EOL>collection_measures.sort()<EOL>if not self.quiet:<EOL><INDENT>print_table([(k, str(self.measures[k])) for k in collection_measures])<EOL><DEDENT><DEDENT> | Determines counts for unique words, repetitions, etc using the raw text response.
Adds the following measures to the self.measures dictionary:
- COUNT_total_words: count of words (i.e. utterances with semantic content) spoken
by the subject. Filled pauses, silences, coughs, breaths, words by the interviewer,
etc. are all excluded from this count.
- COUNT_permissible_words: Number of words spoken by the subject that qualify as a
valid response according to the clustering criteria. Compound words are counted
as a single word in SEMANTIC clustering, but as two words in PHONETIC clustering.
This is implemented by tokenizing SEMANTIC clustering responses in the __init__
method before calling the current method.
- COUNT_exact_repetitions: Number of words which repeat words spoken earlier in the
response. Responses in SEMANTIC clustering are lemmatized before this function is
called, so slight variations (dog, dogs) may be counted as exact responses.
- COUNT_stem_repetitions: Number of words stems identical to words uttered earlier in
the response, according to the Porter Stemmer. For example, 'sled' and 'sledding'
have the same stem ('sled'), and 'sledding' would be counted as a stem repetition.
- COUNT_examiner_words: Number of words uttered by the examiner. These start
with "E_" in .TextGrid files.
- COUNT_filled_pauses: Number of filled pauses uttered by the subject. These begin
with "FILLEDPAUSE_" in the .TextGrid file.
- COUNT_word_fragments: Number of word fragments uttered by the subject. These
end with "-" in the .TextGrid file.
- COUNT_asides: Words spoken by the subject that do not adhere to the test criteria are
counted as asides, i.e. words that do not start with the appropriate letter or that
do not represent an animal.
- COUNT_unique_permissible_words: Number of works spoken by the subject, less asides,
stem repetitions and exact repetitions. | f13479:c4:m5 |
def compute_similarity_score(self, unit1, unit2): | if self.type == "<STR_LIT>":<EOL><INDENT>word1 = unit1.phonetic_representation<EOL>word2 = unit2.phonetic_representation<EOL>if self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>word1_length, word2_length = len(word1), len(word2)<EOL>if word1_length > word2_length:<EOL><INDENT>word1, word2 = word2, word1<EOL>word1_length, word2_length = word2_length, word1_length<EOL><DEDENT>current = list(range(word1_length + <NUM_LIT:1>))<EOL>for i in range(<NUM_LIT:1>, word2_length + <NUM_LIT:1>):<EOL><INDENT>previous, current = current, [i] + [<NUM_LIT:0>] * word1_length<EOL>for j in range(<NUM_LIT:1>, word1_length + <NUM_LIT:1>):<EOL><INDENT>add, delete = previous[j] + <NUM_LIT:1>, current[j - <NUM_LIT:1>] + <NUM_LIT:1><EOL>change = previous[j - <NUM_LIT:1>]<EOL>if word1[j - <NUM_LIT:1>] != word2[i - <NUM_LIT:1>]:<EOL><INDENT>change += <NUM_LIT:1><EOL><DEDENT>current[j] = min(add, delete, change)<EOL><DEDENT><DEDENT>phonetic_similarity_score = <NUM_LIT:1> - current[word1_length] / word2_length<EOL>return phonetic_similarity_score<EOL><DEDENT>elif self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>if word1[:<NUM_LIT:2>] == word2[:<NUM_LIT:2>] or word1[-<NUM_LIT:2>:] == word2[-<NUM_LIT:2>:]:<EOL><INDENT>common_biphone_score = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>common_biphone_score = <NUM_LIT:0><EOL><DEDENT>return common_biphone_score<EOL><DEDENT><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>word1 = unit1.text<EOL>word2 = unit2.text<EOL>if self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>w1_vec = self.term_vectors[word1]<EOL>w2_vec = self.term_vectors[word2]<EOL>dot = sum([w1*w2 for w1,w2 in zip(w1_vec, w2_vec)])<EOL>norm1 = sqrt(sum([w*w for w in w1_vec]))<EOL>norm2 = sqrt(sum([w*w for w in w2_vec]))<EOL>semantic_relatedness_score = dot/(norm1 * norm2)<EOL>return semantic_relatedness_score<EOL><DEDENT>elif self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>similarity = self.custom_similarity_scores[(word1,word2)]<EOL><DEDENT>except KeyError:<EOL><INDENT>try:<EOL><INDENT>similarity = self.custom_similarity_scores[(word2,word1)]<EOL><DEDENT>except KeyError:<EOL><INDENT>if word1 == word2:<EOL><INDENT>return self.same_word_similarity<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0> <EOL><DEDENT><DEDENT><DEDENT>return similarity<EOL><DEDENT><DEDENT>return None<EOL> | Returns the similarity score between two words.
The type of similarity scoring method used depends on the currently active
method and clustering type.
:param unit1: Unit object corresponding to the first word.
:type unit1: Unit
:param unit2: Unit object corresponding to the second word.
:type unit2: Unit
:return: Number indicating degree of similarity of the two input words.
The maximum value is 1, and a higher value indicates that the words
are more similar.
:rtype : Float
The similarity method used depends both on the type of test being performed
(SEMANTIC or PHONETIC) and the similarity method currently assigned to the
self.current_similarity_measure property of the VFClustEngine object. The
similarity measures used are the following:
- PHONETIC/"phone": the phonetic similarity score (PSS) is calculated
between the phonetic representations of the input units. It is equal
to 1 minus the Levenshtein distance between two strings, normalized
to the length of the longer string. The strings should be compact
phonetic representations of the two words.
(This method is a modification of a Levenshtein distance function
available at http://hetland.org/coding/python/levenshtein.py.)
- PHONETIC/"biphone": the binary common-biphone score (CBS) depends
on whether two words share their initial and/or final biphone
(i.e., set of two phonemes). A score of 1 indicates that two words
have the same intial and/or final biphone; a score of 0 indicates
that two words have neither the same initial nor final biphone.
This is also calculated using the phonetic representation of the
two words.
- SEMANTIC/"lsa": a semantic relatedness score (SRS) is calculated
as the COSINE of the respective term vectors for the first and
second word in an LSA space of the specified clustering_parameter.
Unlike the PHONETIC methods, this method uses the .text property
of the input Unit objects. | f13479:c4:m6 |
def compute_similarity_scores(self): | for i,unit in enumerate(self.parsed_response):<EOL><INDENT>if i < len(self.parsed_response) - <NUM_LIT:1>:<EOL><INDENT>next_unit = self.parsed_response[i + <NUM_LIT:1>]<EOL>self.similarity_scores.append(self.compute_similarity_score(unit, next_unit))<EOL><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print(self.current_similarity_measure, "<STR_LIT>")<EOL>table = [("<STR_LIT>", "<STR_LIT>", "<STR_LIT>")] +[(self.parsed_response[i].text, self.parsed_response[i + <NUM_LIT:1>].text,<EOL>"<STR_LIT>".format(round(self.similarity_scores[i], <NUM_LIT:2>)))<EOL>for i in range(len(self.parsed_response)-<NUM_LIT:1>)]<EOL>print_table(table)<EOL><DEDENT> | Produce a list of similarity scores for each contiguous pair in a response.
Calls compute_similarity_score method for every adjacent pair of words. The results
are not used in clustering; this is merely to provide a visual representation to
print to the screen.
Modifies:
- self.similarity_scores: Fills the list with similarity scores between adjacent
words. At this point this list is never used outside of this method. | f13479:c4:m7 |
def compute_collections(self): | if self.custom_threshold:<EOL><INDENT>self.similarity_threshold = self.custom_threshold<EOL><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>if self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>phonetic_similarity_thresholds = {'<STR_LIT:a>': <NUM_LIT>,<EOL>'<STR_LIT:b>': <NUM_LIT>,<EOL>'<STR_LIT:c>': <NUM_LIT>,<EOL>'<STR_LIT:d>': <NUM_LIT>,<EOL>'<STR_LIT:e>': <NUM_LIT>,<EOL>'<STR_LIT:f>': <NUM_LIT>,<EOL>'<STR_LIT:g>': <NUM_LIT>,<EOL>'<STR_LIT:h>': <NUM_LIT>,<EOL>'<STR_LIT:i>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT:k>': <NUM_LIT>,<EOL>'<STR_LIT:l>': <NUM_LIT>,<EOL>'<STR_LIT:m>': <NUM_LIT>,<EOL>'<STR_LIT:n>': <NUM_LIT>,<EOL>'<STR_LIT:o>': <NUM_LIT>,<EOL>'<STR_LIT:p>': <NUM_LIT>,<EOL>'<STR_LIT:q>': <NUM_LIT>,<EOL>'<STR_LIT:r>': <NUM_LIT>,<EOL>'<STR_LIT:s>': <NUM_LIT>,<EOL>'<STR_LIT:t>': <NUM_LIT>,<EOL>'<STR_LIT:u>': <NUM_LIT>,<EOL>'<STR_LIT:v>': <NUM_LIT>,<EOL>'<STR_LIT:w>': <NUM_LIT>,<EOL>'<STR_LIT:x>': <NUM_LIT>,<EOL>'<STR_LIT:y>': <NUM_LIT>,<EOL>'<STR_LIT:z>': <NUM_LIT>}<EOL>self.similarity_threshold = phonetic_similarity_thresholds[self.letter]<EOL><DEDENT>elif self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>self.similarity_threshold = <NUM_LIT:1><EOL><DEDENT><DEDENT>elif self.type == "<STR_LIT>":<EOL><INDENT>if self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>if self.category == '<STR_LIT>':<EOL><INDENT>thresholds = {'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT:100>': <NUM_LIT>}<EOL>self.similarity_threshold = thresholds[str(self.clustering_parameter)]<EOL><DEDENT><DEDENT>elif self.current_similarity_measure == "<STR_LIT>":<EOL><INDENT>self.similarity_threshold = self.custom_threshold<EOL><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print("<STR_LIT>", self.similarity_threshold)<EOL><DEDENT>for index, unit in enumerate(self.parsed_response):<EOL><INDENT>next_word_index = index + <NUM_LIT:1><EOL>collection = [unit] <EOL>collection_index = [index] <EOL>collection_terminus_found = False<EOL>while not collection_terminus_found:<EOL><INDENT>if next_word_index < len(self.parsed_response):<EOL><INDENT>test = False<EOL>if self.current_collection_type == "<STR_LIT>":<EOL><INDENT>unit2 = self.parsed_response[next_word_index]<EOL>test = all([self.compute_similarity_score(unit2, other_unit) >= self.similarity_thresholdfor other_unit in collection])<EOL><DEDENT>elif self.current_collection_type == "<STR_LIT>":<EOL><INDENT>unit1 = self.parsed_response[next_word_index - <NUM_LIT:1>]<EOL>unit2 = self.parsed_response[next_word_index]<EOL>test = self.compute_similarity_score(unit1,unit2) >= self.similarity_threshold<EOL><DEDENT>if test:<EOL><INDENT>collection.append(self.parsed_response[next_word_index])<EOL>collection_index.append(next_word_index)<EOL>next_word_index += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>collection_index = '<STR_LIT:U+0020>'.join([str(w) for w in collection_index])<EOL>if collection_index not in str(self.collection_indices):<EOL><INDENT>self.collection_indices.append(collection_index)<EOL>self.collection_sizes.append(len(collection))<EOL><DEDENT>collection_terminus_found = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>collection_index = '<STR_LIT:U+0020>'.join([str(w) for w in collection_index])<EOL>if collection_index not in str(self.collection_indices):<EOL><INDENT>self.collection_indices.append(collection_index)<EOL>self.collection_sizes.append(len(collection))<EOL><DEDENT>collection_terminus_found = True<EOL><DEDENT><DEDENT><DEDENT>for index in self.collection_indices:<EOL><INDENT>collection = []<EOL>for i in index.split():<EOL><INDENT>collection.append(self.parsed_response[int(i)])<EOL><DEDENT>self.collection_list.append(collection)<EOL><DEDENT> | Finds the collections (clusters,chains) that exist in parsed_response.
Modified:
- self.collection_sizes: populated with a list of integers indicating
the number of units belonging to each collection
- self.collection_indices: populated with a list of strings indicating
the indices of each element of each collection
- self.collection_list: populated with a list lists, each list containing
Unit objects belonging to each collection
There are two types of collections currently implemented:
- cluster: every entry in a cluster is sufficiently similar to every other entry
- chain: every entry in a chain is sufficiently similar to adjacent entries
Similarity between words is calculated using the compute_similarity_score method.
Scores between words are then thresholded and binarized using empirically-derived
thresholds (see: ???). Overlap of clusters is allowed (a word can be part of
multiple clusters), but overlapping chains are not possible, as any two adjacent
words with a lower-than-threshold similarity breaks the chain. Clusters subsumed
by other clusters are not counted. Singletons, i.e., clusters of size 1, are
included in this analysis.
.. todo: Find source for thresholding values. | f13479:c4:m8 |
def compute_pairwise_similarity_score(self): | pairs = []<EOL>all_scores = []<EOL>for i, unit in enumerate(self.parsed_response):<EOL><INDENT>for j, other_unit in enumerate(self.parsed_response):<EOL><INDENT>if i != j:<EOL><INDENT>pair = (i, j)<EOL>rev_pair = (j, i)<EOL>if pair not in pairs and rev_pair not in pairs:<EOL><INDENT>score = self.compute_similarity_score(unit, other_unit)<EOL>pairs.append(pair)<EOL>pairs.append(rev_pair)<EOL>all_scores.append(score)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>all_scores = [i for i in all_scores if i != self.same_word_similarity]<EOL>self.measures["<STR_LIT>" + self.current_similarity_measure + "<STR_LIT>"] = get_mean(<EOL>all_scores)if len(pairs) > <NUM_LIT:0> else '<STR_LIT>'<EOL> | Computes the average pairwise similarity score between all pairs of Units.
The pairwise similarity is calculated as the sum of similarity scores for all pairwise
word pairs in a response -- except any pair composed of a word and
itself -- divided by the total number of words in an attempt. I.e.,
the mean similarity for all pairwise word pairs.
Adds the following measures to the self.measures dictionary:
- COLLECTION_collection_pairwise_similarity_score_mean: mean of pairwise similarity scores
.. todo: divide by (count-1)? | f13479:c4:m9 |
def compute_collection_measures(self, no_singletons=False): | prefix = "<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:_>" + self.current_collection_type + "<STR_LIT:_>"<EOL>if no_singletons:<EOL><INDENT>prefix += "<STR_LIT>"<EOL><DEDENT>if no_singletons:<EOL><INDENT>collection_sizes_temp = [x for x in self.collection_sizes if x != <NUM_LIT:1>]<EOL><DEDENT>else: <EOL><INDENT>collection_sizes_temp = self.collection_sizes<EOL><DEDENT>self.measures[prefix + '<STR_LIT:count>'] = len(collection_sizes_temp)<EOL>self.measures[prefix + '<STR_LIT>'] = get_mean(collection_sizes_temp)if self.measures[prefix + '<STR_LIT:count>'] > <NUM_LIT:0> else <NUM_LIT:0><EOL>self.measures[prefix + '<STR_LIT>'] = max(collection_sizes_temp)if len(collection_sizes_temp) > <NUM_LIT:0> else <NUM_LIT:0><EOL>self.measures[prefix + '<STR_LIT>'] = self.measures[prefix + '<STR_LIT:count>'] - <NUM_LIT:1><EOL> | Computes summaries of measures using the discovered collections.
:param no_singletons: if True, omits collections of length 1 from all measures
and includes "no_singletons_" in the measure name.
Adds the following measures to the self.measures dictionary, prefaced by
COLLECTION_(similarity_measure)_(collection_type)_:
- count: number of collections
- size_mean: mean size of collections
- size_max: size of largest collection
- switch_count: number of changes between clusters | f13479:c4:m10 |
def compute_duration_measures(self): | prefix = "<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:_>" + self.current_collection_type + "<STR_LIT:_>"<EOL>if self.response_format == '<STR_LIT>':<EOL><INDENT>self.compute_response_vowel_duration("<STR_LIT>") <EOL>self.compute_response_continuant_duration("<STR_LIT>")<EOL>self.compute_between_collection_interval_duration(prefix)<EOL>self.compute_within_collection_interval_duration(prefix)<EOL>self.compute_within_collection_vowel_duration(prefix, no_singletons = True)<EOL>self.compute_within_collection_continuant_duration(prefix, no_singletons = True)<EOL>self.compute_within_collection_vowel_duration(prefix, no_singletons = False)<EOL>self.compute_within_collection_continuant_duration(prefix, no_singletons = False)<EOL><DEDENT> | Helper function for computing measures derived from timing information.
These are only computed if the response is textgrid with timing information.
All times are in seconds. | f13479:c4:m11 |
def compute_response_vowel_duration(self, prefix): | durations = []<EOL>for word in self.full_timed_response:<EOL><INDENT>if word.phones:<EOL><INDENT>for phone in word.phones:<EOL><INDENT>if phone.string in self.vowels:<EOL><INDENT>durations.append(phone.end - phone.start)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(durations)if len(durations) > <NUM_LIT:0> else '<STR_LIT>'<EOL>if not self.quiet:<EOL><INDENT>print("<STR_LIT>", self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT> | Computes mean vowel duration in entire response.
:param str prefix: Prefix for the key entry in self.measures.
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_response_vowel_duration_mean: average
vowel duration of all vowels in the response. | f13479:c4:m12 |
def compute_response_continuant_duration(self, prefix): | durations = []<EOL>for word in self.full_timed_response:<EOL><INDENT>if word.phones:<EOL><INDENT>for phone in word.phones:<EOL><INDENT>if phone.string in self.continuants:<EOL><INDENT>durations.append(phone.end - phone.start)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(durations)if len(durations) > <NUM_LIT:0> else '<STR_LIT>'<EOL>if not self.quiet:<EOL><INDENT>print("<STR_LIT>", self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT> | Computes mean duration for continuants in response.
:param str prefix: Prefix for the key entry in self.measures.
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_response_continuant_duration_mean: average
vowel duration of all vowels in the response. | f13479:c4:m13 |
def compute_between_collection_interval_duration(self, prefix): | durations = [] <EOL>for collection in self.collection_list:<EOL><INDENT>start = collection[<NUM_LIT:0>].start_time<EOL>end = collection[-<NUM_LIT:1>].end_time<EOL>durations.append((start, end))<EOL><DEDENT>interstices = [durations[i + <NUM_LIT:1>][<NUM_LIT:0>] - durations[i][<NUM_LIT:1>] for i, d in enumerate(durations[:-<NUM_LIT:1>])]<EOL>for i, entry in enumerate(interstices):<EOL><INDENT>if interstices[i] < <NUM_LIT:0>:<EOL><INDENT>interstices[i] = <NUM_LIT:0><EOL><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(interstices)if len(interstices) > <NUM_LIT:0> else '<STR_LIT>'<EOL>if not self.quiet:<EOL><INDENT>print()<EOL>print(self.current_similarity_measure + "<STR_LIT>" + self.current_collection_type + "<STR_LIT>")<EOL>table = [(self.current_collection_type + "<STR_LIT>", "<STR_LIT>",<EOL>self.current_collection_type + "<STR_LIT>")] +[(str(d1), str(i1), str(d2)) for d1, i1, d2 in zip(durations[:-<NUM_LIT:1>], interstices, durations[<NUM_LIT:1>:])]<EOL>print_table(table)<EOL>print()<EOL>print("<STR_LIT>" + self.current_similarity_measure + "<STR_LIT>" + self.current_collection_type + "<STR_LIT>",self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT> | Calculates BETWEEN-collection intervals for the current collection and measure type
and takes their mean.
:param str prefix: Prefix for the key entry in self.measures.
Negative intervals (for overlapping clusters) are counted as 0 seconds. Intervals are
calculated as being the difference between the ending time of the last word in a collection
and the start time of the first word in the subsequent collection.
Note that these intervals are not necessarily silences, and may include asides, filled
pauses, words from the examiner, etc.
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_between_collection_interval_duration_mean:
average interval duration separating clusters | f13479:c4:m14 |
def compute_within_collection_interval_duration(self, prefix): | interstices = []<EOL>for cluster in self.collection_list:<EOL><INDENT>if len(cluster) > <NUM_LIT:1>:<EOL><INDENT>for i in range(len(cluster)):<EOL><INDENT>if i != len(cluster) - <NUM_LIT:1>:<EOL><INDENT>interstice = cluster[i+<NUM_LIT:1>].start_time - cluster[i].end_time<EOL>interstices.append(interstice)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(interstices)if len(interstices) > <NUM_LIT:0> else '<STR_LIT>'<EOL>if not self.quiet:<EOL><INDENT>print("<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:->" + self.current_collection_type +"<STR_LIT>", self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT> | Calculates mean between-word duration WITHIN collections.
:param str prefix: Prefix for the key entry in self.measures.
Calculates the mean time between the end of each word in the collection
and the beginning of the next word. Note that these times do not necessarily
reflect pauses, as collection members could be separated by asides or other noises.
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_within_collection_interval_duration_mean | f13479:c4:m15 |
def compute_within_collection_vowel_duration(self, prefix, no_singletons=False): | if no_singletons:<EOL><INDENT>min_size = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>prefix += "<STR_LIT>"<EOL>min_size = <NUM_LIT:1><EOL><DEDENT>durations = []<EOL>for cluster in self.collection_list:<EOL><INDENT>if len(cluster) >= min_size:<EOL><INDENT>for word in cluster:<EOL><INDENT>word = self.full_timed_response[word.index_in_timed_response]<EOL>for phone in word.phones:<EOL><INDENT>if phone.string in self.vowels:<EOL><INDENT>durations.append(phone.end - phone.start)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(durations)if len(durations) > <NUM_LIT:0> else '<STR_LIT>'<EOL>if not self.quiet:<EOL><INDENT>if no_singletons:<EOL><INDENT>print("<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:->" + self.current_collection_type +"<STR_LIT>",self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:->" + self.current_collection_type +"<STR_LIT>",self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT><DEDENT> | Computes the mean duration of vowels from Units within clusters.
:param str prefix: Prefix for the key entry in self.measures
:param bool no_singletons: If False, excludes collections of length 1 from calculations
and adds "no_singletons" to the prefix
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_within_collection_vowel_duration_mean | f13479:c4:m16 |
def compute_within_collection_continuant_duration(self, prefix, no_singletons=False): | if no_singletons:<EOL><INDENT>min_size = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>prefix += "<STR_LIT>"<EOL>min_size = <NUM_LIT:1><EOL><DEDENT>durations = []<EOL>for cluster in self.collection_list:<EOL><INDENT>if len(cluster) >= min_size:<EOL><INDENT>for word in cluster:<EOL><INDENT>word = self.full_timed_response[word.index_in_timed_response]<EOL>for phone in word.phones:<EOL><INDENT>if phone.string in self.continuants:<EOL><INDENT>durations.append(phone.end - phone.start)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>self.measures[prefix + '<STR_LIT>'] = get_mean(durations)if len(durations) > <NUM_LIT:0> else '<STR_LIT>'<EOL>if not self.quiet:<EOL><INDENT>if no_singletons:<EOL><INDENT>print("<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:->" + self.current_collection_type +"<STR_LIT>",self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" + self.current_similarity_measure + "<STR_LIT:->" + self.current_collection_type +"<STR_LIT>",self.measures[prefix + '<STR_LIT>'])<EOL><DEDENT><DEDENT> | Computes the mean duration of continuants from Units within clusters.
:param str prefix: Prefix for the key entry in self.measures
:param bool no_singletons: If False, excludes collections of length 1 from calculations
and adds "no_singletons" to the prefix
Adds the following measures to the self.measures dictionary:
- TIMING_(similarity_measure)_(collection_type)_within_collection_continuant_duration_mean | f13479:c4:m17 |
def print_output(self): | if self.response_format == "<STR_LIT>":<EOL><INDENT>for key in self.measures:<EOL><INDENT>if "<STR_LIT>" in key:<EOL><INDENT>self.measures[key] = "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>if not self.quiet:<EOL><INDENT>print()<EOL>print(self.type.upper() + "<STR_LIT>")<EOL>keys = [e for e in self.measures if '<STR_LIT>' in e]<EOL>keys.sort()<EOL>print("<STR_LIT>")<EOL>print_table([(entry, str(self.measures[entry])) for entry in keys])<EOL>keys = [e for e in self.measures if '<STR_LIT>' in e]<EOL>keys.sort()<EOL>print()<EOL>print("<STR_LIT>")<EOL>print_table([(entry, str(self.measures[entry])) for entry in keys])<EOL>if self.response_format == "<STR_LIT>":<EOL><INDENT>keys = [e for e in self.measures if '<STR_LIT>' in e]<EOL>keys.sort()<EOL>print()<EOL>print("<STR_LIT>")<EOL>print_table([(entry, str(self.measures[entry])) for entry in keys])<EOL><DEDENT><DEDENT>if self.target_file:<EOL><INDENT>with open(self.target_file, '<STR_LIT:w>') as outfile:<EOL><INDENT>header = ['<STR_LIT>'] +[self.type + "<STR_LIT:_>" + e for e in self.measures if '<STR_LIT>' in e] +[self.type + "<STR_LIT:_>" + e for e in self.measures if '<STR_LIT>' in e] +[self.type + "<STR_LIT:_>" + e for e in self.measures if '<STR_LIT>' in e]<EOL>writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL)<EOL>writer.writerow(header)<EOL>writer.writerow([self.measures["<STR_LIT>"]] +<EOL>[self.measures["<STR_LIT:_>".join(e.split('<STR_LIT:_>')[<NUM_LIT:1>:])] for e in header[<NUM_LIT:1>:]])<EOL><DEDENT><DEDENT> | Outputs final list of measures to screen a csv file.
The .csv file created has the same name as the input file, with
"vfclust_TYPE_CATEGORY" appended to the filename, where TYPE indicates
the type of task performed done (SEMANTIC or PHONETIC) and CATEGORY
indicates the category requirement of the stimulus (i.e. 'f' or 'animals'
for phonetic and semantic fluency test, respectively. | f13479:c4:m18 |
def __init__(self, textgrid): | textgrid = open(textgrid, '<STR_LIT:r>').read()<EOL>self.word_intervals = textgrid[textgrid.index('<STR_LIT>'):textgrid.index('<STR_LIT>')]<EOL>self.word_intervals = self.word_intervals.split('<STR_LIT>')<EOL>del self.word_intervals[-<NUM_LIT:1>]<EOL>self.word_intervals = [interval + '<STR_LIT:$>' for interval in <EOL>self.word_intervals]<EOL>self.phone_intervals = textgrid[textgrid.index('<STR_LIT>'):]<EOL>self.phone_intervals = self.phone_intervals[self.phone_intervals.<EOL>index('<STR_LIT>'):]<EOL>self.phone_intervals = self.phone_intervals.split('<STR_LIT>')<EOL>del self.phone_intervals[-<NUM_LIT:1>]<EOL>self.phone_intervals = [interval + '<STR_LIT:$>' for interval in <EOL>self.phone_intervals]<EOL> | Extract word and phone intervals from a TextGrid.
These word and phone intervals contain the words and phones themselves,
as well as their respective start and end times in the audio recording. | f13480:c0:m0 |
def parse_phones(self): | phones = []<EOL>for i in self.phone_intervals:<EOL><INDENT>start = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LIT:\n>'))<EOL>end = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LIT:\n>'))<EOL>phone = i[i.index('<STR_LIT>')+<NUM_LIT:1>:i.index("<STR_LIT:$>")]<EOL>phones.append(Phone(phone, start, end))<EOL><DEDENT>return phones<EOL> | Parse TextGrid phone intervals.
This method parses the phone intervals in a TextGrid to extract each
phone and each phone's start and end times in the audio recording. For
each phone, it instantiates the class Phone(), with the phone and its
start and end times as attributes of that class instance. | f13480:c0:m1 |
def parse_words(self): | phones = self.parse_phones()<EOL>words = []<EOL>for i in self.word_intervals:<EOL><INDENT>start = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LIT:\n>'))<EOL>end = float(i[i.index('<STR_LIT>')+<NUM_LIT:7>:<EOL>i.index('<STR_LIT>')+<NUM_LIT:12>].strip('<STR_LIT:\t>').strip('<STR_LIT:\n>'))<EOL>word = i[i.index('<STR_LIT>')+<NUM_LIT:1>:i.index("<STR_LIT:$>")]<EOL>words.append(Word(word, start, end))<EOL><DEDENT>for word in words:<EOL><INDENT>for phone in phones:<EOL><INDENT>if phone.start >= word.start and phone.end <= word.end:<EOL><INDENT>word.phones.append(phone)<EOL><DEDENT><DEDENT><DEDENT>return words<EOL> | Parse TextGrid word intervals.
This method parses the word intervals in a TextGrid to extract each
word and each word's start and end times in the audio recording. For
each word, it instantiates the class Word(), with the word and its
start and end times as attributes of that class instance. Further, it
appends the class instance's attribute 'phones' for each phone that
occurs in that word. (It does this by checking which phones' start and
end times are subsumed by the start and end times of the word.) | f13480:c0:m2 |
def mv_release(m): | release = getattr(m, '<STR_LIT>', None)<EOL>if release is not None:<EOL><INDENT>release()<EOL><DEDENT> | Release memoryview | f13499:m0 |
def logical_lines(lines): | if isinstance(lines, string_types):<EOL><INDENT>lines = StringIO(lines)<EOL><DEDENT>buf = []<EOL>for line in lines:<EOL><INDENT>if buf and not line.startswith('<STR_LIT:U+0020>'):<EOL><INDENT>chunk = '<STR_LIT>'.join(buf).strip()<EOL>if chunk:<EOL><INDENT>yield chunk<EOL><DEDENT>buf[:] = []<EOL><DEDENT>buf.append(line)<EOL><DEDENT>chunk = '<STR_LIT>'.join(buf).strip()<EOL>if chunk:<EOL><INDENT>yield chunk<EOL><DEDENT> | Merge lines into chunks according to q rules | f13504:m0 |
def q(line, cell=None, _ns=None): | if cell is None:<EOL><INDENT>return pyq.q(line)<EOL><DEDENT>if _ns is None:<EOL><INDENT>_ns = vars(sys.modules['<STR_LIT:__main__>'])<EOL><DEDENT>input = output = None<EOL>preload = []<EOL>outs = {}<EOL>try:<EOL><INDENT>h = pyq.q('<STR_LIT>')<EOL>if line:<EOL><INDENT>for opt, value in getopt(line.split(), "<STR_LIT>")[<NUM_LIT:0>]:<EOL><INDENT>if opt == '<STR_LIT>':<EOL><INDENT>preload.append(value)<EOL><DEDENT>elif opt == '<STR_LIT>':<EOL><INDENT>h = pyq.K(str('<STR_LIT::>' + value))<EOL><DEDENT>elif opt == '<STR_LIT>':<EOL><INDENT>output = str(value) <EOL><DEDENT>elif opt == '<STR_LIT>':<EOL><INDENT>input = str(value).split('<STR_LIT:U+002C>')<EOL><DEDENT>elif opt in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>outs[int(opt[<NUM_LIT:1>])] = None<EOL><DEDENT><DEDENT><DEDENT>if outs:<EOL><INDENT>if int(h) != <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for fd in outs:<EOL><INDENT>tmpfd, tmpfile = mkstemp()<EOL>try:<EOL><INDENT>pyq.q(r'<STR_LIT>' % (fd, tmpfile))<EOL><DEDENT>finally:<EOL><INDENT>os.unlink(tmpfile)<EOL>os.close(tmpfd)<EOL><DEDENT><DEDENT><DEDENT>r = None<EOL>for script in preload:<EOL><INDENT>h(pyq.kp(r"<STR_LIT>" + script))<EOL><DEDENT>if input is not None:<EOL><INDENT>for chunk in logical_lines(cell):<EOL><INDENT>func = "<STR_LIT>" % ('<STR_LIT:;>'.join(input), chunk)<EOL>args = tuple(_ns[i] for i in input)<EOL>if r != Q_NONE:<EOL><INDENT>r.show()<EOL><DEDENT>r = h((pyq.kp(func),) + args)<EOL>if outs:<EOL><INDENT>_forward_outputs(outs)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for chunk in logical_lines(cell):<EOL><INDENT>if r != Q_NONE:<EOL><INDENT>r.show()<EOL><DEDENT>r = h(pyq.kp(chunk))<EOL>if outs:<EOL><INDENT>_forward_outputs(outs)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except pyq.kerr as e:<EOL><INDENT>print("<STR_LIT>" % e)<EOL><DEDENT>else:<EOL><INDENT>if output is not None:<EOL><INDENT>if output.startswith('<STR_LIT>'):<EOL><INDENT>pyq.q('<STR_LIT>', output[<NUM_LIT:2>:], r)<EOL><DEDENT>else:<EOL><INDENT>_ns[output] = r<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if r != Q_NONE:<EOL><INDENT>return r<EOL><DEDENT><DEDENT><DEDENT> | Run q code.
Options:
-l (dir|script) - pre-load database or script
-h host:port - execute on the given host
-o var - send output to a variable named var.
-i var1,..,varN - input variables
-1/-2 - redirect stdout/stderr | f13504:m2 |
def load_ipython_extension(ipython): | ipython.register_magic_function(q, '<STR_LIT>')<EOL>fmr = ipython.display_formatter.formatters['<STR_LIT>']<EOL>fmr.for_type(pyq.K, _q_formatter)<EOL> | Register %q and %%q magics and pretty display for K objects | f13504:m4 |
def get_unit(a): | typestr = a.dtype.str<EOL>i = typestr.find('<STR_LIT:[>')<EOL>if i == -<NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>", a.dtype)<EOL><DEDENT>return typestr[i + <NUM_LIT:1>: -<NUM_LIT:1>]<EOL> | Extract the time unit from array's dtype | f13505:m0 |
def dtypeof(x): | t = abs(x._t)<EOL>if t < <NUM_LIT:20>:<EOL><INDENT>return _DTYPES[t]<EOL><DEDENT>return '<STR_LIT:O>'<EOL> | Return the dtype corresponding to a given q object | f13505:m1 |
def k2a(a, x): | func, scale = None, <NUM_LIT:1><EOL>t = abs(x._t)<EOL>if <NUM_LIT:12> <= t <= <NUM_LIT:15>:<EOL><INDENT>unit = get_unit(a)<EOL>attr, shift, func, scale = _UNIT[unit]<EOL>a[:] = getattr(x, attr).data<EOL>a += shift<EOL><DEDENT>elif <NUM_LIT:16> <= t <= <NUM_LIT>:<EOL><INDENT>unit = get_unit(a)<EOL>func, scale = _SCALE[unit]<EOL>a[:] = x.timespan.data<EOL><DEDENT>else:<EOL><INDENT>a[:] = list(x)<EOL><DEDENT>if func is not None:<EOL><INDENT>func = getattr(numpy, func)<EOL>a[:] = func(a.view(dtype='<STR_LIT>'), scale)<EOL><DEDENT>if a.dtype.char in '<STR_LIT>':<EOL><INDENT>n = x.null<EOL>if n.any:<EOL><INDENT>a[n] = None<EOL><DEDENT><DEDENT> | Rescale data from a K object x to array a. | f13505:m2 |
def array(self, dtype=None): | t = self._t<EOL>if <NUM_LIT:11> <= t < <NUM_LIT>:<EOL><INDENT>dtype = dtypeof(self)<EOL>a = numpy.empty(len(self), dtype)<EOL>k2a(a, self)<EOL>return a<EOL><DEDENT>if t == <NUM_LIT>:<EOL><INDENT>if dtype is None:<EOL><INDENT>dtype = list(zip(self.cols, (dtypeof(c) for c in self.flip.value)))<EOL><DEDENT>dtype = numpy.dtype(dtype)<EOL>a = numpy.empty(int(self.count), dtype)<EOL>for c in dtype.fields:<EOL><INDENT>k2a(a[c], self[c])<EOL><DEDENT>return a<EOL><DEDENT>return numpy.array(list(self), dtype)<EOL> | An implementation of __array__() | f13505:m3 |
def d9(x): | return K._d9(K._kp(x))<EOL> | like K._d9, but takes python bytes | f13507:m2 |
def versions(): | stream = sys.stdout if _PY3K else sys.stderr<EOL>print('<STR_LIT>', __version__, file=stream)<EOL>if _np is not None:<EOL><INDENT>print('<STR_LIT>', _np.__version__, file=stream)<EOL><DEDENT>print('<STR_LIT>' % tuple(q('<STR_LIT>')), file=stream)<EOL>print('<STR_LIT>', sys.version, file=stream)<EOL> | Report versions | f13507:m9 |
def __getitem__(self, x): | try:<EOL><INDENT>return _K.__getitem__(self, x)<EOL><DEDENT>except (TypeError, NotImplementedError):<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>start, stop, step = x.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>i = K(x)<EOL>if self._t == <NUM_LIT> and i._t < <NUM_LIT:0>:<EOL><INDENT>return self.value[self._k(<NUM_LIT:0>, "<STR_LIT:?>", self.key, i)]<EOL><DEDENT>else:<EOL><INDENT>return self._k(<NUM_LIT:0>, "<STR_LIT:@>", self, i)<EOL><DEDENT><DEDENT>if step == <NUM_LIT:1>:<EOL><INDENT>return self._k(<NUM_LIT:0>, "<STR_LIT>", self._J([start, stop - start]), self)<EOL><DEDENT>i = start + step * q.til(max(<NUM_LIT:0>, (stop - start) // step))<EOL>return self._k(<NUM_LIT:0>, "<STR_LIT>", self, i)<EOL> | >>> k("10 20 30 40 50")[k("1 3")]
k('20 40')
>>> k("`a`b`c!1 2 3")['b']
2 | f13507:c0:m5 |
def __getattr__(self, a): | t = self._t<EOL>if t == <NUM_LIT>:<EOL><INDENT>return self._k(<NUM_LIT:0>, '<STR_LIT>' % a, self)<EOL><DEDENT>if t == <NUM_LIT>:<EOL><INDENT>if self._k(<NUM_LIT:0>, "<STR_LIT>", self):<EOL><INDENT>if a == '<STR_LIT>':<EOL><INDENT>raise AttributeError<EOL><DEDENT>return self._k(<NUM_LIT:0>, '<STR_LIT>' % a, self)<EOL><DEDENT>return self._k(<NUM_LIT:0>, '<STR_LIT>' % a, self)<EOL><DEDENT>if <NUM_LIT:12> <= abs(t) < <NUM_LIT:20>:<EOL><INDENT>try:<EOL><INDENT>return self._k(<NUM_LIT:0>, "<STR_LIT>" % a, self)<EOL><DEDENT>except kerr:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise AttributeError(a)<EOL> | table columns can be accessed via dot notation
>>> q("([]a:1 2 3; b:10 20 30)").a
k('1 2 3') | f13507:c0:m6 |
def __int__(self): | t = self._t<EOL>if t >= <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return int(self.inspect(self._fields[-t]))<EOL> | converts K scalars to python int
>>> [int(q(x)) for x in '1b 2h 3 4e `5 6.0 2000.01.08'.split()]
[1, 2, 3, 4, 5, 6, 7] | f13507:c0:m7 |
def __float__(self): | t = self._t<EOL>if t >= <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return float(self.inspect(self._fields[-t]))<EOL> | converts K scalars to python float
>>> [float(q(x)) for x in '1b 2h 3 4e `5 6.0 2000.01.08'.split()]
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] | f13507:c0:m8 |
def __eq__(self, other): | try:<EOL><INDENT>other = K(other)<EOL><DEDENT>except TypeError:<EOL><INDENT>return False<EOL><DEDENT>return bool(k('<STR_LIT>')(self, other))<EOL> | >>> K(1) == K(1)
True
>>> K(1) == None
False | f13507:c0:m11 |
def __ne__(self, other): | return bool(k('<STR_LIT>')(self, other))<EOL> | >>> K(1) != K(2)
True | f13507:c0:m12 |
def __contains__(self, item): | if self._t:<EOL><INDENT>x = q('<STR_LIT>', item, self)<EOL><DEDENT>else:<EOL><INDENT>x = q('<STR_LIT>', item, self)<EOL><DEDENT>return bool(x)<EOL> | membership test
>>> 1 in q('1 2 3')
True
>>> 'abc' not in q('(1;2.0;`abc)')
False | f13507:c0:m13 |
def keys(self): | return self._k(<NUM_LIT:0>, '<STR_LIT:key>', self)<EOL> | returns q('key', self)
Among other uses, enables interoperability between q and
python dicts.
>>> from collections import OrderedDict
>>> OrderedDict(q('`a`b!1 2'))
OrderedDict([('a', 1), ('b', 2)])
>>> d = {}; d.update(q('`a`b!1 2'))
>>> list(sorted(d.items()))
[('a', 1), ('b', 2)] | f13507:c0:m14 |
def show(self, start=<NUM_LIT:0>, geometry=None, output=None): | if output is None:<EOL><INDENT>output = sys.stdout<EOL><DEDENT>if geometry is None:<EOL><INDENT>geometry = q.value(kp("<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>geometry = self._I(geometry)<EOL><DEDENT>if start < <NUM_LIT:0>:<EOL><INDENT>start += q.count(self)<EOL><DEDENT>if self._id() != nil._id():<EOL><INDENT>r = self._show(geometry, start)<EOL><DEDENT>else:<EOL><INDENT>r = '<STR_LIT>'<EOL><DEDENT>if isinstance(output, type):<EOL><INDENT>return output(r)<EOL><DEDENT>try:<EOL><INDENT>output.write(r)<EOL><DEDENT>except TypeError:<EOL><INDENT>output.write(str(r))<EOL><DEDENT> | pretty-print data to the console
(similar to q.show, but uses python stdout by default)
>>> x = q('([k:`x`y`z]a:1 2 3;b:10 20 30)')
>>> x.show() # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
x| 1 10
y| 2 20
z| 3 30
the first optional argument, 'start' specifies the first row to be
printed (negative means from the end)
>>> x.show(2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
z| 3 30
>>> x.show(-2) # doctest: +NORMALIZE_WHITESPACE
k| a b
-| ----
y| 2 20
z| 3 30
the geometry is the height and width of the console
>>> x.show(geometry=[4, 6])
k| a..
-| -..
x| 1..
.. | f13507:c0:m15 |
def select(self, columns=(), by=(), where=(), **kwds): | return self._seu('<STR_LIT>', columns, by, where, kwds)<EOL> | select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3 | f13507:c0:m18 |
def exec_(self, columns=(), by=(), where=(), **kwds): | return self._seu('<STR_LIT>', columns, by, where, kwds)<EOL> | exec from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.exec_('a', where='b > 10').show()
2 3 | f13507:c0:m19 |
def update(self, columns=(), by=(), where=(), **kwds): | return self._seu('<STR_LIT>', columns, by, where, kwds)<EOL> | update from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.update('a*2',
... where='b > 20').show() # doctest: +NORMALIZE_WHITESPACE
a b
----
1 10
2 20
6 30 | f13507:c0:m20 |
def __fspath__(self): | if self._t != -<NUM_LIT:11>: <EOL><INDENT>raise TypeError<EOL><DEDENT>sym = str(self)<EOL>if not sym.startswith('<STR_LIT::>'):<EOL><INDENT>raise TypeError<EOL><DEDENT>return sym[<NUM_LIT:1>:]<EOL> | Return the file system path representation of the object. | f13507:c0:m24 |
def __complex__(self): | if self._t != <NUM_LIT> or self.key != ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>return complex(float(self))<EOL><DEDENT>return complex(float(self.re), float(self.im))<EOL> | Called to implement the built-in function complex(). | f13507:c0:m25 |
@classmethod<EOL><INDENT>def dict(cls, *args, **kwds):<DEDENT> | if args:<EOL><INDENT>if len(args) > <NUM_LIT:1>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>x = args[<NUM_LIT:0>]<EOL>keys = []<EOL>vals = []<EOL>try:<EOL><INDENT>x_keys = x.keys<EOL><DEDENT>except AttributeError:<EOL><INDENT>for k, v in x:<EOL><INDENT>keys.append(k)<EOL>vals.append(v)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>keys = x_keys()<EOL>vals = [x[k] for k in keys]<EOL><DEDENT>return q('<STR_LIT:!>', keys, vals)<EOL><DEDENT>else:<EOL><INDENT>if kwds:<EOL><INDENT>keys = []<EOL>vals = []<EOL>for k, v in kwds.items():<EOL><INDENT>keys.append(k)<EOL>vals.append(v)<EOL><DEDENT>return q('<STR_LIT:!>', keys, vals)<EOL><DEDENT>else:<EOL><INDENT>return q('<STR_LIT>')<EOL><DEDENT><DEDENT> | Construct a q dictionary
K.dict() -> new empty q dictionary (q('()!()')
K.dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
K.dict(iterable) -> new dictionary initialized from an iterable
yielding (key, value) pairs
K.dict(**kwargs) -> new dictionary initialized with the name=value
pairs in the keyword argument list.
For example: K.dict(one=1, two=2) | f13507:c0:m26 |
def __call__(self, m=None, *args): | try:<EOL><INDENT>return K._k(<NUM_LIT:0>, m, *map(K, args))<EOL><DEDENT>except TypeError:<EOL><INDENT>if m is not None:<EOL><INDENT>raise<EOL><DEDENT>if self._cmd is None:<EOL><INDENT>from .cmd import Cmd<EOL>object.__setattr__(self, '<STR_LIT>', Cmd())<EOL><DEDENT>self._cmd.cmdloop()<EOL><DEDENT> | Execute q code. | f13507:c1:m1 |
def console_size(fd=<NUM_LIT:1>): | try:<EOL><INDENT>import fcntl<EOL>import termios<EOL>import struct<EOL><DEDENT>except ImportError:<EOL><INDENT>size = os.getenv('<STR_LIT>', <NUM_LIT>), os.getenv('<STR_LIT>', <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>size = struct.unpack('<STR_LIT>', fcntl.ioctl(fd, termios.TIOCGWINSZ,<EOL>b'<STR_LIT>'))<EOL><DEDENT>return size<EOL> | Return console size as a (LINES, COLUMNS) tuple | f13508:m0 |
def run(q_prompt=False): | lines, columns = console_size()<EOL>q(r'<STR_LIT>' % (lines, columns))<EOL>if len(sys.argv) > <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>q(r'<STR_LIT>' % sys.argv[<NUM_LIT:1>])<EOL><DEDENT>except kerr as e:<EOL><INDENT>print(e)<EOL>raise SystemExit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>del sys.argv[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>if q_prompt:<EOL><INDENT>q()<EOL><DEDENT>ptp.run()<EOL> | Run a prompt-toolkit based REPL | f13508:m1 |
def precmd(self, line): | if line.startswith('<STR_LIT>'):<EOL><INDENT>if not q("<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>q("<STR_LIT>")<EOL><DEDENT>except kerr:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT><DEDENT>if line == '<STR_LIT>':<EOL><INDENT>line += "<STR_LIT>"<EOL><DEDENT>return line<EOL> | Support for help | f13509:c0:m1 |
def onecmd(self, line): | if line == '<STR_LIT:\\>':<EOL><INDENT>return True<EOL><DEDENT>elif line == '<STR_LIT>':<EOL><INDENT>print('<STR_LIT:\r>', end='<STR_LIT>')<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>v = q(line)<EOL><DEDENT>except kerr as e:<EOL><INDENT>print("<STR_LIT>" % e.args[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>if v != q('<STR_LIT>'):<EOL><INDENT>v.show()<EOL><DEDENT><DEDENT>return False<EOL><DEDENT> | Interpret the line | f13509:c0:m2 |
def get_bottom_toolbar_tokens(cli): | mem = q('<STR_LIT>', '<STR_LIT>') // <NUM_LIT> <EOL>return [(Token.Toolbar, "<STR_LIT>".format(KDB_INFO, mem))]<EOL> | Return a list of tokens for the bottom toolbar | f13510:m0 |
def get_prompt_tokens(_): | namespace = q(r'<STR_LIT>')<EOL>if namespace == '<STR_LIT:.>':<EOL><INDENT>namespace = '<STR_LIT>'<EOL><DEDENT>return [(Token.Generic.Prompt, '<STR_LIT>' % namespace)]<EOL> | Return a list of tokens for the prompt | f13510:m1 |
def cmdloop(self, intro=None): | style = style_from_pygments(BasicStyle, style_dict)<EOL>self.preloop()<EOL>stop = None<EOL>while not stop:<EOL><INDENT>line = prompt(get_prompt_tokens=get_prompt_tokens, lexer=lexer,<EOL>get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,<EOL>history=history, style=style, true_color=True,<EOL>on_exit='<STR_LIT>', on_abort='<STR_LIT>',<EOL>completer=QCompleter())<EOL>if line is None or line.strip() == r'<STR_LIT:\\>':<EOL><INDENT>raise SystemExit<EOL><DEDENT>else:<EOL><INDENT>line = self.precmd(line)<EOL>stop = self.onecmd(line)<EOL><DEDENT>stop = self.postcmd(stop, line)<EOL><DEDENT>self.postloop()<EOL> | A Cmd.cmdloop implementation | f13510:m2 |
def get_completions(self, document, complete_event): | <EOL>m = HSYM_RE.match(document.text_before_cursor)<EOL>if m:<EOL><INDENT>text = m.group(<NUM_LIT:1>)<EOL>doc = Document(text, len(text))<EOL>for c in self.path_completer.get_completions(doc, complete_event):<EOL><INDENT>yield c<EOL><DEDENT><DEDENT>else:<EOL><INDENT>word_before_cursor = document.get_word_before_cursor(False)<EOL>for words, meta in self.words_info:<EOL><INDENT>for a in words:<EOL><INDENT>if a.startswith(word_before_cursor):<EOL><INDENT>yield Completion(a, -len(word_before_cursor),<EOL>display_meta=meta)<EOL><DEDENT><DEDENT><DEDENT><DEDENT> | Yield completions | f13510:c0:m1 |
def add_data_file(data_files, target, source): | for t, f in data_files:<EOL><INDENT>if t == target:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data_files.append((target, []))<EOL>f = data_files[-<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT>if source not in f:<EOL><INDENT>f.append(source)<EOL><DEDENT> | Add an entry to data_files | f13511:m0 |
def get_q_home(env): | q_home = env.get('<STR_LIT>')<EOL>if q_home:<EOL><INDENT>return q_home<EOL><DEDENT>for v in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>prefix = env.get(v)<EOL>if prefix:<EOL><INDENT>q_home = os.path.join(prefix, '<STR_LIT:q>')<EOL>if os.path.isdir(q_home):<EOL><INDENT>return q_home<EOL><DEDENT><DEDENT><DEDENT>if WINDOWS:<EOL><INDENT>q_home = os.path.join(env['<STR_LIT>'], r'<STR_LIT>')<EOL>if os.path.isdir(q_home):<EOL><INDENT>return q_home<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL> | Derive q home from the environment | f13511:m2 |
def get_q_version(q_home): | with open(os.path.join(q_home, '<STR_LIT>')) as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>return line[<NUM_LIT:2>:<NUM_LIT:5>]<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'<EOL> | Return version of q installed at q_home | f13511:m5 |
def compactness_frompts(geoseries): | measure = (<EOL><NUM_LIT:4> * <NUM_LIT> * (<EOL>(geoseries.unary_union).convex_hull.area)<EOL>) / (<EOL>(geoseries.unary_union).convex_hull.length<EOL>)<EOL>return measure<EOL> | Inverse of 4 * pi * Area / perimeter^2 | f13513:m2 |
def _get_target_nearest(self): | reps_query = """<STR_LIT>""".format(<EOL>maxorigin=self.origins.index.max(),<EOL>origin_table=self.origin_table,<EOL>target_table=self.target_table<EOL>)<EOL>nearest_reps = self.context.query(<EOL>reps_query,<EOL>decode_geom=True<EOL>)<EOL>nearest_reps = gpd.GeoDataFrame(nearest_reps, geometry='<STR_LIT>')<EOL>init_labels = nearest_reps['<STR_LIT>'].values<EOL>self.targets['<STR_LIT>'] = init_labels<EOL>logging.info('<STR_LIT>')<EOL>return nearest_reps<EOL> | Get nearest target for each origin | f13513:c0:m2 |
def _get_demand_graph(self): | <EOL>K = self.origins.shape[<NUM_LIT:0>]<EOL>demand = self.nearest_targets.groupby('<STR_LIT>')['<STR_LIT>'].count().to_dict()<EOL>self.targets = self.targets.sort_values('<STR_LIT>').reset_index(drop=True)<EOL>g = nx.DiGraph()<EOL>g.add_nodes_from(self.targets['<STR_LIT>'], demand=-<NUM_LIT:1>)<EOL>for idx in demand:<EOL><INDENT>g.add_node(int(idx), demand=demand[idx])<EOL><DEDENT>dict_M = {<EOL>i: (<EOL>self.targets[self.targets['<STR_LIT>'] == i]['<STR_LIT>'].values<EOL>if i in self.targets.target_id.values<EOL>else np.array([demand[i]])<EOL>)<EOL>for i in g.nodes<EOL>}<EOL>logging.info('<STR_LIT>')<EOL>return dict_M, demand<EOL> | create demand graph | f13513:c0:m3 |
def calc(self, maxiter=<NUM_LIT:100>, fixedprec=<NUM_LIT>): | source_data_holder = []<EOL>N = self.targets.shape[<NUM_LIT:0>]<EOL>K = self.origins.shape[<NUM_LIT:0>]<EOL>M, demand = self._get_demand_graph()<EOL>max_dist_trip = <NUM_LIT> <EOL>cost_holder = []<EOL>itercnt = <NUM_LIT:0><EOL>while True:<EOL><INDENT>itercnt += <NUM_LIT:1><EOL>logging.info(f'<STR_LIT>')<EOL>g = nx.DiGraph()<EOL>self.targets = self.targets.sort_values('<STR_LIT>').reset_index(drop=True)<EOL>g.add_nodes_from(self.targets['<STR_LIT>'], demand=-<NUM_LIT:1>) <EOL>for idx in self.nearest_targets.origin_id:<EOL><INDENT>g.add_node(int(idx), demand=demand[idx])<EOL><DEDENT>cost_dist = dist_vect(<EOL>np.tile(self.targets['<STR_LIT>'].values, K),<EOL>np.tile(self.targets['<STR_LIT>'].values, K),<EOL>np.repeat(self.origins['<STR_LIT>'].values, N),<EOL>np.repeat(self.origins['<STR_LIT>'].values, N)<EOL>)[:, np.newaxis].T<EOL>scaler_dist = MinMaxScaler()<EOL>cost_dist_trans = scaler_dist.fit_transform(cost_dist.T).T<EOL>cost_dist_trans[cost_dist > max_dist_trip] = <NUM_LIT:10><EOL>cluster_sales = self.targets.groupby('<STR_LIT>').sum()[self.demand_col][:, np.newaxis]<EOL>D = cluster_sales.shape[<NUM_LIT:1>]<EOL>cost_sales = abs(<EOL>np.array([<EOL>np.linalg.norm(<EOL>np.repeat(cluster_sales, N)[:, np.newaxis]- np.tile(cluster_sales.mean(), (K * N))[:,np.newaxis],<EOL>axis=<NUM_LIT:1><EOL>)<EOL>])<EOL>)<EOL>scaler_sales = MinMaxScaler()<EOL>cost_sales = scaler_sales.fit_transform(cost_sales.T).T<EOL>cost_total = cost_dist_trans + cost_sales<EOL>cost_holder.append(sum(cost_total[<NUM_LIT:0>]))<EOL>data_to_center_edges = np.concatenate(<EOL>(<EOL>np.tile(self.targets['<STR_LIT>'], K).T[:, np.newaxis],<EOL>np.array([np.tile(int(i+<NUM_LIT:1>), self.targets.shape[<NUM_LIT:0>]) for i in range(K)]).reshape(self.targets.shape[<NUM_LIT:0>] * K, <NUM_LIT:1>),<EOL>cost_total.T * <NUM_LIT><EOL>),<EOL>axis=<NUM_LIT:1><EOL>).astype(np.uint64)<EOL>g.add_weighted_edges_from(data_to_center_edges)<EOL>a = <NUM_LIT><EOL>g.add_node(a, demand=self.targets.shape[<NUM_LIT:0>] - np.sum(list(demand.values())))<EOL>C_to_a_edges = np.concatenate(<EOL>(<EOL>np.array([int(i + <NUM_LIT:1>) for i in range(K)]).T[:, np.newaxis],<EOL>np.tile([[a, ]], K).T<EOL>),<EOL>axis=<NUM_LIT:1><EOL>)<EOL>g.add_edges_from(C_to_a_edges)<EOL>f = nx.min_cost_flow(g)<EOL>M_new = {}<EOL>p = {}<EOL>for i in list(g.nodes)[:-<NUM_LIT:1>]:<EOL><INDENT>p = sorted(f[i].items(), key=lambda x: x[<NUM_LIT:1>])[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL>M_new[i] = p<EOL><DEDENT>self.targets['<STR_LIT>'] = self.targets.apply(lambda x: M_new[x['<STR_LIT>']], axis=<NUM_LIT:1>)<EOL>C = <NUM_LIT:50><EOL>nx.set_edge_attributes(g, C, '<STR_LIT>')<EOL>if np.all(M_new == M):<EOL><INDENT>print("<STR_LIT>")<EOL>self.results = {<EOL>'<STR_LIT>': M,<EOL>'<STR_LIT>': f,<EOL>'<STR_LIT>': g,<EOL>'<STR_LIT>': self.targets,<EOL>'<STR_LIT>': cost_holder<EOL>}<EOL>return True<EOL><DEDENT>M = M_new<EOL>source_data_holder.append(self.targets['<STR_LIT>'].values)<EOL>if maxiter is not None and itercnt >= maxiter:<EOL><INDENT>self.results = {<EOL>'<STR_LIT>': M,<EOL>'<STR_LIT>': f,<EOL>'<STR_LIT>': g,<EOL>'<STR_LIT>': self.targets,<EOL>'<STR_LIT>': cost_holder<EOL>}<EOL>return True<EOL><DEDENT><DEDENT> | Min Cost Flow | f13513:c0:m4 |
def results_to_table(self): | <EOL>baseline_labels = self.nearest_targets['<STR_LIT>'].values<EOL>mcf_labels = self.results['<STR_LIT>']['<STR_LIT>'].values<EOL>outcome = pd.DataFrame({<EOL>'<STR_LIT>': [<EOL>'<STR_LIT>'.format(lng=v[<NUM_LIT:0>], lat=v[<NUM_LIT:1>])<EOL>for v in zip(self.results['<STR_LIT>']['<STR_LIT>'].values, self.results['<STR_LIT>']['<STR_LIT>'].values)],<EOL>'<STR_LIT>': self.results['<STR_LIT>']['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.results['<STR_LIT>']['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.origins.reindex(baseline_labels)['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.origins.reindex(baseline_labels)['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.results['<STR_LIT>'].target_id,<EOL>'<STR_LIT>': self.results['<STR_LIT>'][self.demand_col].values,<EOL>'<STR_LIT>': baseline_labels<EOL>}<EOL>)<EOL>outcomes2 = pd.DataFrame({<EOL>'<STR_LIT>': [<EOL>'<STR_LIT>'.format(lng=v[<NUM_LIT:0>], lat=v[<NUM_LIT:1>])<EOL>for v in zip(<EOL>self.results['<STR_LIT>']['<STR_LIT>'].values,<EOL>self.results['<STR_LIT>']['<STR_LIT>'].values<EOL>)<EOL>],<EOL>'<STR_LIT>': self.results['<STR_LIT>']['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.results['<STR_LIT>']['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.origins.reindex(mcf_labels)['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.origins.reindex(mcf_labels)['<STR_LIT>'].values,<EOL>'<STR_LIT>': self.results['<STR_LIT>'].target_id,<EOL>'<STR_LIT>': self.results['<STR_LIT>'][self.demand_col].values,<EOL>'<STR_LIT>': mcf_labels<EOL>},<EOL>index=self.results['<STR_LIT>'].target_id<EOL>)<EOL>now = datetime.datetime.now()<EOL>out_table = '<STR_LIT>'.format(now.strftime("<STR_LIT>"))<EOL>logging.info('<STR_LIT>'.format(out_table))<EOL>self.context.write(outcomes2.reset_index(drop=True), out_table)<EOL>logging.info('<STR_LIT>'.format(out_table))<EOL>return out_table<EOL> | Process self.results and send to carto table | f13513:c0:m5 |
def is_profile_in_legacy_format(profile): | if isinstance(profile, dict):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(profile, str):<EOL><INDENT>try:<EOL><INDENT>profile = json.loads(profile)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>if "<STR_LIT>" in profile:<EOL><INDENT>return False<EOL><DEDENT>if "<STR_LIT>" in profile:<EOL><INDENT>return False<EOL><DEDENT>is_in_legacy_format = False<EOL>if "<STR_LIT>" in profile:<EOL><INDENT>is_in_legacy_format = True<EOL><DEDENT>elif "<STR_LIT>" in profile:<EOL><INDENT>is_in_legacy_format = True<EOL><DEDENT>elif "<STR_LIT>" in profile:<EOL><INDENT>is_in_legacy_format = True<EOL><DEDENT>elif "<STR_LIT>" in profile:<EOL><INDENT>is_in_legacy_format = True<EOL><DEDENT>elif "<STR_LIT>" in profile:<EOL><INDENT>is_in_legacy_format = True<EOL><DEDENT>return is_in_legacy_format<EOL> | Is a given profile JSON object in legacy format? | f13516:m1 |
def profile_v3_to_proofs(profile, fqdn, refresh=False, address = None): | proofs = []<EOL>try:<EOL><INDENT>test = list(profile.items())<EOL><DEDENT>except:<EOL><INDENT>return proofs<EOL><DEDENT>if '<STR_LIT>' in profile:<EOL><INDENT>accounts = profile['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return proofs<EOL><DEDENT>for account in accounts:<EOL><INDENT>if '<STR_LIT>' in account and account['<STR_LIT>'].lower() not in SITES:<EOL><INDENT>continue<EOL><DEDENT>if '<STR_LIT>' in account and account['<STR_LIT>'] == "<STR_LIT:http>":<EOL><INDENT>try:<EOL><INDENT>proof = {"<STR_LIT>": account['<STR_LIT>'],<EOL>"<STR_LIT>": account['<STR_LIT>'],<EOL>"<STR_LIT>": account['<STR_LIT>'],<EOL>"<STR_LIT>": False}<EOL>if is_valid_proof(account['<STR_LIT>'], account['<STR_LIT>'],<EOL>fqdn, account['<STR_LIT>'], address = address):<EOL><INDENT>proof["<STR_LIT>"] = True<EOL><DEDENT>proofs.append(proof)<EOL><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>return proofs<EOL> | Convert profile format v3 to proofs | f13519:m5 |
def find_label(label, label_color, label_description): | edit = None<EOL>for name, values in label_list.items():<EOL><INDENT>color, description = values<EOL>if isinstance(name, tuple):<EOL><INDENT>old_name = name[<NUM_LIT:0>]<EOL>new_name = name[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>old_name = name<EOL>new_name = name<EOL><DEDENT>if label.lower() == old_name.lower():<EOL><INDENT>edit = LabelEdit(old_name, new_name, color, description)<EOL>break<EOL><DEDENT><DEDENT>return edit<EOL> | Find label. | f13524:m0 |
def update_labels(repo): | updated = set()<EOL>for label in repo.get_labels():<EOL><INDENT>edit = find_label(label.name, label.color, label.description)<EOL>if edit is not None:<EOL><INDENT>print('<STR_LIT>'.format(edit.new, edit.color, edit.description))<EOL>label.edit(edit.new, edit.color, edit.description)<EOL>updated.add(edit.old)<EOL>updated.add(edit.new)<EOL><DEDENT>else:<EOL><INDENT>if DELETE_UNSPECIFIED:<EOL><INDENT>print('<STR_LIT>'.format(label.name, label.color, label.description))<EOL>label.delete()<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'.format(label.name, label.color, label.description))<EOL><DEDENT>updated.add(label.name)<EOL><DEDENT><DEDENT>for name, values in label_list.items():<EOL><INDENT>color, description = values<EOL>if isinstance(name, tuple):<EOL><INDENT>new_name = name[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>new_name = name<EOL><DEDENT>if new_name not in updated:<EOL><INDENT>print('<STR_LIT>'.format(new_name, color, description))<EOL>repo.create_label(new_name, color, description)<EOL><DEDENT><DEDENT> | Update labels. | f13524:m1 |
def get_auth(): | import getpass<EOL>user = input("<STR_LIT>") <EOL>pswd = getpass.getpass('<STR_LIT>')<EOL>return Github(user, pswd)<EOL> | Get authentication. | f13524:m2 |
def main(): | if len(sys.argv) > <NUM_LIT:1> and os.path.exists(sys.argv[<NUM_LIT:1>]):<EOL><INDENT>try:<EOL><INDENT>with open(sys.argv[<NUM_LIT:1>], '<STR_LIT:r>') as f:<EOL><INDENT>user_name, password = f.read().strip().split('<STR_LIT::>')<EOL><DEDENT>git = Github(user_name, password)<EOL>password = None<EOL><DEDENT>except Exception:<EOL><INDENT>git = get_auth()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>git = get_auth()<EOL><DEDENT>user = git.get_user()<EOL>print('<STR_LIT>')<EOL>for repo in user.get_repos():<EOL><INDENT>if repo.owner.name == user.name:<EOL><INDENT>if repo.name == REPO_NAME:<EOL><INDENT>print(repo.name)<EOL>update_labels(repo)<EOL>break<EOL><DEDENT><DEDENT><DEDENT> | Main. | f13524:m3 |
def setUp(self): | sv.purge()<EOL>self.quirks = True<EOL> | Setup. | f13525:c2:m0 |
def skip_quirks(func): | def skip_if(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if self.quirks is True:<EOL><INDENT>raise pytest.skip('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return skip_if<EOL> | Decorator that skips when quirks mode is enabled. | f13526:m0 |
def skip_py3(func): | def skip_if(self, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if PY3:<EOL><INDENT>raise pytest.skip('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return func(self, *args, **kwargs)<EOL><DEDENT><DEDENT>return skip_if<EOL> | Decorator that skips when running in Python 3. | f13526:m1 |
def available_parsers(*parsers): | ran_test = False<EOL>for parser in parsers:<EOL><INDENT>if (<EOL>(parser in ('<STR_LIT>', '<STR_LIT>') and not LXML_PRESENT) or<EOL>(parser == '<STR_LIT>' and not HTML5LIB_PRESENT)<EOL>):<EOL><INDENT>print('<STR_LIT>'.format(parser))<EOL><DEDENT>else:<EOL><INDENT>ran_test = True<EOL>yield parser<EOL><DEDENT><DEDENT>if not ran_test:<EOL><INDENT>raise pytest.skip('<STR_LIT>')<EOL><DEDENT> | Filter a list of parsers, down to the available ones.
If there are none, report the test as skipped to pytest. | f13526:m2 |
def wrap_xhtml(self, html): | return """<STR_LIT>""".format(html)<EOL> | Wrap HTML content with XHTML header and body. | f13526:c0:m0 |
def setUp(self): | sv.purge()<EOL>self.quirks = False<EOL> | Setup. | f13526:c0:m1 |
def purge(self): | sv.purge()<EOL> | Purge cache. | f13526:c0:m2 |
def compile_pattern(self, selectors, namespaces=None, custom=None, flags=<NUM_LIT:0>): | print('<STR_LIT>', selectors)<EOL>flags |= sv.DEBUG<EOL>if self.quirks:<EOL><INDENT>flags |= sv._QUIRKS<EOL><DEDENT>return sv.compile(selectors, namespaces=namespaces, custom=custom, flags=flags)<EOL> | Compile pattern. | f13526:c0:m3 |
def soup(self, markup, parser): | print('<STR_LIT>', parser)<EOL>return bs4.BeautifulSoup(textwrap.dedent(markup.replace('<STR_LIT:\r\n>', '<STR_LIT:\n>')), parser)<EOL> | Get soup. | f13526:c0:m4 |
def get_parsers(self, flags): | mode = flags & <NUM_LIT><EOL>if mode == HTML:<EOL><INDENT>parsers = ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>elif mode == PYHTML:<EOL><INDENT>parsers = ('<STR_LIT>',)<EOL><DEDENT>elif mode == LXML_HTML:<EOL><INDENT>parsers = ('<STR_LIT>',)<EOL><DEDENT>elif mode in (HTML5, <NUM_LIT:0>):<EOL><INDENT>parsers = ('<STR_LIT>',)<EOL><DEDENT>elif mode in (XHTML, XML):<EOL><INDENT>parsers = ('<STR_LIT>',)<EOL><DEDENT>return parsers<EOL> | Get parsers. | f13526:c0:m5 |
def assert_raises(self, pattern, exception, namespace=None, custom=None): | print('<STR_LIT>')<EOL>with self.assertRaises(exception):<EOL><INDENT>self.compile_pattern(pattern, namespaces=namespace, custom=custom)<EOL><DEDENT> | Assert raises. | f13526:c0:m6 |
def assert_selector(self, markup, selectors, expected_ids, namespaces={}, custom=None, flags=<NUM_LIT:0>): | parsers = self.get_parsers(flags)<EOL>print('<STR_LIT>')<EOL>selector = self.compile_pattern(selectors, namespaces, custom)<EOL>for parser in available_parsers(*parsers):<EOL><INDENT>soup = self.soup(markup, parser)<EOL>ids = []<EOL>for el in selector.select(soup):<EOL><INDENT>print('<STR_LIT>', el.name)<EOL>ids.append(el.attrs['<STR_LIT:id>'])<EOL><DEDENT>self.assertEqual(sorted(ids), sorted(expected_ids))<EOL><DEDENT> | Assert selector. | f13526:c0:m7 |
def setUp(self): | self.purge()<EOL>self.quirks = True<EOL> | Setup. | f13527:c1:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.