-
Notifications
You must be signed in to change notification settings - Fork 118
Support numpy literals #213
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
karenfeng
merged 10 commits into
projectglow:master
from
karenfeng:support-numpy-pandas
May 29, 2020
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f1928ea
WIP
karenfeng acb0383
Ndarray
karenfeng 2c4a6ac
More tests
karenfeng 514889a
Support flat array
karenfeng 3340d9b
Move registering
karenfeng 462ab8e
pytest
karenfeng 093808e
Make docstring more accurate
karenfeng 4df226e
idempotent registration
karenfeng 56e7321
Test fixup
karenfeng d6d1c08
Move import out
karenfeng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import numpy as np | ||
| from py4j.java_collections import JavaArray | ||
| from pyspark import SparkContext | ||
| from typeguard import check_argument_types, check_return_type | ||
|
|
||
|
|
||
| def _is_numpy_double_array(object, dimensions: int) -> bool: | ||
| assert check_argument_types() | ||
| output = isinstance(object, np.ndarray) and len(object.shape) == dimensions and object.dtype.type == np.double | ||
| assert check_return_type(output) | ||
| return output | ||
|
|
||
|
|
||
| def _convert_numpy_to_java_array(np_arr: np.ndarray) -> JavaArray: | ||
| """ | ||
| Converts a flat numpy array of doubles to a Java array of doubles. | ||
| """ | ||
| assert check_argument_types() | ||
| assert len(np_arr.shape) == 1 | ||
| assert np_arr.dtype.type == np.double | ||
|
|
||
| sc = SparkContext._active_spark_context | ||
| java_arr = sc._gateway.new_array(sc._jvm.double, np_arr.shape[0]) | ||
| for idx, ele in enumerate(np_arr): | ||
| java_arr[idx] = ele.item() | ||
|
|
||
| assert check_return_type(java_arr) | ||
| return java_arr | ||
|
|
||
|
|
||
| class OneDimensionalDoubleNumpyArrayConverter(object): | ||
| """ | ||
| Replaces any 1-dimensional numpy array of doubles with a literal Java array. | ||
|
|
||
| Added in version 0.4.0. | ||
|
|
||
| Examples: | ||
| >>> import numpy as np | ||
| >>> from pyspark.sql.functions import lit | ||
| >>> from pyspark.sql.types import StringType | ||
| >>> str_list = ['a', 'b'] | ||
| >>> df = spark.createDataFrame(str_list, StringType()) | ||
| >>> ndarray = np.array([1.0, 2.1, 3.2]) | ||
| >>> df.withColumn("array", lit(ndarray)).collect() | ||
| [Row(value='a', array=[1.0, 2.1, 3.2]), Row(value='b', array=[1.0, 2.1, 3.2])] | ||
| """ | ||
|
|
||
| def can_convert(self, object): | ||
| return _is_numpy_double_array(object, dimensions = 1) | ||
|
|
||
| def convert(self, object, gateway_client): | ||
| sc = SparkContext._active_spark_context | ||
| java_arr = _convert_numpy_to_java_array(object) | ||
| return java_arr | ||
|
|
||
|
|
||
| class TwoDimensionalDoubleNumpyArrayConverter(object): | ||
| """ | ||
| Replaces any 2-dimensional numpy array of doubles with a literal DenseMatrix. | ||
|
|
||
| Added in version 0.4.0. | ||
|
|
||
| Examples: | ||
| >>> import numpy as np | ||
| >>> from pyspark.sql.functions import lit | ||
| >>> from pyspark.sql.types import StringType | ||
| >>> str_list = ['a', 'b'] | ||
| >>> df = spark.createDataFrame(str_list, StringType()) | ||
| >>> ndarray = np.array([[1.0, 2.1, 3.2], [4.3, 5.4, 6.5]]) | ||
| >>> df.withColumn("matrix", lit(ndarray)).collect() | ||
| [Row(value='a', matrix=DenseMatrix(2, 3, [1.0, 2.1, 3.2, 4.3, 5.4, 6.5], False)), Row(value='b', matrix=DenseMatrix(2, 3, [1.0, 2.1, 3.2, 4.3, 5.4, 6.5], False))] | ||
| """ | ||
|
|
||
| def can_convert(self, object): | ||
| return _is_numpy_double_array(object, dimensions = 2) | ||
|
|
||
| def convert(self, object, gateway_client): | ||
| sc = SparkContext._active_spark_context | ||
| flat_arr = object.ravel() | ||
| java_arr = _convert_numpy_to_java_array(flat_arr) | ||
| dense_matrix = sc._jvm.org.apache.spark.ml.linalg.DenseMatrix(object.shape[0], object.shape[1], java_arr) | ||
| matrix_udt = sc._jvm.org.apache.spark.ml.linalg.MatrixUDT() | ||
| converter = sc._jvm.org.apache.spark.sql.catalyst.CatalystTypeConverters.createToCatalystConverter(matrix_udt) | ||
| literal_matrix = sc._jvm.org.apache.spark.sql.catalyst.expressions.Literal.create( | ||
| converter.apply(dense_matrix), matrix_udt) | ||
| return literal_matrix | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| from glow.conversions import OneDimensionalDoubleNumpyArrayConverter, TwoDimensionalDoubleNumpyArrayConverter | ||
| from importlib import reload | ||
| import numpy as np | ||
| from py4j.protocol import Py4JJavaError | ||
| from pyspark.ml.linalg import DenseMatrix | ||
| from pyspark.sql.functions import lit | ||
| from pyspark.sql.types import StringType | ||
| import pytest | ||
|
|
||
|
|
||
| def test_convert_matrix(spark): | ||
| str_list = ['a', 'b'] | ||
| df = spark.createDataFrame(str_list, StringType()) | ||
| ndarray = np.array([[1.0, 2.1, 3.2], [4.3, 5.4, 6.5]]) | ||
| output_rows = df.withColumn("matrix", lit(ndarray)).collect() | ||
| expected_matrix = DenseMatrix(2, 3, [1.0, 2.1, 3.2, 4.3, 5.4, 6.5]) | ||
| assert(output_rows[0].matrix == expected_matrix) | ||
| assert(output_rows[1].matrix == expected_matrix) | ||
|
|
||
|
|
||
| def test_convert_array(spark): | ||
| str_list = ['a', 'b'] | ||
| df = spark.createDataFrame(str_list, StringType()) | ||
| ndarray = np.array([1.0, 2.1, 3.2]) | ||
| output_rows = df.withColumn("array", lit(ndarray)).collect() | ||
| expected_array = [1.0, 2.1, 3.2] | ||
| assert(output_rows[0].array == expected_array) | ||
| assert(output_rows[1].array == expected_array) | ||
|
|
||
|
|
||
| def test_convert_checks_dimension(spark): | ||
| # No support for 3-dimensional arrays | ||
| ndarray = np.array([[[1.]]]) | ||
| with pytest.raises(Py4JJavaError): | ||
| lit(ndarray) | ||
|
|
||
|
|
||
| def test_convert_matrix_checks_type(spark): | ||
| ndarray = np.array([[1, 2], [3, 4]]) | ||
| with pytest.raises(AttributeError): | ||
| lit(ndarray) | ||
|
|
||
|
|
||
| def test_convert_array_checks_type(spark): | ||
| ndarray = np.array([1, 2]) | ||
| with pytest.raises(AttributeError): | ||
| lit(ndarray) | ||
|
|
||
|
|
||
| def test_register_converters_idempotent(spark): | ||
| import glow.glow | ||
| for _ in range(3): | ||
| reload(glow.glow) | ||
| one_d_converters = 0 | ||
| two_d_converters = 0 | ||
| for c in spark._sc._gateway._gateway_client.converters: | ||
| if type(c) is OneDimensionalDoubleNumpyArrayConverter: | ||
| one_d_converters += 1 | ||
| if type(c) is TwoDimensionalDoubleNumpyArrayConverter: | ||
| two_d_converters += 1 | ||
| assert(one_d_converters == 1) | ||
| assert(two_d_converters == 1) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hm, it seems a little weird that we explicitly wrap in a
Literalhere. Does that mean that this conversion doesn't work withspark.createDataFrame? Not sure I would expect that as a user.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately the PySpark pathways for
createDataFrameandlitare very different. Passing this as aLiteralallows us to bypass the usual type-checking and conversion logic.