<s> from __future__ import division <EOL> import numpy as np <EOL> import pandas as pd <EOL> def utils_to_probs ( utils ) : <EOL> """<STR_LIT>""" <EOL> prob_min = <NUM_LIT> <EOL> prob_max = np . inf <EOL> utils_arr = np . exp ( utils . as_matrix ( ) . astype ( '<STR_LIT:float>' ) ) <EOL> arr_sum = utils_arr . sum ( axis = <NUM_LIT:1> ) <EOL> if np . isinf ( arr_sum ) . any ( ) : <EOL> raise RuntimeError ( '<STR_LIT>' ) <EOL> np . clip ( utils_arr , prob_min , prob_max , out = utils_arr ) <EOL> np . divide ( <EOL> utils_arr , arr_sum . reshape ( len ( utils_arr ) , <NUM_LIT:1> ) , <EOL> out = utils_arr ) <EOL> utils_arr [ np . isnan ( utils_arr ) ] = prob_min <EOL> np . clip ( utils_arr , prob_min , prob_max , out = utils_arr ) <EOL> return pd . DataFrame ( utils_arr , columns = utils . columns , index = utils . index ) <EOL> def make_choices ( probs ) : <EOL> """<STR_LIT>""" <EOL> nchoosers = len ( probs ) <EOL> probs_arr = ( <EOL> probs . as_matrix ( ) . cumsum ( axis = <NUM_LIT:1> ) - np . random . random ( ( nchoosers , <NUM_LIT:1> ) ) ) <EOL> rows , cols = np . where ( probs_arr > <NUM_LIT:0> ) <EOL> choices = ( s . iat [ <NUM_LIT:0> ] for _ , s in pd . Series ( cols ) . groupby ( rows ) ) <EOL> return pd . Series ( choices , index = probs . index ) <EOL> def interaction_dataset ( choosers , alternatives , sample_size = None ) : <EOL> """<STR_LIT>""" <EOL> if not choosers . index . is_unique : <EOL> raise RuntimeError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> if not alternatives . index . is_unique : <EOL> raise RuntimeError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> numchoosers = len ( choosers ) <EOL> numalts = len ( alternatives ) <EOL> sample_size = sample_size or numalts <EOL> alts_idx = np . arange ( numalts ) <EOL> if sample_size < numalts : <EOL> sample = np . concatenate ( tuple ( <EOL> np . random . choice ( alts_idx , sample_size , replace = False ) <EOL> for _ in range ( numchoosers ) ) ) <EOL> else : <EOL> sample = np . tile ( alts_idx , numchoosers ) <EOL> alts_sample = alternatives . take ( sample ) <EOL> alts_sample [ '<STR_LIT>' ] = np . repeat ( choosers . index . values , sample_size ) <EOL> alts_sample = pd . merge ( <EOL> alts_sample , choosers , left_on = '<STR_LIT>' , right_index = True , <EOL> suffixes = ( '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> return alts_sample </s>
