idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
233,600
def enable_torque ( self , ids ) : self . _set_torque_enable ( dict ( zip ( ids , itertools . repeat ( True ) ) ) )
Enables torque of the motors with the specified ids .
233,601
def disable_torque ( self , ids ) : self . _set_torque_enable ( dict ( zip ( ids , itertools . repeat ( False ) ) ) )
Disables torque of the motors with the specified ids .
233,602
def get_pid_gain ( self , ids , ** kwargs ) : return tuple ( [ tuple ( reversed ( t ) ) for t in self . _get_pid_gain ( ids , ** kwargs ) ] )
Gets the pid gain for the specified motors .
233,603
def set_pid_gain ( self , pid_for_id , ** kwargs ) : pid_for_id = dict ( itertools . izip ( pid_for_id . iterkeys ( ) , [ tuple ( reversed ( t ) ) for t in pid_for_id . values ( ) ] ) ) self . _set_pid_gain ( pid_for_id , ** kwargs )
Sets the pid gain to the specified motors .
233,604
def get_control_table ( self , ids , ** kwargs ) : error_handler = kwargs [ 'error_handler' ] if ( 'error_handler' in kwargs ) else self . _error_handler convert = kwargs [ 'convert' ] if ( 'convert' in kwargs ) else self . _convert bl = ( 'goal position speed load' , 'present position speed load' ) controls = [ c for ...
Gets the full control table for the specified motors .
233,605
def check_motor_eprom_configuration ( config , dxl_io , motor_names ) : changed_angle_limits = { } changed_return_delay_time = { } for name in motor_names : m = config [ 'motors' ] [ name ] id = m [ 'id' ] try : old_limits = dxl_io . get_angle_limit ( ( id , ) ) [ 0 ] old_return_delay_time = dxl_io . get_return_delay_t...
Change the angles limits depanding on the robot configuration ; Check if the return delay time is set to 0 .
233,606
def _get_gdcmconv ( ) : gdcmconv_executable = settings . gdcmconv_path if gdcmconv_executable is None : gdcmconv_executable = _which ( 'gdcmconv' ) if gdcmconv_executable is None : gdcmconv_executable = _which ( 'gdcmconv.exe' ) if gdcmconv_executable is None : raise ConversionError ( 'GDCMCONV_NOT_FOUND' ) return gdcm...
Get the full path to gdcmconv . If not found raise error
233,607
def compress_directory ( dicom_directory ) : if _is_compressed ( dicom_directory ) : return logger . info ( 'Compressing dicom files in %s' % dicom_directory ) for root , _ , files in os . walk ( dicom_directory ) : for dicom_file in files : if is_dicom_file ( os . path . join ( root , dicom_file ) ) : _compress_dicom ...
This function can be used to convert a folder of jpeg compressed images to an uncompressed ones
233,608
def is_dicom_file ( filename ) : file_stream = open ( filename , 'rb' ) file_stream . seek ( 128 ) data = file_stream . read ( 4 ) file_stream . close ( ) if data == b'DICM' : return True if settings . pydicom_read_force : try : dicom_headers = pydicom . read_file ( filename , defer_size = "1 KB" , stop_before_pixels =...
Util function to check if file is a dicom file the first 128 bytes are preamble the next 4 bytes should contain DICM otherwise it is not a dicom
233,609
def _is_compressed ( dicom_file , force = False ) : header = pydicom . read_file ( dicom_file , defer_size = "1 KB" , stop_before_pixels = True , force = force ) uncompressed_types = [ "1.2.840.10008.1.2" , "1.2.840.10008.1.2.1" , "1.2.840.10008.1.2.1.99" , "1.2.840.10008.1.2.2" ] if 'TransferSyntaxUID' in header . fil...
Check if dicoms are compressed or not
233,610
def _decompress_dicom ( dicom_file , output_file ) : gdcmconv_executable = _get_gdcmconv ( ) subprocess . check_output ( [ gdcmconv_executable , '-w' , dicom_file , output_file ] )
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
233,611
def dicom_diff ( file1 , file2 ) : datasets = compressed_dicom . read_file ( file1 ) , compressed_dicom . read_file ( file2 ) rep = [ ] for dataset in datasets : lines = ( str ( dataset . file_meta ) + "\n" + str ( dataset ) ) . split ( '\n' ) lines = [ line + '\n' for line in lines ] rep . append ( lines ) diff = diff...
Shows the fields that differ between two DICOM images .
233,612
def _get_number_of_slices ( self , slice_type ) : if slice_type == SliceType . AXIAL : return self . dimensions [ self . axial_orientation . normal_component ] elif slice_type == SliceType . SAGITTAL : return self . dimensions [ self . sagittal_orientation . normal_component ] elif slice_type == SliceType . CORONAL : r...
Get the number of slices in a certain direction
233,613
def _get_first_header ( dicom_directory ) : for root , _ , file_names in os . walk ( dicom_directory ) : for file_name in file_names : file_path = os . path . join ( root , file_name ) if not compressed_dicom . is_dicom_file ( file_path ) : continue return compressed_dicom . read_file ( file_path , stop_before_pixels =...
Function to get the first dicom file form a directory and return the header Useful to determine the type of data to convert
233,614
def _reorient_3d ( image ) : new_image = numpy . zeros ( [ image . dimensions [ image . sagittal_orientation . normal_component ] , image . dimensions [ image . coronal_orientation . normal_component ] , image . dimensions [ image . axial_orientation . normal_component ] ] , dtype = image . nifti_data . dtype ) if imag...
Reorganize the data for a 3d nifti
233,615
def dicom_to_nifti ( dicom_input , output_file = None ) : assert common . is_philips ( dicom_input ) if common . is_multiframe_dicom ( dicom_input ) : _assert_explicit_vr ( dicom_input ) logger . info ( 'Found multiframe dicom' ) if _is_multiframe_4d ( dicom_input ) : logger . info ( 'Found sequence type: MULTIFRAME 4D...
This is the main dicom to nifti conversion fuction for philips images . As input philips images are required . It will then determine the type of images and do the correct conversion
233,616
def _assert_explicit_vr ( dicom_input ) : if settings . validate_multiframe_implicit : header = dicom_input [ 0 ] if header . file_meta [ 0x0002 , 0x0010 ] . value == '1.2.840.10008.1.2' : raise ConversionError ( 'IMPLICIT_VR_ENHANCED_DICOM' )
Assert that explicit vr is used
233,617
def _is_multiframe_4d ( dicom_input ) : if not common . is_multiframe_dicom ( dicom_input ) : return False header = dicom_input [ 0 ] number_of_stack_slices = common . get_ss_value ( header [ Tag ( 0x2001 , 0x105f ) ] [ 0 ] [ Tag ( 0x2001 , 0x102d ) ] ) number_of_stacks = int ( int ( header . NumberOfFrames ) / number_...
Use this function to detect if a dicom series is a philips multiframe 4D dataset
233,618
def _is_singleframe_4d ( dicom_input ) : header = dicom_input [ 0 ] slice_number_mr_tag = Tag ( 0x2001 , 0x100a ) if slice_number_mr_tag not in header : return False grouped_dicoms = _get_grouped_dicoms ( dicom_input ) if len ( grouped_dicoms ) <= 1 : return False return True
Use this function to detect if a dicom series is a philips singleframe 4D dataset
233,619
def _is_bval_type_a ( grouped_dicoms ) : bval_tag = Tag ( 0x2001 , 0x1003 ) bvec_x_tag = Tag ( 0x2005 , 0x10b0 ) bvec_y_tag = Tag ( 0x2005 , 0x10b1 ) bvec_z_tag = Tag ( 0x2005 , 0x10b2 ) for group in grouped_dicoms : if bvec_x_tag in group [ 0 ] and _is_float ( common . get_fl_value ( group [ 0 ] [ bvec_x_tag ] ) ) and...
Check if the bvals are stored in the first of 2 currently known ways for single frame dti
233,620
def _is_bval_type_b ( grouped_dicoms ) : bval_tag = Tag ( 0x0018 , 0x9087 ) bvec_tag = Tag ( 0x0018 , 0x9089 ) for group in grouped_dicoms : if bvec_tag in group [ 0 ] and bval_tag in group [ 0 ] : bvec = common . get_fd_array_value ( group [ 0 ] [ bvec_tag ] , 3 ) bval = common . get_fd_value ( group [ 0 ] [ bval_tag ...
Check if the bvals are stored in the second of 2 currently known ways for single frame dti
233,621
def _multiframe_to_nifti ( dicom_input , output_file ) : logger . info ( 'Read dicom file' ) multiframe_dicom = dicom_input [ 0 ] logger . info ( 'Creating data block' ) full_block = _multiframe_to_block ( multiframe_dicom ) logger . info ( 'Creating affine' ) affine = _create_affine_multiframe ( multiframe_dicom ) log...
This function will convert philips 4D or anatomical multiframe series to a nifti
233,622
def _singleframe_to_nifti ( grouped_dicoms , output_file ) : logger . info ( 'Creating data block' ) full_block = _singleframe_to_block ( grouped_dicoms ) logger . info ( 'Creating affine' ) affine , slice_increment = common . create_affine ( grouped_dicoms [ 0 ] ) logger . info ( 'Creating nifti' ) nii_image = nibabel...
This function will convert a philips singleframe series to a nifti
233,623
def _create_affine_multiframe ( multiframe_dicom ) : first_frame = multiframe_dicom [ Tag ( 0x5200 , 0x9230 ) ] [ 0 ] last_frame = multiframe_dicom [ Tag ( 0x5200 , 0x9230 ) ] [ - 1 ] image_orient1 = numpy . array ( first_frame . PlaneOrientationSequence [ 0 ] . ImageOrientationPatient ) [ 0 : 3 ] . astype ( float ) im...
Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4D if in mosaic format
233,624
def _multiframe_to_block ( multiframe_dicom ) : number_of_stack_slices = int ( common . get_ss_value ( multiframe_dicom [ Tag ( 0x2001 , 0x105f ) ] [ 0 ] [ Tag ( 0x2001 , 0x102d ) ] ) ) number_of_stacks = int ( int ( multiframe_dicom . NumberOfFrames ) / number_of_stack_slices ) size_x = multiframe_dicom . pixel_array ...
Generate a full datablock containing all stacks
233,625
def _fix_diffusion_images ( bvals , bvecs , nifti , nifti_file ) : if numpy . count_nonzero ( bvecs ) == 0 or not numpy . count_nonzero ( bvals [ - 1 ] ) == 0 : return nifti , bvals , bvecs bvals = bvals [ : - 1 ] bvecs = bvecs [ : - 1 ] new_nifti = nibabel . Nifti1Image ( nifti . get_data ( ) [ : , : , : , : - 1 ] , n...
This function will remove the last timepoint from the nifti bvals and bvecs if the last vector is 0 0 0 This is sometimes added at the end by philips
233,626
def dicom_to_nifti ( dicom_input , output_file ) : if len ( dicom_input ) <= 0 : raise ConversionError ( 'NO_DICOM_FILES_FOUND' ) dicom_input = _remove_duplicate_slices ( dicom_input ) dicom_input = _remove_localizers_by_imagetype ( dicom_input ) if settings . validate_slicecount : dicom_input = _remove_localizers_by_o...
This function will convert an anatomical dicom series to a nifti
233,627
def _convert_slice_incement_inconsistencies ( dicom_input ) : increment = numpy . array ( dicom_input [ 0 ] . ImagePositionPatient ) - numpy . array ( dicom_input [ 1 ] . ImagePositionPatient ) max_slice_increment = 0 slice_incement_groups = [ ] current_group = [ dicom_input [ 0 ] , dicom_input [ 1 ] ] previous_image_p...
If there is slice increment inconsistency detected for the moment CT images then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment
233,628
def is_hitachi ( dicom_input ) : header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False if header . Modality . upper ( ) != 'MR' : return False if 'HITACHI' not in header . Manufacturer . upper ( ) : return False return True
Use this function to detect if a dicom series is a hitachi dataset
233,629
def is_ge ( dicom_input ) : header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False if header . Modality . upper ( ) != 'MR' : return False if 'GE MEDICAL SYSTEMS' not in header . Manufacturer . upper ( ) : return False return True
Use this function to detect if a dicom series is a GE dataset
233,630
def is_philips ( dicom_input ) : header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False if header . Modality . upper ( ) != 'MR' : return False if 'PHILIPS' not in header . Manufacturer . upper ( ) : return False return True
Use this function to detect if a dicom series is a philips dataset
233,631
def is_siemens ( dicom_input ) : header = dicom_input [ 0 ] if 'Manufacturer' not in header or 'Modality' not in header : return False if header . Modality . upper ( ) != 'MR' : return False if 'SIEMENS' not in header . Manufacturer . upper ( ) : return False return True
Use this function to detect if a dicom series is a siemens dataset
233,632
def _get_slice_pixeldata ( dicom_slice ) : data = dicom_slice . pixel_array if dicom_slice . BitsAllocated != dicom_slice . BitsStored and dicom_slice . HighBit == dicom_slice . BitsStored - 1 and dicom_slice . PixelRepresentation == 1 : if dicom_slice . BitsAllocated == 16 : data = data . astype ( numpy . int16 ) max_...
the slice and intercept calculation can cause the slices to have different dtypes we should get the correct dtype that can cover all of them
233,633
def set_fd_value ( tag , value ) : if tag . VR == 'OB' or tag . VR == 'UN' : value = struct . pack ( 'd' , value ) tag . value = value
Setters for data that also work with implicit transfersyntax
233,634
def set_ss_value ( tag , value ) : if tag . VR == 'OB' or tag . VR == 'UN' : value = struct . pack ( 'h' , value ) tag . value = value
Setter for data that also work with implicit transfersyntax
233,635
def apply_scaling ( data , dicom_headers ) : private_scale_slope_tag = Tag ( 0x2005 , 0x100E ) private_scale_intercept_tag = Tag ( 0x2005 , 0x100D ) if 'RescaleSlope' in dicom_headers or 'RescaleIntercept' in dicom_headers or private_scale_slope_tag in dicom_headers or private_scale_intercept_tag in dicom_headers : res...
Rescale the data based on the RescaleSlope and RescaleOffset Based on the scaling from pydicomseries
233,636
def write_bvec_file ( bvecs , bvec_file ) : if bvec_file is None : return logger . info ( 'Saving BVEC file: %s' % bvec_file ) with open ( bvec_file , 'w' ) as text_file : text_file . write ( '%s\n' % ' ' . join ( map ( str , bvecs [ : , 0 ] ) ) ) text_file . write ( '%s\n' % ' ' . join ( map ( str , bvecs [ : , 1 ] ) ...
Write an array of bvecs to a bvec file
233,637
def write_bval_file ( bvals , bval_file ) : if bval_file is None : return logger . info ( 'Saving BVAL file: %s' % bval_file ) with open ( bval_file , 'w' ) as text_file : text_file . write ( '%s\n' % ' ' . join ( map ( str , bvals ) ) )
Write an array of bvals to a bval file
233,638
def sort_dicoms ( dicoms ) : dicom_input_sorted_x = sorted ( dicoms , key = lambda x : ( x . ImagePositionPatient [ 0 ] ) ) dicom_input_sorted_y = sorted ( dicoms , key = lambda x : ( x . ImagePositionPatient [ 1 ] ) ) dicom_input_sorted_z = sorted ( dicoms , key = lambda x : ( x . ImagePositionPatient [ 2 ] ) ) diff_x...
Sort the dicoms based om the image possition patient
233,639
def validate_orientation ( dicoms ) : first_image_orient1 = numpy . array ( dicoms [ 0 ] . ImageOrientationPatient ) [ 0 : 3 ] first_image_orient2 = numpy . array ( dicoms [ 0 ] . ImageOrientationPatient ) [ 3 : 6 ] for dicom_ in dicoms : image_orient1 = numpy . array ( dicom_ . ImageOrientationPatient ) [ 0 : 3 ] imag...
Validate that all dicoms have the same orientation
233,640
def set_tr_te ( nifti_image , repetition_time , echo_time ) : nifti_image . header . structarr [ 'pixdim' ] [ 4 ] = repetition_time / 1000.0 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
233,641
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 , outpu...
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
233,642
def _4d_to_nifti ( grouped_dicoms , output_file ) : logger . info ( 'Creating data block' ) full_block = _get_full_block ( grouped_dicoms ) logger . info ( 'Creating affine' ) affine , slice_increment = common . create_affine ( grouped_dicoms [ 0 ] ) logger . info ( 'Creating nifti' ) nii_image = nibabel . Nifti1Image ...
This function will convert ge 4d series to a nifti
233,643
def dicom_to_nifti ( dicom_input , output_file = None ) : assert common . is_hitachi ( dicom_input ) 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
233,644
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 ( gr...
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
233,645
def _get_sorted_mosaics ( dicom_input ) : sorted_mosaics = sorted ( dicom_input , key = lambda x : x . AcquisitionNumber ) for index in range ( 0 , len ( sorted_mosaics ) - 1 ) : if sorted_mosaics [ index ] . AcquisitionNumber >= sorted_mosaics [ index + 1 ] . AcquisitionNumber : raise ConversionValidationError ( "INCO...
Search all mosaics in the dicom directory sort and validate them
233,646
def _mosaic_to_block ( mosaic ) : mosaic_type = _get_mosaic_type ( mosaic ) 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'sSliceArr...
Convert a mosaic slice to a block of data by reading the headers splitting the mosaic and appending
233,647
def _create_affine_siemens_mosaic ( dicom_input ) : dicom_header = dicom_input [ 0 ] 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 = fl...
Function to create the affine matrix for a siemens mosaic dataset This will work for siemens dti and 4d if in mosaic format
233,648
def resample_single_nifti ( input_nifti ) : 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
233,649
def convert_directory ( dicom_directory , output_folder , compression = True , reorient = True ) : dicom_series = { } for root , _ , files in os . walk ( dicom_directory ) : for dicom_file in files : file_path = os . path . join ( root , dicom_file ) try : if compressed_dicom . is_dicom_file ( file_path ) : dicom_heade...
This function will order all dicom files by series and order them one by one
233,650
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 .
233,651
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 .
233,652
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 .
233,653
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 .
233,654
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 .
233,655
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 s...
Create a new MenuBorderStyle instance based on the given border style type .
233,656
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 .
233,657
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 .
233,658
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_st...
Validate input_string against a regex pattern
233,659
def process_user_input ( self ) : user_input = self . screen . input ( ) try : indexes = self . __parse_range_list ( user_input ) 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 .
233,660
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 .
233,661
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 .
233,662
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 .
233,663
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
233,664
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
233,665
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
233,666
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 .
233,667
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 .
233,668
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 .
233,669
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 .
233,670
def ensure_columns_are_in_dataframe ( columns , dataframe , col_title = '' , data_title = 'data' ) : assert isinstance ( columns , Iterable ) assert isinstance ( dataframe , pd . DataFrame ) assert isinstance ( col_title , str ) assert isinstance ( data_title , str ) problem_cols = [ col for col in columns if col not i...
Checks whether each column in columns is in dataframe . Raises ValueError if any of the columns are not in the dataframe .
233,671
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 .
233,672
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 .
233,673
def ensure_specification_cols_are_in_dataframe ( specification , dataframe ) : try : assert isinstance ( specification , OrderedDict ) except AssertionError : raise TypeError ( "`specification` must be an OrderedDict." ) assert isinstance ( dataframe , pd . DataFrame ) problem_cols = [ ] dataframe_cols = dataframe . co...
Checks whether each column in specification is in dataframe . Raises ValueError if any of the columns are not in the dataframe .
233,674
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 ]...
Check the validity of the keys and values in the names dictionary .
233,675
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,...
Ensure that all of the columns from dataframe are in the list of used_cols . Will raise a helpful UserWarning if otherwise .
233,676
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 .
233,677
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 ValueErr...
Checks that the total number of recorded choices equals the total number of observations . If this is not the case raise helpful ValueError messages .
233,678
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_d...
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 .
233,679
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 .
233,680
def get_original_order_unique_ids ( id_array ) : assert isinstance ( id_array , np . ndarray ) assert len ( id_array . shape ) == 1 original_unique_id_indices = np . sort ( np . unique ( id_array , return_index = True ) [ 1 ] ) original_order_unique_ids = id_array [ original_unique_id_indices ] return original_order_un...
Get the unique id s of id_array in their original order of appearance .
233,681
def create_sparse_mapping ( id_array , unique_ids = None ) : if unique_ids is None : unique_ids = get_original_order_unique_ids ( id_array ) assert isinstance ( unique_ids , np . ndarray ) assert isinstance ( id_array , np . ndarray ) assert unique_ids . ndim == 1 assert id_array . ndim == 1 represented_ids = np . in1d...
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 .
233,682
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 .
233,683
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 .
233,684
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()" r...
Ensures that all chosen alternatives in wide_df are present in the availability_vars dict . Raises a helpful ValueError if not .
233,685
def ensure_each_wide_obs_chose_an_available_alternative ( obs_id_col , choice_col , availability_vars , wide_data ) : wide_availability_values = wide_data [ list ( availability_vars . values ( ) ) ] . values unavailable_condition = ( ( wide_availability_values == 0 ) . sum ( axis = 1 ) . astype ( bool ) ) problem_obs =...
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 .
233,686
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 == [ ] pr...
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 .
233,687
def ensure_contiguity_in_observation_rows ( obs_id_vector ) : 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 ...
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 .
233,688
def relate_obs_ids_to_chosen_alts ( obs_id_array , alt_id_array , choice_array ) : chosen_alts_to_obs_ids = { } for alt_id in np . sort ( np . unique ( alt_id_array ) ) : selection_condition = np . where ( ( alt_id_array == alt_id ) & ( choice_array == 1 ) ) chosen_alts_to_obs_ids [ alt_id ] = np . sort ( np . unique (...
Creates a dictionary that relates each unique alternative id to the set of observations ids that chose the given alternative .
233,689
def create_cross_sectional_bootstrap_samples ( obs_id_array , alt_id_array , choice_array , num_samples , seed = None ) : chosen_alts_to_obs_ids = relate_obs_ids_to_chosen_alts ( obs_id_array , alt_id_array , choice_array ) num_obs_per_group , tot_num_obs = get_num_obs_choosing_each_alternative ( chosen_alts_to_obs_ids...
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 f...
233,690
def create_bootstrap_id_array ( obs_id_per_sample ) : n_rows , n_cols = obs_id_per_sample . shape bootstrap_id_array = np . tile ( np . arange ( n_cols ) + 1 , n_rows ) . reshape ( ( n_rows , n_cols ) ) 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 .
233,691
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 . form...
Checks whether or not col_name is in df and raises a helpful error msg if the desired condition is not met .
233,692
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 .
233,693
def create_bootstrap_dataframe ( orig_df , obs_id_col , resampled_obs_ids_1d , groupby_dict , boot_id_col = "bootstrap_id" ) : check_column_existence ( obs_id_col , orig_df , presence = True ) check_column_existence ( boot_id_col , orig_df , presence = False ) obs_id_values = orig_df [ obs_id_col ] . values ensure_resa...
Will create the altered dataframe of data needed to estimate a choice model with the particular observations that belong to the current bootstrap sample .
233,694
def get_param_names ( model_obj ) : all_names = deepcopy ( model_obj . ind_var_names ) if model_obj . intercept_names is not None : all_names = model_obj . intercept_names + all_names if model_obj . shape_names is not None : all_names = model_obj . shape_names + all_names if model_obj . nest_names is not None : all_nam...
Extracts all the names to be displayed for the estimated parameters .
233,695
def get_param_list_for_prediction ( model_obj , replicates ) : ensure_samples_is_ndim_ndarray ( replicates , ndim = 2 , name = 'replicates' ) 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 )...
Create the param_list argument for use with model_obj . predict .
233,696
def generate_bootstrap_replicates ( self , num_samples , 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 , boot_seed = None , weights = None )...
Generates the bootstrap replicates for one s given model and dataset .
233,697
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" ) pri...
Generates the jackknife replicates for one s given model and dataset .
233,698
def calc_log_likes_for_replicates ( self , replicates = 'bootstrap' , num_draws = None , seed = None ) : ensure_replicates_kwarg_validity ( replicates ) replicate_vec = getattr ( self , replicates + "_replicates" ) . values choice_col = self . model_obj . choice_col current_model_type = self . model_obj . model_type no...
Calculate the log - likelihood value of one s replicates given one s dataset .
233,699
def calc_gradient_norm_for_replicates ( self , replicates = 'bootstrap' , ridge = None , constrained_pos = None , weights = None ) : ensure_replicates_kwarg_validity ( replicates ) estimation_obj = create_estimation_obj ( self . model_obj , self . mle_params . values , ridge = ridge , constrained_pos = constrained_pos ...
Calculate the Euclidean - norm of the gradient of one s replicates given one s dataset .