idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
15,500
def codebox ( msg = "" , title = " " , text = "" ) : return tb . textbox ( msg , title , text , codebox = 1 )
Display some text in a monospaced font with no line wrapping . This function is suitable for displaying code and text that is formatted using spaces .
15,501
def _calculateEncodingKey ( comparator ) : encodingName = None for k , v in list ( _encodings . items ( ) ) : if v == comparator : encodingName = k break return encodingName
Gets the first key of all available encodings where the corresponding value matches the comparator .
15,502
def _initUI ( self ) : self . semicolonRadioButton = QtGui . QRadioButton ( 'Semicolon' ) self . commaRadioButton = QtGui . QRadioButton ( 'Comma' ) self . tabRadioButton = QtGui . QRadioButton ( 'Tab' ) self . otherRadioButton = QtGui . QRadioButton ( 'Other' ) self . commaRadioButton . setChecked ( True ) self . othe...
Creates the inital layout with all subwidgets .
15,503
def currentSelected ( self ) : if self . commaRadioButton . isChecked ( ) : return ',' elif self . semicolonRadioButton . isChecked ( ) : return ';' elif self . tabRadioButton . isChecked ( ) : return '\t' elif self . otherRadioButton . isChecked ( ) : return self . otherSeparatorLineEdit . text ( ) return
Returns the currently selected delimiter character .
15,504
def _openFile ( self ) : file_types = "Comma Separated Values (*.csv);;Text files (*.txt);;All Files (*)" ret = QtGui . QFileDialog . getOpenFileName ( self , self . tr ( 'open file' ) , filter = file_types ) if isinstance ( ret , tuple ) : ret = ret [ 0 ] if ret : self . _filenameLineEdit . setText ( ret ) self . _upd...
Opens a file dialog and sets a value for the QLineEdit widget .
15,505
def _updateFilename ( self ) : self . _filename = self . _filenameLineEdit . text ( ) self . _guessEncoding ( self . _filename ) self . _previewFile ( )
Calls several methods after the filename changed .
15,506
def _guessEncoding ( self , path ) : if os . path . exists ( path ) and path . lower ( ) . endswith ( 'csv' ) : encoding = None if encoding is not None : if encoding . startswith ( 'utf' ) : encoding = encoding . replace ( '-' , '' ) encoding = encoding . replace ( '-' , '_' ) viewValue = _encodings . get ( encoding ) ...
Opens a file from the given path and checks the file encoding .
15,507
def _updateEncoding ( self , index ) : encoding = self . _encodingComboBox . itemText ( index ) encoding = encoding . lower ( ) self . _encodingKey = _calculateEncodingKey ( encoding ) self . _previewFile ( )
Changes the value of the encoding combo box to the value of given index .
15,508
def _previewFile ( self ) : dataFrame = self . _loadCSVDataFrame ( ) dataFrameModel = DataFrameModel ( dataFrame , filePath = self . _filename ) dataFrameModel . enableEditing ( True ) self . _previewTableView . setModel ( dataFrameModel ) columnModel = dataFrameModel . columnDtypeModel ( ) columnModel . changeFailed ....
Updates the preview widgets with new models for both tab panes .
15,509
def _loadCSVDataFrame ( self ) : if self . _filename and os . path . exists ( self . _filename ) : encoding = self . _encodingKey or 'UTF_8' try : dataFrame = superReadFile ( self . _filename , sep = self . _delimiter , first_codec = encoding , header = self . _header ) dataFrame = dataFrame . apply ( fillNoneValues ) ...
Loads the given csv file with pandas and generate a new dataframe .
15,510
def accepted ( self ) : model = self . _previewTableView . model ( ) if model is not None : df = model . dataFrame ( ) . copy ( ) dfModel = DataFrameModel ( df ) self . load . emit ( dfModel , self . _filename ) print ( ( "Emitted model for {}" . format ( self . _filename ) ) ) self . _resetWidgets ( ) self . accept ( ...
Successfully close the widget and return the loaded model .
15,511
def encode_pin ( self , pin , matrix = None ) : if matrix is None : _ , matrix = self . read_pin ( ) return "" . join ( [ str ( matrix . index ( p ) + 1 ) for p in pin ] )
Transform correct PIN according to the displayed matrix .
15,512
def _xdr_read_asset ( unpacker ) : asset = messages . StellarAssetType ( type = unpacker . unpack_uint ( ) ) if asset . type == ASSET_TYPE_ALPHA4 : asset . code = unpacker . unpack_fstring ( 4 ) asset . issuer = _xdr_read_address ( unpacker ) if asset . type == ASSET_TYPE_ALPHA12 : asset . code = unpacker . unpack_fstr...
Reads a stellar Asset from unpacker
15,513
def _crc16_checksum ( bytes ) : crc = 0x0000 polynomial = 0x1021 for byte in bytes : for i in range ( 8 ) : bit = ( byte >> ( 7 - i ) & 1 ) == 1 c15 = ( crc >> 15 & 1 ) == 1 crc <<= 1 if c15 ^ bit : crc ^= polynomial return crc & 0xFFFF
Returns the CRC - 16 checksum of bytearray bytes
15,514
def b58encode ( v ) : long_value = 0 for c in v : long_value = long_value * 256 + c result = "" while long_value >= __b58base : div , mod = divmod ( long_value , __b58base ) result = __b58chars [ mod ] + result long_value = div result = __b58chars [ long_value ] + result nPad = 0 for c in v : if c == 0 : nPad += 1 else...
encode v which is a string of bytes to base58 .
15,515
def normalize_nfc ( txt ) : if isinstance ( txt , bytes ) : txt = txt . decode ( ) return unicodedata . normalize ( "NFC" , txt ) . encode ( )
Normalize message to NFC and return bytes suitable for protobuf . This seems to be bitcoin - qt standard of doing things .
15,516
def get_protocol ( handle : Handle , want_v2 : bool ) -> Protocol : force_v1 = int ( os . environ . get ( "TREZOR_PROTOCOL_V1" , 1 ) ) if want_v2 and not force_v1 : return ProtocolV2 ( handle ) else : return ProtocolV1 ( handle )
Make a Protocol instance for the given handle .
15,517
def _ping ( self ) -> bool : assert self . socket is not None resp = None try : self . socket . sendall ( b"PINGPING" ) resp = self . socket . recv ( 8 ) except Exception : pass return resp == b"PONGPONG"
Test if the device is listening .
15,518
def combine_keys ( pks : Iterable [ Ed25519PublicPoint ] ) -> Ed25519PublicPoint : P = [ _ed25519 . decodepoint ( pk ) for pk in pks ] combine = reduce ( _ed25519 . edwards_add , P ) return Ed25519PublicPoint ( _ed25519 . encodepoint ( combine ) )
Combine a list of Ed25519 points into a global CoSi key .
15,519
def combine_sig ( global_R : Ed25519PublicPoint , sigs : Iterable [ Ed25519Signature ] ) -> Ed25519Signature : S = [ _ed25519 . decodeint ( si ) for si in sigs ] s = sum ( S ) % _ed25519 . l sig = global_R + _ed25519 . encodeint ( s ) return Ed25519Signature ( sig )
Combine a list of signatures into a single CoSi signature .
15,520
def get_nonce ( sk : Ed25519PrivateKey , data : bytes , ctr : int = 0 ) -> Tuple [ int , Ed25519PublicPoint ] : h = _ed25519 . H ( sk ) bytesize = _ed25519 . b // 8 assert len ( h ) == bytesize * 2 r = _ed25519 . Hint ( h [ bytesize : ] + data + ctr . to_bytes ( 4 , "big" ) ) R = _ed25519 . scalarmult ( _ed25519 . B , ...
Calculate CoSi nonces for given data . These differ from Ed25519 deterministic nonces in that there is a counter appended at end .
15,521
def verify ( signature : Ed25519Signature , digest : bytes , pub_key : Ed25519PublicPoint ) -> None : _ed25519 . checkvalid ( signature , digest , pub_key )
Verify Ed25519 signature . Raise exception if the signature is invalid .
15,522
def sign_with_privkey ( digest : bytes , privkey : Ed25519PrivateKey , global_pubkey : Ed25519PublicPoint , nonce : int , global_commit : Ed25519PublicPoint , ) -> Ed25519Signature : h = _ed25519 . H ( privkey ) a = _ed25519 . decodecoord ( h ) S = ( nonce + _ed25519 . Hint ( global_commit + global_pubkey + digest ) * ...
Create a CoSi signature of digest with the supplied private key . This function needs to know the global public key and global commitment .
15,523
def _patch_prebuild ( cls ) : orig_run = cls . run def new_run ( self ) : self . run_command ( "prebuild" ) orig_run ( self ) cls . run = new_run
Patch a setuptools command to depend on prebuild
15,524
def get_default_client ( path = None , ui = None , ** kwargs ) : from . transport import get_transport from . ui import ClickUI transport = get_transport ( path , prefix_search = True ) if ui is None : ui = ClickUI ( ) return TrezorClient ( transport , ui , ** kwargs )
Get a client for a connected Trezor device .
15,525
def sel_entries ( self ) : ENTIRE_RECORD = 0xff rsp = self . send_message_with_name ( 'GetSelInfo' ) if rsp . entries == 0 : return reservation_id = self . get_sel_reservation_id ( ) next_record_id = 0 while True : req = create_request_by_name ( 'GetSelEntry' ) req . reservation_id = reservation_id req . record_id = ne...
Generator which returns all SEL entries .
15,526
def initiate_upgrade_action_and_wait ( self , components_mask , action , timeout = 2 , interval = 0.1 ) : try : self . initiate_upgrade_action ( components_mask , action ) except CompletionCodeError as e : if e . cc == CC_LONG_DURATION_CMD_IN_PROGRESS : self . wait_for_long_duration_command ( constants . CMDID_HPM_INIT...
Initiate Upgrade Action and wait for long running command .
15,527
def upload_binary ( self , binary , timeout = 2 , interval = 0.1 ) : block_number = 0 block_size = self . _determine_max_block_size ( ) for chunk in chunks ( binary , block_size ) : try : self . upload_firmware_block ( block_number , chunk ) except CompletionCodeError as e : if e . cc == CC_LONG_DURATION_CMD_IN_PROGRES...
Upload all firmware blocks from binary and wait for long running command .
15,528
def finish_upload_and_wait ( self , component , length , timeout = 2 , interval = 0.1 ) : try : rsp = self . finish_firmware_upload ( component , length ) check_completion_code ( rsp . completion_code ) except CompletionCodeError as e : if e . cc == CC_LONG_DURATION_CMD_IN_PROGRESS : self . wait_for_long_duration_comma...
Finish the firmware upload process and wait for long running command .
15,529
def activate_firmware_and_wait ( self , rollback_override = None , timeout = 2 , interval = 1 ) : try : self . activate_firmware ( rollback_override ) except CompletionCodeError as e : if e . cc == CC_LONG_DURATION_CMD_IN_PROGRESS : self . wait_for_long_duration_command ( constants . CMDID_HPM_ACTIVATE_FIRMWARE , timeo...
Activate the new uploaded firmware and wait for long running command .
15,530
def _decode_data ( self , data ) : self . major = data [ 0 ] if data [ 1 ] is 0xff : self . minor = data [ 1 ] elif data [ 1 ] <= 0x99 : self . minor = int ( data [ 1 : 2 ] . tostring ( ) . decode ( 'bcd+' ) ) else : raise DecodingError ( )
data is array . array
15,531
def set_routing ( self , routing ) : if is_string ( routing ) : routing = ast . literal_eval ( routing ) self . routing = [ Routing ( * route ) for route in routing ]
Set the path over which a target is reachable .
15,532
def raw_command ( self , lun , netfn , raw_bytes ) : return self . interface . send_and_receive_raw ( self . target , lun , netfn , raw_bytes )
Send the raw command data and return the raw response .
15,533
def _send_and_receive ( self , target , lun , netfn , cmdid , payload ) : self . _inc_sequence_number ( ) header = IpmbHeaderReq ( ) header . netfn = netfn header . rs_lun = lun header . rs_sa = target . ipmb_address header . rq_seq = self . next_sequence_number header . rq_lun = 0 header . rq_sa = self . slave_address...
Send and receive data using RMCP interface .
15,534
def send_and_receive_raw ( self , target , lun , netfn , raw_bytes ) : return self . _send_and_receive ( target = target , lun = lun , netfn = netfn , cmdid = array ( 'B' , raw_bytes ) [ 0 ] , payload = raw_bytes [ 1 : ] )
Interface function to send and receive raw message .
15,535
def send_and_receive ( self , req ) : rx_data = self . _send_and_receive ( target = req . target , lun = req . lun , netfn = req . netfn , cmdid = req . cmdid , payload = encode_message ( req ) ) rsp = create_message ( req . netfn + 1 , req . cmdid , req . group_extension ) decode_message ( rsp , rx_data ) return rsp
Interface function to send and receive an IPMI message .
15,536
def delete_sdr ( self , record_id ) : reservation_id = self . reserve_device_sdr_repository ( ) rsp = self . send_message_with_name ( 'DeleteSdr' , reservation_id = reservation_id , record_id = record_id ) return rsp . record_id
Deletes the sensor record specified by record_id .
15,537
def get_sdr_data_helper ( reserve_fn , get_fn , record_id , reservation_id = None ) : if reservation_id is None : reservation_id = reserve_fn ( ) ( next_id , data ) = get_fn ( reservation_id , record_id , 0 , 5 ) header = ByteBuffer ( data ) record_id = header . pop_unsigned_int ( 2 ) record_version = header . pop_unsi...
Helper function to retrieve the sdr data using the specified functions .
15,538
def clear_repository_helper ( reserve_fn , clear_fn , retry = 5 , reservation = None ) : if reservation is None : reservation = reserve_fn ( ) reservation = _clear_repository ( reserve_fn , clear_fn , INITIATE_ERASE , retry , reservation ) time . sleep ( 0.5 ) reservation = _clear_repository ( reserve_fn , clear_fn , G...
Helper function to start repository erasure and wait until finish . This helper is used by clear_sel and clear_sdr_repository .
15,539
def encode_ipmb_msg ( header , data ) : msg = array ( 'B' ) msg . fromstring ( header . encode ( ) ) if data is not None : a = array ( 'B' ) a . fromstring ( data ) msg . extend ( a ) msg . append ( checksum ( msg [ 3 : ] ) ) return msg . tostring ( )
Encode an IPMB message .
15,540
def encode_send_message ( payload , rq_sa , rs_sa , channel , seq , tracking = 1 ) : req = create_request_by_name ( 'SendMessage' ) req . channel . number = channel req . channel . tracking = tracking data = encode_message ( req ) header = IpmbHeaderReq ( ) header . netfn = req . __netfn__ header . rs_lun = 0 header . ...
Encode a send message command and embedd the message to be send .
15,541
def rx_filter ( header , data ) : rsp_header = IpmbHeaderRsp ( ) rsp_header . decode ( data ) data = array ( 'B' , data ) checks = [ ( checksum ( data [ 0 : 3 ] ) , 0 , 'Header checksum failed' ) , ( checksum ( data [ 3 : ] ) , 0 , 'payload checksum failed' ) , ( rsp_header . netfn , header . netfn | 1 , 'NetFn mismatc...
Check if the message in rx_data matches to the information in header .
15,542
def _pack ( self ) : data = ByteBuffer ( ) if not hasattr ( self , '__fields__' ) : return data . array for field in self . __fields__ : field . encode ( self , data ) return data . array
Pack the message and return an array .
15,543
def _encode ( self ) : data = ByteBuffer ( ) if not hasattr ( self , '__fields__' ) : return data . tostring ( ) for field in self . __fields__ : field . encode ( self , data ) return data . tostring ( )
Encode the message and return a bytestring .
15,544
def _decode ( self , data ) : if not hasattr ( self , '__fields__' ) : raise NotImplementedError ( 'You have to overwrite this method' ) data = ByteBuffer ( data ) cc = None for field in self . __fields__ : try : field . decode ( self , data ) except CompletionCodeError as e : cc = e . cc break if ( cc is None or cc ==...
Decode the bytestring message .
15,545
def _send_and_receive ( self , target , lun , netfn , cmdid , payload ) : self . _inc_sequence_number ( ) header = IpmbHeaderReq ( ) header . netfn = netfn header . rs_lun = lun header . rs_sa = target . ipmb_address header . rq_seq = self . next_sequence_number header . rq_lun = 0 header . rq_sa = self . slave_address...
Send and receive data using aardvark interface .
15,546
def get_device_sdr ( self , record_id , reservation_id = None ) : ( next_id , record_data ) = get_sdr_data_helper ( self . reserve_device_sdr_repository , self . _get_device_sdr_chunk , record_id , reservation_id ) return sdr . SdrCommon . from_data ( record_data , next_id )
Collects all data from the sensor device to get the SDR specified by record id .
15,547
def get_sensor_reading ( self , sensor_number , lun = 0 ) : rsp = self . send_message_with_name ( 'GetSensorReading' , sensor_number = sensor_number , lun = lun ) reading = rsp . sensor_reading if rsp . config . initial_update_in_progress : reading = None states = None if rsp . states1 is not None : states = rsp . stat...
Returns the sensor reading at the assertion states for the given sensor number .
15,548
def set_sensor_thresholds ( self , sensor_number , lun = 0 , unr = None , ucr = None , unc = None , lnc = None , lcr = None , lnr = None ) : req = create_request_by_name ( 'SetSensorThresholds' ) req . sensor_number = sensor_number req . lun = lun thresholds = dict ( unr = unr , ucr = ucr , unc = unc , lnc = lnc , lcr ...
Set the sensor thresholds that are not None
15,549
def _generate_feature ( feature_type , feature_size , signal_magnitude , thickness = 1 ) : if feature_size <= 2 : feature_type = 'cube' if feature_type == 'cube' : signal = np . ones ( ( feature_size , feature_size , feature_size ) ) elif feature_type == 'loop' : signal = np . zeros ( ( feature_size , feature_size , fe...
Generate features corresponding to signal
15,550
def _insert_idxs ( feature_centre , feature_size , dimensions ) : x_idx = [ int ( feature_centre [ 0 ] - ( feature_size / 2 ) ) + 1 , int ( feature_centre [ 0 ] - ( feature_size / 2 ) + feature_size ) + 1 ] y_idx = [ int ( feature_centre [ 1 ] - ( feature_size / 2 ) ) + 1 , int ( feature_centre [ 1 ] - ( feature_size /...
Returns the indices of where to put the signal into the signal volume
15,551
def generate_signal ( dimensions , feature_coordinates , feature_size , feature_type , signal_magnitude = [ 1 ] , signal_constant = 1 , ) : volume_signal = np . zeros ( dimensions ) feature_quantity = round ( feature_coordinates . shape [ 0 ] ) if len ( feature_size ) == 1 : feature_size = feature_size * feature_quanti...
Generate volume containing signal
15,552
def generate_stimfunction ( onsets , event_durations , total_time , weights = [ 1 ] , timing_file = None , temporal_resolution = 100.0 , ) : if timing_file is not None : with open ( timing_file ) as f : text = f . readlines ( ) onsets = list ( ) event_durations = list ( ) weights = list ( ) for line in text : onset , d...
Return the function for the timecourse events
15,553
def export_3_column ( stimfunction , filename , temporal_resolution = 100.0 ) : stim_counter = 0 event_counter = 0 while stim_counter < stimfunction . shape [ 0 ] : if stimfunction [ stim_counter , 0 ] != 0 : event_onset = str ( stim_counter / temporal_resolution ) weight = str ( stimfunction [ stim_counter , 0 ] ) eve...
Output a tab separated three column timing file
15,554
def export_epoch_file ( stimfunction , filename , tr_duration , temporal_resolution = 100.0 ) : epoch_file = [ 0 ] * len ( stimfunction ) for ppt_counter in range ( len ( stimfunction ) ) : stimfunction_ppt = np . abs ( stimfunction [ ppt_counter ] ) > 0 stride = tr_duration * temporal_resolution stimfunction_downsampl...
Output an epoch file necessary for some inputs into brainiak
15,555
def _double_gamma_hrf ( response_delay = 6 , undershoot_delay = 12 , response_dispersion = 0.9 , undershoot_dispersion = 0.9 , response_scale = 1 , undershoot_scale = 0.035 , temporal_resolution = 100.0 , ) : hrf_length = 30 hrf = [ 0 ] * int ( hrf_length * temporal_resolution ) response_peak = response_delay * respons...
Create the double gamma HRF with the timecourse evoked activity . Default values are based on Glover 1999 and Walvaert Durnez Moerkerke Verdoolaege and Rosseel 2011
15,556
def apply_signal ( signal_function , volume_signal , ) : timepoints = signal_function . shape [ 0 ] timecourses = signal_function . shape [ 1 ] signal = np . zeros ( [ volume_signal . shape [ 0 ] , volume_signal . shape [ 1 ] , volume_signal . shape [ 2 ] , timepoints ] ) idxs = np . where ( volume_signal != 0 ) if tim...
Combine the signal volume with its timecourse
15,557
def _calc_sfnr ( volume , mask , ) : brain_voxels = volume [ mask > 0 ] mean_voxels = np . nanmean ( brain_voxels , 1 ) order = 2 seq = np . linspace ( 1 , brain_voxels . shape [ 1 ] , brain_voxels . shape [ 1 ] ) detrend_poly = np . polyfit ( seq , brain_voxels . transpose ( ) , order ) detrend_voxels = np . zeros ( b...
Calculate the the SFNR of a volume Calculates the Signal to Fluctuation Noise Ratio the mean divided by the detrended standard deviation of each brain voxel . Based on Friedman and Glover 2006
15,558
def _calc_snr ( volume , mask , dilation = 5 , reference_tr = None , ) : if reference_tr is None : reference_tr = list ( range ( volume . shape [ 3 ] ) ) if dilation > 0 : mask_dilated = ndimage . morphology . binary_dilation ( mask , iterations = dilation ) else : mask_dilated = mask brain_voxels = volume [ mask > 0 ]...
Calculate the the SNR of a volume Calculates the Signal to Noise Ratio the mean of brain voxels divided by the standard deviation across non - brain voxels . Specify a TR value to calculate the mean and standard deviation for that TR . To calculate the standard deviation of non - brain voxels we can subtract any baseli...
15,559
def _calc_ARMA_noise ( volume , mask , auto_reg_order = 1 , ma_order = 1 , sample_num = 100 , ) : if len ( volume . shape ) > 1 : brain_timecourse = volume [ mask > 0 ] else : brain_timecourse = volume . reshape ( 1 , len ( volume ) ) voxel_idxs = list ( range ( brain_timecourse . shape [ 0 ] ) ) np . random . shuffle ...
Calculate the the ARMA noise of a volume This calculates the autoregressive and moving average noise of the volume over time by sampling brain voxels and averaging them .
15,560
def calc_noise ( volume , mask , template , noise_dict = None , ) : if template . max ( ) > 1.1 : raise ValueError ( 'Template out of range' ) if mask is None : raise ValueError ( 'Mask not supplied' ) if noise_dict is None : noise_dict = { 'voxel_size' : [ 1.0 , 1.0 , 1.0 ] } elif 'voxel_size' not in noise_dict : nois...
Calculates the noise properties of the volume supplied . This estimates what noise properties the volume has . For instance it determines the spatial smoothness the autoregressive noise system noise etc . Read the doc string for generate_noise to understand how these different types of noise interact .
15,561
def _generate_noise_system ( dimensions_tr , spatial_sd , temporal_sd , spatial_noise_type = 'gaussian' , temporal_noise_type = 'gaussian' , ) : def noise_volume ( dimensions , noise_type , ) : if noise_type == 'rician' : noise = stats . rice . rvs ( b = 0 , loc = 0 , scale = 1.527 , size = dimensions ) elif noise_type...
Generate the scanner noise
15,562
def _generate_noise_temporal_task ( stimfunction_tr , motion_noise = 'gaussian' , ) : stimfunction_tr = stimfunction_tr != 0 if motion_noise == 'gaussian' : noise = stimfunction_tr * np . random . normal ( 0 , 1 , size = stimfunction_tr . shape ) elif motion_noise == 'rician' : noise = stimfunction_tr * stats . rice . ...
Generate the signal dependent noise
15,563
def _generate_noise_temporal_drift ( trs , tr_duration , basis = "discrete_cos" , period = 150 , ) : if basis == 'discrete_cos' : timepoints = np . linspace ( 0 , trs - 1 , trs ) timepoints = ( ( timepoints * tr_duration ) / period ) * 2 * np . pi duration = trs * tr_duration basis_funcs = int ( np . floor ( duration /...
Generate the drift noise
15,564
def _generate_noise_temporal_autoregression ( timepoints , noise_dict , dimensions , mask , ) : auto_reg_rho = noise_dict [ 'auto_reg_rho' ] ma_rho = noise_dict [ 'ma_rho' ] auto_reg_order = len ( auto_reg_rho ) ma_order = len ( ma_rho ) if ma_order > auto_reg_order : msg = 'MA order (%d) is greater than AR order (%d)....
Generate the autoregression noise Make a slowly drifting timecourse with the given autoregression parameters . This can take in both AR and MA components
15,565
def _generate_noise_temporal_phys ( timepoints , resp_freq = 0.2 , heart_freq = 1.17 , ) : resp_phase = ( np . random . rand ( 1 ) * 2 * np . pi ) [ 0 ] heart_phase = ( np . random . rand ( 1 ) * 2 * np . pi ) [ 0 ] resp_rate = ( resp_freq * 2 * np . pi ) heart_rate = ( heart_freq * 2 * np . pi ) resp_radians = np . mu...
Generate the physiological noise . Create noise representing the heart rate and respiration of the data . Default values based on Walvaert Durnez Moerkerke Verdoolaege and Rosseel 2011
15,566
def _generate_noise_spatial ( dimensions , mask = None , fwhm = 4.0 , ) : if len ( dimensions ) == 4 : logger . warning ( '4 dimensions have been supplied, only using 3' ) dimensions = dimensions [ 0 : 3 ] if dimensions [ 0 ] != dimensions [ 1 ] or dimensions [ 1 ] != dimensions [ 2 ] : max_dim = np . max ( dimensions ...
Generate code for Gaussian Random Fields .
15,567
def _generate_noise_temporal ( stimfunction_tr , tr_duration , dimensions , template , mask , noise_dict ) : trs = len ( stimfunction_tr ) timepoints = list ( np . linspace ( 0 , ( trs - 1 ) * tr_duration , trs ) ) noise_volume = np . zeros ( ( dimensions [ 0 ] , dimensions [ 1 ] , dimensions [ 2 ] , trs ) ) if noise_d...
Generate the temporal noise Generate the time course of the average brain voxel . To change the relative mixing of the noise components change the sigma s specified below .
15,568
def _noise_dict_update ( noise_dict ) : default_dict = { 'task_sigma' : 0 , 'drift_sigma' : 0 , 'auto_reg_sigma' : 1 , 'auto_reg_rho' : [ 0.5 ] , 'ma_rho' : [ 0.0 ] , 'physiological_sigma' : 0 , 'sfnr' : 90 , 'snr' : 50 , 'max_activity' : 1000 , 'voxel_size' : [ 1.0 , 1.0 , 1.0 ] , 'fwhm' : 4 , 'matched' : 1 } for defa...
Update the noise dictionary parameters with default values in case any were missing
15,569
def _fit_spatial ( noise , noise_temporal , mask , template , spatial_sd , temporal_sd , noise_dict , fit_thresh , fit_delta , iterations , ) : dim_tr = noise . shape base = template * noise_dict [ 'max_activity' ] base = base . reshape ( dim_tr [ 0 ] , dim_tr [ 1 ] , dim_tr [ 2 ] , 1 ) mean_signal = ( base [ mask > 0 ...
Fit the noise model to match the SNR of the data
15,570
def _fit_temporal ( noise , mask , template , stimfunction_tr , tr_duration , spatial_sd , temporal_proportion , temporal_sd , noise_dict , fit_thresh , fit_delta , iterations , ) : dim_tr = noise . shape dim = dim_tr [ 0 : 3 ] base = template * noise_dict [ 'max_activity' ] base = base . reshape ( dim [ 0 ] , dim [ 1 ...
Fit the noise model to match the SFNR and AR of the data
15,571
def load_images_from_dir ( in_dir : Union [ str , Path ] , suffix : str = "nii.gz" , ) -> Iterable [ SpatialImage ] : if isinstance ( in_dir , str ) : in_dir = Path ( in_dir ) files = sorted ( in_dir . glob ( "*" + suffix ) ) for f in files : logger . debug ( 'Starting to read file %s' , f ) yield nib . load ( str ( f ...
Load images from directory .
15,572
def load_images ( image_paths : Iterable [ Union [ str , Path ] ] ) -> Iterable [ SpatialImage ] : for image_path in image_paths : if isinstance ( image_path , Path ) : string_path = str ( image_path ) else : string_path = image_path logger . debug ( 'Starting to read file %s' , string_path ) yield nib . load ( string_...
Load images from paths .
15,573
def load_boolean_mask ( path : Union [ str , Path ] , predicate : Callable [ [ np . ndarray ] , np . ndarray ] = None ) -> np . ndarray : if not isinstance ( path , str ) : path = str ( path ) data = nib . load ( path ) . get_data ( ) if predicate is not None : mask = predicate ( data ) else : mask = data . astype ( np...
Load boolean nibabel . SpatialImage mask .
15,574
def load_labels ( path : Union [ str , Path ] ) -> List [ SingleConditionSpec ] : condition_specs = np . load ( str ( path ) ) return [ c . view ( SingleConditionSpec ) for c in condition_specs ]
Load labels files .
15,575
def save_as_nifti_file ( data : np . ndarray , affine : np . ndarray , path : Union [ str , Path ] ) -> None : if not isinstance ( path , str ) : path = str ( path ) img = Nifti1Pair ( data , affine ) nib . nifti1 . save ( img , path )
Create a Nifti file and save it .
15,576
def _mse_converged ( self ) : prior = self . global_prior_ [ 0 : self . prior_size ] posterior = self . global_posterior_ [ 0 : self . prior_size ] mse = mean_squared_error ( prior , posterior , multioutput = 'uniform_average' ) if mse > self . threshold : return False , mse else : return True , mse
Check convergence based on mean squared difference between prior and posterior
15,577
def _get_gather_offset ( self , size ) : gather_size = np . zeros ( size ) . astype ( int ) gather_offset = np . zeros ( size ) . astype ( int ) num_local_subjs = np . zeros ( size ) . astype ( int ) subject_map = { } for idx , s in enumerate ( np . arange ( self . n_subj ) ) : cur_rank = idx % size gather_size [ cur_r...
Calculate the offset for gather result from this process
15,578
def _get_weight_size ( self , data , n_local_subj ) : weight_size = np . zeros ( 1 ) . astype ( int ) local_weight_offset = np . zeros ( n_local_subj ) . astype ( int ) for idx , subj_data in enumerate ( data ) : if idx > 0 : local_weight_offset [ idx ] = weight_size [ 0 ] weight_size [ 0 ] += self . K * subj_data . sh...
Calculate the size of weight for this process
15,579
def _get_subject_info ( self , n_local_subj , data ) : max_sample_tr = np . zeros ( n_local_subj ) . astype ( int ) max_sample_voxel = np . zeros ( n_local_subj ) . astype ( int ) for idx in np . arange ( n_local_subj ) : nvoxel = data [ idx ] . shape [ 0 ] ntr = data [ idx ] . shape [ 1 ] max_sample_voxel [ idx ] = mi...
Calculate metadata for subjects allocated to this process
15,580
def _get_mpi_info ( self ) : rank = self . comm . Get_rank ( ) size = self . comm . Get_size ( ) return rank , size
get basic MPI info
15,581
def _init_prior_posterior ( self , rank , R , n_local_subj ) : if rank == 0 : idx = np . random . choice ( n_local_subj , 1 ) self . global_prior_ , self . global_centers_cov , self . global_widths_var = self . get_template ( R [ idx [ 0 ] ] ) self . global_centers_cov_scaled = self . global_centers_cov / float ( self ...
set prior for this subject
15,582
def _assign_posterior ( self ) : prior_centers = self . get_centers ( self . global_prior_ ) posterior_centers = self . get_centers ( self . global_posterior_ ) posterior_widths = self . get_widths ( self . global_posterior_ ) posterior_centers_mean_cov = self . get_centers_mean_cov ( self . global_posterior_ ) posteri...
assign posterior to the right prior based on Hungarian algorithm
15,583
def _update_global_posterior ( self , rank , m , outer_converged ) : if rank == 0 : self . _map_update_posterior ( ) self . _assign_posterior ( ) is_converged , _ = self . _converged ( ) if is_converged : logger . info ( "converged at %d outer iter" % ( m ) ) outer_converged [ 0 ] = 1 else : self . global_prior_ = self...
Update global posterior and then check convergence
15,584
def _update_weight ( self , data , R , n_local_subj , local_weight_offset ) : for s , subj_data in enumerate ( data ) : base = s * self . prior_size centers = self . local_posterior_ [ base : base + self . K * self . n_dim ] . reshape ( ( self . K , self . n_dim ) ) start_idx = base + self . K * self . n_dim end_idx = ...
update local weight
15,585
def _fit_htfa ( self , data , R ) : rank , size = self . _get_mpi_info ( ) use_gather = True if self . n_subj % size == 0 else False n_local_subj = len ( R ) max_sample_tr , max_sample_voxel = self . _get_subject_info ( n_local_subj , data ) tfa = [ ] for s , subj_data in enumerate ( data ) : tfa . append ( TFA ( max_i...
HTFA main algorithm
15,586
def _check_input ( self , X , R ) : if not isinstance ( X , list ) : raise TypeError ( "Input data should be a list" ) if not isinstance ( R , list ) : raise TypeError ( "Coordinates should be a list" ) if len ( X ) < 1 : raise ValueError ( "Need at leat one subject to train the model.\ Got...
Check whether input data and coordinates in right type
15,587
def get_sigma ( x , min_limit = - np . inf , max_limit = np . inf ) : z = np . append ( x , [ min_limit , max_limit ] ) sigma = np . ones ( x . shape ) for i in range ( x . size ) : xleft = z [ np . argmin ( [ ( x [ i ] - k ) if k < x [ i ] else np . inf for k in z ] ) ] xright = z [ np . argmin ( [ ( k - x [ i ] ) if ...
Compute the standard deviations around the points for a 1D GMM .
15,588
def get_next_sample ( x , y , min_limit = - np . inf , max_limit = np . inf ) : z = np . array ( list ( zip ( x , y ) ) , dtype = np . dtype ( [ ( 'x' , float ) , ( 'y' , float ) ] ) ) z = np . sort ( z , order = 'y' ) n = y . shape [ 0 ] g = int ( np . round ( np . ceil ( 0.15 * n ) ) ) ldata = z [ 0 : g ] gdata = z [...
Get the next point to try given the previous samples .
15,589
def fmin ( loss_fn , space , max_evals , trials , init_random_evals = 30 , explore_prob = 0.2 ) : for s in space : if not hasattr ( space [ s ] [ 'dist' ] , 'rvs' ) : raise ValueError ( 'Unknown distribution type for variable' ) if 'lo' not in space [ s ] : space [ s ] [ 'lo' ] = - np . inf if 'hi' not in space [ s ] :...
Find the minimum of function through hyper parameter optimization .
15,590
def get_gmm_pdf ( self , x ) : def my_norm_pdf ( xt , mu , sigma ) : z = ( xt - mu ) / sigma return ( math . exp ( - 0.5 * z * z ) / ( math . sqrt ( 2. * np . pi ) * sigma ) ) y = 0 if ( x < self . min_limit ) : return 0 if ( x > self . max_limit ) : return 0 for _x in range ( self . points . size ) : y += ( my_norm_pd...
Calculate the GMM likelihood for a single point .
15,591
def get_samples ( self , n ) : normalized_w = self . weights / np . sum ( self . weights ) get_rand_index = st . rv_discrete ( values = ( range ( self . N ) , normalized_w ) ) . rvs ( size = n ) samples = np . zeros ( n ) k = 0 j = 0 while ( k < n ) : i = get_rand_index [ j ] j = j + 1 if ( j == n ) : get_rand_index = ...
Sample the GMM distribution .
15,592
def _separate_epochs ( activity_data , epoch_list ) : time1 = time . time ( ) raw_data = [ ] labels = [ ] for sid in range ( len ( epoch_list ) ) : epoch = epoch_list [ sid ] for cond in range ( epoch . shape [ 0 ] ) : sub_epoch = epoch [ cond , : , : ] for eid in range ( epoch . shape [ 1 ] ) : r = np . sum ( sub_epoc...
create data epoch by epoch
15,593
def _randomize_single_subject ( data , seed = None ) : if seed is not None : np . random . seed ( seed ) np . random . shuffle ( data )
Randomly permute the voxels of the subject .
15,594
def _randomize_subject_list ( data_list , random ) : if random == RandomType . REPRODUCIBLE : for i in range ( len ( data_list ) ) : _randomize_single_subject ( data_list [ i ] , seed = i ) elif random == RandomType . UNREPRODUCIBLE : for data in data_list : _randomize_single_subject ( data )
Randomly permute the voxels of a subject list .
15,595
def prepare_fcma_data ( images , conditions , mask1 , mask2 = None , random = RandomType . NORANDOM , comm = MPI . COMM_WORLD ) : rank = comm . Get_rank ( ) labels = [ ] raw_data1 = [ ] raw_data2 = [ ] if rank == 0 : logger . info ( 'start to apply masks and separate epochs' ) if mask2 is not None : masks = ( mask1 , m...
Prepare data for correlation - based computation and analysis .
15,596
def generate_epochs_info ( epoch_list ) : time1 = time . time ( ) epoch_info = [ ] for sid , epoch in enumerate ( epoch_list ) : for cond in range ( epoch . shape [ 0 ] ) : sub_epoch = epoch [ cond , : , : ] for eid in range ( epoch . shape [ 1 ] ) : r = np . sum ( sub_epoch [ eid , : ] ) if r > 0 : start = np . nonzer...
use epoch_list to generate epoch_info defined below
15,597
def prepare_mvpa_data ( images , conditions , mask ) : activity_data = list ( mask_images ( images , mask , np . float32 ) ) epoch_info = generate_epochs_info ( conditions ) num_epochs = len ( epoch_info ) ( d1 , _ ) = activity_data [ 0 ] . shape processed_data = np . empty ( [ d1 , num_epochs ] ) labels = np . empty (...
Prepare data for activity - based model training and prediction .
15,598
def prepare_searchlight_mvpa_data ( images , conditions , data_type = np . float32 , random = RandomType . NORANDOM ) : time1 = time . time ( ) epoch_info = generate_epochs_info ( conditions ) num_epochs = len ( epoch_info ) processed_data = None logger . info ( 'there are %d subjects, and in total %d epochs' % ( len (...
obtain the data for activity - based voxel selection using Searchlight
15,599
def from_tri_2_sym ( tri , dim ) : symm = np . zeros ( ( dim , dim ) ) symm [ np . triu_indices ( dim ) ] = tri return symm
convert a upper triangular matrix in 1D format to 2D symmetric matrix