idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
246,700
def initialize_labels ( self , labels : Set [ str ] ) -> Tuple [ dict , dict ] : logger . debug ( "Creating mappings for labels" ) label_to_index = { label : index for index , label in enumerate ( [ "pad" ] + sorted ( list ( labels ) ) ) } index_to_label = { index : phn for index , phn in enumerate ( [ "pad" ] + sorted...
Create mappings from label to index and index to label
246,701
def prepare_feats ( self ) -> None : logger . debug ( "Preparing input features" ) self . feat_dir . mkdir ( parents = True , exist_ok = True ) should_extract_feats = False for path in self . wav_dir . iterdir ( ) : if not path . suffix == ".wav" : logger . info ( "Non wav file found in wav directory: %s" , path ) cont...
Prepares input features
246,702
def make_data_splits ( self , max_samples : int ) -> None : train_f_exists = self . train_prefix_fn . is_file ( ) valid_f_exists = self . valid_prefix_fn . is_file ( ) test_f_exists = self . test_prefix_fn . is_file ( ) if train_f_exists and valid_f_exists and test_f_exists : logger . debug ( "Split for training, valid...
Splits the utterances into training validation and test sets .
246,703
def divide_prefixes ( prefixes : List [ str ] , seed : int = 0 ) -> Tuple [ List [ str ] , List [ str ] , List [ str ] ] : if len ( prefixes ) < 3 : raise PersephoneException ( "{} cannot be split into 3 groups as it only has {} items" . format ( prefixes , len ( prefixes ) ) ) Ratios = namedtuple ( "Ratios" , [ "train...
Divide data into training validation and test subsets
246,704
def indices_to_labels ( self , indices : Sequence [ int ] ) -> List [ str ] : return [ ( self . INDEX_TO_LABEL [ index ] ) for index in indices ]
Converts a sequence of indices into their corresponding labels .
246,705
def labels_to_indices ( self , labels : Sequence [ str ] ) -> List [ int ] : return [ self . LABEL_TO_INDEX [ label ] for label in labels ]
Converts a sequence of labels into their corresponding indices .
246,706
def num_feats ( self ) : if not self . _num_feats : filename = self . get_train_fns ( ) [ 0 ] [ 0 ] feats = np . load ( filename ) if len ( feats . shape ) == 3 : self . _num_feats = feats . shape [ 1 ] * feats . shape [ 2 ] elif len ( feats . shape ) == 2 : self . _num_feats = feats . shape [ 1 ] else : raise ValueErr...
The number of features per time step in the corpus .
246,707
def prefixes_to_fns ( self , prefixes : List [ str ] ) -> Tuple [ List [ str ] , List [ str ] ] : feat_fns = [ str ( self . feat_dir / ( "%s.%s.npy" % ( prefix , self . feat_type ) ) ) for prefix in prefixes ] label_fns = [ str ( self . label_dir / ( "%s.%s" % ( prefix , self . label_type ) ) ) for prefix in prefixes ]...
Fetches the file paths to the features files and labels files corresponding to the provided list of features
246,708
def get_train_fns ( self ) -> Tuple [ List [ str ] , List [ str ] ] : return self . prefixes_to_fns ( self . train_prefixes )
Fetches the training set of the corpus .
246,709
def get_valid_fns ( self ) -> Tuple [ List [ str ] , List [ str ] ] : return self . prefixes_to_fns ( self . valid_prefixes )
Fetches the validation set of the corpus .
246,710
def review ( self ) -> None : for prefix in self . determine_prefixes ( ) : print ( "Utterance: {}" . format ( prefix ) ) wav_fn = self . feat_dir / "{}.wav" . format ( prefix ) label_fn = self . label_dir / "{}.{}" . format ( prefix , self . label_type ) with label_fn . open ( ) as f : transcript = f . read ( ) . stri...
Used to play the WAV files and compare with the transcription .
246,711
def pickle ( self ) -> None : pickle_path = self . tgt_dir / "corpus.p" logger . debug ( "pickling %r object and saving it to path %s" , self , pickle_path ) with pickle_path . open ( "wb" ) as f : pickle . dump ( self , f )
Pickles the Corpus object in a file in tgt_dir .
246,712
def zero_pad ( matrix , to_length ) : assert matrix . shape [ 0 ] <= to_length if not matrix . shape [ 0 ] <= to_length : logger . error ( "zero_pad cannot be performed on matrix with shape {}" " to length {}" . format ( matrix . shape [ 0 ] , to_length ) ) raise ValueError result = np . zeros ( ( to_length , ) + matri...
Zero pads along the 0th dimension to make sure the utterance array x is of length to_length .
246,713
def load_batch_x ( path_batch , flatten = False , time_major = False ) : utterances = [ np . load ( str ( path ) ) for path in path_batch ] utter_lens = [ utterance . shape [ 0 ] for utterance in utterances ] max_len = max ( utter_lens ) batch_size = len ( path_batch ) shape = ( batch_size , max_len ) + tuple ( utteran...
Loads a batch of input features given a list of paths to numpy arrays in that batch .
246,714
def batch_per ( hyps : Sequence [ Sequence [ T ] ] , refs : Sequence [ Sequence [ T ] ] ) -> float : macro_per = 0.0 for i in range ( len ( hyps ) ) : ref = [ phn_i for phn_i in refs [ i ] if phn_i != 0 ] hyp = [ phn_i for phn_i in hyps [ i ] if phn_i != 0 ] macro_per += distance . edit_distance ( ref , hyp ) / len ( r...
Calculates the phoneme error rate of a batch .
246,715
def filter_by_size ( feat_dir : Path , prefixes : List [ str ] , feat_type : str , max_samples : int ) -> List [ str ] : prefix_lens = get_prefix_lens ( Path ( feat_dir ) , prefixes , feat_type ) prefixes = [ prefix for prefix , length in prefix_lens if length <= max_samples ] return prefixes
Sorts the files by their length and returns those with less than or equal to max_samples length . Returns the filename prefixes of those files . The main job of the method is to filter but the sorting may give better efficiency when doing dynamic batching unless it gets shuffled downstream .
246,716
def wav_length ( fn : str ) -> float : args = [ config . SOX_PATH , fn , "-n" , "stat" ] p = subprocess . Popen ( args , stdin = PIPE , stdout = PIPE , stderr = PIPE ) length_line = str ( p . communicate ( ) [ 1 ] ) . split ( "\\n" ) [ 1 ] . split ( ) print ( length_line ) assert length_line [ 0 ] == "Length" return fl...
Returns the length of the WAV file in seconds .
246,717
def pull_en_words ( ) -> None : ENGLISH_WORDS_URL = "https://github.com/dwyl/english-words.git" en_words_path = Path ( config . EN_WORDS_PATH ) if not en_words_path . is_file ( ) : subprocess . run ( [ "git" , "clone" , ENGLISH_WORDS_URL , str ( en_words_path . parent ) ] )
Fetches a repository containing English words .
246,718
def get_en_words ( ) -> Set [ str ] : pull_en_words ( ) with open ( config . EN_WORDS_PATH ) as words_f : raw_words = words_f . readlines ( ) en_words = set ( [ word . strip ( ) . lower ( ) for word in raw_words ] ) NA_WORDS_IN_EN_DICT = set ( [ "kore" , "nani" , "karri" , "imi" , "o" , "yaw" , "i" , "bi" , "aye" , "im...
Returns a list of English words which can be used to filter out code - switched sentences .
246,719
def explore_elan_files ( elan_paths ) : for elan_path in elan_paths : print ( elan_path ) eafob = Eaf ( elan_path ) tier_names = eafob . get_tier_names ( ) for tier in tier_names : print ( "\t" , tier ) try : for annotation in eafob . get_annotation_data_for_tier ( tier ) : print ( "\t\t" , annotation ) except KeyError...
A function to explore the tiers of ELAN files .
246,720
def sort_annotations ( annotations : List [ Tuple [ int , int , str ] ] ) -> List [ Tuple [ int , int , str ] ] : return sorted ( annotations , key = lambda x : x [ 0 ] )
Sorts the annotations by their start_time .
246,721
def utterances_from_tier ( eafob : Eaf , tier_name : str ) -> List [ Utterance ] : try : speaker = eafob . tiers [ tier_name ] [ 2 ] [ "PARTICIPANT" ] except KeyError : speaker = None tier_utterances = [ ] annotations = sort_annotations ( list ( eafob . get_annotation_data_for_tier ( tier_name ) ) ) for i , annotation ...
Returns utterances found in the given Eaf object in the given tier .
246,722
def utterances_from_eaf ( eaf_path : Path , tier_prefixes : Tuple [ str , ... ] ) -> List [ Utterance ] : if not eaf_path . is_file ( ) : raise FileNotFoundError ( "Cannot find {}" . format ( eaf_path ) ) eaf = Eaf ( eaf_path ) utterances = [ ] for tier_name in sorted ( list ( eaf . tiers ) ) : for tier_prefix in tier_...
Extracts utterances in tiers that start with tier_prefixes found in the ELAN . eaf XML file at eaf_path .
246,723
def utterances_from_dir ( eaf_dir : Path , tier_prefixes : Tuple [ str , ... ] ) -> List [ Utterance ] : logger . info ( "EAF from directory: {}, searching with tier_prefixes {}" . format ( eaf_dir , tier_prefixes ) ) utterances = [ ] for eaf_path in eaf_dir . glob ( "**/*.eaf" ) : eaf_utterances = utterances_from_eaf ...
Returns the utterances found in ELAN files in a directory .
246,724
def load_batch ( self , fn_batch ) : inverse = list ( zip ( * fn_batch ) ) feat_fn_batch = inverse [ 0 ] target_fn_batch = inverse [ 1 ] batch_inputs , batch_inputs_lens = utils . load_batch_x ( feat_fn_batch , flatten = False ) batch_targets_list = [ ] for targets_path in target_fn_batch : with open ( targets_path , e...
Loads a batch with the given prefixes . The prefixes is the full path to the training example minus the extension .
246,725
def train_batch_gen ( self ) -> Iterator : if len ( self . train_fns ) == 0 : raise PersephoneException ( ) fn_batches = self . make_batches ( self . train_fns ) if self . rand : random . shuffle ( fn_batches ) for fn_batch in fn_batches : logger . debug ( "Batch of training filenames: %s" , pprint . pformat ( fn_batch...
Returns a generator that outputs batches in the training data .
246,726
def valid_batch ( self ) : valid_fns = list ( zip ( * self . corpus . get_valid_fns ( ) ) ) return self . load_batch ( valid_fns )
Returns a single batch with all the validation cases .
246,727
def untranscribed_batch_gen ( self ) : feat_fns = self . corpus . get_untranscribed_fns ( ) fn_batches = self . make_batches ( feat_fns ) for fn_batch in fn_batches : batch_inputs , batch_inputs_lens = utils . load_batch_x ( fn_batch , flatten = False ) yield batch_inputs , batch_inputs_lens , fn_batch
A batch generator for all the untranscribed data .
246,728
def human_readable_hyp_ref ( self , dense_decoded , dense_y ) : hyps = [ ] refs = [ ] for i in range ( len ( dense_decoded ) ) : ref = [ phn_i for phn_i in dense_y [ i ] if phn_i != 0 ] hyp = [ phn_i for phn_i in dense_decoded [ i ] if phn_i != 0 ] ref = self . corpus . indices_to_labels ( ref ) hyp = self . corpus . i...
Returns a human readable version of the hypothesis for manual inspection along with the reference .
246,729
def human_readable ( self , dense_repr : Sequence [ Sequence [ int ] ] ) -> List [ List [ str ] ] : transcripts = [ ] for dense_r in dense_repr : non_empty_phonemes = [ phn_i for phn_i in dense_r if phn_i != 0 ] transcript = self . corpus . indices_to_labels ( non_empty_phonemes ) transcripts . append ( transcript ) re...
Returns a human readable version of a dense representation of either or reference to facilitate simple manual inspection .
246,730
def calc_time ( self ) -> None : def get_number_of_frames ( feat_fns ) : total = 0 for feat_fn in feat_fns : num_frames = len ( np . load ( feat_fn ) ) total += num_frames return total def numframes_to_minutes ( num_frames ) : minutes = ( ( num_frames * 10 ) / 1000 ) / 60 return minutes total_frames = 0 train_fns = [ t...
Prints statistics about the the total duration of recordings in the corpus .
246,731
def lstm_cell ( hidden_size ) : return tf . contrib . rnn . LSTMCell ( hidden_size , use_peepholes = True , state_is_tuple = True )
Wrapper function to create an LSTM cell .
246,732
def write_desc ( self ) -> None : path = os . path . join ( self . exp_dir , "model_description.txt" ) with open ( path , "w" ) as desc_f : for key , val in self . __dict__ . items ( ) : print ( "%s=%s" % ( key , val ) , file = desc_f ) import json json_path = os . path . join ( self . exp_dir , "model_description.json...
Writes a description of the model to the exp_dir .
246,733
def empty_wav ( wav_path : Union [ Path , str ] ) -> bool : with wave . open ( str ( wav_path ) , 'rb' ) as wav_f : return wav_f . getnframes ( ) == 0
Check if a wav contains data
246,734
def extract_energy ( rate , sig ) : mfcc = python_speech_features . mfcc ( sig , rate , appendEnergy = True ) energy_row_vec = mfcc [ : , 0 ] energy_col_vec = energy_row_vec [ : , np . newaxis ] return energy_col_vec
Extracts the energy of frames .
246,735
def fbank ( wav_path , flat = True ) : ( rate , sig ) = wav . read ( wav_path ) if len ( sig ) == 0 : logger . warning ( "Empty wav: {}" . format ( wav_path ) ) fbank_feat = python_speech_features . logfbank ( sig , rate , nfilt = 40 ) energy = extract_energy ( rate , sig ) feat = np . hstack ( [ energy , fbank_feat ] ...
Currently grabs log Mel filterbank deltas and double deltas .
246,736
def mfcc ( wav_path ) : ( rate , sig ) = wav . read ( wav_path ) feat = python_speech_features . mfcc ( sig , rate , appendEnergy = True ) delta_feat = python_speech_features . delta ( feat , 2 ) all_feats = [ feat , delta_feat ] all_feats = np . array ( all_feats ) all_feats = np . swapaxes ( all_feats , 0 , 1 ) all_f...
Grabs MFCC features with energy and derivates .
246,737
def from_dir ( dirpath : Path , feat_type : str ) -> None : logger . info ( "Extracting features from directory {}" . format ( dirpath ) ) dirname = str ( dirpath ) def all_wavs_processed ( ) -> bool : for fn in os . listdir ( dirname ) : prefix , ext = os . path . splitext ( fn ) if ext == ".wav" : if not os . path . ...
Performs feature extraction from the WAV files in a directory .
246,738
def convert_wav ( org_wav_fn : Path , tgt_wav_fn : Path ) -> None : if not org_wav_fn . exists ( ) : raise FileNotFoundError args = [ config . FFMPEG_PATH , "-i" , str ( org_wav_fn ) , "-ac" , "1" , "-ar" , "16000" , str ( tgt_wav_fn ) ] subprocess . run ( args )
Converts the wav into a 16bit mono 16000Hz wav .
246,739
def kaldi_pitch ( wav_dir : str , feat_dir : str ) -> None : logger . debug ( "Make wav.scp and pitch.scp files" ) prefixes = [ ] for fn in os . listdir ( wav_dir ) : prefix , ext = os . path . splitext ( fn ) if ext == ".wav" : prefixes . append ( prefix ) wav_scp_path = os . path . join ( feat_dir , "wavs.scp" ) with...
Extract Kaldi pitch features . Assumes 16k mono wav files .
246,740
def get_exp_dir_num ( parent_dir : str ) -> int : return max ( [ int ( fn . split ( "." ) [ 0 ] ) for fn in os . listdir ( parent_dir ) if fn . split ( "." ) [ 0 ] . isdigit ( ) ] + [ - 1 ] )
Gets the number of the current experiment directory .
246,741
def transcribe ( model_path , corpus ) : exp_dir = prep_exp_dir ( ) model = get_simple_model ( exp_dir , corpus ) model . transcribe ( model_path )
Applies a trained model to untranscribed data in a Corpus .
246,742
def trim_wav_ms ( in_path : Path , out_path : Path , start_time : int , end_time : int ) -> None : try : trim_wav_sox ( in_path , out_path , start_time , end_time ) except FileNotFoundError : trim_wav_pydub ( in_path , out_path , start_time , end_time ) except subprocess . CalledProcessError : trim_wav_pydub ( in_path ...
Extracts part of a WAV File .
246,743
def trim_wav_pydub ( in_path : Path , out_path : Path , start_time : int , end_time : int ) -> None : logger . info ( "Using pydub/ffmpeg to create {} from {}" . format ( out_path , in_path ) + " using a start_time of {} and an end_time of {}" . format ( start_time , end_time ) ) if out_path . is_file ( ) : return in_e...
Crops the wav file .
246,744
def trim_wav_sox ( in_path : Path , out_path : Path , start_time : int , end_time : int ) -> None : if out_path . is_file ( ) : logger . info ( "Output path %s already exists, not trimming file" , out_path ) return start_time_secs = millisecs_to_secs ( start_time ) end_time_secs = millisecs_to_secs ( end_time ) args = ...
Crops the wav file at in_fn so that the audio between start_time and end_time is output to out_fn . Measured in milliseconds .
246,745
def extract_wavs ( utterances : List [ Utterance ] , tgt_dir : Path , lazy : bool ) -> None : tgt_dir . mkdir ( parents = True , exist_ok = True ) for utter in utterances : wav_fn = "{}.{}" . format ( utter . prefix , "wav" ) out_wav_path = tgt_dir / wav_fn if lazy and out_wav_path . is_file ( ) : logger . info ( "File...
Extracts WAVs from the media files associated with a list of Utterance objects and stores it in a target directory .
246,746
def filter_labels ( sent : Sequence [ str ] , labels : Set [ str ] = None ) -> List [ str ] : if labels : return [ tok for tok in sent if tok in labels ] return list ( sent )
Returns only the tokens present in the sentence that are in labels .
246,747
def filtered_error_rate ( hyps_path : Union [ str , Path ] , refs_path : Union [ str , Path ] , labels : Set [ str ] ) -> float : if isinstance ( hyps_path , Path ) : hyps_path = str ( hyps_path ) if isinstance ( refs_path , Path ) : refs_path = str ( refs_path ) with open ( hyps_path ) as hyps_f : lines = hyps_f . rea...
Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels .
246,748
def fmt_latex_output ( hyps : Sequence [ Sequence [ str ] ] , refs : Sequence [ Sequence [ str ] ] , prefixes : Sequence [ str ] , out_fn : Path , ) -> None : alignments_ = [ min_edit_distance_align ( ref , hyp ) for hyp , ref in zip ( hyps , refs ) ] with out_fn . open ( "w" ) as out_f : print ( latex_header ( ) , fil...
Output the hypotheses and references to a LaTeX source file for pretty printing .
246,749
def fmt_confusion_matrix ( hyps : Sequence [ Sequence [ str ] ] , refs : Sequence [ Sequence [ str ] ] , label_set : Set [ str ] = None , max_width : int = 25 ) -> str : if not label_set : raise NotImplementedError ( ) alignments = [ min_edit_distance_align ( ref , hyp ) for hyp , ref in zip ( hyps , refs ) ] arrow_cou...
Formats a confusion matrix over substitutions ignoring insertions and deletions .
246,750
def fmt_latex_untranscribed ( hyps : Sequence [ Sequence [ str ] ] , prefixes : Sequence [ str ] , out_fn : Path ) -> None : hyps_prefixes = list ( zip ( hyps , prefixes ) ) def utter_id_key ( hyp_prefix ) : hyp , prefix = hyp_prefix prefix_split = prefix . split ( "." ) return ( prefix_split [ 0 ] , int ( prefix_split...
Formats automatic hypotheses that have not previously been transcribed in LaTeX .
246,751
def segment_into_chars ( utterance : str ) -> str : if not isinstance ( utterance , str ) : raise TypeError ( "Input type must be a string. Got {}." . format ( type ( utterance ) ) ) utterance . strip ( ) utterance = utterance . replace ( " " , "" ) return " " . join ( utterance )
Segments an utterance into space delimited characters .
246,752
def make_indices_to_labels ( labels : Set [ str ] ) -> Dict [ int , str ] : return { index : label for index , label in enumerate ( [ "pad" ] + sorted ( list ( labels ) ) ) }
Creates a mapping from indices to labels .
246,753
def preprocess_french ( trans , fr_nlp , remove_brackets_content = True ) : if remove_brackets_content : trans = pangloss . remove_content_in_brackets ( trans , "[]" ) trans = fr_nlp ( " " . join ( trans . split ( ) [ : ] ) ) trans = " " . join ( [ token . lower_ for token in trans if not token . is_punct ] ) return tr...
Takes a list of sentences in french and preprocesses them .
246,754
def trim_wavs ( org_wav_dir = ORG_WAV_DIR , tgt_wav_dir = TGT_WAV_DIR , org_xml_dir = ORG_XML_DIR ) : logging . info ( "Trimming wavs..." ) if not os . path . exists ( os . path . join ( tgt_wav_dir , "TEXT" ) ) : os . makedirs ( os . path . join ( tgt_wav_dir , "TEXT" ) ) if not os . path . exists ( os . path . join (...
Extracts sentence - level transcriptions translations and wavs from the Na Pangloss XML and WAV files . But otherwise doesn t preprocess them .
246,755
def prepare_labels ( label_type , org_xml_dir = ORG_XML_DIR , label_dir = LABEL_DIR ) : if not os . path . exists ( os . path . join ( label_dir , "TEXT" ) ) : os . makedirs ( os . path . join ( label_dir , "TEXT" ) ) if not os . path . exists ( os . path . join ( label_dir , "WORDLIST" ) ) : os . makedirs ( os . path ...
Prepare the neural network output targets .
246,756
def prepare_untran ( feat_type , tgt_dir , untran_dir ) : org_dir = str ( untran_dir ) wav_dir = os . path . join ( str ( tgt_dir ) , "wav" , "untranscribed" ) feat_dir = os . path . join ( str ( tgt_dir ) , "feat" , "untranscribed" ) if not os . path . isdir ( wav_dir ) : os . makedirs ( wav_dir ) if not os . path . i...
Preprocesses untranscribed audio .
246,757
def prepare_feats ( feat_type , org_wav_dir = ORG_WAV_DIR , feat_dir = FEAT_DIR , tgt_wav_dir = TGT_WAV_DIR , org_xml_dir = ORG_XML_DIR , label_dir = LABEL_DIR ) : if not os . path . isdir ( TGT_DIR ) : os . makedirs ( TGT_DIR ) if not os . path . isdir ( FEAT_DIR ) : os . makedirs ( FEAT_DIR ) if not os . path . isdir...
Prepare the input features .
246,758
def get_story_prefixes ( label_type , label_dir = LABEL_DIR ) : prefixes = [ prefix for prefix in os . listdir ( os . path . join ( label_dir , "TEXT" ) ) if prefix . endswith ( ".%s" % label_type ) ] prefixes = [ os . path . splitext ( os . path . join ( "TEXT" , prefix ) ) [ 0 ] for prefix in prefixes ] return prefix...
Gets the Na text prefixes .
246,759
def get_stories ( label_type ) : prefixes = get_story_prefixes ( label_type ) texts = list ( set ( [ prefix . split ( "." ) [ 0 ] . split ( "/" ) [ 1 ] for prefix in prefixes ] ) ) return texts
Returns a list of the stories in the Na corpus .
246,760
def make_data_splits ( self , max_samples , valid_story = None , test_story = None ) : if valid_story or test_story : if not ( valid_story and test_story ) : raise PersephoneException ( "We need a valid story if we specify a test story " "and vice versa. This shouldn't be required but for " "now it is." ) train , valid...
Split data into train valid and test groups
246,761
def output_story_prefixes ( self ) : if not self . test_story : raise NotImplementedError ( "I want to write the prefixes to a file" "called <test_story>_prefixes.txt, but there's no test_story." ) fn = os . path . join ( TGT_DIR , "%s_prefixes.txt" % self . test_story ) with open ( fn , "w" ) as f : for utter_id in se...
Writes the set of prefixes to a file this is useful for pretty printing in results . latex_output .
246,762
def add_data_file ( data_files , target , source ) : for t , f in data_files : if t == target : break else : data_files . append ( ( target , [ ] ) ) f = data_files [ - 1 ] [ 1 ] if source not in f : f . append ( source )
Add an entry to data_files
246,763
def get_q_home ( env ) : q_home = env . get ( 'QHOME' ) if q_home : return q_home for v in [ 'VIRTUAL_ENV' , 'HOME' ] : prefix = env . get ( v ) if prefix : q_home = os . path . join ( prefix , 'q' ) if os . path . isdir ( q_home ) : return q_home if WINDOWS : q_home = os . path . join ( env [ 'SystemDrive' ] , r'\q' )...
Derive q home from the environment
246,764
def get_q_version ( q_home ) : with open ( os . path . join ( q_home , 'q.k' ) ) as f : for line in f : if line . startswith ( 'k:' ) : return line [ 2 : 5 ] return '2.2'
Return version of q installed at q_home
246,765
def precmd ( self , line ) : if line . startswith ( 'help' ) : if not q ( "`help in key`.q" ) : try : q ( "\\l help.q" ) except kerr : return '-1"no help available - install help.q"' if line == 'help' : line += "`" return line
Support for help
246,766
def onecmd ( self , line ) : if line == '\\' : return True elif line == 'EOF' : print ( '\r' , end = '' ) return True else : try : v = q ( line ) except kerr as e : print ( "'%s" % e . args [ 0 ] ) else : if v != q ( '::' ) : v . show ( ) return False
Interpret the line
246,767
def run ( q_prompt = False ) : lines , columns = console_size ( ) q ( r'\c %d %d' % ( lines , columns ) ) if len ( sys . argv ) > 1 : try : q ( r'\l %s' % sys . argv [ 1 ] ) except kerr as e : print ( e ) raise SystemExit ( 1 ) else : del sys . argv [ 1 ] if q_prompt : q ( ) ptp . run ( )
Run a prompt - toolkit based REPL
246,768
def get_unit ( a ) : typestr = a . dtype . str i = typestr . find ( '[' ) if i == - 1 : raise TypeError ( "Expected a datetime64 array, not %s" , a . dtype ) return typestr [ i + 1 : - 1 ]
Extract the time unit from array s dtype
246,769
def k2a ( a , x ) : func , scale = None , 1 t = abs ( x . _t ) if 12 <= t <= 15 : unit = get_unit ( a ) attr , shift , func , scale = _UNIT [ unit ] a [ : ] = getattr ( x , attr ) . data a += shift elif 16 <= t <= 19 : unit = get_unit ( a ) func , scale = _SCALE [ unit ] a [ : ] = x . timespan . data else : a [ : ] = l...
Rescale data from a K object x to array a .
246,770
def show ( self , start = 0 , geometry = None , output = None ) : if output is None : output = sys . stdout if geometry is None : geometry = q . value ( kp ( "\\c" ) ) else : geometry = self . _I ( geometry ) if start < 0 : start += q . count ( self ) if self . _id ( ) != nil . _id ( ) : r = self . _show ( geometry , s...
pretty - print data to the console
246,771
def select ( self , columns = ( ) , by = ( ) , where = ( ) , ** kwds ) : return self . _seu ( 'select' , columns , by , where , kwds )
select from self
246,772
def exec_ ( self , columns = ( ) , by = ( ) , where = ( ) , ** kwds ) : return self . _seu ( 'exec' , columns , by , where , kwds )
exec from self
246,773
def update ( self , columns = ( ) , by = ( ) , where = ( ) , ** kwds ) : return self . _seu ( 'update' , columns , by , where , kwds )
update from self
246,774
def dict ( cls , * args , ** kwds ) : if args : if len ( args ) > 1 : raise TypeError ( "Too many positional arguments" ) x = args [ 0 ] keys = [ ] vals = [ ] try : x_keys = x . keys except AttributeError : for k , v in x : keys . append ( k ) vals . append ( v ) else : keys = x_keys ( ) vals = [ x [ k ] for k in keys ...
Construct a q dictionary
246,775
def logical_lines ( lines ) : if isinstance ( lines , string_types ) : lines = StringIO ( lines ) buf = [ ] for line in lines : if buf and not line . startswith ( ' ' ) : chunk = '' . join ( buf ) . strip ( ) if chunk : yield chunk buf [ : ] = [ ] buf . append ( line ) chunk = '' . join ( buf ) . strip ( ) if chunk : y...
Merge lines into chunks according to q rules
246,776
def q ( line , cell = None , _ns = None ) : if cell is None : return pyq . q ( line ) if _ns is None : _ns = vars ( sys . modules [ '__main__' ] ) input = output = None preload = [ ] outs = { } try : h = pyq . q ( '0i' ) if line : for opt , value in getopt ( line . split ( ) , "h:l:o:i:12" ) [ 0 ] : if opt == '-l' : pr...
Run q code .
246,777
def load_ipython_extension ( ipython ) : ipython . register_magic_function ( q , 'line_cell' ) fmr = ipython . display_formatter . formatters [ 'text/plain' ] fmr . for_type ( pyq . K , _q_formatter )
Register %q and %%q magics and pretty display for K objects
246,778
def get_prompt_tokens ( _ ) : namespace = q ( r'\d' ) if namespace == '.' : namespace = '' return [ ( Token . Generic . Prompt , 'q%s)' % namespace ) ]
Return a list of tokens for the prompt
246,779
def cmdloop ( self , intro = None ) : style = style_from_pygments ( BasicStyle , style_dict ) self . preloop ( ) stop = None while not stop : line = prompt ( get_prompt_tokens = get_prompt_tokens , lexer = lexer , get_bottom_toolbar_tokens = get_bottom_toolbar_tokens , history = history , style = style , true_color = T...
A Cmd . cmdloop implementation
246,780
def eval ( source , kwd_dict = None , ** kwds ) : kwd_dict = kwd_dict or kwds with ctx ( kwd_dict ) : return handleLine ( source )
Evaluate a snuggs expression .
246,781
def _make_matchers ( self , crontab ) : crontab = _aliases . get ( crontab , crontab ) ct = crontab . split ( ) if len ( ct ) == 5 : ct . insert ( 0 , '0' ) ct . append ( '*' ) elif len ( ct ) == 6 : ct . insert ( 0 , '0' ) _assert ( len ( ct ) == 7 , "improper number of cron entries specified; got %i need 5 to 7" % ( ...
This constructs the full matcher struct .
246,782
def next ( self , now = None , increments = _increments , delta = True , default_utc = WARN_CHANGE ) : if default_utc is WARN_CHANGE and ( isinstance ( now , _number_types ) or ( now and not now . tzinfo ) or now is None ) : warnings . warn ( WARNING_CHANGE_MESSAGE , FutureWarning , 2 ) default_utc = False now = now or...
How long to wait in seconds before this crontab entry can next be executed .
246,783
def _tostring ( value ) : if value is True : value = 'true' elif value is False : value = 'false' elif value is None : value = '' return unicode ( value )
Convert value to XML compatible string
246,784
def _fromstring ( value ) : if value is None : return None if value . lower ( ) == 'true' : return True elif value . lower ( ) == 'false' : return False try : return int ( value ) except ValueError : pass try : if float ( '-inf' ) < float ( value ) < float ( 'inf' ) : return float ( value ) except ValueError : pass ret...
Convert XML string value to None boolean int or float
246,785
def by_col ( cls , df , cols , w = None , inplace = False , pvalue = 'sim' , outvals = None , ** stat_kws ) : if outvals is None : outvals = [ ] outvals . extend ( [ 'bb' , 'p_sim_bw' , 'p_sim_bb' ] ) pvalue = '' return _univariate_handler ( df , cols , w = w , inplace = inplace , pvalue = pvalue , outvals = outvals , ...
Function to compute a Join_Count statistic on a dataframe
246,786
def Moran_BV_matrix ( variables , w , permutations = 0 , varnames = None ) : try : import pandas if isinstance ( variables , pandas . DataFrame ) : varnames = pandas . Index . tolist ( variables . columns ) variables_n = [ ] for var in varnames : variables_n . append ( variables [ str ( var ) ] . values ) else : variab...
Bivariate Moran Matrix
246,787
def _Moran_BV_Matrix_array ( variables , w , permutations = 0 , varnames = None ) : if varnames is None : varnames = [ 'x{}' . format ( i ) for i in range ( k ) ] k = len ( variables ) rk = list ( range ( 0 , k - 1 ) ) results = { } for i in rk : for j in range ( i + 1 , k ) : y1 = variables [ i ] y2 = variables [ j ] ...
Base calculation for MORAN_BV_Matrix
246,788
def by_col ( cls , df , x , y = None , w = None , inplace = False , pvalue = 'sim' , outvals = None , ** stat_kws ) : return _bivariate_handler ( df , x , y = y , w = w , inplace = inplace , pvalue = pvalue , outvals = outvals , swapname = cls . __name__ . lower ( ) , stat = cls , ** stat_kws )
Function to compute a Moran_BV statistic on a dataframe
246,789
def by_col ( cls , df , events , populations , w = None , inplace = False , pvalue = 'sim' , outvals = None , swapname = '' , ** stat_kws ) : if not inplace : new = df . copy ( ) cls . by_col ( new , events , populations , w = w , inplace = True , pvalue = pvalue , outvals = outvals , swapname = swapname , ** stat_kws ...
Function to compute a Moran_Rate statistic on a dataframe
246,790
def flatten ( l , unique = True ) : l = reduce ( lambda x , y : x + y , l ) if not unique : return list ( l ) return list ( set ( l ) )
flatten a list of lists
246,791
def weighted_median ( d , w ) : dtype = [ ( 'w' , '%s' % w . dtype ) , ( 'v' , '%s' % d . dtype ) ] d_w = np . array ( list ( zip ( w , d ) ) , dtype = dtype ) d_w . sort ( order = 'v' ) reordered_w = d_w [ 'w' ] . cumsum ( ) cumsum_threshold = reordered_w [ - 1 ] * 1.0 / 2 median_inx = ( reordered_w >= cumsum_threshol...
A utility function to find a median of d based on w
246,792
def sum_by_n ( d , w , n ) : t = len ( d ) h = t // n d = d * w return np . array ( [ sum ( d [ i : i + h ] ) for i in range ( 0 , t , h ) ] )
A utility function to summarize a data array into n values after weighting the array with another weight array w
246,793
def crude_age_standardization ( e , b , n ) : r = e * 1.0 / b b_by_n = sum_by_n ( b , 1.0 , n ) age_weight = b * 1.0 / b_by_n . repeat ( len ( e ) // n ) return sum_by_n ( r , age_weight , n )
A utility function to compute rate through crude age standardization
246,794
def direct_age_standardization ( e , b , s , n , alpha = 0.05 ) : age_weight = ( 1.0 / b ) * ( s * 1.0 / sum_by_n ( s , 1.0 , n ) . repeat ( len ( s ) // n ) ) adjusted_r = sum_by_n ( e , age_weight , n ) var_estimate = sum_by_n ( e , np . square ( age_weight ) , n ) g_a = np . square ( adjusted_r ) / var_estimate g_b ...
A utility function to compute rate through direct age standardization
246,795
def indirect_age_standardization ( e , b , s_e , s_b , n , alpha = 0.05 ) : smr = standardized_mortality_ratio ( e , b , s_e , s_b , n ) s_r_all = sum ( s_e * 1.0 ) / sum ( s_b * 1.0 ) adjusted_r = s_r_all * smr e_by_n = sum_by_n ( e , 1.0 , n ) log_smr = np . log ( smr ) log_smr_sd = 1.0 / np . sqrt ( e_by_n ) norm_th...
A utility function to compute rate through indirect age standardization
246,796
def _univariate_handler ( df , cols , stat = None , w = None , inplace = True , pvalue = 'sim' , outvals = None , swapname = '' , ** kwargs ) : if not inplace : new_df = df . copy ( ) _univariate_handler ( new_df , cols , stat = stat , w = w , pvalue = pvalue , inplace = True , outvals = outvals , swapname = swapname ,...
Compute a univariate descriptive statistic stat over columns cols in df .
246,797
def _bivariate_handler ( df , x , y = None , w = None , inplace = True , pvalue = 'sim' , outvals = None , ** kwargs ) : real_swapname = kwargs . pop ( 'swapname' , '' ) if isinstance ( y , str ) : y = [ y ] if isinstance ( x , str ) : x = [ x ] if not inplace : new_df = df . copy ( ) _bivariate_handler ( new_df , x , ...
Compute a descriptive bivariate statistic over two sets of columns x and y contained in df .
246,798
def _swap_ending ( s , ending , delim = '_' ) : parts = [ x for x in s . split ( delim ) [ : - 1 ] if x != '' ] parts . append ( ending ) return delim . join ( parts )
Replace the ending of a string delimited into an arbitrary number of chunks by delim with the ending provided
246,799
def is_sequence ( i , include = None ) : return ( hasattr ( i , '__getitem__' ) and iterable ( i ) or bool ( include ) and isinstance ( i , include ) )
Return a boolean indicating whether i is a sequence in the SymPy sense . If anything that fails the test below should be included as being a sequence for your application set include to that object s type ; multiple types should be passed as a tuple of types .