imr-framework / pypulseq

Pulseq in Python
https://pypulseq.readthedocs.io
GNU Affero General Public License v3.0
115 stars 62 forks source link

Error during sequence write when Sequence contains no gradients #53

Closed lukas-k closed 3 years ago

lukas-k commented 3 years ago

Describe the bug When writing a Sequence which doesn't contain gradients, an error occurs:

~\Anaconda3\envs\mri\lib\site-packages\pypulseq\Sequence\write_seq.py in write(self, file_name) 83 ---> 84 if any(arb_grad_mask): 85 output_file.write('# Format of arbitrary gradients:\n') 86 output_file.write('# id amplitude shape_id delay\n')`

TypeError: 'bool' object is not iterable

This happens, because when a Sequence doesn't contain gradients, the EventLibrary self.grad_library is empty and in Line 80 of write_seq.py the variable grad_lib_values will contain a numpy array object as: array([], dtype=float64)

The empty numpy array can be compared (boolean) element-wise with objects which can be interpreted by numpy as a float data type, for example the integer number 1 or the float 3.3. This will result in an empty boolean array as expected: array([], dtype=bool)

However, when comparing the grad_lib_values array with a string / character 'g' or 't', numpy can not interpret the string as a float and the '==' operator will be applied as an object comparison, which in turn results in a boolean 'False'.

any(False) will throw the error shown above.

Suggested fix To overcome this problem, one suggestion is to create the boolean array grad_lib_values inside a try-catch-block using np.equal (which will then throw an exception numpy.core._exceptions.UFuncTypeError: ufunc 'equal' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('bool')) or to use the if any(...) inside a try-catch-block and skip / notify if the exception above occurs.

Desktop

sravan953 commented 3 years ago

Hi @lukas-k , thanks for reporting this issue. Also, thanks for being so elaborate, helps a lot! :)

I found that changing line 84 to np.any(arb_grad_mask) successfully fixed the issue. Do you anticipate any other crashes or do you think this change (in other relevant lines too) will be sufficient?

lukas-k commented 3 years ago

Hello, thank you for fixing this issue. I think, this will prevent crashes when using sequences containing no gradients at all. All the best, Lukas

sravan953 commented 3 years ago

Thank you! Just pushed the relevant commit.