@@ -526,6 +526,26 @@ def _handle_info_reading(sidecar_fname, raw):
526526 return raw
527527
528528
529+ def _str_to_num (sequence ):
530+ """Convert event values from string to either float or int, if possible.
531+
532+ Often (but not always!) the `value` column was written by MNE-BIDS and can be
533+ assumed to represent integer event IDs (as would be found in MNE-Python events
534+ arrays / event_id dicts). But let's be agnostic about that, and meanwhile if the
535+ conversion to `float` succeeds but `int` fails we might as well return floats.
536+ """
537+ try :
538+ sequence = np .asarray (sequence ).astype (float )
539+ except ValueError :
540+ pass
541+ else :
542+ try :
543+ sequence = sequence .astype (int )
544+ except ValueError :
545+ pass
546+ return sequence
547+
548+
529549def _handle_events_reading (events_fname , raw ):
530550 """Read associated events.tsv and convert valid events to annotations on Raw."""
531551 logger .info (f"Reading events from { events_fname } ." )
@@ -557,7 +577,10 @@ def _handle_events_reading(events_fname, raw):
557577 trial_types = events_dict [trial_type_col_name ]
558578 # handle event values (if provided); ensure pairings are 1 value per description
559579 if "value" in events_dict :
560- values = np .asarray (events_dict ["value" ], dtype = str )
580+ # drop rows where `value` is `n/a` (only when making our `event_id` dict;
581+ # `value = n/a` doesn't prevent annotation). Then, try to convert to numeric
582+ culled = _drop (events_dict , "n/a" , "value" )
583+ values = _str_to_num (events_dict ["value" ])
561584 for trial_type in np .unique (trial_types ):
562585 idx = np .where (trial_type == np .atleast_1d (trial_types ))[0 ]
563586 matching_values = values [idx ]
@@ -574,11 +597,8 @@ def _handle_events_reading(events_fname, raw):
574597 new_name = f"{ trial_type } /{ value } "
575598 logger .info (f" Renaming event: { trial_type } -> { new_name } " )
576599 trial_types [ii ] = new_name
577- # drop rows where `value` is `n/a` & convert remaining `value` to int (only
578- # when making our `event_id` dict; `value = n/a` doesn't prevent annotation)
579- culled = _drop (events_dict , "n/a" , "value" )
580600 event_id = dict (
581- zip (culled [trial_type_col_name ], np . asarray (culled ["value" ], dtype = int ))
601+ zip (culled [trial_type_col_name ], _str_to_num (culled ["value" ]))
582602 )
583603 else :
584604 event_id = dict (zip (trial_types , np .arange (len (trial_types ))))
0 commit comments