Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions python/pyspark/sql/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ def _(col):
return _


def _create_zero_arg_function(name, doc=""):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is actually not zero arg is it?

I'm tempted to not rely on this magic function here, since we only have two functions. Then you can also have docstring test inline.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we add a lot of functions like this in the future, then we can add this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was a lot of scoping issues. We couldn't get it to work with Josh when it wasn't in a function of it's own :/

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cov() can provide the covariance between all columns for example. The functions might increase pretty soon!

""" Create a zero arg function by name"""
def _(val=None):
sc = SparkContext._active_spark_context
if val:
jc = getattr(sc._jvm.functions, name)(val)
else:
jc = getattr(sc._jvm.functions, name)()
return Column(jc)
_.__name__ = name
_.__doc__ = doc
return _


_functions = {
'lit': 'Creates a :class:`Column` of literal value.',
'col': 'Returns a :class:`Column` based on the given column name.',
Expand All @@ -67,11 +81,18 @@ def _(col):
'sumDistinct': 'Aggregate function: returns the sum of distinct values in the expression.',
}

_randfunctions = {
'rand': 'Generate a random column with i.i.d. samples from U[0.0, 1.0].',
'randn': 'Generate a column with i.i.d. samples from the standard normal distribution.'
}

for _name, _doc in _functions.items():
globals()[_name] = _create_function(_name, _doc)
for _name, _doc in _randfunctions.items():
globals()[_name] = _create_zero_arg_function(_name, _doc)
del _name, _doc
__all__ += _functions.keys()
__all__ += _randfunctions.keys()
__all__.sort()


Expand Down
10 changes: 10 additions & 0 deletions python/pyspark/sql/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,16 @@ def assert_close(a, b):
assert_close([math.hypot(i, 2 * i) for i in range(10)],
df.select(functions.hypot(df.a, df.b)).collect())

def test_rand_functions(self):
df = self.df
from pyspark.sql import functions
rnd = df.select('key', functions.rand()).collect()
for row in rnd:
assert row[1] >= 0.0 and row[1] <= 1.0, "got: %s" % row[1]
rndn = df.select('key', functions.randn(5L)).collect()
for row in rndn:
assert row[1] >= -4.0 and row[1] <= 4.0, "got: %s" % row[1]

def test_save_and_load(self):
df = self.df
tmpPath = tempfile.mkdtemp()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.catalyst.expressions.randfuncs
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think it's ok to not have this package. I only suggested it for math because there were so many of them.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There can be so many of these as well in the future :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how many realistically will we add?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, if we make RDG generic, and users can plug in their own distributions, then we won't need to add any. MLlib has 6 generators, but I can think of 3-4 more on top of that.


import org.apache.spark.TaskContext
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.types.{DoubleType, DataType}
import org.apache.spark.util.random.XORShiftRandom

/**
* A Random distribution generating expression.
* TODO: This can be made generic to generate any type of random distribution, or any type of
* StructType.
*
* Since this expression is stateful, it cannot be a case object.
*/
private[sql] abstract class RDG(seed: Long) extends LeafExpression with Serializable {
self: Product =>

/**
* Record ID within each partition. By being transient, the Random Number Generator is
* reset every time we serialize and deserialize it.
*/
@transient private[this] lazy val rng = new XORShiftRandom(seed + TaskContext.get().partitionId())

override type EvaluatedType = Double

override def nullable: Boolean = false

override def dataType: DataType = DoubleType

def generateNumber(random: XORShiftRandom): Double

override def eval(input: Row): Double = {
generateNumber(rng)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just let the child class implement eval

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How will I pass rng to the child? Have the child generate that as well?

}
}

/** Generate a random column with i.i.d. uniformly distributed values in [0, 1). */
private[sql] case class Rand(seed: Long) extends RDG(seed) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't need private[sql] since everything in catalyst is private.

override def generateNumber(random: XORShiftRandom): Double = random.nextDouble()
}

/** Generate a random column with i.i.d. gaussian random distribution. */
private[sql] case class Randn(seed: Long) extends RDG(seed) {
override def generateNumber(random: XORShiftRandom): Double = random.nextGaussian()
}
31 changes: 30 additions & 1 deletion sql/core/src/main/scala/org/apache/spark/sql/functions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ import org.apache.spark.annotation.Experimental
import org.apache.spark.sql.catalyst.ScalaReflection
import org.apache.spark.sql.catalyst.analysis.{UnresolvedFunction, Star}
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.randfuncs.{Randn, Rand}
import org.apache.spark.sql.types._

import org.apache.spark.util.Utils

/**
* :: Experimental ::
Expand Down Expand Up @@ -346,6 +347,34 @@ object functions {
*/
def not(e: Column): Column = !e

/**
* Generate a random column with i.i.d. samples from U[0.0, 1.0].
*
* @group normal_funcs
*/
def rand(seed: Long): Column = Rand(seed)

/**
* Generate a random column with i.i.d. samples from U[0.0, 1.0].
*
* @group normal_funcs
*/
def rand(): Column = rand(Utils.random.nextLong)

/**
* Generate a column with i.i.d. samples from the standard normal distribution.
*
* @group normal_funcs
*/
def randn(seed: Long): Column = Randn(seed)

/**
* Generate a column with i.i.d. samples from the standard normal distribution.
*
* @group normal_funcs
*/
def randn(): Column = randn(Utils.random.nextLong)

/**
* Partition ID of the Spark task.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ import org.apache.spark.sql.functions.lit
/**
* :: Experimental ::
* Mathematical Functions available for [[DataFrame]].
*
* @groupname double_funcs Functions that require DoubleType as an input
*/
@Experimental
// scalastyle:off
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ public void testVarargMethods() {
df2.select(pow("a", "a"), pow("b", 2.0));
df2.select(pow(col("a"), col("b")), exp("b"));
df2.select(sin("a"), acos("b"));

df2.select(rand(), acos("b"));
df2.select(col("*"), randn(5L));
}

@Ignore
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

package org.apache.spark.sql

import org.scalatest.Matchers._

import org.apache.spark.sql.functions._
import org.apache.spark.sql.test.TestSQLContext
import org.apache.spark.sql.test.TestSQLContext.implicits._
Expand Down Expand Up @@ -349,4 +351,24 @@ class ColumnExpressionSuite extends QueryTest {
assert(schema("value").metadata === Metadata.empty)
assert(schema("abc").metadata === metadata)
}

test("rand") {
val randCol = testData.select('key, rand(5L).as("rand"))
randCol.columns.length should be (2)
val rows = randCol.collect()
rows.foreach { row =>
assert(row.getDouble(1) <= 1.0)
assert(row.getDouble(1) >= 0.0)
}
}

test("randn") {
val randCol = testData.select('key, randn(5L).as("rand"))
randCol.columns.length should be (2)
val rows = randCol.collect()
rows.foreach { row =>
assert(row.getDouble(1) <= 4.0)
assert(row.getDouble(1) >= -4.0)
}
}
}