arokem / python-matlab-bridge

A simple Python => MATLAB(R) interface and a matlab_magic for ipython
BSD 2-Clause "Simplified" License
335 stars 96 forks source link

JSON Doesn't Allow Inf/NaN #210

Open brunobeltran opened 9 years ago

brunobeltran commented 9 years ago

Currently, if I try to load in any variables from Matlab that contain infs or NaNs, the program does the "right thing", but the variables get returned polluted with error messages where the fields should be.

In the IPython Notebook, this can cause the get_variable routine to hang indefinitely. Usually, however, we get something like the following:

In [1]: lab.run_code('a.b = inf; a.c = [inf -inf nan 1 0];')
Out[1]:
{'content': {'datadir': '/tmp/MatlabData/', 'figures': [], 'stdout': ''},
 'result': [],
 'stack': [],
 'success': True}

In [2]: lab.get_variable('a')
Out[2]:
{'b': 'Java exception occurred: \norg.json.JSONException: JSON does not allow non-finite numbers.\n\tat org.json.JSONObject.testValidity(JSONObject.java:1288)\n\tat org.json.JSONObject.put(JSONObject.java:1100)\n\tat org.json.JSONObject.put(JSONObject.java:1037)',
 'c': array([[ inf, -inf,  nan,   1.,   0.]])}

Seems like a simple hack around the problem would be to simply return scalars as 1-by-1 numpy arrays instead...

brunobeltran commented 9 years ago

Did some quick digging, and it seems this fix will have to be implemented on the MATLAB side, since that's where the JSON encoding is happening. Specifically, around line 161 of json_dump.m is where the Java exception occurs.

Per the following stack overflow answer, http://stackoverflow.com/questions/13581843/php-how-to-encode-infinity-or-nan-numbers-to-json I will try to throw together a fix that treats +-inf and NaN as special cases when encoding the JSON, since JSON does not support either of these values natively (it appears that people usually just convert them to strings before encoding when working in Javascript, for example).