idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
232,700 | def set_tr_te ( nifti_image , repetition_time , echo_time ) : # set the repetition time in pixdim nifti_image . header . structarr [ 'pixdim' ] [ 4 ] = repetition_time / 1000.0 # set tr and te in db_name field nifti_image . header . structarr [ 'db_name' ] = '?TR:%.3f TE:%d' % ( repetition_time , echo_time ) return nifti_image | Set the tr and te in the nifti headers | 115 | 11 |
232,701 | def dicom_to_nifti ( dicom_input , output_file = None ) : assert common . is_ge ( dicom_input ) logger . info ( 'Reading and sorting dicom files' ) grouped_dicoms = _get_grouped_dicoms ( dicom_input ) if _is_4d ( grouped_dicoms ) : logger . info ( 'Found sequence type: 4D' ) return _4d_to_nifti ( grouped_dicoms , output_file ) logger . info ( 'Assuming anatomical data' ) return convert_generic . dicom_to_nifti ( dicom_input , output_file ) | This is the main dicom to nifti conversion fuction for ge images . As input ge images are required . It will then determine the type of images and do the correct conversion | 156 | 38 |
232,702 | def _4d_to_nifti ( grouped_dicoms , output_file ) : # Create mosaic block logger . info ( 'Creating data block' ) full_block = _get_full_block ( grouped_dicoms ) logger . info ( 'Creating affine' ) # Create the nifti header info affine , slice_increment = common . create_affine ( grouped_dicoms [ 0 ] ) logger . info ( 'Creating nifti' ) # Convert to nifti nii_image = nibabel . Nifti1Image ( full_block , affine ) common . set_tr_te ( nii_image , float ( grouped_dicoms [ 0 ] [ 0 ] . RepetitionTime ) , float ( grouped_dicoms [ 0 ] [ 0 ] . EchoTime ) ) logger . info ( 'Saving nifti to disk %s' % output_file ) # Save to disk if output_file is not None : nii_image . to_filename ( output_file ) if _is_diffusion_imaging ( grouped_dicoms ) : bval_file = None bvec_file = None # Create the bval en bevec files if output_file is not None : base_path = os . path . dirname ( output_file ) base_name = os . path . splitext ( os . path . splitext ( os . path . basename ( output_file ) ) [ 0 ] ) [ 0 ] logger . info ( 'Creating bval en bvec files' ) bval_file = '%s/%s.bval' % ( base_path , base_name ) bvec_file = '%s/%s.bvec' % ( base_path , base_name ) bval , bvec = _create_bvals_bvecs ( grouped_dicoms , bval_file , bvec_file ) return { 'NII_FILE' : output_file , 'BVAL_FILE' : bval_file , 'BVEC_FILE' : bvec_file , 'NII' : nii_image , 'BVAL' : bval , 'BVEC' : bvec , 'MAX_SLICE_INCREMENT' : slice_increment } return { 'NII_FILE' : output_file , 'NII' : nii_image } | This function will convert ge 4d series to a nifti | 528 | 13 |
232,703 | def dicom_to_nifti ( dicom_input , output_file = None ) : assert common . is_hitachi ( dicom_input ) # TODO add validations and conversion for DTI and fMRI once testdata is available logger . info ( 'Assuming anatomical data' ) return convert_generic . dicom_to_nifti ( dicom_input , output_file ) | This is the main dicom to nifti conversion fuction for hitachi images . As input hitachi images are required . It will then determine the type of images and do the correct conversion | 92 | 40 |
232,704 | def dicom_to_nifti ( dicom_input , output_file = None ) : assert common . is_siemens ( dicom_input ) if _is_4d ( dicom_input ) : logger . info ( 'Found sequence type: MOSAIC 4D' ) return _mosaic_4d_to_nifti ( dicom_input , output_file ) grouped_dicoms = _classic_get_grouped_dicoms ( dicom_input ) if _is_classic_4d ( grouped_dicoms ) : logger . info ( 'Found sequence type: CLASSIC 4D' ) return _classic_4d_to_nifti ( grouped_dicoms , output_file ) logger . info ( 'Assuming anatomical data' ) return convert_generic . dicom_to_nifti ( dicom_input , output_file ) | This is the main dicom to nifti conversion function for ge images . As input ge images are required . It will then determine the type of images and do the correct conversion | 208 | 37 |
232,705 | def _get_sorted_mosaics ( dicom_input ) : # Order all dicom files by acquisition number sorted_mosaics = sorted ( dicom_input , key = lambda x : x . AcquisitionNumber ) for index in range ( 0 , len ( sorted_mosaics ) - 1 ) : # Validate that there are no duplicate AcquisitionNumber if sorted_mosaics [ index ] . AcquisitionNumber >= sorted_mosaics [ index + 1 ] . AcquisitionNumber : raise ConversionValidationError ( "INCONSISTENT_ACQUISITION_NUMBERS" ) return sorted_mosaics | Search all mosaics in the dicom directory sort and validate them | 137 | 14 |
232,706 | def _mosaic_to_block ( mosaic ) : # get the mosaic type mosaic_type = _get_mosaic_type ( mosaic ) # get the size of one tile format is 64p*64 or 80*80 or something similar matches = re . findall ( r'(\d+)\D+(\d+)\D*' , str ( mosaic [ Tag ( 0x0051 , 0x100b ) ] . value ) ) [ 0 ] ascconv_headers = _get_asconv_headers ( mosaic ) size = [ int ( matches [ 0 ] ) , int ( matches [ 1 ] ) , int ( re . findall ( r'sSliceArray\.lSize\s*=\s*(\d+)' , ascconv_headers ) [ 0 ] ) ] # get the number of rows and columns number_x = int ( mosaic . Rows / size [ 0 ] ) number_y = int ( mosaic . Columns / size [ 1 ] ) # recreate 2d slice data_2d = mosaic . pixel_array # create 3d block data_3d = numpy . zeros ( ( size [ 2 ] , size [ 1 ] , size [ 0 ] ) , dtype = data_2d . dtype ) # fill 3d block by taking the correct portions of the slice z_index = 0 for y_index in range ( 0 , number_y ) : if z_index >= size [ 2 ] : break for x_index in range ( 0 , number_x ) : if mosaic_type == MosaicType . ASCENDING : data_3d [ z_index , : , : ] = data_2d [ size [ 1 ] * y_index : size [ 1 ] * ( y_index + 1 ) , size [ 0 ] * x_index : size [ 0 ] * ( x_index + 1 ) ] else : data_3d [ size [ 2 ] - ( z_index + 1 ) , : , : ] = data_2d [ size [ 1 ] * y_index : size [ 1 ] * ( y_index + 1 ) , size [ 0 ] * x_index : size [ 0 ] * ( x_index + 1 ) ] z_index += 1 if z_index >= size [ 2 ] : break # reorient the block of data data_3d = numpy . transpose ( data_3d , ( 2 , 1 , 0 ) ) return data_3d | Convert a mosaic slice to a block of data by reading the headers splitting the mosaic and appending | 533 | 20 |
232,707 | def _create_affine_siemens_mosaic ( dicom_input ) : # read dicom series with pds dicom_header = dicom_input [ 0 ] # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine) image_orient1 = numpy . array ( dicom_header . ImageOrientationPatient ) [ 0 : 3 ] image_orient2 = numpy . array ( dicom_header . ImageOrientationPatient ) [ 3 : 6 ] normal = numpy . cross ( image_orient1 , image_orient2 ) delta_r = float ( dicom_header . PixelSpacing [ 0 ] ) delta_c = float ( dicom_header . PixelSpacing [ 1 ] ) image_pos = dicom_header . ImagePositionPatient delta_s = dicom_header . SpacingBetweenSlices return numpy . array ( [ [ - image_orient1 [ 0 ] * delta_c , - image_orient2 [ 0 ] * delta_r , - delta_s * normal [ 0 ] , - image_pos [ 0 ] ] , [ - image_orient1 [ 1 ] * delta_c , - image_orient2 [ 1 ] * delta_r , - delta_s * normal [ 1 ] , - image_pos [ 1 ] ] , [ image_orient1 [ 2 ] * delta_c , image_orient2 [ 2 ] * delta_r , delta_s * normal [ 2 ] , image_pos [ 2 ] ] , [ 0 , 0 , 0 , 1 ] ] ) | Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4d if in mosaic format | 381 | 30 |
232,708 | def resample_single_nifti ( input_nifti ) : # read the input image input_image = nibabel . load ( input_nifti ) output_image = resample_nifti_images ( [ input_image ] ) output_image . to_filename ( input_nifti ) | Resample a gantry tilted image in place | 70 | 9 |
232,709 | def convert_directory ( dicom_directory , output_folder , compression = True , reorient = True ) : # sort dicom files by series uid dicom_series = { } for root , _ , files in os . walk ( dicom_directory ) : for dicom_file in files : file_path = os . path . join ( root , dicom_file ) # noinspection PyBroadException try : if compressed_dicom . is_dicom_file ( file_path ) : # read the dicom as fast as possible # (max length for SeriesInstanceUID is 64 so defer_size 100 should be ok) dicom_headers = compressed_dicom . read_file ( file_path , defer_size = "1 KB" , stop_before_pixels = False , force = dicom2nifti . settings . pydicom_read_force ) if not _is_valid_imaging_dicom ( dicom_headers ) : logger . info ( "Skipping: %s" % file_path ) continue logger . info ( "Organizing: %s" % file_path ) if dicom_headers . SeriesInstanceUID not in dicom_series : dicom_series [ dicom_headers . SeriesInstanceUID ] = [ ] dicom_series [ dicom_headers . SeriesInstanceUID ] . append ( dicom_headers ) except : # Explicitly capturing all errors here to be able to continue processing all the rest logger . warning ( "Unable to read: %s" % file_path ) traceback . print_exc ( ) # start converting one by one for series_id , dicom_input in iteritems ( dicom_series ) : base_filename = "" # noinspection PyBroadException try : # construct the filename for the nifti base_filename = "" if 'SeriesNumber' in dicom_input [ 0 ] : base_filename = _remove_accents ( '%s' % dicom_input [ 0 ] . SeriesNumber ) if 'SeriesDescription' in dicom_input [ 0 ] : base_filename = _remove_accents ( '%s_%s' % ( base_filename , dicom_input [ 0 ] . SeriesDescription ) ) elif 'SequenceName' in dicom_input [ 0 ] : base_filename = _remove_accents ( '%s_%s' % ( base_filename , dicom_input [ 0 ] . SequenceName ) ) elif 'ProtocolName' in dicom_input [ 0 ] : base_filename = _remove_accents ( '%s_%s' % ( base_filename , dicom_input [ 0 ] . ProtocolName ) ) else : base_filename = _remove_accents ( dicom_input [ 0 ] . SeriesInstanceUID ) logger . info ( '--------------------------------------------' ) logger . info ( 'Start converting %s' % base_filename ) if compression : nifti_file = os . path . join ( output_folder , base_filename + '.nii.gz' ) else : nifti_file = os . path . join ( output_folder , base_filename + '.nii' ) convert_dicom . dicom_array_to_nifti ( dicom_input , nifti_file , reorient ) gc . collect ( ) except : # Explicitly capturing app exceptions here to be able to continue processing logger . info ( "Unable to convert: %s" % base_filename ) traceback . print_exc ( ) | This function will order all dicom files by series and order them one by one | 806 | 17 |
232,710 | def clear_data ( self ) : self . __header . title = None self . __header . subtitle = None self . __prologue . text = None self . __epilogue . text = None self . __items_section . items = None | Clear menu data from previous menu generation . | 54 | 8 |
232,711 | def inner_horizontal_border ( self ) : return u"{lm}{lv}{hz}{rv}" . format ( lm = ' ' * self . margins . left , lv = self . border_style . outer_vertical_inner_right , rv = self . border_style . outer_vertical_inner_left , hz = self . inner_horizontals ( ) ) | The complete inner horizontal border section including the left and right border verticals . | 89 | 15 |
232,712 | def outer_horizontal_border_bottom ( self ) : return u"{lm}{lv}{hz}{rv}" . format ( lm = ' ' * self . margins . left , lv = self . border_style . bottom_left_corner , rv = self . border_style . bottom_right_corner , hz = self . outer_horizontals ( ) ) | The complete outer bottom horizontal border section including left and right margins . | 87 | 13 |
232,713 | def outer_horizontal_border_top ( self ) : return u"{lm}{lv}{hz}{rv}" . format ( lm = ' ' * self . margins . left , lv = self . border_style . top_left_corner , rv = self . border_style . top_right_corner , hz = self . outer_horizontals ( ) ) | The complete outer top horizontal border section including left and right margins . | 87 | 13 |
232,714 | def row ( self , content = '' , align = 'left' ) : return u"{lm}{vert}{cont}{vert}" . format ( lm = ' ' * self . margins . left , vert = self . border_style . outer_vertical , cont = self . _format_content ( content , align ) ) | A row of the menu which comprises the left and right verticals plus the given content . | 71 | 18 |
232,715 | def create_border ( self , border_style_type ) : if border_style_type == MenuBorderStyleType . ASCII_BORDER : return self . create_ascii_border ( ) elif border_style_type == MenuBorderStyleType . LIGHT_BORDER : return self . create_light_border ( ) elif border_style_type == MenuBorderStyleType . HEAVY_BORDER : return self . create_heavy_border ( ) elif border_style_type == MenuBorderStyleType . DOUBLE_LINE_BORDER : return self . create_doubleline_border ( ) elif border_style_type == MenuBorderStyleType . HEAVY_OUTER_LIGHT_INNER_BORDER : return self . create_heavy_outer_light_inner_border ( ) elif border_style_type == MenuBorderStyleType . DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER : return self . create_doubleline_outer_light_inner_border ( ) else : # Use ASCII if we don't recognize the type self . logger . info ( 'Unrecognized border style type: {}. Defaulting to ASCII.' . format ( border_style_type ) ) return self . create_ascii_border ( ) | Create a new MenuBorderStyle instance based on the given border style type . | 289 | 15 |
232,716 | def is_win_python35_or_earlier ( ) : return sys . platform . startswith ( "win" ) and sys . version_info . major < 3 or ( sys . version_info . major == 3 and sys . version_info . minor < 6 ) | Convenience method to determine if the current platform is Windows and Python version 3 . 5 or earlier . | 60 | 21 |
232,717 | def set_menu ( self , menu ) : self . menu = menu self . submenu . parent = menu | Sets the menu of this item . Should be used instead of directly accessing the menu attribute for this class . | 23 | 22 |
232,718 | def validate ( self , input_string ) : validation_result = False try : validation_result = bool ( match ( pattern = self . pattern , string = input_string ) ) except TypeError as e : self . log . error ( 'Exception while validating Regex, pattern={}, input_string={} - exception: {}' . format ( self . pattern , input_string , e ) ) return validation_result | Validate input_string against a regex pattern | 89 | 9 |
232,719 | def process_user_input ( self ) : user_input = self . screen . input ( ) try : indexes = self . __parse_range_list ( user_input ) # Subtract 1 from each number for its actual index number indexes [ : ] = [ x - 1 for x in indexes if 0 < x < len ( self . items ) + 1 ] for index in indexes : self . current_option = index self . select ( ) except Exception as e : return | This overrides the method in ConsoleMenu to allow for comma - delimited and range inputs . | 101 | 19 |
232,720 | def remove_item ( self , item ) : for idx , _item in enumerate ( self . items ) : if item == _item : del self . items [ idx ] return True return False | Remove the specified item from the menu . | 43 | 8 |
232,721 | def remove_exit ( self ) : if self . items : if self . items [ - 1 ] is self . exit_item : del self . items [ - 1 ] return True return False | Remove the exit item if necessary . Used to make sure we only remove the exit item not something else . | 40 | 21 |
232,722 | def draw ( self ) : self . screen . printf ( self . formatter . format ( title = self . title , subtitle = self . subtitle , items = self . items , prologue_text = self . prologue_text , epilogue_text = self . epilogue_text ) ) | Refresh the screen and redraw the menu . Should be called whenever something changes that needs to be redrawn . | 64 | 23 |
232,723 | def process_user_input ( self ) : user_input = self . get_input ( ) try : num = int ( user_input ) except Exception : return if 0 < num < len ( self . items ) + 1 : self . current_option = num - 1 self . select ( ) return user_input | Gets the next single character and decides what to do with it | 67 | 13 |
232,724 | def go_down ( self ) : if self . current_option < len ( self . items ) - 1 : self . current_option += 1 else : self . current_option = 0 self . draw ( ) | Go down one wrap to beginning if necessary | 45 | 8 |
232,725 | def go_up ( self ) : if self . current_option > 0 : self . current_option += - 1 else : self . current_option = len ( self . items ) - 1 self . draw ( ) | Go up one wrap to end if necessary | 46 | 8 |
232,726 | def get_selection ( cls , strings , title = "Select an option" , subtitle = None , exit_option = True , _menu = None ) : menu = cls ( strings , title , subtitle , exit_option ) if _menu is not None : _menu . append ( menu ) menu . show ( ) menu . join ( ) return menu . selected_option | Single - method way of getting a selection out of a list of strings . | 79 | 15 |
232,727 | def ensure_object_is_ordered_dict ( item , title ) : assert isinstance ( title , str ) if not isinstance ( item , OrderedDict ) : msg = "{} must be an OrderedDict. {} passed instead." raise TypeError ( msg . format ( title , type ( item ) ) ) return None | Checks that the item is an OrderedDict . If not raises ValueError . | 71 | 18 |
232,728 | def ensure_object_is_string ( item , title ) : assert isinstance ( title , str ) if not isinstance ( item , str ) : msg = "{} must be a string. {} passed instead." raise TypeError ( msg . format ( title , type ( item ) ) ) return None | Checks that the item is a string . If not raises ValueError . | 63 | 15 |
232,729 | def ensure_object_is_ndarray ( item , title ) : assert isinstance ( title , str ) if not isinstance ( item , np . ndarray ) : msg = "{} must be a np.ndarray. {} passed instead." raise TypeError ( msg . format ( title , type ( item ) ) ) return None | Ensures that a given mapping matrix is a dense numpy array . Raises a helpful TypeError if otherwise . | 71 | 24 |
232,730 | def ensure_columns_are_in_dataframe ( columns , dataframe , col_title = '' , data_title = 'data' ) : # Make sure columns is an iterable assert isinstance ( columns , Iterable ) # Make sure dataframe is a pandas dataframe assert isinstance ( dataframe , pd . DataFrame ) # Make sure title is a string assert isinstance ( col_title , str ) assert isinstance ( data_title , str ) problem_cols = [ col for col in columns if col not in dataframe . columns ] if problem_cols != [ ] : if col_title == '' : msg = "{} not in {}.columns" final_msg = msg . format ( problem_cols , data_title ) else : msg = "The following columns in {} are not in {}.columns: {}" final_msg = msg . format ( col_title , data_title , problem_cols ) raise ValueError ( final_msg ) return None | Checks whether each column in columns is in dataframe . Raises ValueError if any of the columns are not in the dataframe . | 216 | 28 |
232,731 | def check_argument_type ( long_form , specification_dict ) : if not isinstance ( long_form , pd . DataFrame ) : msg = "long_form should be a pandas dataframe. It is a {}" raise TypeError ( msg . format ( type ( long_form ) ) ) ensure_object_is_ordered_dict ( specification_dict , "specification_dict" ) return None | Ensures that long_form is a pandas dataframe and that specification_dict is an OrderedDict raising a ValueError otherwise . | 90 | 30 |
232,732 | def ensure_alt_id_in_long_form ( alt_id_col , long_form ) : if alt_id_col not in long_form . columns : msg = "alt_id_col == {} is not a column in long_form." raise ValueError ( msg . format ( alt_id_col ) ) return None | Ensures alt_id_col is in long_form and raises a ValueError if not . | 74 | 21 |
232,733 | def ensure_specification_cols_are_in_dataframe ( specification , dataframe ) : # Make sure specification is an OrderedDict try : assert isinstance ( specification , OrderedDict ) except AssertionError : raise TypeError ( "`specification` must be an OrderedDict." ) # Make sure dataframe is a pandas dataframe assert isinstance ( dataframe , pd . DataFrame ) problem_cols = [ ] dataframe_cols = dataframe . columns for key in specification : if key not in dataframe_cols : problem_cols . append ( key ) if problem_cols != [ ] : msg = "The following keys in the specification are not in 'data':\n{}" raise ValueError ( msg . format ( problem_cols ) ) return None | Checks whether each column in specification is in dataframe . Raises ValueError if any of the columns are not in the dataframe . | 178 | 28 |
232,734 | def check_keys_and_values_of_name_dictionary ( names , specification_dict , num_alts ) : if names . keys ( ) != specification_dict . keys ( ) : msg = "names.keys() does not equal specification_dict.keys()" raise ValueError ( msg ) for key in names : specification = specification_dict [ key ] name_object = names [ key ] if isinstance ( specification , list ) : try : assert isinstance ( name_object , list ) assert len ( name_object ) == len ( specification ) assert all ( [ isinstance ( x , str ) for x in name_object ] ) except AssertionError : msg = "names[{}] must be a list AND it must have the same" msg_2 = " number of strings as there are elements of the" msg_3 = " corresponding list in specification_dict" raise ValueError ( msg . format ( key ) + msg_2 + msg_3 ) else : if specification == "all_same" : if not isinstance ( name_object , str ) : msg = "names[{}] should be a string" . format ( key ) raise TypeError ( msg ) else : # This means speciffication == 'all_diff' try : assert isinstance ( name_object , list ) assert len ( name_object ) == num_alts except AssertionError : msg_1 = "names[{}] should be a list with {} elements," msg_2 = " 1 element for each possible alternative" msg = ( msg_1 . format ( key , num_alts ) + msg_2 ) raise ValueError ( msg ) return None | Check the validity of the keys and values in the names dictionary . | 360 | 13 |
232,735 | def ensure_all_columns_are_used ( num_vars_accounted_for , dataframe , data_title = 'long_data' ) : dataframe_vars = set ( dataframe . columns . tolist ( ) ) num_dataframe_vars = len ( dataframe_vars ) if num_vars_accounted_for == num_dataframe_vars : pass elif num_vars_accounted_for < num_dataframe_vars : msg = "Note, there are {:,} variables in {} but the inputs" msg_2 = " ind_vars, alt_specific_vars, and subset_specific_vars only" msg_3 = " account for {:,} variables." warnings . warn ( msg . format ( num_dataframe_vars , data_title ) + msg_2 + msg_3 . format ( num_vars_accounted_for ) ) else : # This means num_vars_accounted_for > num_dataframe_vars msg = "There are more variable specified in ind_vars, " msg_2 = "alt_specific_vars, and subset_specific_vars ({:,}) than there" msg_3 = " are variables in {} ({:,})" warnings . warn ( msg + msg_2 . format ( num_vars_accounted_for ) + msg_3 . format ( data_title , num_dataframe_vars ) ) return None | Ensure that all of the columns from dataframe are in the list of used_cols . Will raise a helpful UserWarning if otherwise . | 326 | 29 |
232,736 | def check_dataframe_for_duplicate_records ( obs_id_col , alt_id_col , df ) : if df . duplicated ( subset = [ obs_id_col , alt_id_col ] ) . any ( ) : msg = "One or more observation-alternative_id pairs is not unique." raise ValueError ( msg ) return None | Checks a cross - sectional dataframe of long - format data for duplicate observations . Duplicate observations are defined as rows with the same observation id value and the same alternative id value . | 82 | 38 |
232,737 | def ensure_num_chosen_alts_equals_num_obs ( obs_id_col , choice_col , df ) : num_obs = df [ obs_id_col ] . unique ( ) . shape [ 0 ] num_choices = df [ choice_col ] . sum ( ) if num_choices < num_obs : msg = "One or more observations have not chosen one " msg_2 = "of the alternatives available to him/her" raise ValueError ( msg + msg_2 ) if num_choices > num_obs : msg = "One or more observations has chosen multiple alternatives" raise ValueError ( msg ) return None | Checks that the total number of recorded choices equals the total number of observations . If this is not the case raise helpful ValueError messages . | 143 | 28 |
232,738 | def check_type_and_values_of_alt_name_dict ( alt_name_dict , alt_id_col , df ) : if not isinstance ( alt_name_dict , dict ) : msg = "alt_name_dict should be a dictionary. Passed value was a {}" raise TypeError ( msg . format ( type ( alt_name_dict ) ) ) if not all ( [ x in df [ alt_id_col ] . values for x in alt_name_dict . keys ( ) ] ) : msg = "One or more of alt_name_dict's keys are not " msg_2 = "in long_data[alt_id_col]" raise ValueError ( msg + msg_2 ) return None | Ensures that alt_name_dict is a dictionary and that its keys are in the alternative id column of df . Raises helpful errors if either condition is not met . | 160 | 36 |
232,739 | def ensure_ridge_is_scalar_or_none ( ridge ) : if ( ridge is not None ) and not isinstance ( ridge , Number ) : msg_1 = "ridge should be None or an int, float, or long." msg_2 = "The passed value of ridge had type: {}" . format ( type ( ridge ) ) raise TypeError ( msg_1 + msg_2 ) return None | Ensures that ridge is either None or a scalar value . Raises a helpful TypeError otherwise . | 90 | 22 |
232,740 | def get_original_order_unique_ids ( id_array ) : assert isinstance ( id_array , np . ndarray ) assert len ( id_array . shape ) == 1 # Get the indices of the unique IDs in their order of appearance # Note the [1] is because the np.unique() call will return both the sorted # unique IDs and the indices original_unique_id_indices = np . sort ( np . unique ( id_array , return_index = True ) [ 1 ] ) # Get the unique ids, in their original order of appearance original_order_unique_ids = id_array [ original_unique_id_indices ] return original_order_unique_ids | Get the unique id s of id_array in their original order of appearance . | 152 | 16 |
232,741 | def create_sparse_mapping ( id_array , unique_ids = None ) : # Create unique_ids if necessary if unique_ids is None : unique_ids = get_original_order_unique_ids ( id_array ) # Check function arguments for validity assert isinstance ( unique_ids , np . ndarray ) assert isinstance ( id_array , np . ndarray ) assert unique_ids . ndim == 1 assert id_array . ndim == 1 # Figure out which ids in id_array are represented in unique_ids represented_ids = np . in1d ( id_array , unique_ids ) # Determine the number of rows in id_array that are in unique_ids num_non_zero_rows = represented_ids . sum ( ) # Figure out the dimensions of the resulting sparse matrix num_rows = id_array . size num_cols = unique_ids . size # Specify the non-zero values that will be present in the sparse matrix. data = np . ones ( num_non_zero_rows , dtype = int ) # Specify which rows will have non-zero entries in the sparse matrix. row_indices = np . arange ( num_rows ) [ represented_ids ] # Map the unique id's to their respective columns unique_id_dict = dict ( zip ( unique_ids , np . arange ( num_cols ) ) ) # Figure out the column indices of the non-zero entries, and do so in a way # that avoids a key error (i.e. only look up ids that are represented) col_indices = np . array ( [ unique_id_dict [ x ] for x in id_array [ represented_ids ] ] ) # Create and return the sparse matrix return csr_matrix ( ( data , ( row_indices , col_indices ) ) , shape = ( num_rows , num_cols ) ) | Will create a scipy . sparse compressed - sparse - row matrix that maps each row represented by an element in id_array to the corresponding value of the unique ids in id_array . | 419 | 40 |
232,742 | def check_wide_data_for_blank_choices ( choice_col , wide_data ) : if wide_data [ choice_col ] . isnull ( ) . any ( ) : msg_1 = "One or more of the values in wide_data[choice_col] is null." msg_2 = " Remove null values in the choice column or fill them in." raise ValueError ( msg_1 + msg_2 ) return None | Checks wide_data for null values in the choice column and raises a helpful ValueError if null values are found . | 96 | 24 |
232,743 | def ensure_unique_obs_ids_in_wide_data ( obs_id_col , wide_data ) : if len ( wide_data [ obs_id_col ] . unique ( ) ) != wide_data . shape [ 0 ] : msg = "The values in wide_data[obs_id_col] are not unique, " msg_2 = "but they need to be." raise ValueError ( msg + msg_2 ) return None | Ensures that there is one observation per row in wide_data . Raises a helpful ValueError if otherwise . | 98 | 24 |
232,744 | def ensure_chosen_alternatives_are_in_user_alt_ids ( choice_col , wide_data , availability_vars ) : if not wide_data [ choice_col ] . isin ( availability_vars . keys ( ) ) . all ( ) : msg = "One or more values in wide_data[choice_col] is not in the user " msg_2 = "provided alternative ids in availability_vars.keys()" raise ValueError ( msg + msg_2 ) return None | Ensures that all chosen alternatives in wide_df are present in the availability_vars dict . Raises a helpful ValueError if not . | 113 | 30 |
232,745 | def ensure_each_wide_obs_chose_an_available_alternative ( obs_id_col , choice_col , availability_vars , wide_data ) : # Determine the various availability values for each observation wide_availability_values = wide_data [ list ( availability_vars . values ( ) ) ] . values # Isolate observations for whom one or more alternatives are unavailable unavailable_condition = ( ( wide_availability_values == 0 ) . sum ( axis = 1 ) . astype ( bool ) ) # Iterate over the observations with one or more unavailable alternatives # Check that each such observation's chosen alternative was available problem_obs = [ ] for idx , row in wide_data . loc [ unavailable_condition ] . iterrows ( ) : if row . at [ availability_vars [ row . at [ choice_col ] ] ] != 1 : problem_obs . append ( row . at [ obs_id_col ] ) if problem_obs != [ ] : msg = "The following observations chose unavailable alternatives:\n{}" raise ValueError ( msg . format ( problem_obs ) ) return None | Checks whether or not each observation with a restricted choice set chose an alternative that was personally available to him or her . Will raise a helpful ValueError if this is not the case . | 240 | 37 |
232,746 | def ensure_all_wide_alt_ids_are_chosen ( choice_col , alt_specific_vars , availability_vars , wide_data ) : sorted_alt_ids = np . sort ( wide_data [ choice_col ] . unique ( ) ) try : problem_ids = [ x for x in availability_vars if x not in sorted_alt_ids ] problem_type = "availability_vars" assert problem_ids == [ ] problem_ids = [ ] for new_column in alt_specific_vars : for alt_id in alt_specific_vars [ new_column ] : if alt_id not in sorted_alt_ids and alt_id not in problem_ids : problem_ids . append ( alt_id ) problem_type = "alt_specific_vars" assert problem_ids == [ ] except AssertionError : msg = "The following alternative ids from {} are not " msg_2 = "observed in wide_data[choice_col]:\n{}" raise ValueError ( msg . format ( problem_type ) + msg_2 . format ( problem_ids ) ) return None | Checks to make sure all user - specified alternative id s both in alt_specific_vars and availability_vars are observed in the choice column of wide_data . | 252 | 36 |
232,747 | def ensure_contiguity_in_observation_rows ( obs_id_vector ) : # Check that the choice situation id for each row is larger than or equal # to the choice situation id of the preceding row. contiguity_check_array = ( obs_id_vector [ 1 : ] - obs_id_vector [ : - 1 ] ) >= 0 if not contiguity_check_array . all ( ) : problem_ids = obs_id_vector [ np . where ( ~ contiguity_check_array ) ] msg_1 = "All rows pertaining to a given choice situation must be " msg_2 = "contiguous. \nRows pertaining to the following observation " msg_3 = "id's are not contiguous: \n{}" raise ValueError ( msg_1 + msg_2 + msg_3 . format ( problem_ids . tolist ( ) ) ) else : return None | Ensures that all rows pertaining to a given choice situation are located next to one another . Raises a helpful ValueError otherwise . This check is needed because the hessian calculation function requires the design matrix to have contiguity in rows with the same observation id . | 199 | 55 |
232,748 | def relate_obs_ids_to_chosen_alts ( obs_id_array , alt_id_array , choice_array ) : # Figure out which units of observation chose each alternative. chosen_alts_to_obs_ids = { } for alt_id in np . sort ( np . unique ( alt_id_array ) ) : # Determine which observations chose the current alternative. selection_condition = np . where ( ( alt_id_array == alt_id ) & ( choice_array == 1 ) ) # Store the sorted, unique ids that chose the current alternative. chosen_alts_to_obs_ids [ alt_id ] = np . sort ( np . unique ( obs_id_array [ selection_condition ] ) ) # Return the desired dictionary. return chosen_alts_to_obs_ids | Creates a dictionary that relates each unique alternative id to the set of observations ids that chose the given alternative . | 182 | 23 |
232,749 | def create_cross_sectional_bootstrap_samples ( obs_id_array , alt_id_array , choice_array , num_samples , seed = None ) : # Determine the units of observation that chose each alternative. chosen_alts_to_obs_ids = relate_obs_ids_to_chosen_alts ( obs_id_array , alt_id_array , choice_array ) # Determine the number of unique units of observation per group and overall num_obs_per_group , tot_num_obs = get_num_obs_choosing_each_alternative ( chosen_alts_to_obs_ids ) # Initialize the array that will store the observation ids for each sample ids_per_sample = np . empty ( ( num_samples , tot_num_obs ) , dtype = float ) if seed is not None : # Check the validity of the seed argument. if not isinstance ( seed , int ) : msg = "`boot_seed` MUST be an int." raise ValueError ( msg ) # If desiring reproducibility, set the random seed within numpy np . random . seed ( seed ) # Initialize a variable to keep track of what column we're on. col_idx = 0 for alt_id in num_obs_per_group : # Get the set of observations that chose the current alternative. relevant_ids = chosen_alts_to_obs_ids [ alt_id ] # Determine the number of needed resampled ids. resample_size = num_obs_per_group [ alt_id ] # Resample, with replacement, observations who chose this alternative. current_ids = ( np . random . choice ( relevant_ids , size = resample_size * num_samples , replace = True ) . reshape ( ( num_samples , resample_size ) ) ) # Determine the last column index to use when storing the resampled ids end_col = col_idx + resample_size # Assign the sampled ids to the correct columns of ids_per_sample ids_per_sample [ : , col_idx : end_col ] = current_ids # Update the column index col_idx += resample_size # Return the resampled observation ids. return ids_per_sample | Determines the unique observations that will be present in each bootstrap sample . This function DOES NOT create the new design matrices or a new long - format dataframe for each bootstrap sample . Note that these will be correct bootstrap samples for cross - sectional datasets . This function will not work correctly for panel datasets . | 513 | 66 |
232,750 | def create_bootstrap_id_array ( obs_id_per_sample ) : # Determine the shape of the object to be returned. n_rows , n_cols = obs_id_per_sample . shape # Create the array of bootstrap ids. bootstrap_id_array = np . tile ( np . arange ( n_cols ) + 1 , n_rows ) . reshape ( ( n_rows , n_cols ) ) # Return the desired object return bootstrap_id_array | Creates a 2D ndarray that contains the bootstrap ids for each replication of each unit of observation that is an the set of bootstrap samples . | 114 | 33 |
232,751 | def check_column_existence ( col_name , df , presence = True ) : if presence : if col_name not in df . columns : msg = "Ensure that `{}` is in `df.columns`." raise ValueError ( msg . format ( col_name ) ) else : if col_name in df . columns : msg = "Ensure that `{}` is not in `df.columns`." raise ValueError ( msg . format ( col_name ) ) return None | Checks whether or not col_name is in df and raises a helpful error msg if the desired condition is not met . | 109 | 25 |
232,752 | def ensure_resampled_obs_ids_in_df ( resampled_obs_ids , orig_obs_id_array ) : if not np . in1d ( resampled_obs_ids , orig_obs_id_array ) . all ( ) : msg = "All values in `resampled_obs_ids` MUST be in `orig_obs_id_array`." raise ValueError ( msg ) return None | Checks whether all ids in resampled_obs_ids are in orig_obs_id_array . Raises a helpful ValueError if not . | 97 | 33 |
232,753 | def create_bootstrap_dataframe ( orig_df , obs_id_col , resampled_obs_ids_1d , groupby_dict , boot_id_col = "bootstrap_id" ) : # Check the validity of the passed arguments. check_column_existence ( obs_id_col , orig_df , presence = True ) check_column_existence ( boot_id_col , orig_df , presence = False ) # Alias the observation id column obs_id_values = orig_df [ obs_id_col ] . values # Check the validity of the resampled observation ids. ensure_resampled_obs_ids_in_df ( resampled_obs_ids_1d , obs_id_values ) # Initialize a list to store the component dataframes that will be # concatenated to form the final bootstrap_df component_dfs = [ ] # Populate component_dfs for boot_id , obs_id in enumerate ( resampled_obs_ids_1d ) : # Extract the dataframe that we desire. extracted_df = groupby_dict [ obs_id ] . copy ( ) # Add the bootstrap id value. extracted_df [ boot_id_col ] = boot_id + 1 # Store the component dataframe component_dfs . append ( extracted_df ) # Create and return the desired dataframe. bootstrap_df = pd . concat ( component_dfs , axis = 0 , ignore_index = True ) return bootstrap_df | Will create the altered dataframe of data needed to estimate a choice model with the particular observations that belong to the current bootstrap sample . | 338 | 27 |
232,754 | def get_param_names ( model_obj ) : # Get the index coefficient names all_names = deepcopy ( model_obj . ind_var_names ) # Add the intercept names if any exist if model_obj . intercept_names is not None : all_names = model_obj . intercept_names + all_names # Add the shape names if any exist if model_obj . shape_names is not None : all_names = model_obj . shape_names + all_names # Add the nest names if any exist if model_obj . nest_names is not None : all_names = model_obj . nest_names + all_names return all_names | Extracts all the names to be displayed for the estimated parameters . | 144 | 14 |
232,755 | def get_param_list_for_prediction ( model_obj , replicates ) : # Check the validity of the passed arguments ensure_samples_is_ndim_ndarray ( replicates , ndim = 2 , name = 'replicates' ) # Determine the number of index coefficients, outside intercepts, # shape parameters, and nest parameters num_idx_coefs = len ( model_obj . ind_var_names ) intercept_names = model_obj . intercept_names num_outside_intercepts = 0 if intercept_names is None else len ( intercept_names ) shape_names = model_obj . shape_names num_shapes = 0 if shape_names is None else len ( shape_names ) nest_names = model_obj . nest_names num_nests = 0 if nest_names is None else len ( nest_names ) parameter_numbers = [ num_nests , num_shapes , num_outside_intercepts , num_idx_coefs ] current_idx = 0 param_list = [ ] for param_num in parameter_numbers : if param_num == 0 : param_list . insert ( 0 , None ) continue upper_idx = current_idx + param_num param_list . insert ( 0 , replicates [ : , current_idx : upper_idx ] . T ) current_idx += param_num return param_list | Create the param_list argument for use with model_obj . predict . | 314 | 15 |
232,756 | def generate_jackknife_replicates ( self , mnl_obj = None , mnl_init_vals = None , mnl_fit_kwargs = None , extract_init_vals = None , print_res = False , method = "BFGS" , loss_tol = 1e-06 , gradient_tol = 1e-06 , maxiter = 1000 , ridge = None , constrained_pos = None ) : print ( "Generating Jackknife Replicates" ) print ( time . strftime ( "%a %m-%d-%Y %I:%M%p" ) ) sys . stdout . flush ( ) # Take note of the observation id column that is to be used obs_id_col = self . model_obj . obs_id_col # Get the array of original observation ids orig_obs_id_array = self . model_obj . data [ obs_id_col ] . values # Get an array of the unique observation ids. unique_obs_ids = np . sort ( np . unique ( orig_obs_id_array ) ) # Determine how many observations are in one's dataset. num_obs = unique_obs_ids . size # Determine how many parameters are being estimated. num_params = self . mle_params . size # Get keyword arguments for final model estimation with new data. fit_kwargs = { "print_res" : print_res , "method" : method , "loss_tol" : loss_tol , "gradient_tol" : gradient_tol , "maxiter" : maxiter , "ridge" : ridge , "constrained_pos" : constrained_pos , "just_point" : True } # Get the specification and name dictionary of the MNL model. mnl_spec = None if mnl_obj is None else mnl_obj . specification mnl_names = None if mnl_obj is None else mnl_obj . name_spec # Initialize the array of jackknife replicates point_replicates = np . empty ( ( num_obs , num_params ) , dtype = float ) # Create an iterable for iteration iterable_for_iteration = PROGRESS ( enumerate ( unique_obs_ids ) , desc = "Creating Jackknife Replicates" , total = unique_obs_ids . size ) # Populate the array of jackknife replicates for pos , obs_id in iterable_for_iteration : # Create the dataframe without the current observation new_df = self . model_obj . data . loc [ orig_obs_id_array != obs_id ] # Get the point estimate for this new dataset current_results = retrieve_point_est ( self . model_obj , new_df , obs_id_col , num_params , mnl_spec , mnl_names , mnl_init_vals , mnl_fit_kwargs , extract_init_vals = extract_init_vals , * * fit_kwargs ) # Store the estimated parameters point_replicates [ pos ] = current_results [ 'x' ] # Store the jackknife replicates as a pandas dataframe self . jackknife_replicates = pd . DataFrame ( point_replicates , columns = self . mle_params . index ) # Print a 'finished' message for users print ( "Finished Generating Jackknife Replicates" ) print ( time . strftime ( "%a %m-%d-%Y %I:%M%p" ) ) return None | Generates the jackknife replicates for one s given model and dataset . | 770 | 15 |
232,757 | def calc_log_likes_for_replicates ( self , replicates = 'bootstrap' , num_draws = None , seed = None ) : # Check the validity of the kwargs ensure_replicates_kwarg_validity ( replicates ) # Get the desired type of replicates replicate_vec = getattr ( self , replicates + "_replicates" ) . values # Determine the choice column choice_col = self . model_obj . choice_col # Split the control flow based on whether we're using a Nested Logit current_model_type = self . model_obj . model_type non_2d_predictions = [ model_type_to_display_name [ "Nested Logit" ] , model_type_to_display_name [ "Mixed Logit" ] ] if current_model_type not in non_2d_predictions : # Get the param list for this set of replicates param_list = get_param_list_for_prediction ( self . model_obj , replicate_vec ) # Get the 'chosen_probs' using the desired set of replicates chosen_probs = self . model_obj . predict ( self . model_obj . data , param_list = param_list , return_long_probs = False , choice_col = choice_col ) else : # Initialize a list of chosen probs chosen_probs_list = [ ] # Create an iterable for iteration iterable_for_iteration = PROGRESS ( xrange ( replicate_vec . shape [ 0 ] ) , desc = "Calculate Gradient Norms" , total = replicate_vec . shape [ 0 ] ) # Populate the list of chosen probabilities for each vector of # parameter values for idx in iterable_for_iteration : # Get the param list for this set of replicates param_list = get_param_list_for_prediction ( self . model_obj , replicate_vec [ idx ] [ None , : ] ) # Use 1D parameters in the prediction function param_list = [ x . ravel ( ) if x is not None else x for x in param_list ] # Get the 'chosen_probs' using the desired set of replicates chosen_probs = self . model_obj . predict ( self . model_obj . data , param_list = param_list , return_long_probs = False , choice_col = choice_col , num_draws = num_draws , seed = seed ) # store those chosen prob_results chosen_probs_list . append ( chosen_probs [ : , None ] ) # Get the final array of chosen probs chosen_probs = np . concatenate ( chosen_probs_list , axis = 1 ) # Calculate the log_likelihood log_likelihoods = np . log ( chosen_probs ) . sum ( axis = 0 ) # Store the log-likelihood values attribute_name = replicates + "_log_likelihoods" log_like_series = pd . Series ( log_likelihoods , name = attribute_name ) setattr ( self , attribute_name , log_like_series ) return log_likelihoods | Calculate the log - likelihood value of one s replicates given one s dataset . | 706 | 18 |
232,758 | def calc_gradient_norm_for_replicates ( self , replicates = 'bootstrap' , ridge = None , constrained_pos = None , weights = None ) : # Check the validity of the kwargs ensure_replicates_kwarg_validity ( replicates ) # Create the estimation object estimation_obj = create_estimation_obj ( self . model_obj , self . mle_params . values , ridge = ridge , constrained_pos = constrained_pos , weights = weights ) # Prepare the estimation object to calculate the gradients if hasattr ( estimation_obj , "set_derivatives" ) : estimation_obj . set_derivatives ( ) # Get the array of parameter replicates replicate_array = getattr ( self , replicates + "_replicates" ) . values # Determine the number of replicates num_reps = replicate_array . shape [ 0 ] # Initialize an empty array to store the gradient norms gradient_norms = np . empty ( ( num_reps , ) , dtype = float ) # Create an iterable for iteration iterable_for_iteration = PROGRESS ( xrange ( num_reps ) , desc = "Calculating Gradient Norms" , total = num_reps ) # Iterate through the rows of the replicates and calculate and store # the gradient norm for each replicated parameter vector. for row in iterable_for_iteration : current_params = replicate_array [ row ] gradient = estimation_obj . convenience_calc_gradient ( current_params ) gradient_norms [ row ] = np . linalg . norm ( gradient ) return gradient_norms | Calculate the Euclidean - norm of the gradient of one s replicates given one s dataset . | 358 | 22 |
232,759 | def calc_percentile_interval ( self , conf_percentage ) : # Get the alpha % that corresponds to the given confidence percentage. alpha = bc . get_alpha_from_conf_percentage ( conf_percentage ) # Create the column names for the dataframe of confidence intervals single_column_names = [ '{:.3g}%' . format ( alpha / 2.0 ) , '{:.3g}%' . format ( 100 - alpha / 2.0 ) ] # Calculate the desired confidence intervals. conf_intervals = bc . calc_percentile_interval ( self . bootstrap_replicates . values , conf_percentage ) # Store the desired confidence intervals self . percentile_interval = pd . DataFrame ( conf_intervals . T , index = self . mle_params . index , columns = single_column_names ) return None | Calculates percentile bootstrap confidence intervals for one s model . | 194 | 13 |
232,760 | def calc_abc_interval ( self , conf_percentage , init_vals , epsilon = 0.001 , * * fit_kwargs ) : print ( "Calculating Approximate Bootstrap Confidence (ABC) Intervals" ) print ( time . strftime ( "%a %m-%d-%Y %I:%M%p" ) ) sys . stdout . flush ( ) # Get the alpha % that corresponds to the given confidence percentage. alpha = bc . get_alpha_from_conf_percentage ( conf_percentage ) # Create the column names for the dataframe of confidence intervals single_column_names = [ '{:.3g}%' . format ( alpha / 2.0 ) , '{:.3g}%' . format ( 100 - alpha / 2.0 ) ] # Calculate the ABC confidence intervals conf_intervals = abc . calc_abc_interval ( self . model_obj , self . mle_params . values , init_vals , conf_percentage , epsilon = epsilon , * * fit_kwargs ) # Store the ABC confidence intervals self . abc_interval = pd . DataFrame ( conf_intervals . T , index = self . mle_params . index , columns = single_column_names ) return None | Calculates Approximate Bootstrap Confidence Intervals for one s model . | 291 | 17 |
232,761 | def calc_conf_intervals ( self , conf_percentage , interval_type = 'all' , init_vals = None , epsilon = abc . EPSILON , * * fit_kwargs ) : if interval_type == 'pi' : self . calc_percentile_interval ( conf_percentage ) elif interval_type == 'bca' : self . calc_bca_interval ( conf_percentage ) elif interval_type == 'abc' : self . calc_abc_interval ( conf_percentage , init_vals , epsilon = epsilon , * * fit_kwargs ) elif interval_type == 'all' : print ( "Calculating Percentile Confidence Intervals" ) sys . stdout . flush ( ) self . calc_percentile_interval ( conf_percentage ) print ( "Calculating BCa Confidence Intervals" ) sys . stdout . flush ( ) self . calc_bca_interval ( conf_percentage ) # Note we don't print a user message here since that is done in # self.calc_abc_interval(). self . calc_abc_interval ( conf_percentage , init_vals , epsilon = epsilon , * * fit_kwargs ) # Get the alpha % for the given confidence percentage. alpha = bc . get_alpha_from_conf_percentage ( conf_percentage ) # Get lists of the interval type names and the endpoint names interval_type_names = [ 'percentile_interval' , 'BCa_interval' , 'ABC_interval' ] endpoint_names = [ '{:.3g}%' . format ( alpha / 2.0 ) , '{:.3g}%' . format ( 100 - alpha / 2.0 ) ] # Create the column names for the dataframe of confidence intervals multi_index_names = list ( itertools . product ( interval_type_names , endpoint_names ) ) df_column_index = pd . MultiIndex . from_tuples ( multi_index_names ) # Create the dataframe containing all confidence intervals self . all_intervals = pd . concat ( [ self . percentile_interval , self . bca_interval , self . abc_interval ] , axis = 1 , ignore_index = True ) # Store the column names for the combined confidence intervals self . all_intervals . columns = df_column_index self . all_intervals . index = self . mle_params . index else : msg = "interval_type MUST be in `['pi', 'bca', 'abc', 'all']`" raise ValueError ( msg ) return None | Calculates percentile bias - corrected and accelerated and approximate bootstrap confidence intervals . | 596 | 16 |
232,762 | def create_calc_dh_d_alpha ( estimator ) : if estimator . intercept_ref_pos is not None : needed_idxs = range ( estimator . rows_to_alts . shape [ 1 ] ) needed_idxs . remove ( estimator . intercept_ref_pos ) dh_d_alpha = ( estimator . rows_to_alts . copy ( ) . transpose ( ) [ needed_idxs , : ] . transpose ( ) ) else : dh_d_alpha = None # Create a function that will take in the pre-formed matrix, replace its # data in-place with the new data, and return the correct dh_dalpha on each # iteration of the minimizer calc_dh_d_alpha = partial ( _cloglog_transform_deriv_alpha , output_array = dh_d_alpha ) return calc_dh_d_alpha | Return the function that can be used in the various gradient and hessian calculations to calculate the derivative of the transformation with respect to the outside intercept parameters . | 197 | 31 |
232,763 | def calc_individual_chi_squares ( residuals , long_probabilities , rows_to_obs ) : chi_squared_terms = np . square ( residuals ) / long_probabilities return rows_to_obs . T . dot ( chi_squared_terms ) | Calculates individual chi - squared values for each choice situation in the dataset . | 64 | 16 |
232,764 | def calc_rho_and_rho_bar_squared ( final_log_likelihood , null_log_likelihood , num_est_parameters ) : rho_squared = 1.0 - final_log_likelihood / null_log_likelihood rho_bar_squared = 1.0 - ( ( final_log_likelihood - num_est_parameters ) / null_log_likelihood ) return rho_squared , rho_bar_squared | Calculates McFadden s rho - squared and rho - bar squared for the given model . | 111 | 21 |
232,765 | def calc_and_store_post_estimation_results ( results_dict , estimator ) : # Store the final log-likelihood final_log_likelihood = - 1 * results_dict [ "fun" ] results_dict [ "final_log_likelihood" ] = final_log_likelihood # Get the final array of estimated parameters final_params = results_dict [ "x" ] # Add the estimated parameters to the results dictionary split_res = estimator . convenience_split_params ( final_params , return_all_types = True ) results_dict [ "nest_params" ] = split_res [ 0 ] results_dict [ "shape_params" ] = split_res [ 1 ] results_dict [ "intercept_params" ] = split_res [ 2 ] results_dict [ "utility_coefs" ] = split_res [ 3 ] # Get the probability of the chosen alternative and long_form probabilities chosen_probs , long_probs = estimator . convenience_calc_probs ( final_params ) results_dict [ "chosen_probs" ] = chosen_probs results_dict [ "long_probs" ] = long_probs ##### # Calculate the residuals and individual chi-square values ##### # Calculate the residual vector if len ( long_probs . shape ) == 1 : residuals = estimator . choice_vector - long_probs else : residuals = estimator . choice_vector [ : , None ] - long_probs results_dict [ "residuals" ] = residuals # Calculate the observation specific chi-squared components args = [ residuals , long_probs , estimator . rows_to_obs ] results_dict [ "ind_chi_squareds" ] = calc_individual_chi_squares ( * args ) # Calculate and store the rho-squared and rho-bar-squared log_likelihood_null = results_dict [ "log_likelihood_null" ] rho_results = calc_rho_and_rho_bar_squared ( final_log_likelihood , log_likelihood_null , final_params . shape [ 0 ] ) results_dict [ "rho_squared" ] = rho_results [ 0 ] results_dict [ "rho_bar_squared" ] = rho_results [ 1 ] ##### # Calculate the gradient, hessian, and BHHH approximation to the fisher # info matrix ##### results_dict [ "final_gradient" ] = estimator . convenience_calc_gradient ( final_params ) results_dict [ "final_hessian" ] = estimator . convenience_calc_hessian ( final_params ) results_dict [ "fisher_info" ] = estimator . convenience_calc_fisher_approx ( final_params ) # Store the constrained positions that was used in this estimation process results_dict [ "constrained_pos" ] = estimator . constrained_pos return results_dict | Calculates and stores post - estimation results that require the use of the systematic utility transformation functions or the various derivative functions . Note that this function is only valid for logit - type models . | 670 | 39 |
232,766 | def estimate ( init_values , estimator , method , loss_tol , gradient_tol , maxiter , print_results , use_hessian = True , just_point = False , * * kwargs ) : if not just_point : # Perform preliminary calculations log_likelihood_at_zero = estimator . convenience_calc_log_likelihood ( estimator . zero_vector ) initial_log_likelihood = estimator . convenience_calc_log_likelihood ( init_values ) if print_results : # Print the log-likelihood at zero null_msg = "Log-likelihood at zero: {:,.4f}" print ( null_msg . format ( log_likelihood_at_zero ) ) # Print the log-likelihood at the starting values init_msg = "Initial Log-likelihood: {:,.4f}" print ( init_msg . format ( initial_log_likelihood ) ) sys . stdout . flush ( ) # Get the hessian fucntion for this estimation process hess_func = estimator . calc_neg_hessian if use_hessian else None # Estimate the actual parameters of the model start_time = time . time ( ) results = minimize ( estimator . calc_neg_log_likelihood_and_neg_gradient , init_values , method = method , jac = True , hess = hess_func , tol = loss_tol , options = { 'gtol' : gradient_tol , "maxiter" : maxiter } , * * kwargs ) if not just_point : if print_results : # Stop timing the estimation process and report the timing results end_time = time . time ( ) elapsed_sec = ( end_time - start_time ) elapsed_min = elapsed_sec / 60.0 if elapsed_min > 1.0 : msg = "Estimation Time for Point Estimation: {:.2f} minutes." print ( msg . format ( elapsed_min ) ) else : msg = "Estimation Time for Point Estimation: {:.2f} seconds." print ( msg . format ( elapsed_sec ) ) print ( "Final log-likelihood: {:,.4f}" . format ( - 1 * results [ "fun" ] ) ) sys . stdout . flush ( ) # Store the log-likelihood at zero results [ "log_likelihood_null" ] = log_likelihood_at_zero # Calculate and store the post-estimation results results = calc_and_store_post_estimation_results ( results , estimator ) return results | Estimate the given choice model that is defined by estimator . | 566 | 13 |
232,767 | def calc_neg_log_likelihood_and_neg_gradient ( self , params ) : neg_log_likelihood = - 1 * self . convenience_calc_log_likelihood ( params ) neg_gradient = - 1 * self . convenience_calc_gradient ( params ) if self . constrained_pos is not None : neg_gradient [ self . constrained_pos ] = 0 return neg_log_likelihood , neg_gradient | Calculates and returns the negative of the log - likelihood and the negative of the gradient . This function is used as the objective function in scipy . optimize . minimize . | 96 | 36 |
232,768 | def ensure_samples_is_ndim_ndarray ( samples , name = 'bootstrap' , ndim = 2 ) : assert isinstance ( ndim , int ) assert isinstance ( name , str ) if not isinstance ( samples , np . ndarray ) or not ( samples . ndim == ndim ) : sample_name = name + "_samples" msg = "`{}` MUST be a {}D ndarray." . format ( sample_name , ndim ) raise ValueError ( msg ) return None | Ensures that samples is an ndim numpy array . Raises a helpful ValueError if otherwise . | 115 | 22 |
232,769 | def create_estimation_obj ( model_obj , init_vals , mappings = None , ridge = None , constrained_pos = None , weights = None ) : # Get the mapping matrices for each model mapping_matrices = model_obj . get_mappings_for_fit ( ) if mappings is None else mappings # Create the zero vector for each model. zero_vector = np . zeros ( init_vals . shape [ 0 ] ) # Get the internal model name internal_model_name = display_name_to_model_type [ model_obj . model_type ] # Get the split parameter function and estimator class for this model. estimator_class , current_split_func = ( model_type_to_resources [ internal_model_name ] [ 'estimator' ] , model_type_to_resources [ internal_model_name ] [ 'split_func' ] ) # Create the estimator instance that is desired. estimation_obj = estimator_class ( model_obj , mapping_matrices , ridge , zero_vector , current_split_func , constrained_pos , weights = weights ) # Return the created object return estimation_obj | Should return a model estimation object corresponding to the model type of the model_obj . | 256 | 17 |
232,770 | def ensure_wide_weights_is_1D_or_2D_ndarray ( wide_weights ) : if not isinstance ( wide_weights , np . ndarray ) : msg = "wide_weights MUST be a ndarray." raise ValueError ( msg ) ndim = wide_weights . ndim if not 0 < ndim < 3 : msg = "wide_weights MUST be a 1D or 2D ndarray." raise ValueError ( msg ) return None | Ensures that wide_weights is a 1D or 2D ndarray . Raises a helpful ValueError if otherwise . | 104 | 27 |
232,771 | def check_validity_of_long_form_args ( model_obj , wide_weights , rows_to_obs ) : # Ensure model_obj has the necessary method for create_long_form_weights ensure_model_obj_has_mapping_constructor ( model_obj ) # Ensure wide_weights is a 1D or 2D ndarray. ensure_wide_weights_is_1D_or_2D_ndarray ( wide_weights ) # Ensure rows_to_obs is a scipy sparse matrix ensure_rows_to_obs_validity ( rows_to_obs ) return None | Ensures the args to create_long_form_weights have expected properties . | 136 | 17 |
232,772 | def calc_finite_diff_terms_for_abc ( model_obj , mle_params , init_vals , epsilon , * * fit_kwargs ) : # Determine the number of observations in this dataset. num_obs = model_obj . data [ model_obj . obs_id_col ] . unique ( ) . size # Determine the initial weights per observation. init_weights_wide = np . ones ( num_obs , dtype = float ) / num_obs # Initialize wide weights for elements of the second order influence array. init_wide_weights_plus = ( 1 - epsilon ) * init_weights_wide init_wide_weights_minus = ( 1 + epsilon ) * init_weights_wide # Initialize the second order influence array term_plus = np . empty ( ( num_obs , init_vals . shape [ 0 ] ) , dtype = float ) term_minus = np . empty ( ( num_obs , init_vals . shape [ 0 ] ) , dtype = float ) # Get the rows_to_obs mapping matrix for this model. rows_to_obs = model_obj . get_mappings_for_fit ( ) [ 'rows_to_obs' ] # Extract the initial weights from the fit kwargs new_fit_kwargs = deepcopy ( fit_kwargs ) if fit_kwargs is not None and 'weights' in fit_kwargs : orig_weights = fit_kwargs [ 'weights' ] del new_fit_kwargs [ 'weights' ] else : orig_weights = 1 # Make sure we're just getting the point estimate new_fit_kwargs [ 'just_point' ] = True # Populate the second order influence array for obs in xrange ( num_obs ) : # Note we create the long weights in a for-loop to avoid creating a # num_obs by num_obs matrix, which may be a problem for large datasets # Get the wide format weights for this observation current_wide_weights_plus = init_wide_weights_plus . copy ( ) current_wide_weights_plus [ obs ] += epsilon current_wide_weights_minus = init_wide_weights_minus . copy ( ) current_wide_weights_minus [ obs ] -= epsilon # Get the long format weights for this observation long_weights_plus = ( create_long_form_weights ( model_obj , current_wide_weights_plus , rows_to_obs = rows_to_obs ) * orig_weights ) long_weights_minus = ( create_long_form_weights ( model_obj , current_wide_weights_minus , rows_to_obs = rows_to_obs ) * orig_weights ) # Get the needed influence estimates. term_plus [ obs ] = model_obj . fit_mle ( init_vals , weights = long_weights_plus , * * new_fit_kwargs ) [ 'x' ] term_minus [ obs ] = model_obj . fit_mle ( init_vals , weights = long_weights_minus , * * new_fit_kwargs ) [ 'x' ] return term_plus , term_minus | Calculates the terms needed for the finite difference approximations of the empirical influence and second order empirical influence functions . | 696 | 24 |
232,773 | def calc_abc_interval ( model_obj , mle_params , init_vals , conf_percentage , epsilon = 0.001 , * * fit_kwargs ) : # Check validity of arguments check_conf_percentage_validity ( conf_percentage ) # Calculate the empirical influence component and second order empirical # influence component for each observation empirical_influence , second_order_influence = calc_influence_arrays_for_abc ( model_obj , mle_params , init_vals , epsilon , * * fit_kwargs ) # Calculate the acceleration constant for the ABC interval. acceleration = calc_acceleration_abc ( empirical_influence ) # Use the delta method to calculate the standard error of the MLE parameter # estimate of the model using the original data. std_error = calc_std_error_abc ( empirical_influence ) # Approximate the bias of the MLE parameter estimates. bias = calc_bias_abc ( second_order_influence ) # Calculate the quadratic coefficient. Note we are using the 'efron' # version of the desired function because the direct implementation of the # formulas in the textbook don't return the correct results. The 'efron' # versions re-implement the calculations from 'abcnon.R' in Efron's # 'bootstrap' library in R. # quadratic_coef = calc_quadratic_coef_abc(model_obj, # mle_params, # init_vals, # empirical_influence, # std_error, # epsilon, # **fit_kwargs) quadratic_coef = efron_quadratic_coef_abc ( model_obj , mle_params , init_vals , empirical_influence , std_error , epsilon , * * fit_kwargs ) # Calculate the total curvature of the level surface of the weight vector, # where the set of weights in the surface are those where the weighted MLE # equals the original (i.e. the equal-weighted) MLE. total_curvature = calc_total_curvature_abc ( bias , std_error , quadratic_coef ) # Calculate the bias correction constant. bias_correction = calc_bias_correction_abc ( acceleration , total_curvature ) # Calculate the lower limit of the conf_percentage confidence intervals # Note we are using the 'efron' version of the desired function because the # direct implementation of the formulas in the textbook don't return the # correct results. The 'efron' versions re-implement the calculations from # 'abcnon.R' in Efron's 'bootstrap' library in R. # lower_endpoint, upper_endpoint =\ # calc_endpoints_for_abc_confidence_interval(conf_percentage, # model_obj, # init_vals, # bias_correction, # acceleration, # std_error, # empirical_influence, # **fit_kwargs) lower_endpoint , upper_endpoint = efron_endpoints_for_abc_confidence_interval ( conf_percentage , model_obj , init_vals , bias_correction , acceleration , std_error , empirical_influence , * * fit_kwargs ) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints ( lower_endpoint , upper_endpoint ) return conf_intervals | Calculate approximate bootstrap confidence intervals . | 771 | 9 |
232,774 | def check_length_of_init_values ( design_3d , init_values ) : if init_values . shape [ 0 ] != design_3d . shape [ 2 ] : msg_1 = "The initial values are of the wrong dimension. " msg_2 = "They should be of dimension {}" . format ( design_3d . shape [ 2 ] ) raise ValueError ( msg_1 + msg_2 ) return None | Ensures that the initial values are of the correct length given the design matrix that they will be dot - producted with . Raises a ValueError if that is not the case and provides a useful error message to users . | 95 | 46 |
232,775 | def add_mixl_specific_results_to_estimation_res ( estimator , results_dict ) : # Get the probability of each sequence of choices, given the draws prob_res = mlc . calc_choice_sequence_probs ( results_dict [ "long_probs" ] , estimator . choice_vector , estimator . rows_to_mixers , return_type = 'all' ) # Add the various items to the results_dict. results_dict [ "simulated_sequence_probs" ] = prob_res [ 0 ] results_dict [ "expanded_sequence_probs" ] = prob_res [ 1 ] return results_dict | Stores particular items in the results dictionary that are unique to mixed logit - type models . In particular this function calculates and adds sequence_probs and expanded_sequence_probs to the results dictionary . The constrained_pos object is also stored to the results_dict . | 148 | 56 |
232,776 | def identify_degenerate_nests ( nest_spec ) : degenerate_positions = [ ] for pos , key in enumerate ( nest_spec ) : if len ( nest_spec [ key ] ) == 1 : degenerate_positions . append ( pos ) return degenerate_positions | Identify the nests within nest_spec that are degenerate i . e . those nests with only a single alternative within the nest . | 65 | 27 |
232,777 | def check_length_of_initial_values ( self , init_values ) : # Figure out how many shape parameters we should have and how many # index coefficients we should have num_nests = self . rows_to_nests . shape [ 1 ] num_index_coefs = self . design . shape [ 1 ] assumed_param_dimensions = num_index_coefs + num_nests if init_values . shape [ 0 ] != assumed_param_dimensions : msg = "The initial values are of the wrong dimension" msg_1 = "It should be of dimension {}" msg_2 = "But instead it has dimension {}" raise ValueError ( msg + msg_1 . format ( assumed_param_dimensions ) + msg_2 . format ( init_values . shape [ 0 ] ) ) return None | Ensures that the initial values are of the correct length . | 181 | 13 |
232,778 | def convenience_split_params ( self , params , return_all_types = False ) : return split_param_vec ( params , self . rows_to_nests , return_all_types = return_all_types ) | Splits parameter vector into nest parameters and index parameters . | 50 | 11 |
232,779 | def robust_outer_product ( vec_1 , vec_2 ) : mantissa_1 , exponents_1 = np . frexp ( vec_1 ) mantissa_2 , exponents_2 = np . frexp ( vec_2 ) new_mantissas = mantissa_1 [ None , : ] * mantissa_2 [ : , None ] new_exponents = exponents_1 [ None , : ] + exponents_2 [ : , None ] return new_mantissas * np . exp2 ( new_exponents ) | Calculates a robust outer product of two vectors that may or may not contain very small values . | 122 | 20 |
232,780 | def calc_percentile_interval ( bootstrap_replicates , conf_percentage ) : # Check validity of arguments check_conf_percentage_validity ( conf_percentage ) ensure_samples_is_ndim_ndarray ( bootstrap_replicates , ndim = 2 ) # Get the alpha * 100% value alpha = get_alpha_from_conf_percentage ( conf_percentage ) # Get the lower and upper percentiles that demarcate the desired interval. lower_percent = alpha / 2.0 upper_percent = 100.0 - lower_percent # Calculate the lower and upper endpoints of the confidence intervals. # Note that the particular choices of interpolation methods are made in # order to produce conservatively wide confidence intervals and ensure that # all returned endpoints in the confidence intervals are actually observed # in the bootstrap distribution. This is in accordance with the spirit of # Efron and Tibshirani (1994). lower_endpoint = np . percentile ( bootstrap_replicates , lower_percent , interpolation = 'lower' , axis = 0 ) upper_endpoint = np . percentile ( bootstrap_replicates , upper_percent , interpolation = 'higher' , axis = 0 ) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints ( lower_endpoint , upper_endpoint ) return conf_intervals | Calculate bootstrap confidence intervals based on raw percentiles of the bootstrap distribution of samples . | 304 | 20 |
232,781 | def calc_bca_interval ( bootstrap_replicates , jackknife_replicates , mle_params , conf_percentage ) : # Check validity of arguments check_conf_percentage_validity ( conf_percentage ) ensure_samples_is_ndim_ndarray ( bootstrap_replicates , ndim = 2 ) ensure_samples_is_ndim_ndarray ( jackknife_replicates , name = 'jackknife' , ndim = 2 ) # Calculate the alpha * 100% value alpha_percent = get_alpha_from_conf_percentage ( conf_percentage ) # Estimate the bias correction for the bootstrap samples bias_correction = calc_bias_correction_bca ( bootstrap_replicates , mle_params ) # Estimate the acceleration acceleration = calc_acceleration_bca ( jackknife_replicates ) # Get the lower and upper percent value for the raw bootstrap samples. lower_percents = calc_lower_bca_percentile ( alpha_percent , bias_correction , acceleration ) upper_percents = calc_upper_bca_percentile ( alpha_percent , bias_correction , acceleration ) # Get the lower and upper endpoints for the desired confidence intervals. lower_endpoints = np . diag ( np . percentile ( bootstrap_replicates , lower_percents , interpolation = 'lower' , axis = 0 ) ) upper_endpoints = np . diag ( np . percentile ( bootstrap_replicates , upper_percents , interpolation = 'higher' , axis = 0 ) ) # Combine the enpoints into a single ndarray. conf_intervals = combine_conf_endpoints ( lower_endpoints , upper_endpoints ) return conf_intervals | Calculate bias - corrected and accelerated bootstrap confidence intervals . | 394 | 13 |
232,782 | def extract_default_init_vals ( orig_model_obj , mnl_point_series , num_params ) : # Initialize the initial values init_vals = np . zeros ( num_params , dtype = float ) # Figure out which values in mnl_point_series are the index coefficients no_outside_intercepts = orig_model_obj . intercept_names is None if no_outside_intercepts : init_index_coefs = mnl_point_series . values init_intercepts = None else : init_index_coefs = mnl_point_series . loc [ orig_model_obj . ind_var_names ] . values init_intercepts = mnl_point_series . loc [ orig_model_obj . intercept_names ] . values # Add any mixing variables to the index coefficients. if orig_model_obj . mixing_vars is not None : num_mixing_vars = len ( orig_model_obj . mixing_vars ) init_index_coefs = np . concatenate ( [ init_index_coefs , np . zeros ( num_mixing_vars ) ] , axis = 0 ) # Account for the special transformation of the index coefficients that is # needed for the asymmetric logit model. if orig_model_obj . model_type == model_type_to_display_name [ "Asym" ] : multiplier = np . log ( len ( np . unique ( orig_model_obj . alt_IDs ) ) ) # Cast the initial index coefficients to a float dtype to ensure # successful broadcasting init_index_coefs = init_index_coefs . astype ( float ) # Adjust the scale of the index coefficients for the asymmetric logit. init_index_coefs /= multiplier # Combine the initial interept values with the initial index coefficients if init_intercepts is not None : init_index_coefs = np . concatenate ( [ init_intercepts , init_index_coefs ] , axis = 0 ) # Add index coefficients (and mixing variables) to the total initial array num_index = init_index_coefs . shape [ 0 ] init_vals [ - 1 * num_index : ] = init_index_coefs # Note that the initial values for the transformed nest coefficients and # the shape parameters is zero so we don't have to change anything return init_vals | Get the default initial values for the desired model type based on the point estimate of the MNL model that is closest to the desired model . | 538 | 28 |
232,783 | def get_model_abbrev ( model_obj ) : # Get the 'display name' for our model. model_type = model_obj . model_type # Find the model abbreviation for this model's display name. for key in model_type_to_display_name : if model_type_to_display_name [ key ] == model_type : return key # If none of the strings in model_type_to_display_name matches our model # object, then raise an error. msg = "Model object has an unknown or incorrect model type." raise ValueError ( msg ) | Extract the string used to specify the model type of this model object in pylogit . create_chohice_model . | 128 | 28 |
232,784 | def get_model_creation_kwargs ( model_obj ) : # Extract the model abbreviation for this model model_abbrev = get_model_abbrev ( model_obj ) # Create a dictionary to store the keyword arguments needed to Initialize # the new model object.d model_kwargs = { "model_type" : model_abbrev , "names" : model_obj . name_spec , "intercept_names" : model_obj . intercept_names , "intercept_ref_pos" : model_obj . intercept_ref_position , "shape_names" : model_obj . shape_names , "shape_ref_pos" : model_obj . shape_ref_position , "nest_spec" : model_obj . nest_spec , "mixing_vars" : model_obj . mixing_vars , "mixing_id_col" : model_obj . mixing_id_col } return model_kwargs | Get a dictionary of the keyword arguments needed to create the passed model object using pylogit . create_choice_model . | 214 | 26 |
232,785 | def ensure_valid_model_type ( specified_type , model_type_list ) : if specified_type not in model_type_list : msg_1 = "The specified model_type was not valid." msg_2 = "Valid model-types are {}" . format ( model_type_list ) msg_3 = "The passed model-type was: {}" . format ( specified_type ) total_msg = "\n" . join ( [ msg_1 , msg_2 , msg_3 ] ) raise ValueError ( total_msg ) return None | Checks to make sure that specified_type is in model_type_list and raises a helpful error if this is not the case . | 122 | 28 |
232,786 | def ensure_valid_nums_in_specification_cols ( specification , dataframe ) : problem_cols = [ ] for col in specification : # The condition below checks for values that are not floats or integers # This will catch values that are strings. if dataframe [ col ] . dtype . kind not in [ 'f' , 'i' , 'u' ] : problem_cols . append ( col ) # The condition below checks for positive or negative inifinity values. elif np . isinf ( dataframe [ col ] ) . any ( ) : problem_cols . append ( col ) # This condition will check for NaN values. elif np . isnan ( dataframe [ col ] ) . any ( ) : problem_cols . append ( col ) if problem_cols != [ ] : msg = "The following columns contain either +/- inifinity values, " msg_2 = "NaN values, or values that are not real numbers " msg_3 = "(e.g. strings):\n{}" total_msg = msg + msg_2 + msg_3 raise ValueError ( total_msg . format ( problem_cols ) ) return None | Checks whether each column in specification contains numeric data excluding positive or negative infinity and excluding NaN . Raises ValueError if any of the columns do not meet these requirements . | 257 | 35 |
232,787 | def check_length_of_shape_or_intercept_names ( name_list , num_alts , constrained_param , list_title ) : if len ( name_list ) != ( num_alts - constrained_param ) : msg_1 = "{} is of the wrong length:" . format ( list_title ) msg_2 = "len({}) == {}" . format ( list_title , len ( name_list ) ) correct_length = num_alts - constrained_param msg_3 = "The correct length is: {}" . format ( correct_length ) total_msg = "\n" . join ( [ msg_1 , msg_2 , msg_3 ] ) raise ValueError ( total_msg ) return None | Ensures that the length of the parameter names matches the number of parameters that will be estimated . Will raise a ValueError otherwise . | 162 | 27 |
232,788 | def check_type_of_nest_spec_keys_and_values ( nest_spec ) : try : assert all ( [ isinstance ( k , str ) for k in nest_spec ] ) assert all ( [ isinstance ( nest_spec [ k ] , list ) for k in nest_spec ] ) except AssertionError : msg = "All nest_spec keys/values must be strings/lists." raise TypeError ( msg ) return None | Ensures that the keys and values of nest_spec are strings and lists . Raises a helpful ValueError if they are . | 98 | 27 |
232,789 | def check_for_empty_nests_in_nest_spec ( nest_spec ) : empty_nests = [ ] for k in nest_spec : if len ( nest_spec [ k ] ) == 0 : empty_nests . append ( k ) if empty_nests != [ ] : msg = "The following nests are INCORRECTLY empty: {}" raise ValueError ( msg . format ( empty_nests ) ) return None | Ensures that the values of nest_spec are not empty lists . Raises a helpful ValueError if they are . | 98 | 25 |
232,790 | def ensure_alt_ids_in_nest_spec_are_ints ( nest_spec , list_elements ) : try : assert all ( [ isinstance ( x , int ) for x in list_elements ] ) except AssertionError : msg = "All elements of the nest_spec values should be integers" raise ValueError ( msg ) return None | Ensures that the alternative id s in nest_spec are integers . Raises a helpful ValueError if they are not . | 79 | 26 |
232,791 | def ensure_alt_ids_are_only_in_one_nest ( nest_spec , list_elements ) : try : assert len ( set ( list_elements ) ) == len ( list_elements ) except AssertionError : msg = "Each alternative id should only be in a single nest." raise ValueError ( msg ) return None | Ensures that the alternative id s in nest_spec are only associated with a single nest . Raises a helpful ValueError if they are not . | 77 | 31 |
232,792 | def ensure_all_alt_ids_have_a_nest ( nest_spec , list_elements , all_ids ) : unaccounted_alt_ids = [ ] for alt_id in all_ids : if alt_id not in list_elements : unaccounted_alt_ids . append ( alt_id ) if unaccounted_alt_ids != [ ] : msg = "Associate the following alternative ids with a nest: {}" raise ValueError ( msg . format ( unaccounted_alt_ids ) ) return None | Ensures that the alternative id s in nest_spec are all associated with a nest . Raises a helpful ValueError if they are not . | 117 | 30 |
232,793 | def ensure_nest_alts_are_valid_alts ( nest_spec , list_elements , all_ids ) : invalid_alt_ids = [ ] for x in list_elements : if x not in all_ids : invalid_alt_ids . append ( x ) if invalid_alt_ids != [ ] : msg = "The following elements are not in df[alt_id_col]: {}" raise ValueError ( msg . format ( invalid_alt_ids ) ) return None | Ensures that the alternative id s in nest_spec are all in the universal choice set for this dataset . Raises a helpful ValueError if they are not . | 110 | 34 |
232,794 | def check_type_and_size_of_param_list ( param_list , expected_length ) : try : assert isinstance ( param_list , list ) assert len ( param_list ) == expected_length except AssertionError : msg = "param_list must be a list containing {} elements." raise ValueError ( msg . format ( expected_length ) ) return None | Ensure that param_list is a list with the expected length . Raises a helpful ValueError if this is not the case . | 82 | 27 |
232,795 | def check_type_of_param_list_elements ( param_list ) : try : assert isinstance ( param_list [ 0 ] , np . ndarray ) assert all ( [ ( x is None or isinstance ( x , np . ndarray ) ) for x in param_list ] ) except AssertionError : msg = "param_list[0] must be a numpy array." msg_2 = "All other elements must be numpy arrays or None." total_msg = msg + "\n" + msg_2 raise TypeError ( total_msg ) return None | Ensures that all elements of param_list are ndarrays or None . Raises a helpful ValueError if otherwise . | 128 | 27 |
232,796 | def check_num_columns_in_param_list_arrays ( param_list ) : try : num_columns = param_list [ 0 ] . shape [ 1 ] assert all ( [ x is None or ( x . shape [ 1 ] == num_columns ) for x in param_list ] ) except AssertionError : msg = "param_list arrays should have equal number of columns." raise ValueError ( msg ) return None | Ensure that each array in param_list that is not None has the same number of columns . Raises a helpful ValueError if otherwise . | 97 | 29 |
232,797 | def ensure_all_mixing_vars_are_in_the_name_dict ( mixing_vars , name_dict , ind_var_names ) : if mixing_vars is None : return None # Determine the strings in mixing_vars that are missing from ind_var_names problem_names = [ variable_name for variable_name in mixing_vars if variable_name not in ind_var_names ] # Create error messages for the case where we have a name dictionary and # the case where we do not have a name dictionary. msg_0 = "The following parameter names were not in the values of the " msg_1 = "passed name dictionary: \n{}" msg_with_name_dict = msg_0 + msg_1 . format ( problem_names ) msg_2 = "The following paramter names did not match any of the default " msg_3 = "names generated for the parameters to be estimated: \n{}" msg_4 = "The default names that were generated were: \n{}" msg_without_name_dict = ( msg_2 + msg_3 . format ( problem_names ) + msg_4 . format ( ind_var_names ) ) # Raise a helpful ValueError if any mixing_vars were missing from # ind_var_names if problem_names != [ ] : if name_dict : raise ValueError ( msg_with_name_dict ) else : raise ValueError ( msg_without_name_dict ) return None | Ensures that all of the variables listed in mixing_vars are present in ind_var_names . Raises a helpful ValueError if otherwise . | 326 | 32 |
232,798 | def compute_aic ( model_object ) : assert isinstance ( model_object . params , pd . Series ) assert isinstance ( model_object . log_likelihood , Number ) return - 2 * model_object . log_likelihood + 2 * model_object . params . size | Compute the Akaike Information Criteria for an estimated model . | 62 | 14 |
232,799 | def compute_bic ( model_object ) : assert isinstance ( model_object . params , pd . Series ) assert isinstance ( model_object . log_likelihood , Number ) assert isinstance ( model_object . nobs , Number ) log_likelihood = model_object . log_likelihood num_obs = model_object . nobs num_params = model_object . params . size return - 2 * log_likelihood + np . log ( num_obs ) * num_params | Compute the Bayesian Information Criteria for an estimated model . | 109 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.