Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def array_repeat(col, count):
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.array_repeat(_to_java_column(col), count)) | [
"\n Collection function: creates an array containing a column repeated count times.\n\n >>> df = spark.createDataFrame([('ab',)], ['data'])\n >>> df.select(array_repeat(df.data, 3).alias('r')).collect()\n [Row(r=[u'ab', u'ab', u'ab'])]\n "
] |
Please provide a description of the function:def map_concat(*cols):
sc = SparkContext._active_spark_context
if len(cols) == 1 and isinstance(cols[0], (list, set)):
cols = cols[0]
jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column))
return Column(jc) | [
"Returns the union of all the given maps.\n\n :param cols: list of column names (string) or list of :class:`Column` expressions\n\n >>> from pyspark.sql.functions import map_concat\n >>> df = spark.sql(\"SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c', 1, 'd') as map2\")\n >>> df.select(map_concat(\"map1... |
Please provide a description of the function:def sequence(start, stop, step=None):
sc = SparkContext._active_spark_context
if step is None:
return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop)))
else:
return Column(sc._jvm.functions.sequence(
_to_java_column(start), _to_java_column(stop), _to_java_column(step))) | [
"\n Generate a sequence of integers from `start` to `stop`, incrementing by `step`.\n If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,\n otherwise -1.\n\n >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))\n >>> df1.select(sequence('C1', 'C2').alias('r')).coll... |
Please provide a description of the function:def from_csv(col, schema, options={}):
sc = SparkContext._active_spark_context
if isinstance(schema, basestring):
schema = _create_column_from_literal(schema)
elif isinstance(schema, Column):
schema = _to_java_column(schema)
else:
raise TypeError("schema argument should be a column or string")
jc = sc._jvm.functions.from_csv(_to_java_column(col), schema, options)
return Column(jc) | [
"\n Parses a column containing a CSV string to a row with the specified schema.\n Returns `null`, in the case of an unparseable string.\n\n :param col: string column in CSV format\n :param schema: a string with schema in DDL format to use when parsing the CSV column.\n :param options: options to cont... |
Please provide a description of the function:def udf(f=None, returnType=StringType()):
# The following table shows most of Python data and SQL type conversions in normal UDFs that
# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near
# future. The table might have to be eventually documented externally.
# Please see SPARK-25666's PR to see the codes in order to generate the table below.
#
# +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa
# |SQL Type \ Python Value(Type)|None(NoneType)|True(bool)|1(int)|1(long)| a(str)| a(unicode)| 1970-01-01(date)|1970-01-01 00:00:00(datetime)|1.0(float)|array('i', [1])(array)|[1](list)| (1,)(tuple)| ABC(bytearray)| 1(Decimal)|{'a': 1}(dict)|Row(kwargs=1)(Row)|Row(namedtuple=1)(Row)| # noqa
# +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa
# | boolean| None| True| None| None| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | tinyint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | smallint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | int| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | bigint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa
# | string| None| u'true'| u'1'| u'1'| u'a'| u'a'|u'java.util.Grego...| u'java.util.Grego...| u'1.0'| u'[I@24a83055'| u'[1]'|u'[Ljava.lang.Obj...| u'[B@49093632'| u'1'| u'{a=1}'| X| X| # noqa
# | date| None| X| X| X| X| X|datetime.date(197...| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa
# | timestamp| None| X| X| X| X| X| X| datetime.datetime...| X| X| X| X| X| X| X| X| X| # noqa
# | float| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa
# | double| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa
# | array<int>| None| None| None| None| None| None| None| None| None| [1]| [1]| [1]| [65, 66, 67]| None| None| X| X| # noqa
# | binary| None| None| None| None|bytearray(b'a')|bytearray(b'a')| None| None| None| None| None| None|bytearray(b'ABC')| None| None| X| X| # noqa
# | decimal(10,0)| None| None| None| None| None| None| None| None| None| None| None| None| None|Decimal('1')| None| X| X| # noqa
# | map<string,int>| None| None| None| None| None| None| None| None| None| None| None| None| None| None| {u'a': 1}| X| X| # noqa
# | struct<_1:int>| None| X| X| X| X| X| X| X| X| X|Row(_1=1)| Row(_1=1)| X| X| Row(_1=None)| Row(_1=1)| Row(_1=1)| # noqa
# +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa
#
# Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be
# used in `returnType`.
# Note: The values inside of the table are generated by `repr`.
# Note: Python 2 is used to generate this table since it is used to check the backward
# compatibility often in practice.
# Note: 'X' means it throws an exception during the conversion.
# decorator @udf, @udf(), @udf(dataType())
if f is None or isinstance(f, (str, DataType)):
# If DataType has been passed as a positional argument
# for decorator use it as a returnType
return_type = f or returnType
return functools.partial(_create_udf, returnType=return_type,
evalType=PythonEvalType.SQL_BATCHED_UDF)
else:
return _create_udf(f=f, returnType=returnType,
evalType=PythonEvalType.SQL_BATCHED_UDF) | [
"Creates a user defined function (UDF).\n\n .. note:: The user-defined functions are considered deterministic by default. Due to\n optimization, duplicate invocations may be eliminated or the function may even be invoked\n more times than it is present in the query. If your function is not determin... |
Please provide a description of the function:def pandas_udf(f=None, returnType=None, functionType=None):
# The following table shows most of Pandas data and SQL type conversions in Pandas UDFs that
# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near
# future. The table might have to be eventually documented externally.
# Please see SPARK-25798's PR to see the codes in order to generate the table below.
#
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
# |SQL Type \ Pandas Value(Type)|None(object(NoneType))|True(bool)|1(int8)|1(int16)| 1(int32)| 1(int64)|1(uint8)|1(uint16)|1(uint32)|1(uint64)|1.0(float16)|1.0(float32)|1.0(float64)|1970-01-01 00:00:00(datetime64[ns])|1970-01-01 00:00:00-05:00(datetime64[ns, US/Eastern])|a(object(string))| 1(object(Decimal))|[1 2 3](object(array[int32]))|1.0(float128)|(1+0j)(complex64)|(1+0j)(complex128)|A(category)|1 days 00:00:00(timedelta64[ns])| # noqa
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
# | boolean| None| True| True| True| True| True| True| True| True| True| False| False| False| False| False| X| X| X| False| False| False| X| False| # noqa
# | tinyint| None| 1| 1| 1| 1| 1| X| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| 0| X| # noqa
# | smallint| None| 1| 1| 1| 1| 1| 1| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa
# | int| None| 1| 1| 1| 1| 1| 1| 1| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa
# | bigint| None| 1| 1| 1| 1| 1| 1| 1| 1| X| 1| 1| 1| 0| 18000000000000| X| X| X| X| X| X| X| X| # noqa
# | float| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X|1.401298464324817...| X| X| X| X| X| X| # noqa
# | double| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X| X| X| X| X| X| X| X| # noqa
# | date| None| X| X| X|datetime.date(197...| X| X| X| X| X| X| X| X| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa
# | timestamp| None| X| X| X| X|datetime.datetime...| X| X| X| X| X| X| X| datetime.datetime...| datetime.datetime...| X| X| X| X| X| X| X| X| # noqa
# | string| None| u''|u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u''| u''| u''| X| X| u'a'| X| X| u''| u''| u''| X| X| # noqa
# | decimal(10,0)| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| Decimal('1')| X| X| X| X| X| X| # noqa
# | array<int>| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| [1, 2, 3]| X| X| X| X| X| # noqa
# | map<string,int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# | struct<_1:int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# | binary| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
#
# Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be
# used in `returnType`.
# Note: The values inside of the table are generated by `repr`.
# Note: Python 2 is used to generate this table since it is used to check the backward
# compatibility often in practice.
# Note: Pandas 0.19.2 and PyArrow 0.9.0 are used.
# Note: Timezone is Singapore timezone.
# Note: 'X' means it throws an exception during the conversion.
# Note: 'binary' type is only supported with PyArrow 0.10.0+ (SPARK-23555).
# decorator @pandas_udf(returnType, functionType)
is_decorator = f is None or isinstance(f, (str, DataType))
if is_decorator:
# If DataType has been passed as a positional argument
# for decorator use it as a returnType
return_type = f or returnType
if functionType is not None:
# @pandas_udf(dataType, functionType=functionType)
# @pandas_udf(returnType=dataType, functionType=functionType)
eval_type = functionType
elif returnType is not None and isinstance(returnType, int):
# @pandas_udf(dataType, functionType)
eval_type = returnType
else:
# @pandas_udf(dataType) or @pandas_udf(returnType=dataType)
eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF
else:
return_type = returnType
if functionType is not None:
eval_type = functionType
else:
eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF
if return_type is None:
raise ValueError("Invalid returnType: returnType can not be None")
if eval_type not in [PythonEvalType.SQL_SCALAR_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]:
raise ValueError("Invalid functionType: "
"functionType must be one the values from PandasUDFType")
if is_decorator:
return functools.partial(_create_udf, returnType=return_type, evalType=eval_type)
else:
return _create_udf(f=f, returnType=return_type, evalType=eval_type) | [
"\n Creates a vectorized user defined function (UDF).\n\n :param f: user-defined function. A python function if used as a standalone function\n :param returnType: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted t... |
Please provide a description of the function:def to_str(value):
if isinstance(value, bool):
return str(value).lower()
elif value is None:
return value
else:
return str(value) | [
"\n A wrapper over str(), but converts bool values to lower case strings.\n If None is given, just returns None, instead of converting it to string \"None\".\n "
] |
Please provide a description of the function:def _set_opts(self, schema=None, **options):
if schema is not None:
self.schema(schema)
for k, v in options.items():
if v is not None:
self.option(k, v) | [
"\n Set named options (filter out those the value is None)\n "
] |
Please provide a description of the function:def format(self, source):
self._jreader = self._jreader.format(source)
return self | [
"Specifies the input data source format.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df = spark.read.format('json').load('python/test_support/sql/people.json')\n >>> df.dtypes\n [('age', 'bigint'), ('name', 'string')]\n\n "
] |
Please provide a description of the function:def schema(self, schema):
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
if isinstance(schema, StructType):
jschema = spark._jsparkSession.parseDataType(schema.json())
self._jreader = self._jreader.schema(jschema)
elif isinstance(schema, basestring):
self._jreader = self._jreader.schema(schema)
else:
raise TypeError("schema should be StructType or string")
return self | [
"Specifies the input schema.\n\n Some data sources (e.g. JSON) can infer the input schema automatically from data.\n By specifying the schema here, the underlying data source can skip the schema\n inference step, and thus speed up data loading.\n\n :param schema: a :class:`pyspark.sql.ty... |
Please provide a description of the function:def option(self, key, value):
self._jreader = self._jreader.option(key, to_str(value))
return self | [
"Adds an input option for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't... |
Please provide a description of the function:def options(self, **options):
for k in options:
self._jreader = self._jreader.option(k, to_str(options[k]))
return self | [
"Adds input options for the underlying data source.\n\n You can set the following option(s) for reading files:\n * ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps\n in the JSON/CSV datasources or partition values.\n If it isn't s... |
Please provide a description of the function:def load(self, path=None, format=None, schema=None, **options):
if format is not None:
self.format(format)
if schema is not None:
self.schema(schema)
self.options(**options)
if isinstance(path, basestring):
return self._df(self._jreader.load(path))
elif path is not None:
if type(path) != list:
path = [path]
return self._df(self._jreader.load(self._spark._sc._jvm.PythonUtils.toSeq(path)))
else:
return self._df(self._jreader.load()) | [
"Loads data from a data source and returns it as a :class`DataFrame`.\n\n :param path: optional string or a list of string for file-system backed data sources.\n :param format: optional string for format of the data source. Default to 'parquet'.\n :param schema: optional :class:`pyspark.sql.typ... |
Please provide a description of the function:def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None,
multiLine=None, allowUnquotedControlChars=None, lineSep=None, samplingRatio=None,
dropFieldIfAllNull=None, encoding=None, locale=None):
self._set_opts(
schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal,
allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames,
allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero,
allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter,
mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, dateFormat=dateFormat,
timestampFormat=timestampFormat, multiLine=multiLine,
allowUnquotedControlChars=allowUnquotedControlChars, lineSep=lineSep,
samplingRatio=samplingRatio, dropFieldIfAllNull=dropFieldIfAllNull, encoding=encoding,
locale=locale)
if isinstance(path, basestring):
path = [path]
if type(path) == list:
return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))
elif isinstance(path, RDD):
def func(iterator):
for x in iterator:
if not isinstance(x, basestring):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = path.mapPartitions(func)
keyed._bypass_serializer = True
jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())
return self._df(self._jreader.json(jrdd))
else:
raise TypeError("path can be only string, list or RDD") | [
"\n Loads JSON files and returns the results as a :class:`DataFrame`.\n\n `JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.\n For JSON (one record per file), set the ``multiLine`` parameter to ``true``.\n\n If the ``schema`` parameter is not specifie... |
Please provide a description of the function:def parquet(self, *paths):
return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) | [
"Loads Parquet files, returning the result as a :class:`DataFrame`.\n\n You can set the following Parquet-specific option(s) for reading Parquet files:\n * ``mergeSchema``: sets whether we should merge schemas collected from all \\\n Parquet part-files. This will override ``spark.sq... |
Please provide a description of the function:def text(self, paths, wholetext=False, lineSep=None):
self._set_opts(wholetext=wholetext, lineSep=lineSep)
if isinstance(paths, basestring):
paths = [paths]
return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq(paths))) | [
"\n Loads text files and returns a :class:`DataFrame` whose schema starts with a\n string column named \"value\", and followed by partitioned columns if there\n are any.\n The text files must be encoded as UTF-8.\n\n By default, each line in the text file is a new row in the resul... |
Please provide a description of the function:def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,
comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,
ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,
negativeInf=None, dateFormat=None, timestampFormat=None, maxColumns=None,
maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None,
columnNameOfCorruptRecord=None, multiLine=None, charToEscapeQuoteEscaping=None,
samplingRatio=None, enforceSchema=None, emptyValue=None, locale=None, lineSep=None):
r
self._set_opts(
schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment,
header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue,
nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf,
dateFormat=dateFormat, timestampFormat=timestampFormat, maxColumns=maxColumns,
maxCharsPerColumn=maxCharsPerColumn,
maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode,
columnNameOfCorruptRecord=columnNameOfCorruptRecord, multiLine=multiLine,
charToEscapeQuoteEscaping=charToEscapeQuoteEscaping, samplingRatio=samplingRatio,
enforceSchema=enforceSchema, emptyValue=emptyValue, locale=locale, lineSep=lineSep)
if isinstance(path, basestring):
path = [path]
if type(path) == list:
return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
elif isinstance(path, RDD):
def func(iterator):
for x in iterator:
if not isinstance(x, basestring):
x = unicode(x)
if isinstance(x, unicode):
x = x.encode("utf-8")
yield x
keyed = path.mapPartitions(func)
keyed._bypass_serializer = True
jrdd = keyed._jrdd.map(self._spark._jvm.BytesToString())
# see SPARK-22112
# There aren't any jvm api for creating a dataframe from rdd storing csv.
# We can do it through creating a jvm dataset firstly and using the jvm api
# for creating a dataframe from dataset storing csv.
jdataset = self._spark._ssql_ctx.createDataset(
jrdd.rdd(),
self._spark._jvm.Encoders.STRING())
return self._df(self._jreader.csv(jdataset))
else:
raise TypeError("path can be only string, list or RDD") | [
"Loads a CSV file and returns the result as a :class:`DataFrame`.\n\n This function will go through the input once to determine the input schema if\n ``inferSchema`` is enabled. To avoid going through the entire data once, disable\n ``inferSchema`` option or specify the schema explicitly using... |
Please provide a description of the function:def orc(self, path):
if isinstance(path, basestring):
path = [path]
return self._df(self._jreader.orc(_to_seq(self._spark._sc, path))) | [
"Loads ORC files, returning the result as a :class:`DataFrame`.\n\n >>> df = spark.read.orc('python/test_support/sql/orc_partitioned')\n >>> df.dtypes\n [('a', 'bigint'), ('b', 'int'), ('c', 'int')]\n "
] |
Please provide a description of the function:def jdbc(self, url, table, column=None, lowerBound=None, upperBound=None, numPartitions=None,
predicates=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
if column is not None:
assert lowerBound is not None, "lowerBound can not be None when ``column`` is specified"
assert upperBound is not None, "upperBound can not be None when ``column`` is specified"
assert numPartitions is not None, \
"numPartitions can not be None when ``column`` is specified"
return self._df(self._jreader.jdbc(url, table, column, int(lowerBound), int(upperBound),
int(numPartitions), jprop))
if predicates is not None:
gateway = self._spark._sc._gateway
jpredicates = utils.toJArray(gateway, gateway.jvm.java.lang.String, predicates)
return self._df(self._jreader.jdbc(url, table, jpredicates, jprop))
return self._df(self._jreader.jdbc(url, table, jprop)) | [
"\n Construct a :class:`DataFrame` representing the database table named ``table``\n accessible via JDBC URL ``url`` and connection ``properties``.\n\n Partitions of the table will be retrieved in parallel if either ``column`` or\n ``predicates`` is specified. ``lowerBound`, ``upperBound... |
Please provide a description of the function:def mode(self, saveMode):
# At the JVM side, the default value of mode is already set to "error".
# So, if the given saveMode is None, we will not call JVM-side's mode method.
if saveMode is not None:
self._jwrite = self._jwrite.mode(saveMode)
return self | [
"Specifies the behavior when data or table already exists.\n\n Options include:\n\n * `append`: Append contents of this :class:`DataFrame` to existing data.\n * `overwrite`: Overwrite existing data.\n * `error` or `errorifexists`: Throw an exception if data already exists.\n * `ig... |
Please provide a description of the function:def format(self, source):
self._jwrite = self._jwrite.format(source)
return self | [
"Specifies the underlying output data source.\n\n :param source: string, name of the data source, e.g. 'json', 'parquet'.\n\n >>> df.write.format('json').save(os.path.join(tempfile.mkdtemp(), 'data'))\n "
] |
Please provide a description of the function:def option(self, key, value):
self._jwrite = self._jwrite.option(key, to_str(value))
return self | [
"Adds an output option for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn... |
Please provide a description of the function:def options(self, **options):
for k in options:
self._jwrite = self._jwrite.option(k, to_str(options[k]))
return self | [
"Adds output options for the underlying data source.\n\n You can set the following option(s) for writing files:\n * ``timeZone``: sets the string that indicates a timezone to be used to format\n timestamps in the JSON/CSV datasources or partition values.\n If it isn't... |
Please provide a description of the function:def partitionBy(self, *cols):
if len(cols) == 1 and isinstance(cols[0], (list, tuple)):
cols = cols[0]
self._jwrite = self._jwrite.partitionBy(_to_seq(self._spark._sc, cols))
return self | [
"Partitions the output by the given columns on the file system.\n\n If specified, the output is laid out on the file system similar\n to Hive's partitioning scheme.\n\n :param cols: name of columns\n\n >>> df.write.partitionBy('year', 'month').parquet(os.path.join(tempfile.mkdtemp(), 'da... |
Please provide a description of the function:def sortBy(self, col, *cols):
if isinstance(col, (list, tuple)):
if cols:
raise ValueError("col is a {0} but cols are not empty".format(type(col)))
col, cols = col[0], col[1:]
if not all(isinstance(c, basestring) for c in cols) or not(isinstance(col, basestring)):
raise TypeError("all names should be `str`")
self._jwrite = self._jwrite.sortBy(col, _to_seq(self._spark._sc, cols))
return self | [
"Sorts the output in each bucket by the given columns on the file system.\n\n :param col: a name of a column, or a list of names.\n :param cols: additional names (optional). If `col` is a list it should be empty.\n\n >>> (df.write.format('parquet') # doctest: +SKIP\n ... .bucketBy(1... |
Please provide a description of the function:def save(self, path=None, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
if path is None:
self._jwrite.save()
else:
self._jwrite.save(path) | [
"Saves the contents of the :class:`DataFrame` to a data source.\n\n The data source is specified by the ``format`` and a set of ``options``.\n If ``format`` is not specified, the default data source configured by\n ``spark.sql.sources.default`` will be used.\n\n :param path: the path in ... |
Please provide a description of the function:def insertInto(self, tableName, overwrite=False):
self._jwrite.mode("overwrite" if overwrite else "append").insertInto(tableName) | [
"Inserts the content of the :class:`DataFrame` to the specified table.\n\n It requires that the schema of the class:`DataFrame` is the same as the\n schema of the table.\n\n Optionally overwriting any existing data.\n "
] |
Please provide a description of the function:def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
self.mode(mode).options(**options)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
self._jwrite.saveAsTable(name) | [
"Saves the content of the :class:`DataFrame` as the specified table.\n\n In the case the table already exists, behavior of this function depends on the\n save mode, specified by the `mode` function (default to throwing an exception).\n When `mode` is `Overwrite`, the schema of the :class:`DataF... |
Please provide a description of the function:def json(self, path, mode=None, compression=None, dateFormat=None, timestampFormat=None,
lineSep=None, encoding=None):
self.mode(mode)
self._set_opts(
compression=compression, dateFormat=dateFormat, timestampFormat=timestampFormat,
lineSep=lineSep, encoding=encoding)
self._jwrite.json(path) | [
"Saves the content of the :class:`DataFrame` in JSON format\n (`JSON Lines text format or newline-delimited JSON <http://jsonlines.org/>`_) at the\n specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation w... |
Please provide a description of the function:def parquet(self, path, mode=None, partitionBy=None, compression=None):
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.parquet(path) | [
"Saves the content of the :class:`DataFrame` in Parquet format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFra... |
Please provide a description of the function:def text(self, path, compression=None, lineSep=None):
self._set_opts(compression=compression, lineSep=lineSep)
self._jwrite.text(path) | [
"Saves the content of the DataFrame in a text file at the specified path.\n The text files will be encoded as UTF-8.\n\n :param path: the path in any Hadoop supported file system\n :param compression: compression codec to use when saving to file. This can be one of the\n ... |
Please provide a description of the function:def csv(self, path, mode=None, compression=None, sep=None, quote=None, escape=None,
header=None, nullValue=None, escapeQuotes=None, quoteAll=None, dateFormat=None,
timestampFormat=None, ignoreLeadingWhiteSpace=None, ignoreTrailingWhiteSpace=None,
charToEscapeQuoteEscaping=None, encoding=None, emptyValue=None, lineSep=None):
r
self.mode(mode)
self._set_opts(compression=compression, sep=sep, quote=quote, escape=escape, header=header,
nullValue=nullValue, escapeQuotes=escapeQuotes, quoteAll=quoteAll,
dateFormat=dateFormat, timestampFormat=timestampFormat,
ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace,
charToEscapeQuoteEscaping=charToEscapeQuoteEscaping,
encoding=encoding, emptyValue=emptyValue, lineSep=lineSep)
self._jwrite.csv(path) | [
"Saves the content of the :class:`DataFrame` in CSV format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` ... |
Please provide a description of the function:def orc(self, path, mode=None, partitionBy=None, compression=None):
self.mode(mode)
if partitionBy is not None:
self.partitionBy(partitionBy)
self._set_opts(compression=compression)
self._jwrite.orc(path) | [
"Saves the content of the :class:`DataFrame` in ORC format at the specified path.\n\n :param path: the path in any Hadoop supported file system\n :param mode: specifies the behavior of the save operation when data already exists.\n\n * ``append``: Append contents of this :class:`DataFrame` ... |
Please provide a description of the function:def jdbc(self, url, table, mode=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
self.mode(mode)._jwrite.jdbc(url, table, jprop) | [
"Saves the content of the :class:`DataFrame` to an external database table via JDBC.\n\n .. note:: Don't create too many partitions in parallel on a large cluster;\n otherwise Spark might crash your external database systems.\n\n :param url: a JDBC URL of the form ``jdbc:subprotocol:subname... |
Please provide a description of the function:def createStream(ssc, kinesisAppName, streamName, endpointUrl, regionName,
initialPositionInStream, checkpointInterval,
storageLevel=StorageLevel.MEMORY_AND_DISK_2,
awsAccessKeyId=None, awsSecretKey=None, decoder=utf8_decoder,
stsAssumeRoleArn=None, stsSessionName=None, stsExternalId=None):
jlevel = ssc._sc._getJavaStorageLevel(storageLevel)
jduration = ssc._jduration(checkpointInterval)
try:
# Use KinesisUtilsPythonHelper to access Scala's KinesisUtils
helper = ssc._jvm.org.apache.spark.streaming.kinesis.KinesisUtilsPythonHelper()
except TypeError as e:
if str(e) == "'JavaPackage' object is not callable":
_print_missing_jar(
"Streaming's Kinesis",
"streaming-kinesis-asl",
"streaming-kinesis-asl-assembly",
ssc.sparkContext.version)
raise
jstream = helper.createStream(ssc._jssc, kinesisAppName, streamName, endpointUrl,
regionName, initialPositionInStream, jduration, jlevel,
awsAccessKeyId, awsSecretKey, stsAssumeRoleArn,
stsSessionName, stsExternalId)
stream = DStream(jstream, ssc, NoOpSerializer())
return stream.map(lambda v: decoder(v)) | [
"\n Create an input stream that pulls messages from a Kinesis stream. This uses the\n Kinesis Client Library (KCL) to pull messages from Kinesis.\n\n .. note:: The given AWS credentials will get saved in DStream checkpoints if checkpointing\n is enabled. Make sure that your checkpoin... |
Please provide a description of the function:def choose_jira_assignee(issue, asf_jira):
while True:
try:
reporter = issue.fields.reporter
commentors = map(lambda x: x.author, issue.fields.comment.comments)
candidates = set(commentors)
candidates.add(reporter)
candidates = list(candidates)
print("JIRA is unassigned, choose assignee")
for idx, author in enumerate(candidates):
if author.key == "apachespark":
continue
annotations = ["Reporter"] if author == reporter else []
if author in commentors:
annotations.append("Commentor")
print("[%d] %s (%s)" % (idx, author.displayName, ",".join(annotations)))
raw_assignee = input(
"Enter number of user, or userid, to assign to (blank to leave unassigned):")
if raw_assignee == "":
return None
else:
try:
id = int(raw_assignee)
assignee = candidates[id]
except:
# assume it's a user id, and try to assign (might fail, we just prompt again)
assignee = asf_jira.user(raw_assignee)
asf_jira.assign_issue(issue.key, assignee.key)
return assignee
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
print("Error assigning JIRA, try again (or leave blank and fix manually)") | [
"\n Prompt the user to choose who to assign the issue to in jira, given a list of candidates,\n including the original reporter and all commentors\n "
] |
Please provide a description of the function:def standardize_jira_ref(text):
jira_refs = []
components = []
# If the string is compliant, no need to process any further
if (re.search(r'^\[SPARK-[0-9]{3,6}\](\[[A-Z0-9_\s,]+\] )+\S+', text)):
return text
# Extract JIRA ref(s):
pattern = re.compile(r'(SPARK[-\s]*[0-9]{3,6})+', re.IGNORECASE)
for ref in pattern.findall(text):
# Add brackets, replace spaces with a dash, & convert to uppercase
jira_refs.append('[' + re.sub(r'\s+', '-', ref.upper()) + ']')
text = text.replace(ref, '')
# Extract spark component(s):
# Look for alphanumeric chars, spaces, dashes, periods, and/or commas
pattern = re.compile(r'(\[[\w\s,.-]+\])', re.IGNORECASE)
for component in pattern.findall(text):
components.append(component.upper())
text = text.replace(component, '')
# Cleanup any remaining symbols:
pattern = re.compile(r'^\W+(.*)', re.IGNORECASE)
if (pattern.search(text) is not None):
text = pattern.search(text).groups()[0]
# Assemble full text (JIRA ref(s), module(s), remaining text)
clean_text = ''.join(jira_refs).strip() + ''.join(components).strip() + " " + text.strip()
# Replace multiple spaces with a single space, e.g. if no jira refs and/or components were
# included
clean_text = re.sub(r'\s+', ' ', clean_text.strip())
return clean_text | [
"\n Standardize the [SPARK-XXXXX] [MODULE] prefix\n Converts \"[SPARK-XXX][mllib] Issue\", \"[MLLib] SPARK-XXX. Issue\" or \"SPARK XXX [MLLIB]: Issue\" to\n \"[SPARK-XXX][MLLIB] Issue\"\n\n >>> standardize_jira_ref(\n ... \"[SPARK-5821] [SQL] ParquetRelation2 CTAS should check if delete is succes... |
Please provide a description of the function:def _parse_libsvm_line(line):
items = line.split(None)
label = float(items[0])
nnz = len(items) - 1
indices = np.zeros(nnz, dtype=np.int32)
values = np.zeros(nnz)
for i in xrange(nnz):
index, value = items[1 + i].split(":")
indices[i] = int(index) - 1
values[i] = float(value)
return label, indices, values | [
"\n Parses a line in LIBSVM format into (label, indices, values).\n "
] |
Please provide a description of the function:def _convert_labeled_point_to_libsvm(p):
from pyspark.mllib.regression import LabeledPoint
assert isinstance(p, LabeledPoint)
items = [str(p.label)]
v = _convert_to_vector(p.features)
if isinstance(v, SparseVector):
nnz = len(v.indices)
for i in xrange(nnz):
items.append(str(v.indices[i] + 1) + ":" + str(v.values[i]))
else:
for i in xrange(len(v)):
items.append(str(i + 1) + ":" + str(v[i]))
return " ".join(items) | [
"Converts a LabeledPoint to a string in LIBSVM format."
] |
Please provide a description of the function:def loadLibSVMFile(sc, path, numFeatures=-1, minPartitions=None):
from pyspark.mllib.regression import LabeledPoint
lines = sc.textFile(path, minPartitions)
parsed = lines.map(lambda l: MLUtils._parse_libsvm_line(l))
if numFeatures <= 0:
parsed.cache()
numFeatures = parsed.map(lambda x: -1 if x[1].size == 0 else x[1][-1]).reduce(max) + 1
return parsed.map(lambda x: LabeledPoint(x[0], Vectors.sparse(numFeatures, x[1], x[2]))) | [
"\n Loads labeled data in the LIBSVM format into an RDD of\n LabeledPoint. The LIBSVM format is a text-based format used by\n LIBSVM and LIBLINEAR. Each line represents a labeled sparse\n feature vector using the following format:\n\n label index1:value1 index2:value2 ...\n\n ... |
Please provide a description of the function:def saveAsLibSVMFile(data, dir):
lines = data.map(lambda p: MLUtils._convert_labeled_point_to_libsvm(p))
lines.saveAsTextFile(dir) | [
"\n Save labeled data in LIBSVM format.\n\n :param data: an RDD of LabeledPoint to be saved\n :param dir: directory to save the data\n\n >>> from tempfile import NamedTemporaryFile\n >>> from fileinput import input\n >>> from pyspark.mllib.regression import LabeledPoint\n ... |
Please provide a description of the function:def loadLabeledPoints(sc, path, minPartitions=None):
minPartitions = minPartitions or min(sc.defaultParallelism, 2)
return callMLlibFunc("loadLabeledPoints", sc, path, minPartitions) | [
"\n Load labeled points saved using RDD.saveAsTextFile.\n\n :param sc: Spark context\n :param path: file or directory path in any Hadoop-supported file\n system URI\n :param minPartitions: min number of partitions\n @return: labeled data stored as an RDD of Lab... |
Please provide a description of the function:def appendBias(data):
vec = _convert_to_vector(data)
if isinstance(vec, SparseVector):
newIndices = np.append(vec.indices, len(vec))
newValues = np.append(vec.values, 1.0)
return SparseVector(len(vec) + 1, newIndices, newValues)
else:
return _convert_to_vector(np.append(vec.toArray(), 1.0)) | [
"\n Returns a new vector with `1.0` (bias) appended to\n the end of the input vector.\n "
] |
Please provide a description of the function:def convertVectorColumnsToML(dataset, *cols):
if not isinstance(dataset, DataFrame):
raise TypeError("Input dataset must be a DataFrame but got {}.".format(type(dataset)))
return callMLlibFunc("convertVectorColumnsToML", dataset, list(cols)) | [
"\n Converts vector columns in an input DataFrame from the\n :py:class:`pyspark.mllib.linalg.Vector` type to the new\n :py:class:`pyspark.ml.linalg.Vector` type under the `spark.ml`\n package.\n\n :param dataset:\n input dataset\n :param cols:\n a list of ... |
Please provide a description of the function:def generateLinearInput(intercept, weights, xMean, xVariance,
nPoints, seed, eps):
weights = [float(weight) for weight in weights]
xMean = [float(mean) for mean in xMean]
xVariance = [float(var) for var in xVariance]
return list(callMLlibFunc(
"generateLinearInputWrapper", float(intercept), weights, xMean,
xVariance, int(nPoints), int(seed), float(eps))) | [
"\n :param: intercept bias factor, the term c in X'w + c\n :param: weights feature vector, the term w in X'w + c\n :param: xMean Point around which the data X is centered.\n :param: xVariance Variance of the given data\n :param: nPoints Number of points to be generated\n ... |
Please provide a description of the function:def generateLinearRDD(sc, nexamples, nfeatures, eps,
nParts=2, intercept=0.0):
return callMLlibFunc(
"generateLinearRDDWrapper", sc, int(nexamples), int(nfeatures),
float(eps), int(nParts), float(intercept)) | [
"\n Generate an RDD of LabeledPoints.\n "
] |
Please provide a description of the function:def train(cls, data, iterations=100, step=1.0, miniBatchFraction=1.0,
initialWeights=None, regParam=0.0, regType=None, intercept=False,
validateData=True, convergenceTol=0.001):
warnings.warn(
"Deprecated in 2.0.0. Use ml.regression.LinearRegression.", DeprecationWarning)
def train(rdd, i):
return callMLlibFunc("trainLinearRegressionModelWithSGD", rdd, int(iterations),
float(step), float(miniBatchFraction), i, float(regParam),
regType, bool(intercept), bool(validateData),
float(convergenceTol))
return _regression_train_wrapper(train, LinearRegressionModel, data, initialWeights) | [
"\n Train a linear regression model using Stochastic Gradient\n Descent (SGD). This solves the least squares regression\n formulation\n\n f(weights) = 1/(2n) ||A weights - y||^2\n\n which is the mean squared error. Here the data matrix has n rows,\n and the input RDD ho... |
Please provide a description of the function:def predict(self, x):
if isinstance(x, RDD):
return x.map(lambda v: self.predict(v))
return np.interp(x, self.boundaries, self.predictions) | [
"\n Predict labels for provided features.\n Using a piecewise linear function.\n 1) If x exactly matches a boundary then associated prediction\n is returned. In case there are multiple predictions with the\n same boundary then one of them is returned. Which one is\n undefin... |
Please provide a description of the function:def save(self, sc, path):
java_boundaries = _py2java(sc, self.boundaries.tolist())
java_predictions = _py2java(sc, self.predictions.tolist())
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel(
java_boundaries, java_predictions, self.isotonic)
java_model.save(sc._jsc.sc(), path) | [
"Save an IsotonicRegressionModel."
] |
Please provide a description of the function:def load(cls, sc, path):
java_model = sc._jvm.org.apache.spark.mllib.regression.IsotonicRegressionModel.load(
sc._jsc.sc(), path)
py_boundaries = _java2py(sc, java_model.boundaryVector()).toArray()
py_predictions = _java2py(sc, java_model.predictionVector()).toArray()
return IsotonicRegressionModel(py_boundaries, py_predictions, java_model.isotonic) | [
"Load an IsotonicRegressionModel."
] |
Please provide a description of the function:def train(cls, data, isotonic=True):
boundaries, predictions = callMLlibFunc("trainIsotonicRegressionModel",
data.map(_convert_to_vector), bool(isotonic))
return IsotonicRegressionModel(boundaries.toArray(), predictions.toArray(), isotonic) | [
"\n Train an isotonic regression model on the given data.\n\n :param data:\n RDD of (label, feature, weight) tuples.\n :param isotonic:\n Whether this is isotonic (which is default) or antitonic.\n (default: True)\n "
] |
Please provide a description of the function:def columnSimilarities(self, threshold=0.0):
java_sims_mat = self._java_matrix_wrapper.call("columnSimilarities", float(threshold))
return CoordinateMatrix(java_sims_mat) | [
"\n Compute similarities between columns of this matrix.\n\n The threshold parameter is a trade-off knob between estimate\n quality and computational cost.\n\n The default threshold setting of 0 guarantees deterministically\n correct results, but uses the brute-force approach of c... |
Please provide a description of the function:def tallSkinnyQR(self, computeQ=False):
decomp = JavaModelWrapper(self._java_matrix_wrapper.call("tallSkinnyQR", computeQ))
if computeQ:
java_Q = decomp.call("Q")
Q = RowMatrix(java_Q)
else:
Q = None
R = decomp.call("R")
return QRDecomposition(Q, R) | [
"\n Compute the QR decomposition of this RowMatrix.\n\n The implementation is designed to optimize the QR decomposition\n (factorization) for the RowMatrix of a tall and skinny shape.\n\n Reference:\n Paul G. Constantine, David F. Gleich. \"Tall and skinny QR\n factorizat... |
Please provide a description of the function:def computeSVD(self, k, computeU=False, rCond=1e-9):
j_model = self._java_matrix_wrapper.call(
"computeSVD", int(k), bool(computeU), float(rCond))
return SingularValueDecomposition(j_model) | [
"\n Computes the singular value decomposition of the RowMatrix.\n\n The given row matrix A of dimension (m X n) is decomposed into\n U * s * V'T where\n\n * U: (m X k) (left singular vectors) is a RowMatrix whose\n columns are the eigenvectors of (A X A')\n * s: DenseV... |
Please provide a description of the function:def multiply(self, matrix):
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
j_model = self._java_matrix_wrapper.call("multiply", matrix)
return RowMatrix(j_model) | [
"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`RowMatrix`\n\n >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]]))\n... |
Please provide a description of the function:def U(self):
u = self.call("U")
if u is not None:
mat_name = u.getClass().getSimpleName()
if mat_name == "RowMatrix":
return RowMatrix(u)
elif mat_name == "IndexedRowMatrix":
return IndexedRowMatrix(u)
else:
raise TypeError("Expected RowMatrix/IndexedRowMatrix got %s" % mat_name) | [
"\n Returns a distributed matrix whose columns are the left\n singular vectors of the SingularValueDecomposition if computeU was set to be True.\n "
] |
Please provide a description of the function:def rows(self):
# We use DataFrames for serialization of IndexedRows from
# Java, so we first convert the RDD of rows to a DataFrame
# on the Scala/Java side. Then we map each Row in the
# DataFrame back to an IndexedRow on this side.
rows_df = callMLlibFunc("getIndexedRows", self._java_matrix_wrapper._java_model)
rows = rows_df.rdd.map(lambda row: IndexedRow(row[0], row[1]))
return rows | [
"\n Rows of the IndexedRowMatrix stored as an RDD of IndexedRows.\n\n >>> mat = IndexedRowMatrix(sc.parallelize([IndexedRow(0, [1, 2, 3]),\n ... IndexedRow(1, [4, 5, 6])]))\n >>> rows = mat.rows\n >>> rows.first()\n IndexedRow(0, [1.0,... |
Please provide a description of the function:def toBlockMatrix(self, rowsPerBlock=1024, colsPerBlock=1024):
java_block_matrix = self._java_matrix_wrapper.call("toBlockMatrix",
rowsPerBlock,
colsPerBlock)
return BlockMatrix(java_block_matrix, rowsPerBlock, colsPerBlock) | [
"\n Convert this matrix to a BlockMatrix.\n\n :param rowsPerBlock: Number of rows that make up each block.\n The blocks forming the final rows are not\n required to have the given number of rows.\n :param colsPerBlock: Number of columns th... |
Please provide a description of the function:def multiply(self, matrix):
if not isinstance(matrix, DenseMatrix):
raise ValueError("Only multiplication with DenseMatrix "
"is supported.")
return IndexedRowMatrix(self._java_matrix_wrapper.call("multiply", matrix)) | [
"\n Multiply this matrix by a local dense matrix on the right.\n\n :param matrix: a local dense matrix whose number of rows must match the number of columns\n of this matrix\n :returns: :py:class:`IndexedRowMatrix`\n\n >>> mat = IndexedRowMatrix(sc.parallelize([(0, ... |
Please provide a description of the function:def entries(self):
# We use DataFrames for serialization of MatrixEntry entries
# from Java, so we first convert the RDD of entries to a
# DataFrame on the Scala/Java side. Then we map each Row in
# the DataFrame back to a MatrixEntry on this side.
entries_df = callMLlibFunc("getMatrixEntries", self._java_matrix_wrapper._java_model)
entries = entries_df.rdd.map(lambda row: MatrixEntry(row[0], row[1], row[2]))
return entries | [
"\n Entries of the CoordinateMatrix stored as an RDD of\n MatrixEntries.\n\n >>> mat = CoordinateMatrix(sc.parallelize([MatrixEntry(0, 0, 1.2),\n ... MatrixEntry(6, 4, 2.1)]))\n >>> entries = mat.entries\n >>> entries.first()\n ... |
Please provide a description of the function:def blocks(self):
# We use DataFrames for serialization of sub-matrix blocks
# from Java, so we first convert the RDD of blocks to a
# DataFrame on the Scala/Java side. Then we map each Row in
# the DataFrame back to a sub-matrix block on this side.
blocks_df = callMLlibFunc("getMatrixBlocks", self._java_matrix_wrapper._java_model)
blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1]))
return blocks | [
"\n The RDD of sub-matrix blocks\n ((blockRowIndex, blockColIndex), sub-matrix) that form this\n distributed matrix.\n\n >>> mat = BlockMatrix(\n ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3,... |
Please provide a description of the function:def persist(self, storageLevel):
if not isinstance(storageLevel, StorageLevel):
raise TypeError("`storageLevel` should be a StorageLevel, got %s" % type(storageLevel))
javaStorageLevel = self._java_matrix_wrapper._sc._getJavaStorageLevel(storageLevel)
self._java_matrix_wrapper.call("persist", javaStorageLevel)
return self | [
"\n Persists the underlying RDD with the specified storage level.\n "
] |
Please provide a description of the function:def add(self, other):
if not isinstance(other, BlockMatrix):
raise TypeError("Other should be a BlockMatrix, got %s" % type(other))
other_java_block_matrix = other._java_matrix_wrapper._java_model
java_block_matrix = self._java_matrix_wrapper.call("add", other_java_block_matrix)
return BlockMatrix(java_block_matrix, self.rowsPerBlock, self.colsPerBlock) | [
"\n Adds two block matrices together. The matrices must have the\n same size and matching `rowsPerBlock` and `colsPerBlock` values.\n If one of the sub matrix blocks that are being added is a\n SparseMatrix, the resulting sub matrix block will also be a\n SparseMatrix, even if it ... |
Please provide a description of the function:def transpose(self):
java_transposed_matrix = self._java_matrix_wrapper.call("transpose")
return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock) | [
"\n Transpose this BlockMatrix. Returns a new BlockMatrix\n instance sharing the same underlying data. Is a lazy operation.\n\n >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),\n ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, ... |
Please provide a description of the function:def _vector_size(v):
if isinstance(v, Vector):
return len(v)
elif type(v) in (array.array, list, tuple, xrange):
return len(v)
elif type(v) == np.ndarray:
if v.ndim == 1 or (v.ndim == 2 and v.shape[1] == 1):
return len(v)
else:
raise ValueError("Cannot treat an ndarray of shape %s as a vector" % str(v.shape))
elif _have_scipy and scipy.sparse.issparse(v):
assert v.shape[1] == 1, "Expected column vector"
return v.shape[0]
else:
raise TypeError("Cannot treat type %s as a vector" % type(v)) | [
"\n Returns the size of the vector.\n\n >>> _vector_size([1., 2., 3.])\n 3\n >>> _vector_size((1., 2., 3.))\n 3\n >>> _vector_size(array.array('d', [1., 2., 3.]))\n 3\n >>> _vector_size(np.zeros(3))\n 3\n >>> _vector_size(np.zeros((3, 1)))\n 3\n >>> _vector_size(np.zeros((1, 3)))... |
Please provide a description of the function:def parse(s):
start = s.find('[')
if start == -1:
raise ValueError("Array should start with '['.")
end = s.find(']')
if end == -1:
raise ValueError("Array should end with ']'.")
s = s[start + 1: end]
try:
values = [float(val) for val in s.split(',') if val]
except ValueError:
raise ValueError("Unable to parse values from %s" % s)
return DenseVector(values) | [
"\n Parse string representation back into the DenseVector.\n\n >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]')\n DenseVector([0.0, 1.0, 2.0, 3.0])\n "
] |
Please provide a description of the function:def dot(self, other):
if type(other) == np.ndarray:
if other.ndim > 1:
assert len(self) == other.shape[0], "dimension mismatch"
return np.dot(self.array, other)
elif _have_scipy and scipy.sparse.issparse(other):
assert len(self) == other.shape[0], "dimension mismatch"
return other.transpose().dot(self.toArray())
else:
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, SparseVector):
return other.dot(self)
elif isinstance(other, Vector):
return np.dot(self.toArray(), other.toArray())
else:
return np.dot(self.toArray(), other) | [
"\n Compute the dot product of two Vectors. We support\n (Numpy array, list, SparseVector, or SciPy sparse)\n and a target NumPy array that is either 1- or 2-dimensional.\n Equivalent to calling numpy.dot of the two vectors.\n\n >>> dense = DenseVector(array.array('d', [1., 2.]))\... |
Please provide a description of the function:def squared_distance(self, other):
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, SparseVector):
return other.squared_distance(self)
elif _have_scipy and scipy.sparse.issparse(other):
return _convert_to_vector(other).squared_distance(self)
if isinstance(other, Vector):
other = other.toArray()
elif not isinstance(other, np.ndarray):
other = np.array(other)
diff = self.toArray() - other
return np.dot(diff, diff) | [
"\n Squared distance of two Vectors.\n\n >>> dense1 = DenseVector(array.array('d', [1., 2.]))\n >>> dense1.squared_distance(dense1)\n 0.0\n >>> dense2 = np.array([2., 1.])\n >>> dense1.squared_distance(dense2)\n 2.0\n >>> dense3 = [2., 1.]\n >>> dense1.... |
Please provide a description of the function:def parse(s):
start = s.find('(')
if start == -1:
raise ValueError("Tuple should start with '('")
end = s.find(')')
if end == -1:
raise ValueError("Tuple should end with ')'")
s = s[start + 1: end].strip()
size = s[: s.find(',')]
try:
size = int(size)
except ValueError:
raise ValueError("Cannot parse size %s." % size)
ind_start = s.find('[')
if ind_start == -1:
raise ValueError("Indices array should start with '['.")
ind_end = s.find(']')
if ind_end == -1:
raise ValueError("Indices array should end with ']'")
new_s = s[ind_start + 1: ind_end]
ind_list = new_s.split(',')
try:
indices = [int(ind) for ind in ind_list if ind]
except ValueError:
raise ValueError("Unable to parse indices from %s." % new_s)
s = s[ind_end + 1:].strip()
val_start = s.find('[')
if val_start == -1:
raise ValueError("Values array should start with '['.")
val_end = s.find(']')
if val_end == -1:
raise ValueError("Values array should end with ']'.")
val_list = s[val_start + 1: val_end].split(',')
try:
values = [float(val) for val in val_list if val]
except ValueError:
raise ValueError("Unable to parse values from %s." % s)
return SparseVector(size, indices, values) | [
"\n Parse string representation back into the SparseVector.\n\n >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')\n SparseVector(4, {0: 4.0, 1: 5.0})\n "
] |
Please provide a description of the function:def dot(self, other):
if isinstance(other, np.ndarray):
if other.ndim not in [2, 1]:
raise ValueError("Cannot call dot with %d-dimensional array" % other.ndim)
assert len(self) == other.shape[0], "dimension mismatch"
return np.dot(self.values, other[self.indices])
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, DenseVector):
return np.dot(other.array[self.indices], self.values)
elif isinstance(other, SparseVector):
# Find out common indices.
self_cmind = np.in1d(self.indices, other.indices, assume_unique=True)
self_values = self.values[self_cmind]
if self_values.size == 0:
return 0.0
else:
other_cmind = np.in1d(other.indices, self.indices, assume_unique=True)
return np.dot(self_values, other.values[other_cmind])
else:
return self.dot(_convert_to_vector(other)) | [
"\n Dot product with a SparseVector or 1- or 2-dimensional Numpy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.dot(a)\n 25.0\n >>> a.dot(array.array('d', [1., 2., 3., 4.]))\n 22.0\n >>> b = SparseVector(4, [2], [1.0])\n >>> a.dot(b)\n 0... |
Please provide a description of the function:def squared_distance(self, other):
assert len(self) == _vector_size(other), "dimension mismatch"
if isinstance(other, np.ndarray) or isinstance(other, DenseVector):
if isinstance(other, np.ndarray) and other.ndim != 1:
raise Exception("Cannot call squared_distance with %d-dimensional array" %
other.ndim)
if isinstance(other, DenseVector):
other = other.array
sparse_ind = np.zeros(other.size, dtype=bool)
sparse_ind[self.indices] = True
dist = other[sparse_ind] - self.values
result = np.dot(dist, dist)
other_ind = other[~sparse_ind]
result += np.dot(other_ind, other_ind)
return result
elif isinstance(other, SparseVector):
result = 0.0
i, j = 0, 0
while i < len(self.indices) and j < len(other.indices):
if self.indices[i] == other.indices[j]:
diff = self.values[i] - other.values[j]
result += diff * diff
i += 1
j += 1
elif self.indices[i] < other.indices[j]:
result += self.values[i] * self.values[i]
i += 1
else:
result += other.values[j] * other.values[j]
j += 1
while i < len(self.indices):
result += self.values[i] * self.values[i]
i += 1
while j < len(other.indices):
result += other.values[j] * other.values[j]
j += 1
return result
else:
return self.squared_distance(_convert_to_vector(other)) | [
"\n Squared distance from a SparseVector or 1-dimensional NumPy array.\n\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\n >>> a.squared_distance(a)\n 0.0\n >>> a.squared_distance(array.array('d', [1., 2., 3., 4.]))\n 11.0\n >>> a.squared_distance(np.array([1., 2., 3.,... |
Please provide a description of the function:def toArray(self):
arr = np.zeros((self.size,), dtype=np.float64)
arr[self.indices] = self.values
return arr | [
"\n Returns a copy of this SparseVector as a 1-dimensional NumPy array.\n "
] |
Please provide a description of the function:def asML(self):
return newlinalg.SparseVector(self.size, self.indices, self.values) | [
"\n Convert this vector to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseVector`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def dense(*elements):
if len(elements) == 1 and not isinstance(elements[0], (float, int, long)):
# it's list, numpy.array or other iterable object.
elements = elements[0]
return DenseVector(elements) | [
"\n Create a dense vector of 64-bit floats from a Python list or numbers.\n\n >>> Vectors.dense([1, 2, 3])\n DenseVector([1.0, 2.0, 3.0])\n >>> Vectors.dense(1.0, 2.0)\n DenseVector([1.0, 2.0])\n "
] |
Please provide a description of the function:def fromML(vec):
if isinstance(vec, newlinalg.DenseVector):
return DenseVector(vec.array)
elif isinstance(vec, newlinalg.SparseVector):
return SparseVector(vec.size, vec.indices, vec.values)
else:
raise TypeError("Unsupported vector type %s" % type(vec)) | [
"\n Convert a vector from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param vec: a :py:class:`pyspark.ml.linalg.Vector`\n :return: a :py:class:`pyspark.mllib.linalg.Vector`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def squared_distance(v1, v2):
v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2)
return v1.squared_distance(v2) | [
"\n Squared distance between two vectors.\n a and b can be of type SparseVector, DenseVector, np.ndarray\n or array.array.\n\n >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\n >>> b = Vectors.dense([2, 5, 4, 1])\n >>> a.squared_distance(b)\n 51.0\n "
] |
Please provide a description of the function:def parse(s):
if s.find('(') == -1 and s.find('[') != -1:
return DenseVector.parse(s)
elif s.find('(') != -1:
return SparseVector.parse(s)
else:
raise ValueError(
"Cannot find tokens '[' or '(' from the input string.") | [
"Parse a string representation back into the Vector.\n\n >>> Vectors.parse('[2,1,2 ]')\n DenseVector([2.0, 1.0, 2.0])\n >>> Vectors.parse(' ( 100, [0], [2])')\n SparseVector(100, {0: 2.0})\n "
] |
Please provide a description of the function:def _equals(v1_indices, v1_values, v2_indices, v2_values):
v1_size = len(v1_values)
v2_size = len(v2_values)
k1 = 0
k2 = 0
all_equal = True
while all_equal:
while k1 < v1_size and v1_values[k1] == 0:
k1 += 1
while k2 < v2_size and v2_values[k2] == 0:
k2 += 1
if k1 >= v1_size or k2 >= v2_size:
return k1 >= v1_size and k2 >= v2_size
all_equal = v1_indices[k1] == v2_indices[k2] and v1_values[k1] == v2_values[k2]
k1 += 1
k2 += 1
return all_equal | [
"\n Check equality between sparse/dense vectors,\n v1_indices and v2_indices assume to be strictly increasing.\n "
] |
Please provide a description of the function:def _convert_to_array(array_like, dtype):
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | [
"\n Convert Matrix attributes which are array-like or buffer to array.\n "
] |
Please provide a description of the function:def toArray(self):
if self.isTransposed:
return np.asfortranarray(
self.values.reshape((self.numRows, self.numCols)))
else:
return self.values.reshape((self.numRows, self.numCols), order='F') | [
"\n Return an numpy.ndarray\n\n >>> m = DenseMatrix(2, 2, range(4))\n >>> m.toArray()\n array([[ 0., 2.],\n [ 1., 3.]])\n "
] |
Please provide a description of the function:def toSparse(self):
if self.isTransposed:
values = np.ravel(self.toArray(), order='F')
else:
values = self.values
indices = np.nonzero(values)[0]
colCounts = np.bincount(indices // self.numRows)
colPtrs = np.cumsum(np.hstack(
(0, colCounts, np.zeros(self.numCols - colCounts.size))))
values = values[indices]
rowIndices = indices % self.numRows
return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values) | [
"Convert to SparseMatrix"
] |
Please provide a description of the function:def asML(self):
return newlinalg.DenseMatrix(self.numRows, self.numCols, self.values, self.isTransposed) | [
"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.DenseMatrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def toArray(self):
A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F')
for k in xrange(self.colPtrs.size - 1):
startptr = self.colPtrs[k]
endptr = self.colPtrs[k + 1]
if self.isTransposed:
A[k, self.rowIndices[startptr:endptr]] = self.values[startptr:endptr]
else:
A[self.rowIndices[startptr:endptr], k] = self.values[startptr:endptr]
return A | [
"\n Return an numpy.ndarray\n "
] |
Please provide a description of the function:def asML(self):
return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,
self.values, self.isTransposed) | [
"\n Convert this matrix to the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :return: :py:class:`pyspark.ml.linalg.SparseMatrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def sparse(numRows, numCols, colPtrs, rowIndices, values):
return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values) | [
"\n Create a SparseMatrix\n "
] |
Please provide a description of the function:def fromML(mat):
if isinstance(mat, newlinalg.DenseMatrix):
return DenseMatrix(mat.numRows, mat.numCols, mat.values, mat.isTransposed)
elif isinstance(mat, newlinalg.SparseMatrix):
return SparseMatrix(mat.numRows, mat.numCols, mat.colPtrs, mat.rowIndices,
mat.values, mat.isTransposed)
else:
raise TypeError("Unsupported matrix type %s" % type(mat)) | [
"\n Convert a matrix from the new mllib-local representation.\n This does NOT copy the data; it copies references.\n\n :param mat: a :py:class:`pyspark.ml.linalg.Matrix`\n :return: a :py:class:`pyspark.mllib.linalg.Matrix`\n\n .. versionadded:: 2.0.0\n "
] |
Please provide a description of the function:def approxNearestNeighbors(self, dataset, key, numNearestNeighbors, distCol="distCol"):
return self._call_java("approxNearestNeighbors", dataset, key, numNearestNeighbors,
distCol) | [
"\n Given a large dataset and an item, approximately find at most k items which have the\n closest distance to the item. If the :py:attr:`outputCol` is missing, the method will\n transform the data; if the :py:attr:`outputCol` exists, it will use that. This allows\n caching of the transf... |
Please provide a description of the function:def approxSimilarityJoin(self, datasetA, datasetB, threshold, distCol="distCol"):
threshold = TypeConverters.toFloat(threshold)
return self._call_java("approxSimilarityJoin", datasetA, datasetB, threshold, distCol) | [
"\n Join two datasets to approximately find all pairs of rows whose distance are smaller than\n the threshold. If the :py:attr:`outputCol` is missing, the method will transform the data;\n if the :py:attr:`outputCol` exists, it will use that. This allows caching of the\n transformed data... |
Please provide a description of the function:def from_labels(cls, labels, inputCol, outputCol=None, handleInvalid=None):
sc = SparkContext._active_spark_context
java_class = sc._gateway.jvm.java.lang.String
jlabels = StringIndexerModel._new_java_array(labels, java_class)
model = StringIndexerModel._create_from_java_class(
"org.apache.spark.ml.feature.StringIndexerModel", jlabels)
model.setInputCol(inputCol)
if outputCol is not None:
model.setOutputCol(outputCol)
if handleInvalid is not None:
model.setHandleInvalid(handleInvalid)
return model | [
"\n Construct the model directly from an array of label strings,\n requires an active SparkContext.\n "
] |
Please provide a description of the function:def from_arrays_of_labels(cls, arrayOfLabels, inputCols, outputCols=None,
handleInvalid=None):
sc = SparkContext._active_spark_context
java_class = sc._gateway.jvm.java.lang.String
jlabels = StringIndexerModel._new_java_array(arrayOfLabels, java_class)
model = StringIndexerModel._create_from_java_class(
"org.apache.spark.ml.feature.StringIndexerModel", jlabels)
model.setInputCols(inputCols)
if outputCols is not None:
model.setOutputCols(outputCols)
if handleInvalid is not None:
model.setHandleInvalid(handleInvalid)
return model | [
"\n Construct the model directly from an array of array of label strings,\n requires an active SparkContext.\n "
] |
Please provide a description of the function:def setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False,
locale=None):
kwargs = self._input_kwargs
return self._set(**kwargs) | [
"\n setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \\\n locale=None)\n Sets params for this StopWordRemover.\n "
] |
Please provide a description of the function:def loadDefaultStopWords(language):
stopWordsObj = _jvm().org.apache.spark.ml.feature.StopWordsRemover
return list(stopWordsObj.loadDefaultStopWords(language)) | [
"\n Loads the default stop words for the given language.\n Supported languages: danish, dutch, english, finnish, french, german, hungarian,\n italian, norwegian, portuguese, russian, spanish, swedish, turkish\n "
] |
Please provide a description of the function:def findSynonyms(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
return self._call_java("findSynonyms", word, num) | [
"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns a dataframe with two fields word and similarity (which\n gives the cosine similarity).\n "
] |
Please provide a description of the function:def findSynonymsArray(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
tuples = self._java_obj.findSynonymsArray(word, num)
return list(map(lambda st: (st._1(), st._2()), list(tuples))) | [
"\n Find \"num\" number of words closest in similarity to \"word\".\n word can be a string or vector representation.\n Returns an array with two fields word and similarity (which\n gives the cosine similarity).\n "
] |
Please provide a description of the function:def install_exception_handler():
original = py4j.protocol.get_return_value
# The original `get_return_value` is not patched, it's idempotent.
patched = capture_sql_exception(original)
# only patch the one used in py4j.java_gateway (call Java API)
py4j.java_gateway.get_return_value = patched | [
"\n Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.\n\n When calling Java API, it will call `get_return_value` to parse the returned object.\n If any exception happened in JVM, the result will be Java exception object, it raise\n py4j.protocol.Py4JJavaError. We repl... |
Please provide a description of the function:def toJArray(gateway, jtype, arr):
jarr = gateway.new_array(jtype, len(arr))
for i in range(0, len(arr)):
jarr[i] = arr[i]
return jarr | [
"\n Convert python list to java type array\n :param gateway: Py4j Gateway\n :param jtype: java type of element in array\n :param arr: python type list\n "
] |
Please provide a description of the function:def require_minimum_pandas_version():
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pandas_version = "0.19.2"
from distutils.version import LooseVersion
try:
import pandas
have_pandas = True
except ImportError:
have_pandas = False
if not have_pandas:
raise ImportError("Pandas >= %s must be installed; however, "
"it was not found." % minimum_pandas_version)
if LooseVersion(pandas.__version__) < LooseVersion(minimum_pandas_version):
raise ImportError("Pandas >= %s must be installed; however, "
"your version was %s." % (minimum_pandas_version, pandas.__version__)) | [
" Raise ImportError if minimum version of Pandas is not installed\n "
] |
Please provide a description of the function:def require_minimum_pyarrow_version():
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pyarrow_version = "0.12.1"
from distutils.version import LooseVersion
try:
import pyarrow
have_arrow = True
except ImportError:
have_arrow = False
if not have_arrow:
raise ImportError("PyArrow >= %s must be installed; however, "
"it was not found." % minimum_pyarrow_version)
if LooseVersion(pyarrow.__version__) < LooseVersion(minimum_pyarrow_version):
raise ImportError("PyArrow >= %s must be installed; however, "
"your version was %s." % (minimum_pyarrow_version, pyarrow.__version__)) | [
" Raise ImportError if minimum version of pyarrow is not installed\n "
] |
Please provide a description of the function:def launch_gateway(conf=None, popen_kwargs=None):
if "PYSPARK_GATEWAY_PORT" in os.environ:
gateway_port = int(os.environ["PYSPARK_GATEWAY_PORT"])
gateway_secret = os.environ["PYSPARK_GATEWAY_SECRET"]
# Process already exists
proc = None
else:
SPARK_HOME = _find_spark_home()
# Launch the Py4j gateway using Spark's run command so that we pick up the
# proper classpath and settings from spark-env.sh
on_windows = platform.system() == "Windows"
script = "./bin/spark-submit.cmd" if on_windows else "./bin/spark-submit"
command = [os.path.join(SPARK_HOME, script)]
if conf:
for k, v in conf.getAll():
command += ['--conf', '%s=%s' % (k, v)]
submit_args = os.environ.get("PYSPARK_SUBMIT_ARGS", "pyspark-shell")
if os.environ.get("SPARK_TESTING"):
submit_args = ' '.join([
"--conf spark.ui.enabled=false",
submit_args
])
command = command + shlex.split(submit_args)
# Create a temporary directory where the gateway server should write the connection
# information.
conn_info_dir = tempfile.mkdtemp()
try:
fd, conn_info_file = tempfile.mkstemp(dir=conn_info_dir)
os.close(fd)
os.unlink(conn_info_file)
env = dict(os.environ)
env["_PYSPARK_DRIVER_CONN_INFO_PATH"] = conn_info_file
# Launch the Java gateway.
popen_kwargs = {} if popen_kwargs is None else popen_kwargs
# We open a pipe to stdin so that the Java gateway can die when the pipe is broken
popen_kwargs['stdin'] = PIPE
# We always set the necessary environment variables.
popen_kwargs['env'] = env
if not on_windows:
# Don't send ctrl-c / SIGINT to the Java gateway:
def preexec_func():
signal.signal(signal.SIGINT, signal.SIG_IGN)
popen_kwargs['preexec_fn'] = preexec_func
proc = Popen(command, **popen_kwargs)
else:
# preexec_fn not supported on Windows
proc = Popen(command, **popen_kwargs)
# Wait for the file to appear, or for the process to exit, whichever happens first.
while not proc.poll() and not os.path.isfile(conn_info_file):
time.sleep(0.1)
if not os.path.isfile(conn_info_file):
raise Exception("Java gateway process exited before sending its port number")
with open(conn_info_file, "rb") as info:
gateway_port = read_int(info)
gateway_secret = UTF8Deserializer().loads(info)
finally:
shutil.rmtree(conn_info_dir)
# In Windows, ensure the Java child processes do not linger after Python has exited.
# In UNIX-based systems, the child process can kill itself on broken pipe (i.e. when
# the parent process' stdin sends an EOF). In Windows, however, this is not possible
# because java.lang.Process reads directly from the parent process' stdin, contending
# with any opportunity to read an EOF from the parent. Note that this is only best
# effort and will not take effect if the python process is violently terminated.
if on_windows:
# In Windows, the child process here is "spark-submit.cmd", not the JVM itself
# (because the UNIX "exec" command is not available). This means we cannot simply
# call proc.kill(), which kills only the "spark-submit.cmd" process but not the
# JVMs. Instead, we use "taskkill" with the tree-kill option "/t" to terminate all
# child processes in the tree (http://technet.microsoft.com/en-us/library/bb491009.aspx)
def killChild():
Popen(["cmd", "/c", "taskkill", "/f", "/t", "/pid", str(proc.pid)])
atexit.register(killChild)
# Connect to the gateway
gateway = JavaGateway(
gateway_parameters=GatewayParameters(port=gateway_port, auth_token=gateway_secret,
auto_convert=True))
# Store a reference to the Popen object for use by the caller (e.g., in reading stdout/stderr)
gateway.proc = proc
# Import the classes used by PySpark
java_import(gateway.jvm, "org.apache.spark.SparkConf")
java_import(gateway.jvm, "org.apache.spark.api.java.*")
java_import(gateway.jvm, "org.apache.spark.api.python.*")
java_import(gateway.jvm, "org.apache.spark.ml.python.*")
java_import(gateway.jvm, "org.apache.spark.mllib.api.python.*")
# TODO(davies): move into sql
java_import(gateway.jvm, "org.apache.spark.sql.*")
java_import(gateway.jvm, "org.apache.spark.sql.api.python.*")
java_import(gateway.jvm, "org.apache.spark.sql.hive.*")
java_import(gateway.jvm, "scala.Tuple2")
return gateway | [
"\n launch jvm gateway\n :param conf: spark configuration passed to spark-submit\n :param popen_kwargs: Dictionary of kwargs to pass to Popen when spawning\n the py4j JVM. This is a developer feature intended for use in\n customizing how pyspark interacts with the py4j JVM (e.g., capturing\n ... |
Please provide a description of the function:def _do_server_auth(conn, auth_secret):
write_with_length(auth_secret.encode("utf-8"), conn)
conn.flush()
reply = UTF8Deserializer().loads(conn)
if reply != "ok":
conn.close()
raise Exception("Unexpected reply from iterator server.") | [
"\n Performs the authentication protocol defined by the SocketAuthHelper class on the given\n file-like object 'conn'.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.