id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
15,000 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | wninsd | def wninsd(left, right, window):
"""
Insert an interval into a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wninsd_c.html
:param left: Left endpoints of new interval.
:type left: float
:param right: Right endpoints of new interval.
:type right: float
... | python | def wninsd(left, right, window):
"""
Insert an interval into a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wninsd_c.html
:param left: Left endpoints of new interval.
:type left: float
:param right: Right endpoints of new interval.
:type right: float
... | [
"def",
"wninsd",
"(",
"left",
",",
"right",
",",
"window",
")",
":",
"assert",
"isinstance",
"(",
"window",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"window",
".",
"dtype",
"==",
"1",
"left",
"=",
"ctypes",
".",
"c_double",
"(",
"left",
")",
"... | Insert an interval into a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wninsd_c.html
:param left: Left endpoints of new interval.
:type left: float
:param right: Right endpoints of new interval.
:type right: float
:param window: Input window.
:type wi... | [
"Insert",
"an",
"interval",
"into",
"a",
"double",
"precision",
"window",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15541-L15558 |
15,001 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | wnintd | def wnintd(a, b):
"""
Place the intersection of two double precision windows into
a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnintd_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spicey... | python | def wnintd(a, b):
"""
Place the intersection of two double precision windows into
a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnintd_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spicey... | [
"def",
"wnintd",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"b",
".",
"dtype",
"==",
"1",
"assert",
"isinstance",
"(",
"b",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"a",
".... | Place the intersection of two double precision windows into
a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnintd_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spiceypy.utils.support_types.SpiceCe... | [
"Place",
"the",
"intersection",
"of",
"two",
"double",
"precision",
"windows",
"into",
"a",
"third",
"window",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15562-L15583 |
15,002 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | wnreld | def wnreld(a, op, b):
"""
Compare two double precision windows.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnreld_c.html
:param a: First window.
:type a: spiceypy.utils.support_types.SpiceCell
:param op: Comparison operator.
:type op: str
:param b: Second window.
:t... | python | def wnreld(a, op, b):
"""
Compare two double precision windows.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnreld_c.html
:param a: First window.
:type a: spiceypy.utils.support_types.SpiceCell
:param op: Comparison operator.
:type op: str
:param b: Second window.
:t... | [
"def",
"wnreld",
"(",
"a",
",",
"op",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"b",
".",
"dtype",
"==",
"1",
"assert",
"isinstance",
"(",
"b",
",",
"stypes",
".",
"SpiceCell",
")",
"asser... | Compare two double precision windows.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnreld_c.html
:param a: First window.
:type a: spiceypy.utils.support_types.SpiceCell
:param op: Comparison operator.
:type op: str
:param b: Second window.
:type b: spiceypy.utils.support_type... | [
"Compare",
"two",
"double",
"precision",
"windows",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15587-L15608 |
15,003 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | wnsumd | def wnsumd(window):
"""
Summarize the contents of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html
:param window: Window to be summarized.
:type window: spiceypy.utils.support_types.SpiceCell
:return:
Total measure of intervals in wi... | python | def wnsumd(window):
"""
Summarize the contents of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html
:param window: Window to be summarized.
:type window: spiceypy.utils.support_types.SpiceCell
:return:
Total measure of intervals in wi... | [
"def",
"wnsumd",
"(",
"window",
")",
":",
"assert",
"isinstance",
"(",
"window",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"window",
".",
"dtype",
"==",
"1",
"meas",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"avg",
"=",
"ctypes",
".",
"c_double",... | Summarize the contents of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html
:param window: Window to be summarized.
:type window: spiceypy.utils.support_types.SpiceCell
:return:
Total measure of intervals in window,
Average measur... | [
"Summarize",
"the",
"contents",
"of",
"a",
"double",
"precision",
"window",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15612-L15637 |
15,004 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | wnunid | def wnunid(a, b):
"""
Place the union of two double precision windows into a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnunid_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spiceypy.utils.sup... | python | def wnunid(a, b):
"""
Place the union of two double precision windows into a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnunid_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spiceypy.utils.sup... | [
"def",
"wnunid",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"b",
".",
"dtype",
"==",
"1",
"assert",
"isinstance",
"(",
"b",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"a",
".... | Place the union of two double precision windows into a third window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnunid_c.html
:param a: Input window A.
:type a: spiceypy.utils.support_types.SpiceCell
:param b: Input window B.
:type b: spiceypy.utils.support_types.SpiceCell
:retu... | [
"Place",
"the",
"union",
"of",
"two",
"double",
"precision",
"windows",
"into",
"a",
"third",
"window",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15641-L15660 |
15,005 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | wnvald | def wnvald(insize, n, window):
"""
Form a valid double precision window from the contents
of a window array.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnvald_c.html
:param insize: Size of window.
:type insize: int
:param n: Original number of endpoints.
:type n: int
... | python | def wnvald(insize, n, window):
"""
Form a valid double precision window from the contents
of a window array.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnvald_c.html
:param insize: Size of window.
:type insize: int
:param n: Original number of endpoints.
:type n: int
... | [
"def",
"wnvald",
"(",
"insize",
",",
"n",
",",
"window",
")",
":",
"assert",
"isinstance",
"(",
"window",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"window",
".",
"dtype",
"==",
"1",
"insize",
"=",
"ctypes",
".",
"c_int",
"(",
"insize",
")",
"n... | Form a valid double precision window from the contents
of a window array.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnvald_c.html
:param insize: Size of window.
:type insize: int
:param n: Original number of endpoints.
:type n: int
:param window: Input window.
:type wi... | [
"Form",
"a",
"valid",
"double",
"precision",
"window",
"from",
"the",
"contents",
"of",
"a",
"window",
"array",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15664-L15685 |
15,006 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | writln | def writln(line, unit):
"""
Internal undocumented command for writing a text line to a logical unit
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, writln.f::
C$Procedure WRITLN ( Write a text line to a logical unit )
SUBROUTINE WRITLN ( LINE, UNIT )
... | python | def writln(line, unit):
"""
Internal undocumented command for writing a text line to a logical unit
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, writln.f::
C$Procedure WRITLN ( Write a text line to a logical unit )
SUBROUTINE WRITLN ( LINE, UNIT )
... | [
"def",
"writln",
"(",
"line",
",",
"unit",
")",
":",
"lineP",
"=",
"stypes",
".",
"stringToCharP",
"(",
"line",
")",
"unit",
"=",
"ctypes",
".",
"c_int",
"(",
"unit",
")",
"line_len",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"line",
")",
")",
... | Internal undocumented command for writing a text line to a logical unit
No URL available; relevant lines from SPICE source:
FORTRAN SPICE, writln.f::
C$Procedure WRITLN ( Write a text line to a logical unit )
SUBROUTINE WRITLN ( LINE, UNIT )
CHARACTER*(*) LINE
... | [
"Internal",
"undocumented",
"command",
"for",
"writing",
"a",
"text",
"line",
"to",
"a",
"logical",
"unit"
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15689-L15720 |
15,007 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | xfmsta | def xfmsta(input_state, input_coord_sys, output_coord_sys, body):
"""
Transform a state between coordinate systems.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xfmsta_c.html
:param input_state: Input state.
:type input_state: 6-Element Array of floats
:param input_coord_sys: Curre... | python | def xfmsta(input_state, input_coord_sys, output_coord_sys, body):
"""
Transform a state between coordinate systems.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xfmsta_c.html
:param input_state: Input state.
:type input_state: 6-Element Array of floats
:param input_coord_sys: Curre... | [
"def",
"xfmsta",
"(",
"input_state",
",",
"input_coord_sys",
",",
"output_coord_sys",
",",
"body",
")",
":",
"input_state",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"input_state",
")",
"input_coord_sys",
"=",
"stypes",
".",
"stringToCharP",
"(",
"input_coord_sys... | Transform a state between coordinate systems.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xfmsta_c.html
:param input_state: Input state.
:type input_state: 6-Element Array of floats
:param input_coord_sys: Current (input) coordinate system.
:type input_coord_sys: str
:param outpu... | [
"Transform",
"a",
"state",
"between",
"coordinate",
"systems",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15774-L15800 |
15,008 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | xpose | def xpose(m):
"""
Transpose a 3x3 matrix
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose_c.html
:param m: Matrix to be transposed
:type m: 3x3-Element Array of floats
:return: Transposed matrix
:rtype: 3x3-Element Array of floats
"""
m = stypes.toDoubleMatrix(m)
... | python | def xpose(m):
"""
Transpose a 3x3 matrix
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose_c.html
:param m: Matrix to be transposed
:type m: 3x3-Element Array of floats
:return: Transposed matrix
:rtype: 3x3-Element Array of floats
"""
m = stypes.toDoubleMatrix(m)
... | [
"def",
"xpose",
"(",
"m",
")",
":",
"m",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"m",
")",
"mout",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
"x",
"=",
"3",
",",
"y",
"=",
"3",
")",
"libspice",
".",
"xpose_c",
"(",
"m",
",",
"mout",
")",
... | Transpose a 3x3 matrix
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose_c.html
:param m: Matrix to be transposed
:type m: 3x3-Element Array of floats
:return: Transposed matrix
:rtype: 3x3-Element Array of floats | [
"Transpose",
"a",
"3x3",
"matrix"
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15804-L15818 |
15,009 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | xpose6 | def xpose6(m):
"""
Transpose a 6x6 matrix
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose6_c.html
:param m: Matrix to be transposed
:type m: list[6][6]
:return: Transposed matrix
:rtype: list[6][6]
"""
m = stypes.toDoubleMatrix(m)
mout = stypes.emptyDoubleMatrix(... | python | def xpose6(m):
"""
Transpose a 6x6 matrix
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose6_c.html
:param m: Matrix to be transposed
:type m: list[6][6]
:return: Transposed matrix
:rtype: list[6][6]
"""
m = stypes.toDoubleMatrix(m)
mout = stypes.emptyDoubleMatrix(... | [
"def",
"xpose6",
"(",
"m",
")",
":",
"m",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"m",
")",
"mout",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
"x",
"=",
"6",
",",
"y",
"=",
"6",
")",
"libspice",
".",
"xpose6_c",
"(",
"m",
",",
"mout",
")",
... | Transpose a 6x6 matrix
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose6_c.html
:param m: Matrix to be transposed
:type m: list[6][6]
:return: Transposed matrix
:rtype: list[6][6] | [
"Transpose",
"a",
"6x6",
"matrix"
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15822-L15836 |
15,010 | AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | xposeg | def xposeg(matrix, nrow, ncol):
"""
Transpose a matrix of arbitrary size
in place, the matrix need not be square.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xposeg_c.html
:param matrix: Matrix to be transposed
:type matrix: NxM-Element Array of floats
:param nrow: Number of r... | python | def xposeg(matrix, nrow, ncol):
"""
Transpose a matrix of arbitrary size
in place, the matrix need not be square.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xposeg_c.html
:param matrix: Matrix to be transposed
:type matrix: NxM-Element Array of floats
:param nrow: Number of r... | [
"def",
"xposeg",
"(",
"matrix",
",",
"nrow",
",",
"ncol",
")",
":",
"matrix",
"=",
"stypes",
".",
"toDoubleMatrix",
"(",
"matrix",
")",
"mout",
"=",
"stypes",
".",
"emptyDoubleMatrix",
"(",
"x",
"=",
"ncol",
",",
"y",
"=",
"nrow",
")",
"ncol",
"=",
... | Transpose a matrix of arbitrary size
in place, the matrix need not be square.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xposeg_c.html
:param matrix: Matrix to be transposed
:type matrix: NxM-Element Array of floats
:param nrow: Number of rows of input matrix.
:type nrow: int
... | [
"Transpose",
"a",
"matrix",
"of",
"arbitrary",
"size",
"in",
"place",
"the",
"matrix",
"need",
"not",
"be",
"square",
"."
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L15840-L15861 |
15,011 | AndrewAnnex/SpiceyPy | spiceypy/utils/callbacks.py | CallUDFUNS | def CallUDFUNS(f, x):
"""
We are given a UDF CFUNCTYPE and want to call it in python
:param f: SpiceUDFUNS
:type f: CFUNCTYPE
:param x: some scalar
:type x: float
:return: value
:rtype: float
"""
value = c_double()
f(x, byref(value))
return value.value | python | def CallUDFUNS(f, x):
"""
We are given a UDF CFUNCTYPE and want to call it in python
:param f: SpiceUDFUNS
:type f: CFUNCTYPE
:param x: some scalar
:type x: float
:return: value
:rtype: float
"""
value = c_double()
f(x, byref(value))
return value.value | [
"def",
"CallUDFUNS",
"(",
"f",
",",
"x",
")",
":",
"value",
"=",
"c_double",
"(",
")",
"f",
"(",
"x",
",",
"byref",
"(",
"value",
")",
")",
"return",
"value",
".",
"value"
] | We are given a UDF CFUNCTYPE and want to call it in python
:param f: SpiceUDFUNS
:type f: CFUNCTYPE
:param x: some scalar
:type x: float
:return: value
:rtype: float | [
"We",
"are",
"given",
"a",
"UDF",
"CFUNCTYPE",
"and",
"want",
"to",
"call",
"it",
"in",
"python"
] | fc20a9b9de68b58eed5b332f0c051fb343a6e335 | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/utils/callbacks.py#L158-L171 |
15,012 | mnick/scikit-tensor | sktensor/dedicom.py | Updater.updateD_G | def updateD_G(self, x):
"""
Compute Gradient for update of D
See [2] for derivation of Gradient
"""
self.precompute(x)
g = zeros(len(x))
Ai = zeros(self.A.shape[0])
for i in range(len(g)):
Ai = self.A[:, i]
g[i] = (self.E * (dot(se... | python | def updateD_G(self, x):
"""
Compute Gradient for update of D
See [2] for derivation of Gradient
"""
self.precompute(x)
g = zeros(len(x))
Ai = zeros(self.A.shape[0])
for i in range(len(g)):
Ai = self.A[:, i]
g[i] = (self.E * (dot(se... | [
"def",
"updateD_G",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"precompute",
"(",
"x",
")",
"g",
"=",
"zeros",
"(",
"len",
"(",
"x",
")",
")",
"Ai",
"=",
"zeros",
"(",
"self",
".",
"A",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
"in",... | Compute Gradient for update of D
See [2] for derivation of Gradient | [
"Compute",
"Gradient",
"for",
"update",
"of",
"D"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/dedicom.py#L226-L239 |
15,013 | mnick/scikit-tensor | sktensor/dedicom.py | Updater.updateD_H | def updateD_H(self, x):
"""
Compute Hessian for update of D
See [2] for derivation of Hessian
"""
self.precompute(x)
H = zeros((len(x), len(x)))
Ai = zeros(self.A.shape[0])
Aj = zeros(Ai.shape)
for i in range(len(x)):
Ai = self.A[:, i]... | python | def updateD_H(self, x):
"""
Compute Hessian for update of D
See [2] for derivation of Hessian
"""
self.precompute(x)
H = zeros((len(x), len(x)))
Ai = zeros(self.A.shape[0])
Aj = zeros(Ai.shape)
for i in range(len(x)):
Ai = self.A[:, i]... | [
"def",
"updateD_H",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"precompute",
"(",
"x",
")",
"H",
"=",
"zeros",
"(",
"(",
"len",
"(",
"x",
")",
",",
"len",
"(",
"x",
")",
")",
")",
"Ai",
"=",
"zeros",
"(",
"self",
".",
"A",
".",
"shape",
... | Compute Hessian for update of D
See [2] for derivation of Hessian | [
"Compute",
"Hessian",
"for",
"update",
"of",
"D"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/dedicom.py#L241-L269 |
15,014 | mnick/scikit-tensor | sktensor/pyutils.py | is_sequence | def is_sequence(obj):
"""
Helper function to determine sequences
across Python 2.x and 3.x
"""
try:
from collections import Sequence
except ImportError:
from operator import isSequenceType
return isSequenceType(obj)
else:
return isinstance(obj, Sequence) | python | def is_sequence(obj):
"""
Helper function to determine sequences
across Python 2.x and 3.x
"""
try:
from collections import Sequence
except ImportError:
from operator import isSequenceType
return isSequenceType(obj)
else:
return isinstance(obj, Sequence) | [
"def",
"is_sequence",
"(",
"obj",
")",
":",
"try",
":",
"from",
"collections",
"import",
"Sequence",
"except",
"ImportError",
":",
"from",
"operator",
"import",
"isSequenceType",
"return",
"isSequenceType",
"(",
"obj",
")",
"else",
":",
"return",
"isinstance",
... | Helper function to determine sequences
across Python 2.x and 3.x | [
"Helper",
"function",
"to",
"determine",
"sequences",
"across",
"Python",
"2",
".",
"x",
"and",
"3",
".",
"x"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/pyutils.py#L8-L19 |
15,015 | mnick/scikit-tensor | sktensor/pyutils.py | is_number | def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number
except ImportError:
from operator import isNumberType
return isNumberType(obj)
else:
return isinstance(obj, Number) | python | def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number
except ImportError:
from operator import isNumberType
return isNumberType(obj)
else:
return isinstance(obj, Number) | [
"def",
"is_number",
"(",
"obj",
")",
":",
"try",
":",
"from",
"numbers",
"import",
"Number",
"except",
"ImportError",
":",
"from",
"operator",
"import",
"isNumberType",
"return",
"isNumberType",
"(",
"obj",
")",
"else",
":",
"return",
"isinstance",
"(",
"obj... | Helper function to determine numbers
across Python 2.x and 3.x | [
"Helper",
"function",
"to",
"determine",
"numbers",
"across",
"Python",
"2",
".",
"x",
"and",
"3",
".",
"x"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/pyutils.py#L22-L33 |
15,016 | mnick/scikit-tensor | sktensor/pyutils.py | func_attr | def func_attr(f, attr):
"""
Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x
"""
if hasattr(f, 'func_%s' % attr):
return getattr(f, 'func_%s' % attr)
elif hasattr(f, '__%s__' % attr):
return getattr(f, '__%s__' % attr)
el... | python | def func_attr(f, attr):
"""
Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x
"""
if hasattr(f, 'func_%s' % attr):
return getattr(f, 'func_%s' % attr)
elif hasattr(f, '__%s__' % attr):
return getattr(f, '__%s__' % attr)
el... | [
"def",
"func_attr",
"(",
"f",
",",
"attr",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"'func_%s'",
"%",
"attr",
")",
":",
"return",
"getattr",
"(",
"f",
",",
"'func_%s'",
"%",
"attr",
")",
"elif",
"hasattr",
"(",
"f",
",",
"'__%s__'",
"%",
"attr",
... | Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x | [
"Helper",
"function",
"to",
"get",
"the",
"attribute",
"of",
"a",
"function",
"like",
"name",
"code",
"defaults",
"across",
"Python",
"2",
".",
"x",
"and",
"3",
".",
"x"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/pyutils.py#L36-L46 |
15,017 | mnick/scikit-tensor | sktensor/pyutils.py | from_to_without | def from_to_without(frm, to, without, step=1, skip=1, reverse=False, separate=False):
"""
Helper function to create ranges with missing entries
"""
if reverse:
frm, to = (to - 1), (frm - 1)
step *= -1
skip *= -1
a = list(range(frm, without, step))
b = list(range(without +... | python | def from_to_without(frm, to, without, step=1, skip=1, reverse=False, separate=False):
"""
Helper function to create ranges with missing entries
"""
if reverse:
frm, to = (to - 1), (frm - 1)
step *= -1
skip *= -1
a = list(range(frm, without, step))
b = list(range(without +... | [
"def",
"from_to_without",
"(",
"frm",
",",
"to",
",",
"without",
",",
"step",
"=",
"1",
",",
"skip",
"=",
"1",
",",
"reverse",
"=",
"False",
",",
"separate",
"=",
"False",
")",
":",
"if",
"reverse",
":",
"frm",
",",
"to",
"=",
"(",
"to",
"-",
"... | Helper function to create ranges with missing entries | [
"Helper",
"function",
"to",
"create",
"ranges",
"with",
"missing",
"entries"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/pyutils.py#L49-L62 |
15,018 | mnick/scikit-tensor | sktensor/dtensor.py | dtensor.unfold | def unfold(self, mode):
"""
Unfolds a dense tensor in mode n.
Parameters
----------
mode : int
Mode in which tensor is unfolded
Returns
-------
unfolded_dtensor : unfolded_dtensor object
Tensor unfolded along mode
Example... | python | def unfold(self, mode):
"""
Unfolds a dense tensor in mode n.
Parameters
----------
mode : int
Mode in which tensor is unfolded
Returns
-------
unfolded_dtensor : unfolded_dtensor object
Tensor unfolded along mode
Example... | [
"def",
"unfold",
"(",
"self",
",",
"mode",
")",
":",
"sz",
"=",
"array",
"(",
"self",
".",
"shape",
")",
"N",
"=",
"len",
"(",
"sz",
")",
"order",
"=",
"(",
"[",
"mode",
"]",
",",
"from_to_without",
"(",
"N",
"-",
"1",
",",
"-",
"1",
",",
"... | Unfolds a dense tensor in mode n.
Parameters
----------
mode : int
Mode in which tensor is unfolded
Returns
-------
unfolded_dtensor : unfolded_dtensor object
Tensor unfolded along mode
Examples
--------
Create dense tens... | [
"Unfolds",
"a",
"dense",
"tensor",
"in",
"mode",
"n",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/dtensor.py#L103-L150 |
15,019 | mnick/scikit-tensor | sktensor/utils.py | accum | def accum(subs, vals, func=np.sum, issorted=False, with_subs=False):
"""
NumPy implementation for Matlab's accumarray
"""
# sort accmap for ediff if not sorted
if not issorted:
sidx = lexsort(subs, axis=0)
subs = [sub[sidx] for sub in subs]
vals = vals[sidx]
idx = np.wher... | python | def accum(subs, vals, func=np.sum, issorted=False, with_subs=False):
"""
NumPy implementation for Matlab's accumarray
"""
# sort accmap for ediff if not sorted
if not issorted:
sidx = lexsort(subs, axis=0)
subs = [sub[sidx] for sub in subs]
vals = vals[sidx]
idx = np.wher... | [
"def",
"accum",
"(",
"subs",
",",
"vals",
",",
"func",
"=",
"np",
".",
"sum",
",",
"issorted",
"=",
"False",
",",
"with_subs",
"=",
"False",
")",
":",
"# sort accmap for ediff if not sorted",
"if",
"not",
"issorted",
":",
"sidx",
"=",
"lexsort",
"(",
"su... | NumPy implementation for Matlab's accumarray | [
"NumPy",
"implementation",
"for",
"Matlab",
"s",
"accumarray"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/utils.py#L5-L26 |
15,020 | mnick/scikit-tensor | sktensor/tucker.py | hooi | def hooi(X, rank, **kwargs):
"""
Compute Tucker decomposition of a tensor using Higher-Order Orthogonal
Iterations.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed
rank : array_like
The rank of the decomposition for each mode of the tensor.
The len... | python | def hooi(X, rank, **kwargs):
"""
Compute Tucker decomposition of a tensor using Higher-Order Orthogonal
Iterations.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed
rank : array_like
The rank of the decomposition for each mode of the tensor.
The len... | [
"def",
"hooi",
"(",
"X",
",",
"rank",
",",
"*",
"*",
"kwargs",
")",
":",
"# init options",
"ainit",
"=",
"kwargs",
".",
"pop",
"(",
"'init'",
",",
"__DEF_INIT",
")",
"maxIter",
"=",
"kwargs",
".",
"pop",
"(",
"'maxIter'",
",",
"__DEF_MAXITER",
")",
"... | Compute Tucker decomposition of a tensor using Higher-Order Orthogonal
Iterations.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed
rank : array_like
The rank of the decomposition for each mode of the tensor.
The length of ``rank`` must match the number of ... | [
"Compute",
"Tucker",
"decomposition",
"of",
"a",
"tensor",
"using",
"Higher",
"-",
"Order",
"Orthogonal",
"Iterations",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/tucker.py#L36-L123 |
15,021 | mnick/scikit-tensor | sktensor/ktensor.py | ktensor.uttkrp | def uttkrp(self, U, mode):
"""
Unfolded tensor times Khatri-Rao product for Kruskal tensors
Parameters
----------
X : tensor_mixin
Tensor whose unfolding should be multiplied.
U : list of array_like
Matrices whose Khatri-Rao product should be mul... | python | def uttkrp(self, U, mode):
"""
Unfolded tensor times Khatri-Rao product for Kruskal tensors
Parameters
----------
X : tensor_mixin
Tensor whose unfolding should be multiplied.
U : list of array_like
Matrices whose Khatri-Rao product should be mul... | [
"def",
"uttkrp",
"(",
"self",
",",
"U",
",",
"mode",
")",
":",
"N",
"=",
"self",
".",
"ndim",
"if",
"mode",
"==",
"1",
":",
"R",
"=",
"U",
"[",
"1",
"]",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"R",
"=",
"U",
"[",
"0",
"]",
".",
"shap... | Unfolded tensor times Khatri-Rao product for Kruskal tensors
Parameters
----------
X : tensor_mixin
Tensor whose unfolding should be multiplied.
U : list of array_like
Matrices whose Khatri-Rao product should be multiplied.
mode : int
Mode in ... | [
"Unfolded",
"tensor",
"times",
"Khatri",
"-",
"Rao",
"product",
"for",
"Kruskal",
"tensors"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/ktensor.py#L84-L111 |
15,022 | mnick/scikit-tensor | sktensor/ktensor.py | ktensor.norm | def norm(self):
"""
Efficient computation of the Frobenius norm for ktensors
Returns
-------
norm : float
Frobenius norm of the ktensor
"""
N = len(self.shape)
coef = outer(self.lmbda, self.lmbda)
for i in range(N):
coef = ... | python | def norm(self):
"""
Efficient computation of the Frobenius norm for ktensors
Returns
-------
norm : float
Frobenius norm of the ktensor
"""
N = len(self.shape)
coef = outer(self.lmbda, self.lmbda)
for i in range(N):
coef = ... | [
"def",
"norm",
"(",
"self",
")",
":",
"N",
"=",
"len",
"(",
"self",
".",
"shape",
")",
"coef",
"=",
"outer",
"(",
"self",
".",
"lmbda",
",",
"self",
".",
"lmbda",
")",
"for",
"i",
"in",
"range",
"(",
"N",
")",
":",
"coef",
"=",
"coef",
"*",
... | Efficient computation of the Frobenius norm for ktensors
Returns
-------
norm : float
Frobenius norm of the ktensor | [
"Efficient",
"computation",
"of",
"the",
"Frobenius",
"norm",
"for",
"ktensors"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/ktensor.py#L113-L126 |
15,023 | mnick/scikit-tensor | sktensor/ktensor.py | ktensor.innerprod | def innerprod(self, X):
"""
Efficient computation of the inner product of a ktensor with another tensor
Parameters
----------
X : tensor_mixin
Tensor to compute the inner product with.
Returns
-------
p : float
Inner product betwe... | python | def innerprod(self, X):
"""
Efficient computation of the inner product of a ktensor with another tensor
Parameters
----------
X : tensor_mixin
Tensor to compute the inner product with.
Returns
-------
p : float
Inner product betwe... | [
"def",
"innerprod",
"(",
"self",
",",
"X",
")",
":",
"N",
"=",
"len",
"(",
"self",
".",
"shape",
")",
"R",
"=",
"len",
"(",
"self",
".",
"lmbda",
")",
"res",
"=",
"0",
"for",
"r",
"in",
"range",
"(",
"R",
")",
":",
"vecs",
"=",
"[",
"]",
... | Efficient computation of the inner product of a ktensor with another tensor
Parameters
----------
X : tensor_mixin
Tensor to compute the inner product with.
Returns
-------
p : float
Inner product between ktensor and X. | [
"Efficient",
"computation",
"of",
"the",
"inner",
"product",
"of",
"a",
"ktensor",
"with",
"another",
"tensor"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/ktensor.py#L128-L150 |
15,024 | mnick/scikit-tensor | sktensor/ktensor.py | ktensor.toarray | def toarray(self):
"""
Converts a ktensor into a dense multidimensional ndarray
Returns
-------
arr : np.ndarray
Fully computed multidimensional array whose shape matches
the original ktensor.
"""
A = dot(self.lmbda, khatrirao(tuple(self.U... | python | def toarray(self):
"""
Converts a ktensor into a dense multidimensional ndarray
Returns
-------
arr : np.ndarray
Fully computed multidimensional array whose shape matches
the original ktensor.
"""
A = dot(self.lmbda, khatrirao(tuple(self.U... | [
"def",
"toarray",
"(",
"self",
")",
":",
"A",
"=",
"dot",
"(",
"self",
".",
"lmbda",
",",
"khatrirao",
"(",
"tuple",
"(",
"self",
".",
"U",
")",
")",
".",
"T",
")",
"return",
"A",
".",
"reshape",
"(",
"self",
".",
"shape",
")"
] | Converts a ktensor into a dense multidimensional ndarray
Returns
-------
arr : np.ndarray
Fully computed multidimensional array whose shape matches
the original ktensor. | [
"Converts",
"a",
"ktensor",
"into",
"a",
"dense",
"multidimensional",
"ndarray"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/ktensor.py#L152-L163 |
15,025 | mnick/scikit-tensor | sktensor/sptensor.py | fromarray | def fromarray(A):
"""Create a sptensor from a dense numpy array"""
subs = np.nonzero(A)
vals = A[subs]
return sptensor(subs, vals, shape=A.shape, dtype=A.dtype) | python | def fromarray(A):
"""Create a sptensor from a dense numpy array"""
subs = np.nonzero(A)
vals = A[subs]
return sptensor(subs, vals, shape=A.shape, dtype=A.dtype) | [
"def",
"fromarray",
"(",
"A",
")",
":",
"subs",
"=",
"np",
".",
"nonzero",
"(",
"A",
")",
"vals",
"=",
"A",
"[",
"subs",
"]",
"return",
"sptensor",
"(",
"subs",
",",
"vals",
",",
"shape",
"=",
"A",
".",
"shape",
",",
"dtype",
"=",
"A",
".",
"... | Create a sptensor from a dense numpy array | [
"Create",
"a",
"sptensor",
"from",
"a",
"dense",
"numpy",
"array"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/sptensor.py#L362-L366 |
15,026 | mnick/scikit-tensor | sktensor/sptensor.py | sptensor._ttm_me_compute | def _ttm_me_compute(self, V, edims, sdims, transp):
"""
Assume Y = T x_i V_i for i = 1...n can fit into memory
"""
shapeY = np.copy(self.shape)
# Determine size of Y
for n in np.union1d(edims, sdims):
shapeY[n] = V[n].shape[1] if transp else V[n].shape[0]
... | python | def _ttm_me_compute(self, V, edims, sdims, transp):
"""
Assume Y = T x_i V_i for i = 1...n can fit into memory
"""
shapeY = np.copy(self.shape)
# Determine size of Y
for n in np.union1d(edims, sdims):
shapeY[n] = V[n].shape[1] if transp else V[n].shape[0]
... | [
"def",
"_ttm_me_compute",
"(",
"self",
",",
"V",
",",
"edims",
",",
"sdims",
",",
"transp",
")",
":",
"shapeY",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"shape",
")",
"# Determine size of Y",
"for",
"n",
"in",
"np",
".",
"union1d",
"(",
"edims",
","... | Assume Y = T x_i V_i for i = 1...n can fit into memory | [
"Assume",
"Y",
"=",
"T",
"x_i",
"V_i",
"for",
"i",
"=",
"1",
"...",
"n",
"can",
"fit",
"into",
"memory"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/sptensor.py#L179-L195 |
15,027 | mnick/scikit-tensor | sktensor/sptensor.py | sptensor.transpose | def transpose(self, axes=None):
"""
Compute transpose of sparse tensors.
Parameters
----------
axes : array_like of ints, optional
Permute the axes according to the values given.
Returns
-------
d : dtensor
dtensor with axes permu... | python | def transpose(self, axes=None):
"""
Compute transpose of sparse tensors.
Parameters
----------
axes : array_like of ints, optional
Permute the axes according to the values given.
Returns
-------
d : dtensor
dtensor with axes permu... | [
"def",
"transpose",
"(",
"self",
",",
"axes",
"=",
"None",
")",
":",
"if",
"axes",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'Sparse tensor transposition without axes argument is not supported'",
")",
"nsubs",
"=",
"tuple",
"(",
"[",
"self",
".",
... | Compute transpose of sparse tensors.
Parameters
----------
axes : array_like of ints, optional
Permute the axes according to the values given.
Returns
-------
d : dtensor
dtensor with axes permuted. | [
"Compute",
"transpose",
"of",
"sparse",
"tensors",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/sptensor.py#L232-L252 |
15,028 | mnick/scikit-tensor | sktensor/sptensor.py | sptensor.concatenate | def concatenate(self, tpl, axis=None):
"""
Concatenates sparse tensors.
Parameters
----------
tpl : tuple of sparse tensors
Tensors to be concatenated.
axis : int, optional
Axis along which concatenation should take place
"""
if ... | python | def concatenate(self, tpl, axis=None):
"""
Concatenates sparse tensors.
Parameters
----------
tpl : tuple of sparse tensors
Tensors to be concatenated.
axis : int, optional
Axis along which concatenation should take place
"""
if ... | [
"def",
"concatenate",
"(",
"self",
",",
"tpl",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'Sparse tensor concatenation without axis argument is not supported'",
")",
"T",
"=",
"self",
"for",
"i",
"i... | Concatenates sparse tensors.
Parameters
----------
tpl : tuple of sparse tensors
Tensors to be concatenated.
axis : int, optional
Axis along which concatenation should take place | [
"Concatenates",
"sparse",
"tensors",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/sptensor.py#L254-L272 |
15,029 | mnick/scikit-tensor | sktensor/sptensor.py | unfolded_sptensor.fold | def fold(self):
"""
Recreate original tensor by folding unfolded_sptensor according toc
``ten_shape``.
Returns
-------
T : sptensor
Sparse tensor that is created by refolding according to ``ten_shape``.
"""
nsubs = zeros((len(self.data), len(s... | python | def fold(self):
"""
Recreate original tensor by folding unfolded_sptensor according toc
``ten_shape``.
Returns
-------
T : sptensor
Sparse tensor that is created by refolding according to ``ten_shape``.
"""
nsubs = zeros((len(self.data), len(s... | [
"def",
"fold",
"(",
"self",
")",
":",
"nsubs",
"=",
"zeros",
"(",
"(",
"len",
"(",
"self",
".",
"data",
")",
",",
"len",
"(",
"self",
".",
"ten_shape",
")",
")",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"if",
"len",
"(",
"self",
".",
"rdims"... | Recreate original tensor by folding unfolded_sptensor according toc
``ten_shape``.
Returns
-------
T : sptensor
Sparse tensor that is created by refolding according to ``ten_shape``. | [
"Recreate",
"original",
"tensor",
"by",
"folding",
"unfolded_sptensor",
"according",
"toc",
"ten_shape",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/sptensor.py#L339-L359 |
15,030 | mnick/scikit-tensor | sktensor/rescal.py | _updateA | def _updateA(X, A, R, P, Z, lmbdaA, orthogonalize):
"""Update step for A"""
n, rank = A.shape
F = zeros((n, rank), dtype=A.dtype)
E = zeros((rank, rank), dtype=A.dtype)
AtA = dot(A.T, A)
for i in range(len(X)):
F += X[i].dot(dot(A, R[i].T)) + X[i].T.dot(dot(A, R[i]))
E += dot(R... | python | def _updateA(X, A, R, P, Z, lmbdaA, orthogonalize):
"""Update step for A"""
n, rank = A.shape
F = zeros((n, rank), dtype=A.dtype)
E = zeros((rank, rank), dtype=A.dtype)
AtA = dot(A.T, A)
for i in range(len(X)):
F += X[i].dot(dot(A, R[i].T)) + X[i].T.dot(dot(A, R[i]))
E += dot(R... | [
"def",
"_updateA",
"(",
"X",
",",
"A",
",",
"R",
",",
"P",
",",
"Z",
",",
"lmbdaA",
",",
"orthogonalize",
")",
":",
"n",
",",
"rank",
"=",
"A",
".",
"shape",
"F",
"=",
"zeros",
"(",
"(",
"n",
",",
"rank",
")",
",",
"dtype",
"=",
"A",
".",
... | Update step for A | [
"Update",
"step",
"for",
"A"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/rescal.py#L212-L234 |
15,031 | mnick/scikit-tensor | sktensor/rescal.py | _compute_fval | def _compute_fval(X, A, R, P, Z, lmbdaA, lmbdaR, lmbdaZ, normX):
"""Compute fit for full slices"""
f = lmbdaA * norm(A) ** 2
for i in range(len(X)):
ARAt = dot(A, dot(R[i], A.T))
f += (norm(X[i] - ARAt) ** 2) / normX[i] + lmbdaR * norm(R[i]) ** 2
return f | python | def _compute_fval(X, A, R, P, Z, lmbdaA, lmbdaR, lmbdaZ, normX):
"""Compute fit for full slices"""
f = lmbdaA * norm(A) ** 2
for i in range(len(X)):
ARAt = dot(A, dot(R[i], A.T))
f += (norm(X[i] - ARAt) ** 2) / normX[i] + lmbdaR * norm(R[i]) ** 2
return f | [
"def",
"_compute_fval",
"(",
"X",
",",
"A",
",",
"R",
",",
"P",
",",
"Z",
",",
"lmbdaA",
",",
"lmbdaR",
",",
"lmbdaZ",
",",
"normX",
")",
":",
"f",
"=",
"lmbdaA",
"*",
"norm",
"(",
"A",
")",
"**",
"2",
"for",
"i",
"in",
"range",
"(",
"len",
... | Compute fit for full slices | [
"Compute",
"fit",
"for",
"full",
"slices"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/rescal.py#L268-L274 |
15,032 | mnick/scikit-tensor | sktensor/cp.py | als | def als(X, rank, **kwargs):
"""
Alternating least-sqaures algorithm to compute the CP decomposition.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed.
rank : int
Tensor rank of the decomposition.
init : {'random', 'nvecs'}, optional
The initializati... | python | def als(X, rank, **kwargs):
"""
Alternating least-sqaures algorithm to compute the CP decomposition.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed.
rank : int
Tensor rank of the decomposition.
init : {'random', 'nvecs'}, optional
The initializati... | [
"def",
"als",
"(",
"X",
",",
"rank",
",",
"*",
"*",
"kwargs",
")",
":",
"# init options",
"ainit",
"=",
"kwargs",
".",
"pop",
"(",
"'init'",
",",
"_DEF_INIT",
")",
"maxiter",
"=",
"kwargs",
".",
"pop",
"(",
"'max_iter'",
",",
"_DEF_MAXITER",
")",
"fi... | Alternating least-sqaures algorithm to compute the CP decomposition.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed.
rank : int
Tensor rank of the decomposition.
init : {'random', 'nvecs'}, optional
The initialization method to use.
- random :... | [
"Alternating",
"least",
"-",
"sqaures",
"algorithm",
"to",
"compute",
"the",
"CP",
"decomposition",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/cp.py#L46-L171 |
15,033 | mnick/scikit-tensor | sktensor/cp.py | _init | def _init(init, X, N, rank, dtype):
"""
Initialization for CP models
"""
Uinit = [None for _ in range(N)]
if isinstance(init, list):
Uinit = init
elif init == 'random':
for n in range(1, N):
Uinit[n] = array(rand(X.shape[n], rank), dtype=dtype)
elif init == 'nvecs... | python | def _init(init, X, N, rank, dtype):
"""
Initialization for CP models
"""
Uinit = [None for _ in range(N)]
if isinstance(init, list):
Uinit = init
elif init == 'random':
for n in range(1, N):
Uinit[n] = array(rand(X.shape[n], rank), dtype=dtype)
elif init == 'nvecs... | [
"def",
"_init",
"(",
"init",
",",
"X",
",",
"N",
",",
"rank",
",",
"dtype",
")",
":",
"Uinit",
"=",
"[",
"None",
"for",
"_",
"in",
"range",
"(",
"N",
")",
"]",
"if",
"isinstance",
"(",
"init",
",",
"list",
")",
":",
"Uinit",
"=",
"init",
"eli... | Initialization for CP models | [
"Initialization",
"for",
"CP",
"models"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/cp.py#L190-L205 |
15,034 | mnick/scikit-tensor | sktensor/core.py | nvecs | def nvecs(X, n, rank, do_flipsign=True, dtype=np.float):
"""
Eigendecomposition of mode-n unfolding of a tensor
"""
Xn = X.unfold(n)
if issparse_mat(Xn):
Xn = csr_matrix(Xn, dtype=dtype)
Y = Xn.dot(Xn.T)
_, U = eigsh(Y, rank, which='LM')
else:
Y = Xn.dot(Xn.T)
... | python | def nvecs(X, n, rank, do_flipsign=True, dtype=np.float):
"""
Eigendecomposition of mode-n unfolding of a tensor
"""
Xn = X.unfold(n)
if issparse_mat(Xn):
Xn = csr_matrix(Xn, dtype=dtype)
Y = Xn.dot(Xn.T)
_, U = eigsh(Y, rank, which='LM')
else:
Y = Xn.dot(Xn.T)
... | [
"def",
"nvecs",
"(",
"X",
",",
"n",
",",
"rank",
",",
"do_flipsign",
"=",
"True",
",",
"dtype",
"=",
"np",
".",
"float",
")",
":",
"Xn",
"=",
"X",
".",
"unfold",
"(",
"n",
")",
"if",
"issparse_mat",
"(",
"Xn",
")",
":",
"Xn",
"=",
"csr_matrix",... | Eigendecomposition of mode-n unfolding of a tensor | [
"Eigendecomposition",
"of",
"mode",
"-",
"n",
"unfolding",
"of",
"a",
"tensor"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/core.py#L275-L294 |
15,035 | mnick/scikit-tensor | sktensor/core.py | flipsign | def flipsign(U):
"""
Flip sign of factor matrices such that largest magnitude
element will be positive
"""
midx = abs(U).argmax(axis=0)
for i in range(U.shape[1]):
if U[midx[i], i] < 0:
U[:, i] = -U[:, i]
return U | python | def flipsign(U):
"""
Flip sign of factor matrices such that largest magnitude
element will be positive
"""
midx = abs(U).argmax(axis=0)
for i in range(U.shape[1]):
if U[midx[i], i] < 0:
U[:, i] = -U[:, i]
return U | [
"def",
"flipsign",
"(",
"U",
")",
":",
"midx",
"=",
"abs",
"(",
"U",
")",
".",
"argmax",
"(",
"axis",
"=",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"U",
".",
"shape",
"[",
"1",
"]",
")",
":",
"if",
"U",
"[",
"midx",
"[",
"i",
"]",
",",
... | Flip sign of factor matrices such that largest magnitude
element will be positive | [
"Flip",
"sign",
"of",
"factor",
"matrices",
"such",
"that",
"largest",
"magnitude",
"element",
"will",
"be",
"positive"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/core.py#L297-L306 |
15,036 | mnick/scikit-tensor | sktensor/core.py | khatrirao | def khatrirao(A, reverse=False):
"""
Compute the columnwise Khatri-Rao product.
Parameters
----------
A : tuple of ndarrays
Matrices for which the columnwise Khatri-Rao product should be computed
reverse : boolean
Compute Khatri-Rao product in reverse order
Examples
--... | python | def khatrirao(A, reverse=False):
"""
Compute the columnwise Khatri-Rao product.
Parameters
----------
A : tuple of ndarrays
Matrices for which the columnwise Khatri-Rao product should be computed
reverse : boolean
Compute Khatri-Rao product in reverse order
Examples
--... | [
"def",
"khatrirao",
"(",
"A",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"A",
",",
"tuple",
")",
":",
"raise",
"ValueError",
"(",
"'A must be a tuple of array likes'",
")",
"N",
"=",
"A",
"[",
"0",
"]",
".",
"shape",
"[",
... | Compute the columnwise Khatri-Rao product.
Parameters
----------
A : tuple of ndarrays
Matrices for which the columnwise Khatri-Rao product should be computed
reverse : boolean
Compute Khatri-Rao product in reverse order
Examples
--------
>>> A = np.random.randn(5, 2)
... | [
"Compute",
"the",
"columnwise",
"Khatri",
"-",
"Rao",
"product",
"."
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/core.py#L333-L378 |
15,037 | mnick/scikit-tensor | sktensor/core.py | teneye | def teneye(dim, order):
"""
Create tensor with superdiagonal all one, rest zeros
"""
I = zeros(dim ** order)
for f in range(dim):
idd = f
for i in range(1, order):
idd = idd + dim ** (i - 1) * (f - 1)
I[idd] = 1
return I.reshape(ones(order) * dim) | python | def teneye(dim, order):
"""
Create tensor with superdiagonal all one, rest zeros
"""
I = zeros(dim ** order)
for f in range(dim):
idd = f
for i in range(1, order):
idd = idd + dim ** (i - 1) * (f - 1)
I[idd] = 1
return I.reshape(ones(order) * dim) | [
"def",
"teneye",
"(",
"dim",
",",
"order",
")",
":",
"I",
"=",
"zeros",
"(",
"dim",
"**",
"order",
")",
"for",
"f",
"in",
"range",
"(",
"dim",
")",
":",
"idd",
"=",
"f",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"order",
")",
":",
"idd",
"=... | Create tensor with superdiagonal all one, rest zeros | [
"Create",
"tensor",
"with",
"superdiagonal",
"all",
"one",
"rest",
"zeros"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/core.py#L381-L391 |
15,038 | mnick/scikit-tensor | sktensor/core.py | tensor_mixin.ttm | def ttm(self, V, mode=None, transp=False, without=False):
"""
Tensor times matrix product
Parameters
----------
V : M x N array_like or list of M_i x N_i array_likes
Matrix or list of matrices for which the tensor times matrix
products should be performed... | python | def ttm(self, V, mode=None, transp=False, without=False):
"""
Tensor times matrix product
Parameters
----------
V : M x N array_like or list of M_i x N_i array_likes
Matrix or list of matrices for which the tensor times matrix
products should be performed... | [
"def",
"ttm",
"(",
"self",
",",
"V",
",",
"mode",
"=",
"None",
",",
"transp",
"=",
"False",
",",
"without",
"=",
"False",
")",
":",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"range",
"(",
"self",
".",
"ndim",
")",
"if",
"isinstance",
"(",
"... | Tensor times matrix product
Parameters
----------
V : M x N array_like or list of M_i x N_i array_likes
Matrix or list of matrices for which the tensor times matrix
products should be performed
mode : int or list of int's, optional
Modes along which t... | [
"Tensor",
"times",
"matrix",
"product"
] | fe517e9661a08164b8d30d2dddf7c96aeeabcf36 | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/core.py#L50-L103 |
15,039 | callowayproject/django-categories | categories/registration.py | _process_registry | def _process_registry(registry, call_func):
"""
Given a dictionary, and a registration function, process the registry
"""
from django.core.exceptions import ImproperlyConfigured
from django.apps import apps
for key, value in list(registry.items()):
model = apps.get_model(*key.split('.')... | python | def _process_registry(registry, call_func):
"""
Given a dictionary, and a registration function, process the registry
"""
from django.core.exceptions import ImproperlyConfigured
from django.apps import apps
for key, value in list(registry.items()):
model = apps.get_model(*key.split('.')... | [
"def",
"_process_registry",
"(",
"registry",
",",
"call_func",
")",
":",
"from",
"django",
".",
"core",
".",
"exceptions",
"import",
"ImproperlyConfigured",
"from",
"django",
".",
"apps",
"import",
"apps",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"regi... | Given a dictionary, and a registration function, process the registry | [
"Given",
"a",
"dictionary",
"and",
"a",
"registration",
"function",
"process",
"the",
"registry"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/registration.py#L118-L146 |
15,040 | callowayproject/django-categories | categories/migration.py | field_exists | def field_exists(app_name, model_name, field_name):
"""
Does the FK or M2M table exist in the database already?
"""
model = apps.get_model(app_name, model_name)
table_name = model._meta.db_table
cursor = connection.cursor()
field_info = connection.introspection.get_table_description(cursor, ... | python | def field_exists(app_name, model_name, field_name):
"""
Does the FK or M2M table exist in the database already?
"""
model = apps.get_model(app_name, model_name)
table_name = model._meta.db_table
cursor = connection.cursor()
field_info = connection.introspection.get_table_description(cursor, ... | [
"def",
"field_exists",
"(",
"app_name",
",",
"model_name",
",",
"field_name",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"app_name",
",",
"model_name",
")",
"table_name",
"=",
"model",
".",
"_meta",
".",
"db_table",
"cursor",
"=",
"connection",
... | Does the FK or M2M table exist in the database already? | [
"Does",
"the",
"FK",
"or",
"M2M",
"table",
"exist",
"in",
"the",
"database",
"already?"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/migration.py#L16-L25 |
15,041 | callowayproject/django-categories | categories/migration.py | drop_field | def drop_field(app_name, model_name, field_name):
"""
Drop the given field from the app's model
"""
app_config = apps.get_app_config(app_name)
model = app_config.get_model(model_name)
field = model._meta.get_field(field_name)
with connection.schema_editor() as schema_editor:
schema_e... | python | def drop_field(app_name, model_name, field_name):
"""
Drop the given field from the app's model
"""
app_config = apps.get_app_config(app_name)
model = app_config.get_model(model_name)
field = model._meta.get_field(field_name)
with connection.schema_editor() as schema_editor:
schema_e... | [
"def",
"drop_field",
"(",
"app_name",
",",
"model_name",
",",
"field_name",
")",
":",
"app_config",
"=",
"apps",
".",
"get_app_config",
"(",
"app_name",
")",
"model",
"=",
"app_config",
".",
"get_model",
"(",
"model_name",
")",
"field",
"=",
"model",
".",
... | Drop the given field from the app's model | [
"Drop",
"the",
"given",
"field",
"from",
"the",
"app",
"s",
"model"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/migration.py#L28-L36 |
15,042 | callowayproject/django-categories | categories/migration.py | migrate_app | def migrate_app(sender, *args, **kwargs):
"""
Migrate all models of this app registered
"""
from .registration import registry
if 'app_config' not in kwargs:
return
app_config = kwargs['app_config']
app_name = app_config.label
fields = [fld for fld in list(registry._field_regis... | python | def migrate_app(sender, *args, **kwargs):
"""
Migrate all models of this app registered
"""
from .registration import registry
if 'app_config' not in kwargs:
return
app_config = kwargs['app_config']
app_name = app_config.label
fields = [fld for fld in list(registry._field_regis... | [
"def",
"migrate_app",
"(",
"sender",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"registration",
"import",
"registry",
"if",
"'app_config'",
"not",
"in",
"kwargs",
":",
"return",
"app_config",
"=",
"kwargs",
"[",
"'app_config'",
"]",
... | Migrate all models of this app registered | [
"Migrate",
"all",
"models",
"of",
"this",
"app",
"registered"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/migration.py#L39-L66 |
15,043 | callowayproject/django-categories | categories/models.py | Category.get_absolute_url | def get_absolute_url(self):
"""Return a path"""
from django.urls import NoReverseMatch
if self.alternate_url:
return self.alternate_url
try:
prefix = reverse('categories_tree_list')
except NoReverseMatch:
prefix = '/'
ancestors = list(... | python | def get_absolute_url(self):
"""Return a path"""
from django.urls import NoReverseMatch
if self.alternate_url:
return self.alternate_url
try:
prefix = reverse('categories_tree_list')
except NoReverseMatch:
prefix = '/'
ancestors = list(... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"from",
"django",
".",
"urls",
"import",
"NoReverseMatch",
"if",
"self",
".",
"alternate_url",
":",
"return",
"self",
".",
"alternate_url",
"try",
":",
"prefix",
"=",
"reverse",
"(",
"'categories_tree_list'",
"... | Return a path | [
"Return",
"a",
"path"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/models.py#L56-L67 |
15,044 | callowayproject/django-categories | categories/models.py | CategoryRelationManager.get_content_type | def get_content_type(self, content_type):
"""
Get all the items of the given content type related to this item.
"""
qs = self.get_queryset()
return qs.filter(content_type__name=content_type) | python | def get_content_type(self, content_type):
"""
Get all the items of the given content type related to this item.
"""
qs = self.get_queryset()
return qs.filter(content_type__name=content_type) | [
"def",
"get_content_type",
"(",
"self",
",",
"content_type",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"content_type__name",
"=",
"content_type",
")"
] | Get all the items of the given content type related to this item. | [
"Get",
"all",
"the",
"items",
"of",
"the",
"given",
"content",
"type",
"related",
"to",
"this",
"item",
"."
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/models.py#L109-L114 |
15,045 | callowayproject/django-categories | categories/models.py | CategoryRelationManager.get_relation_type | def get_relation_type(self, relation_type):
"""
Get all the items of the given relationship type related to this item.
"""
qs = self.get_queryset()
return qs.filter(relation_type=relation_type) | python | def get_relation_type(self, relation_type):
"""
Get all the items of the given relationship type related to this item.
"""
qs = self.get_queryset()
return qs.filter(relation_type=relation_type) | [
"def",
"get_relation_type",
"(",
"self",
",",
"relation_type",
")",
":",
"qs",
"=",
"self",
".",
"get_queryset",
"(",
")",
"return",
"qs",
".",
"filter",
"(",
"relation_type",
"=",
"relation_type",
")"
] | Get all the items of the given relationship type related to this item. | [
"Get",
"all",
"the",
"items",
"of",
"the",
"given",
"relationship",
"type",
"related",
"to",
"this",
"item",
"."
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/models.py#L116-L121 |
15,046 | callowayproject/django-categories | categories/apps.py | handle_class_prepared | def handle_class_prepared(sender, **kwargs):
"""
See if this class needs registering of fields
"""
from .settings import M2M_REGISTRY, FK_REGISTRY
from .registration import registry
sender_app = sender._meta.app_label
sender_name = sender._meta.model_name
for key, val in list(FK_REGISTR... | python | def handle_class_prepared(sender, **kwargs):
"""
See if this class needs registering of fields
"""
from .settings import M2M_REGISTRY, FK_REGISTRY
from .registration import registry
sender_app = sender._meta.app_label
sender_name = sender._meta.model_name
for key, val in list(FK_REGISTR... | [
"def",
"handle_class_prepared",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"settings",
"import",
"M2M_REGISTRY",
",",
"FK_REGISTRY",
"from",
".",
"registration",
"import",
"registry",
"sender_app",
"=",
"sender",
".",
"_meta",
".",
"app_lab... | See if this class needs registering of fields | [
"See",
"if",
"this",
"class",
"needs",
"registering",
"of",
"fields"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/apps.py#L20-L37 |
15,047 | callowayproject/django-categories | categories/editor/tree_editor.py | TreeEditor.get_queryset | def get_queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_queryset()
qs.__class__ = TreeEditorQuerySet
return qs | python | def get_queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_queryset()
qs.__class__ = TreeEditorQuerySet
return qs | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"self",
".",
"model",
".",
"_default_manager",
".",
"get_queryset",
"(",
")",
"qs",
".",
"__class__",
"=",
"TreeEditorQuerySet",
"return",
"qs"
] | Returns a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view. | [
"Returns",
"a",
"QuerySet",
"of",
"all",
"model",
"instances",
"that",
"can",
"be",
"edited",
"by",
"the",
"admin",
"site",
".",
"This",
"is",
"used",
"by",
"changelist_view",
"."
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/editor/tree_editor.py#L283-L290 |
15,048 | callowayproject/django-categories | categories/base.py | CategoryBaseAdmin.deactivate | def deactivate(self, request, queryset):
"""
Set active to False for selected items
"""
selected_cats = self.model.objects.filter(
pk__in=[int(x) for x in request.POST.getlist('_selected_action')])
for item in selected_cats:
if item.active:
... | python | def deactivate(self, request, queryset):
"""
Set active to False for selected items
"""
selected_cats = self.model.objects.filter(
pk__in=[int(x) for x in request.POST.getlist('_selected_action')])
for item in selected_cats:
if item.active:
... | [
"def",
"deactivate",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"selected_cats",
"=",
"self",
".",
"model",
".",
"objects",
".",
"filter",
"(",
"pk__in",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"request",
".",
"POST",
".",
"g... | Set active to False for selected items | [
"Set",
"active",
"to",
"False",
"for",
"selected",
"items"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/base.py#L144-L155 |
15,049 | callowayproject/django-categories | categories/management/commands/import_categories.py | Command.get_indent | def get_indent(self, string):
"""
Look through the string and count the spaces
"""
indent_amt = 0
if string[0] == '\t':
return '\t'
for char in string:
if char == ' ':
indent_amt += 1
else:
return ' ' * ... | python | def get_indent(self, string):
"""
Look through the string and count the spaces
"""
indent_amt = 0
if string[0] == '\t':
return '\t'
for char in string:
if char == ' ':
indent_amt += 1
else:
return ' ' * ... | [
"def",
"get_indent",
"(",
"self",
",",
"string",
")",
":",
"indent_amt",
"=",
"0",
"if",
"string",
"[",
"0",
"]",
"==",
"'\\t'",
":",
"return",
"'\\t'",
"for",
"char",
"in",
"string",
":",
"if",
"char",
"==",
"' '",
":",
"indent_amt",
"+=",
"1",
"e... | Look through the string and count the spaces | [
"Look",
"through",
"the",
"string",
"and",
"count",
"the",
"spaces"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L16-L28 |
15,050 | callowayproject/django-categories | categories/management/commands/import_categories.py | Command.make_category | def make_category(self, string, parent=None, order=1):
"""
Make and save a category object from a string
"""
cat = Category(
name=string.strip(),
slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49],
# arent=parent,
order=order
)
... | python | def make_category(self, string, parent=None, order=1):
"""
Make and save a category object from a string
"""
cat = Category(
name=string.strip(),
slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49],
# arent=parent,
order=order
)
... | [
"def",
"make_category",
"(",
"self",
",",
"string",
",",
"parent",
"=",
"None",
",",
"order",
"=",
"1",
")",
":",
"cat",
"=",
"Category",
"(",
"name",
"=",
"string",
".",
"strip",
"(",
")",
",",
"slug",
"=",
"slugify",
"(",
"SLUG_TRANSLITERATOR",
"("... | Make and save a category object from a string | [
"Make",
"and",
"save",
"a",
"category",
"object",
"from",
"a",
"string"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L31-L46 |
15,051 | callowayproject/django-categories | categories/management/commands/import_categories.py | Command.parse_lines | def parse_lines(self, lines):
"""
Do the work of parsing each line
"""
indent = ''
level = 0
if lines[0][0] == ' ' or lines[0][0] == '\t':
raise CommandError("The first line in the file cannot start with a space or tab.")
# This keeps track of the cu... | python | def parse_lines(self, lines):
"""
Do the work of parsing each line
"""
indent = ''
level = 0
if lines[0][0] == ' ' or lines[0][0] == '\t':
raise CommandError("The first line in the file cannot start with a space or tab.")
# This keeps track of the cu... | [
"def",
"parse_lines",
"(",
"self",
",",
"lines",
")",
":",
"indent",
"=",
"''",
"level",
"=",
"0",
"if",
"lines",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"' '",
"or",
"lines",
"[",
"0",
"]",
"[",
"0",
"]",
"==",
"'\\t'",
":",
"raise",
"CommandError... | Do the work of parsing each line | [
"Do",
"the",
"work",
"of",
"parsing",
"each",
"line"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L48-L74 |
15,052 | callowayproject/django-categories | categories/management/commands/import_categories.py | Command.handle | def handle(self, *file_paths, **options):
"""
Handle the basic import
"""
import os
for file_path in file_paths:
if not os.path.isfile(file_path):
print("File %s not found." % file_path)
continue
f = open(file_path, 'r')
... | python | def handle(self, *file_paths, **options):
"""
Handle the basic import
"""
import os
for file_path in file_paths:
if not os.path.isfile(file_path):
print("File %s not found." % file_path)
continue
f = open(file_path, 'r')
... | [
"def",
"handle",
"(",
"self",
",",
"*",
"file_paths",
",",
"*",
"*",
"options",
")",
":",
"import",
"os",
"for",
"file_path",
"in",
"file_paths",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"print",
"(",
"\"File %s... | Handle the basic import | [
"Handle",
"the",
"basic",
"import"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/management/commands/import_categories.py#L76-L90 |
15,053 | callowayproject/django-categories | categories/templatetags/category_tags.py | get_cat_model | def get_cat_model(model):
"""
Return a class from a string or class
"""
try:
if isinstance(model, string_types):
model_class = apps.get_model(*model.split("."))
elif issubclass(model, CategoryBase):
model_class = model
if model_class is None:
r... | python | def get_cat_model(model):
"""
Return a class from a string or class
"""
try:
if isinstance(model, string_types):
model_class = apps.get_model(*model.split("."))
elif issubclass(model, CategoryBase):
model_class = model
if model_class is None:
r... | [
"def",
"get_cat_model",
"(",
"model",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"model",
",",
"string_types",
")",
":",
"model_class",
"=",
"apps",
".",
"get_model",
"(",
"*",
"model",
".",
"split",
"(",
"\".\"",
")",
")",
"elif",
"issubclass",
"(... | Return a class from a string or class | [
"Return",
"a",
"class",
"from",
"a",
"string",
"or",
"class"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L29-L42 |
15,054 | callowayproject/django-categories | categories/templatetags/category_tags.py | get_category | def get_category(category_string, model=Category):
"""
Convert a string, including a path, and return the Category object
"""
model_class = get_cat_model(model)
category = str(category_string).strip("'\"")
category = category.strip('/')
cat_list = category.split('/')
if len(cat_list) ==... | python | def get_category(category_string, model=Category):
"""
Convert a string, including a path, and return the Category object
"""
model_class = get_cat_model(model)
category = str(category_string).strip("'\"")
category = category.strip('/')
cat_list = category.split('/')
if len(cat_list) ==... | [
"def",
"get_category",
"(",
"category_string",
",",
"model",
"=",
"Category",
")",
":",
"model_class",
"=",
"get_cat_model",
"(",
"model",
")",
"category",
"=",
"str",
"(",
"category_string",
")",
".",
"strip",
"(",
"\"'\\\"\"",
")",
"category",
"=",
"catego... | Convert a string, including a path, and return the Category object | [
"Convert",
"a",
"string",
"including",
"a",
"path",
"and",
"return",
"the",
"Category",
"object"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L45-L69 |
15,055 | callowayproject/django-categories | categories/templatetags/category_tags.py | get_category_drilldown | def get_category_drilldown(parser, token):
"""
Retrieves the specified category, its ancestors and its immediate children
as an iterable.
Syntax::
{% get_category_drilldown "category name" [using "app.Model"] as varname %}
Example::
{% get_category_drilldown "/Grandparent/Parent"... | python | def get_category_drilldown(parser, token):
"""
Retrieves the specified category, its ancestors and its immediate children
as an iterable.
Syntax::
{% get_category_drilldown "category name" [using "app.Model"] as varname %}
Example::
{% get_category_drilldown "/Grandparent/Parent"... | [
"def",
"get_category_drilldown",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"error_str",
"=",
"'%(tagname)s tag should be in the format {%% %(tagname)s '",
"'\"category name\" [using \"app.Model\"] as varname %%} or '",
"'{%% %... | Retrieves the specified category, its ancestors and its immediate children
as an iterable.
Syntax::
{% get_category_drilldown "category name" [using "app.Model"] as varname %}
Example::
{% get_category_drilldown "/Grandparent/Parent" [using "app.Model"] as family %}
or ::
{... | [
"Retrieves",
"the",
"specified",
"category",
"its",
"ancestors",
"and",
"its",
"immediate",
"children",
"as",
"an",
"iterable",
"."
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L95-L136 |
15,056 | callowayproject/django-categories | categories/templatetags/category_tags.py | get_top_level_categories | def get_top_level_categories(parser, token):
"""
Retrieves an alphabetical list of all the categories that have no parents.
Syntax::
{% get_top_level_categories [using "app.Model"] as categories %}
Returns an list of categories [<category>, <category>, <category, ...]
"""
bits = token... | python | def get_top_level_categories(parser, token):
"""
Retrieves an alphabetical list of all the categories that have no parents.
Syntax::
{% get_top_level_categories [using "app.Model"] as categories %}
Returns an list of categories [<category>, <category>, <category, ...]
"""
bits = token... | [
"def",
"get_top_level_categories",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"usage",
"=",
"'Usage: {%% %s [using \"app.Model\"] as <variable> %%}'",
"%",
"bits",
"[",
"0",
"]",
"if",
"len",
"(",
"bits",
")",
... | Retrieves an alphabetical list of all the categories that have no parents.
Syntax::
{% get_top_level_categories [using "app.Model"] as categories %}
Returns an list of categories [<category>, <category>, <category, ...] | [
"Retrieves",
"an",
"alphabetical",
"list",
"of",
"all",
"the",
"categories",
"that",
"have",
"no",
"parents",
"."
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L237-L264 |
15,057 | callowayproject/django-categories | categories/templatetags/category_tags.py | tree_queryset | def tree_queryset(value):
"""
Converts a normal queryset from an MPTT model to include all the ancestors
so a filtered subset of items can be formatted correctly
"""
from django.db.models.query import QuerySet
from copy import deepcopy
if not isinstance(value, QuerySet):
return value... | python | def tree_queryset(value):
"""
Converts a normal queryset from an MPTT model to include all the ancestors
so a filtered subset of items can be formatted correctly
"""
from django.db.models.query import QuerySet
from copy import deepcopy
if not isinstance(value, QuerySet):
return value... | [
"def",
"tree_queryset",
"(",
"value",
")",
":",
"from",
"django",
".",
"db",
".",
"models",
".",
"query",
"import",
"QuerySet",
"from",
"copy",
"import",
"deepcopy",
"if",
"not",
"isinstance",
"(",
"value",
",",
"QuerySet",
")",
":",
"return",
"value",
"... | Converts a normal queryset from an MPTT model to include all the ancestors
so a filtered subset of items can be formatted correctly | [
"Converts",
"a",
"normal",
"queryset",
"from",
"an",
"MPTT",
"model",
"to",
"include",
"all",
"the",
"ancestors",
"so",
"a",
"filtered",
"subset",
"of",
"items",
"can",
"be",
"formatted",
"correctly"
] | 3765851320a79b12c6d3306f3784a2302ea64812 | https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/templatetags/category_tags.py#L346-L377 |
15,058 | maweigert/gputools | gputools/convolve/convolve.py | convolve | def convolve(data, h, res_g=None, sub_blocks=None):
"""
convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge.
"""
if not len(data.shape) in [1, 2, 3]:
... | python | def convolve(data, h, res_g=None, sub_blocks=None):
"""
convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge.
"""
if not len(data.shape) in [1, 2, 3]:
... | [
"def",
"convolve",
"(",
"data",
",",
"h",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"None",
")",
":",
"if",
"not",
"len",
"(",
"data",
".",
"shape",
")",
"in",
"[",
"1",
",",
"2",
",",
"3",
"]",
":",
"raise",
"ValueError",
"(",
"\"dim ... | convolves 1d-3d data with kernel h
data and h can either be numpy arrays or gpu buffer objects (OCLArray,
which must be float32 then)
boundary conditions are clamping to zero at edge. | [
"convolves",
"1d",
"-",
"3d",
"data",
"with",
"kernel",
"h"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/convolve.py#L18-L54 |
15,059 | maweigert/gputools | gputools/convolve/convolve.py | _convolve3_old | def _convolve3_old(data, h, dev=None):
"""convolves 3d data with kernel h on the GPU Device dev
boundary conditions are clamping to edge.
h is converted to float32
if dev == None the default one is used
"""
if dev is None:
dev = get_device()
if dev is None:
raise ValueErro... | python | def _convolve3_old(data, h, dev=None):
"""convolves 3d data with kernel h on the GPU Device dev
boundary conditions are clamping to edge.
h is converted to float32
if dev == None the default one is used
"""
if dev is None:
dev = get_device()
if dev is None:
raise ValueErro... | [
"def",
"_convolve3_old",
"(",
"data",
",",
"h",
",",
"dev",
"=",
"None",
")",
":",
"if",
"dev",
"is",
"None",
":",
"dev",
"=",
"get_device",
"(",
")",
"if",
"dev",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"no OpenCLDevice found...\"",
")",
"dty... | convolves 3d data with kernel h on the GPU Device dev
boundary conditions are clamping to edge.
h is converted to float32
if dev == None the default one is used | [
"convolves",
"3d",
"data",
"with",
"kernel",
"h",
"on",
"the",
"GPU",
"Device",
"dev",
"boundary",
"conditions",
"are",
"clamping",
"to",
"edge",
".",
"h",
"is",
"converted",
"to",
"float32"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/convolve.py#L116-L151 |
15,060 | maweigert/gputools | gputools/transforms/scale.py | _scale_shape | def _scale_shape(dshape, scale = (1,1,1)):
"""returns the shape after scaling (should be the same as ndimage.zoom"""
nshape = np.round(np.array(dshape) * np.array(scale))
return tuple(nshape.astype(np.int)) | python | def _scale_shape(dshape, scale = (1,1,1)):
"""returns the shape after scaling (should be the same as ndimage.zoom"""
nshape = np.round(np.array(dshape) * np.array(scale))
return tuple(nshape.astype(np.int)) | [
"def",
"_scale_shape",
"(",
"dshape",
",",
"scale",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
":",
"nshape",
"=",
"np",
".",
"round",
"(",
"np",
".",
"array",
"(",
"dshape",
")",
"*",
"np",
".",
"array",
"(",
"scale",
")",
")",
"return",
"... | returns the shape after scaling (should be the same as ndimage.zoom | [
"returns",
"the",
"shape",
"after",
"scaling",
"(",
"should",
"be",
"the",
"same",
"as",
"ndimage",
".",
"zoom"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/scale.py#L17-L20 |
15,061 | maweigert/gputools | gputools/fft/fftshift.py | fftshift | def fftshift(arr_obj, axes = None, res_g = None, return_buffer = False):
"""
gpu version of fftshift for numpy arrays or OCLArrays
Parameters
----------
arr_obj: numpy array or OCLArray (float32/complex64)
the array to be fftshifted
axes: list or None
the axes over which to shif... | python | def fftshift(arr_obj, axes = None, res_g = None, return_buffer = False):
"""
gpu version of fftshift for numpy arrays or OCLArrays
Parameters
----------
arr_obj: numpy array or OCLArray (float32/complex64)
the array to be fftshifted
axes: list or None
the axes over which to shif... | [
"def",
"fftshift",
"(",
"arr_obj",
",",
"axes",
"=",
"None",
",",
"res_g",
"=",
"None",
",",
"return_buffer",
"=",
"False",
")",
":",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"list",
"(",
"range",
"(",
"arr_obj",
".",
"ndim",
")",
")",
"if",
... | gpu version of fftshift for numpy arrays or OCLArrays
Parameters
----------
arr_obj: numpy array or OCLArray (float32/complex64)
the array to be fftshifted
axes: list or None
the axes over which to shift (like np.fft.fftshift)
if None, all axes are taken
res_g:
if gi... | [
"gpu",
"version",
"of",
"fftshift",
"for",
"numpy",
"arrays",
"or",
"OCLArrays"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/fftshift.py#L27-L80 |
15,062 | maweigert/gputools | gputools/fft/fftshift.py | _fftshift_single | def _fftshift_single(d_g, res_g, ax = 0):
"""
basic fftshift of an OCLArray
shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k]
= [N1, N, N2]
the we can address each element in the flat buffer by
index = i + N2*j + N2*N*k
where i = 1 .. N2
j = 1 .. N
k = 1 .. N1
... | python | def _fftshift_single(d_g, res_g, ax = 0):
"""
basic fftshift of an OCLArray
shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k]
= [N1, N, N2]
the we can address each element in the flat buffer by
index = i + N2*j + N2*N*k
where i = 1 .. N2
j = 1 .. N
k = 1 .. N1
... | [
"def",
"_fftshift_single",
"(",
"d_g",
",",
"res_g",
",",
"ax",
"=",
"0",
")",
":",
"dtype_kernel_name",
"=",
"{",
"np",
".",
"float32",
":",
"\"fftshift_1_f\"",
",",
"np",
".",
"complex64",
":",
"\"fftshift_1_c\"",
"}",
"N",
"=",
"d_g",
".",
"shape",
... | basic fftshift of an OCLArray
shape(d_g) = [N_0,N_1...., N, .... N_{k-1, N_k]
= [N1, N, N2]
the we can address each element in the flat buffer by
index = i + N2*j + N2*N*k
where i = 1 .. N2
j = 1 .. N
k = 1 .. N1
and the swap of elements is performed on the inde... | [
"basic",
"fftshift",
"of",
"an",
"OCLArray"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/fftshift.py#L83-L119 |
15,063 | maweigert/gputools | gputools/fft/oclfft_convolve.py | fft_convolve | def fft_convolve(data, h, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False,
kernel_is_fftshifted = False):
""" convolves data with kernel h via FFTs
data should be either a numpy array or a OCLArray (see doc for fft)
both data an... | python | def fft_convolve(data, h, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False,
kernel_is_fftshifted = False):
""" convolves data with kernel h via FFTs
data should be either a numpy array or a OCLArray (see doc for fft)
both data an... | [
"def",
"fft_convolve",
"(",
"data",
",",
"h",
",",
"res_g",
"=",
"None",
",",
"plan",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"kernel_is_fft",
"=",
"False",
",",
"kernel_is_fftshifted",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data",
"... | convolves data with kernel h via FFTs
data should be either a numpy array or a OCLArray (see doc for fft)
both data and h should be same shape
if data/h are OCLArrays, then:
- type should be complex64
- shape should be equal and power of two
- h is assumed to be already fftshi... | [
"convolves",
"data",
"with",
"kernel",
"h",
"via",
"FFTs"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft_convolve.py#L15-L45 |
15,064 | maweigert/gputools | gputools/fft/oclfft_convolve.py | _fft_convolve_numpy | def _fft_convolve_numpy(data, h, plan = None,
kernel_is_fft = False,
kernel_is_fftshifted = False):
""" convolving via opencl fft for numpy arrays
data and h must have the same size
"""
if data.shape != h.shape:
raise ValueError("data and kernel ... | python | def _fft_convolve_numpy(data, h, plan = None,
kernel_is_fft = False,
kernel_is_fftshifted = False):
""" convolving via opencl fft for numpy arrays
data and h must have the same size
"""
if data.shape != h.shape:
raise ValueError("data and kernel ... | [
"def",
"_fft_convolve_numpy",
"(",
"data",
",",
"h",
",",
"plan",
"=",
"None",
",",
"kernel_is_fft",
"=",
"False",
",",
"kernel_is_fftshifted",
"=",
"False",
")",
":",
"if",
"data",
".",
"shape",
"!=",
"h",
".",
"shape",
":",
"raise",
"ValueError",
"(",
... | convolving via opencl fft for numpy arrays
data and h must have the same size | [
"convolving",
"via",
"opencl",
"fft",
"for",
"numpy",
"arrays"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft_convolve.py#L49-L80 |
15,065 | maweigert/gputools | gputools/fft/oclfft_convolve.py | _fft_convolve_gpu | def _fft_convolve_gpu(data_g, h_g, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False):
""" fft convolve for gpu buffer
"""
assert_bufs_type(np.complex64,data_g,h_g)
if data_g.shape != h_g.shape:
raise ValueError("data and kernel mu... | python | def _fft_convolve_gpu(data_g, h_g, res_g = None,
plan = None, inplace = False,
kernel_is_fft = False):
""" fft convolve for gpu buffer
"""
assert_bufs_type(np.complex64,data_g,h_g)
if data_g.shape != h_g.shape:
raise ValueError("data and kernel mu... | [
"def",
"_fft_convolve_gpu",
"(",
"data_g",
",",
"h_g",
",",
"res_g",
"=",
"None",
",",
"plan",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"kernel_is_fft",
"=",
"False",
")",
":",
"assert_bufs_type",
"(",
"np",
".",
"complex64",
",",
"data_g",
",",
... | fft convolve for gpu buffer | [
"fft",
"convolve",
"for",
"gpu",
"buffer"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/fft/oclfft_convolve.py#L83-L124 |
15,066 | maweigert/gputools | gputools/convolve/median_filter.py | median_filter | def median_filter(data, size=3, cval = 0, res_g=None, sub_blocks=None):
"""
median filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
cval: scalar,
... | python | def median_filter(data, size=3, cval = 0, res_g=None, sub_blocks=None):
"""
median filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
cval: scalar,
... | [
"def",
"median_filter",
"(",
"data",
",",
"size",
"=",
"3",
",",
"cval",
"=",
"0",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"None",
")",
":",
"if",
"data",
".",
"ndim",
"==",
"2",
":",
"_filt",
"=",
"make_filter",
"(",
"_median_filter_gpu_2... | median filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
cval: scalar,
the constant value for out of border access (cf mode = "constant")
res_g: O... | [
"median",
"filter",
"of",
"given",
"size"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/median_filter.py#L112-L141 |
15,067 | maweigert/gputools | gputools/transforms/transformations.py | rotate | def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"):
"""
rotates data around axis by a given angle
Parameters
----------
data: ndarray
3d array
axis: tuple
axis to rotate by angle about
axis = (x,y,z)
angle: float
cen... | python | def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"):
"""
rotates data around axis by a given angle
Parameters
----------
data: ndarray
3d array
axis: tuple
axis to rotate by angle about
axis = (x,y,z)
angle: float
cen... | [
"def",
"rotate",
"(",
"data",
",",
"axis",
"=",
"(",
"1.",
",",
"0",
",",
"0",
")",
",",
"angle",
"=",
"0.",
",",
"center",
"=",
"None",
",",
"mode",
"=",
"\"constant\"",
",",
"interpolation",
"=",
"\"linear\"",
")",
":",
"if",
"center",
"is",
"N... | rotates data around axis by a given angle
Parameters
----------
data: ndarray
3d array
axis: tuple
axis to rotate by angle about
axis = (x,y,z)
angle: float
center: tuple or None
origin of rotation (cz,cy,cx) in pixels
if None, center is the middle of dat... | [
"rotates",
"data",
"around",
"axis",
"by",
"a",
"given",
"angle"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/transformations.py#L128-L171 |
15,068 | maweigert/gputools | gputools/transforms/transformations.py | map_coordinates | def map_coordinates(data, coordinates, interpolation="linear",
mode='constant'):
"""
Map data to new coordinates by interpolation.
The array of coordinates is used to find, for each point in the output,
the corresponding coordinates in the input.
should correspond to scipy.ndima... | python | def map_coordinates(data, coordinates, interpolation="linear",
mode='constant'):
"""
Map data to new coordinates by interpolation.
The array of coordinates is used to find, for each point in the output,
the corresponding coordinates in the input.
should correspond to scipy.ndima... | [
"def",
"map_coordinates",
"(",
"data",
",",
"coordinates",
",",
"interpolation",
"=",
"\"linear\"",
",",
"mode",
"=",
"'constant'",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
"and",
"data",
".",
"ndim",
"in",
... | Map data to new coordinates by interpolation.
The array of coordinates is used to find, for each point in the output,
the corresponding coordinates in the input.
should correspond to scipy.ndimage.map_coordinates
Parameters
----------
data
coordinates
output
interpolation
m... | [
"Map",
"data",
"to",
"new",
"coordinates",
"by",
"interpolation",
".",
"The",
"array",
"of",
"coordinates",
"is",
"used",
"to",
"find",
"for",
"each",
"point",
"in",
"the",
"output",
"the",
"corresponding",
"coordinates",
"in",
"the",
"input",
"."
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/transformations.py#L174-L237 |
15,069 | maweigert/gputools | gputools/utils/utils.py | pad_to_shape | def pad_to_shape(d, dshape, mode = "constant"):
"""
pad array d to shape dshape
"""
if d.shape == dshape:
return d
diff = np.array(dshape)- np.array(d.shape)
#first shrink
slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff)
res = d[slices]
#then pad... | python | def pad_to_shape(d, dshape, mode = "constant"):
"""
pad array d to shape dshape
"""
if d.shape == dshape:
return d
diff = np.array(dshape)- np.array(d.shape)
#first shrink
slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff)
res = d[slices]
#then pad... | [
"def",
"pad_to_shape",
"(",
"d",
",",
"dshape",
",",
"mode",
"=",
"\"constant\"",
")",
":",
"if",
"d",
".",
"shape",
"==",
"dshape",
":",
"return",
"d",
"diff",
"=",
"np",
".",
"array",
"(",
"dshape",
")",
"-",
"np",
".",
"array",
"(",
"d",
".",
... | pad array d to shape dshape | [
"pad",
"array",
"d",
"to",
"shape",
"dshape"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/utils/utils.py#L4-L17 |
15,070 | maweigert/gputools | gputools/utils/utils.py | pad_to_power2 | def pad_to_power2(data, axis = None, mode="constant"):
"""
pad data to a shape of power 2
if axis == None all axis are padded
"""
if axis is None:
axis = list(range(data.ndim))
if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]):
return data
else:
... | python | def pad_to_power2(data, axis = None, mode="constant"):
"""
pad data to a shape of power 2
if axis == None all axis are padded
"""
if axis is None:
axis = list(range(data.ndim))
if np.all([_is_power2(n) for i, n in enumerate(data.shape) if i in axis]):
return data
else:
... | [
"def",
"pad_to_power2",
"(",
"data",
",",
"axis",
"=",
"None",
",",
"mode",
"=",
"\"constant\"",
")",
":",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"list",
"(",
"range",
"(",
"data",
".",
"ndim",
")",
")",
"if",
"np",
".",
"all",
"(",
"[",
... | pad data to a shape of power 2
if axis == None all axis are padded | [
"pad",
"data",
"to",
"a",
"shape",
"of",
"power",
"2",
"if",
"axis",
"==",
"None",
"all",
"axis",
"are",
"padded"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/utils/utils.py#L27-L38 |
15,071 | maweigert/gputools | gputools/convolve/generic_separable_filters.py | max_filter | def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
"""
maximum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
st... | python | def max_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
"""
maximum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
st... | [
"def",
"max_filter",
"(",
"data",
",",
"size",
"=",
"7",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
":",
"if",
"data",
".",
"ndim",
"==",
"2",
":",
"_filt",
"=",
"make_filter",
"(",
"_generic_filter... | maximum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tili... | [
"maximum",
"filter",
"of",
"given",
"size"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L115-L139 |
15,072 | maweigert/gputools | gputools/convolve/generic_separable_filters.py | min_filter | def min_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
"""
minimum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
st... | python | def min_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1)):
"""
minimum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
st... | [
"def",
"min_filter",
"(",
"data",
",",
"size",
"=",
"7",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
":",
"if",
"data",
".",
"ndim",
"==",
"2",
":",
"_filt",
"=",
"make_filter",
"(",
"_generic_filter... | minimum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tili... | [
"minimum",
"filter",
"of",
"given",
"size"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L142-L167 |
15,073 | maweigert/gputools | gputools/convolve/generic_separable_filters.py | uniform_filter | def uniform_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1), normalized = True):
"""
mean filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g:... | python | def uniform_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1), normalized = True):
"""
mean filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g:... | [
"def",
"uniform_filter",
"(",
"data",
",",
"size",
"=",
"7",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"normalized",
"=",
"True",
")",
":",
"if",
"normalized",
":",
"if",
"np",
".",
"isscalar",
"("... | mean filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling ... | [
"mean",
"filter",
"of",
"given",
"size"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L171-L210 |
15,074 | maweigert/gputools | gputools/convolve/generic_separable_filters.py | _gauss_filter | def _gauss_filter(data, sigma=4, res_g=None, sub_blocks=(1, 1, 1)):
"""
gaussian filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
... | python | def _gauss_filter(data, sigma=4, res_g=None, sub_blocks=(1, 1, 1)):
"""
gaussian filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
... | [
"def",
"_gauss_filter",
"(",
"data",
",",
"sigma",
"=",
"4",
",",
"res_g",
"=",
"None",
",",
"sub_blocks",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
")",
":",
"truncate",
"=",
"4.",
"radius",
"=",
"tuple",
"(",
"int",
"(",
"truncate",
"*",
"s",
"... | gaussian filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock til... | [
"gaussian",
"filter",
"of",
"given",
"size"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/convolve/generic_separable_filters.py#L216-L248 |
15,075 | maweigert/gputools | gputools/separable/separable_approx.py | _separable_series2 | def _separable_series2(h, N=1):
""" finds separable approximations to the 2d function 2d h
returns res = (hx, hy)[N]
s.t. h \approx sum_i outer(res[i,0],res[i,1])
"""
if min(h.shape)<N:
raise ValueError("smallest dimension of h is smaller than approximation order! (%s < %s)"%(min(h.shape),N... | python | def _separable_series2(h, N=1):
""" finds separable approximations to the 2d function 2d h
returns res = (hx, hy)[N]
s.t. h \approx sum_i outer(res[i,0],res[i,1])
"""
if min(h.shape)<N:
raise ValueError("smallest dimension of h is smaller than approximation order! (%s < %s)"%(min(h.shape),N... | [
"def",
"_separable_series2",
"(",
"h",
",",
"N",
"=",
"1",
")",
":",
"if",
"min",
"(",
"h",
".",
"shape",
")",
"<",
"N",
":",
"raise",
"ValueError",
"(",
"\"smallest dimension of h is smaller than approximation order! (%s < %s)\"",
"%",
"(",
"min",
"(",
"h",
... | finds separable approximations to the 2d function 2d h
returns res = (hx, hy)[N]
s.t. h \approx sum_i outer(res[i,0],res[i,1]) | [
"finds",
"separable",
"approximations",
"to",
"the",
"2d",
"function",
"2d",
"h"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L16-L29 |
15,076 | maweigert/gputools | gputools/separable/separable_approx.py | _separable_approx2 | def _separable_approx2(h, N=1):
""" returns the N first approximations to the 2d function h
whose sum should be h
"""
return np.cumsum([np.outer(fy, fx) for fy, fx in _separable_series2(h, N)], 0) | python | def _separable_approx2(h, N=1):
""" returns the N first approximations to the 2d function h
whose sum should be h
"""
return np.cumsum([np.outer(fy, fx) for fy, fx in _separable_series2(h, N)], 0) | [
"def",
"_separable_approx2",
"(",
"h",
",",
"N",
"=",
"1",
")",
":",
"return",
"np",
".",
"cumsum",
"(",
"[",
"np",
".",
"outer",
"(",
"fy",
",",
"fx",
")",
"for",
"fy",
",",
"fx",
"in",
"_separable_series2",
"(",
"h",
",",
"N",
")",
"]",
",",
... | returns the N first approximations to the 2d function h
whose sum should be h | [
"returns",
"the",
"N",
"first",
"approximations",
"to",
"the",
"2d",
"function",
"h",
"whose",
"sum",
"should",
"be",
"h"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L32-L36 |
15,077 | maweigert/gputools | gputools/separable/separable_approx.py | _separable_approx3 | def _separable_approx3(h, N=1):
""" returns the N first approximations to the 3d function h
"""
return np.cumsum([np.einsum("i,j,k", fz, fy, fx) for fz, fy, fx in _separable_series3(h, N)], 0) | python | def _separable_approx3(h, N=1):
""" returns the N first approximations to the 3d function h
"""
return np.cumsum([np.einsum("i,j,k", fz, fy, fx) for fz, fy, fx in _separable_series3(h, N)], 0) | [
"def",
"_separable_approx3",
"(",
"h",
",",
"N",
"=",
"1",
")",
":",
"return",
"np",
".",
"cumsum",
"(",
"[",
"np",
".",
"einsum",
"(",
"\"i,j,k\"",
",",
"fz",
",",
"fy",
",",
"fx",
")",
"for",
"fz",
",",
"fy",
",",
"fx",
"in",
"_separable_series... | returns the N first approximations to the 3d function h | [
"returns",
"the",
"N",
"first",
"approximations",
"to",
"the",
"3d",
"function",
"h"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L85-L88 |
15,078 | maweigert/gputools | gputools/separable/separable_approx.py | separable_approx | def separable_approx(h, N=1):
"""
finds the k-th rank approximation to h, where k = 1..N
similar to separable_series
Parameters
----------
h: ndarray
input array (2 or 2 dimensional)
N: int
order of approximation
Returns
-------
all N apprxoimations res[i],... | python | def separable_approx(h, N=1):
"""
finds the k-th rank approximation to h, where k = 1..N
similar to separable_series
Parameters
----------
h: ndarray
input array (2 or 2 dimensional)
N: int
order of approximation
Returns
-------
all N apprxoimations res[i],... | [
"def",
"separable_approx",
"(",
"h",
",",
"N",
"=",
"1",
")",
":",
"if",
"h",
".",
"ndim",
"==",
"2",
":",
"return",
"_separable_approx2",
"(",
"h",
",",
"N",
")",
"elif",
"h",
".",
"ndim",
"==",
"3",
":",
"return",
"_separable_approx3",
"(",
"h",
... | finds the k-th rank approximation to h, where k = 1..N
similar to separable_series
Parameters
----------
h: ndarray
input array (2 or 2 dimensional)
N: int
order of approximation
Returns
-------
all N apprxoimations res[i], the i-th approximation | [
"finds",
"the",
"k",
"-",
"th",
"rank",
"approximation",
"to",
"h",
"where",
"k",
"=",
"1",
"..",
"N"
] | 6ab26efeb05dceef74cf13aadeeeb9b009b529dd | https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/separable/separable_approx.py#L127-L150 |
15,079 | alculquicondor/psqlparse | psqlparse/nodes/nodes.py | Node.tables | def tables(self):
"""
Generic method that does a depth-first search on the node attributes.
Child classes should override this method for better performance.
"""
_tables = set()
for attr in six.itervalues(self.__dict__):
if isinstance(attr, list):
... | python | def tables(self):
"""
Generic method that does a depth-first search on the node attributes.
Child classes should override this method for better performance.
"""
_tables = set()
for attr in six.itervalues(self.__dict__):
if isinstance(attr, list):
... | [
"def",
"tables",
"(",
"self",
")",
":",
"_tables",
"=",
"set",
"(",
")",
"for",
"attr",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"__dict__",
")",
":",
"if",
"isinstance",
"(",
"attr",
",",
"list",
")",
":",
"for",
"item",
"in",
"attr",
"... | Generic method that does a depth-first search on the node attributes.
Child classes should override this method for better performance. | [
"Generic",
"method",
"that",
"does",
"a",
"depth",
"-",
"first",
"search",
"on",
"the",
"node",
"attributes",
"."
] | 9c2af04f45ddc4068d7fd87580612457d374e97d | https://github.com/alculquicondor/psqlparse/blob/9c2af04f45ddc4068d7fd87580612457d374e97d/psqlparse/nodes/nodes.py#L6-L22 |
15,080 | sloria/konch | docopt.py | Pattern.fix_identities | def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr... | python | def fix_identities(self, uniq=None):
"""Make pattern-tree tips point to same object if they are equal."""
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr... | [
"def",
"fix_identities",
"(",
"self",
",",
"uniq",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'children'",
")",
":",
"return",
"self",
"uniq",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"flat",
"(",
")",
")",
")",
"if",
"un... | Make pattern-tree tips point to same object if they are equal. | [
"Make",
"pattern",
"-",
"tree",
"tips",
"point",
"to",
"same",
"object",
"if",
"they",
"are",
"equal",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/docopt.py#L46-L56 |
15,081 | sloria/konch | setup.py | find_version | def find_version(fname):
"""Attempts to find the version number in the file names fname.
Raises RuntimeError if not found.
"""
version = ""
with open(fname, "r") as fp:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fp:
m = reg.match(line)
... | python | def find_version(fname):
"""Attempts to find the version number in the file names fname.
Raises RuntimeError if not found.
"""
version = ""
with open(fname, "r") as fp:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fp:
m = reg.match(line)
... | [
"def",
"find_version",
"(",
"fname",
")",
":",
"version",
"=",
"\"\"",
"with",
"open",
"(",
"fname",
",",
"\"r\"",
")",
"as",
"fp",
":",
"reg",
"=",
"re",
".",
"compile",
"(",
"r'__version__ = [\\'\"]([^\\'\"]*)[\\'\"]'",
")",
"for",
"line",
"in",
"fp",
... | Attempts to find the version number in the file names fname.
Raises RuntimeError if not found. | [
"Attempts",
"to",
"find",
"the",
"version",
"number",
"in",
"the",
"file",
"names",
"fname",
".",
"Raises",
"RuntimeError",
"if",
"not",
"found",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/setup.py#L46-L60 |
15,082 | sloria/konch | konch.py | format_context | def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
... | python | def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
... | [
"def",
"format_context",
"(",
"context",
":",
"Context",
",",
"formatter",
":",
"typing",
".",
"Union",
"[",
"str",
",",
"Formatter",
"]",
"=",
"\"full\"",
")",
"->",
"str",
":",
"if",
"not",
"context",
":",
"return",
"\"\"",
"if",
"callable",
"(",
"fo... | Output the a context dictionary as a string. | [
"Output",
"the",
"a",
"context",
"dictionary",
"as",
"a",
"string",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L245-L259 |
15,083 | sloria/konch | konch.py | make_banner | def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
... | python | def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
"""Generates a full banner with version info, the given text, and a
formatted list of context variables.
... | [
"def",
"make_banner",
"(",
"text",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"context",
":",
"typing",
".",
"Optional",
"[",
"Context",
"]",
"=",
"None",
",",
"banner_template",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
... | Generates a full banner with version info, the given text, and a
formatted list of context variables. | [
"Generates",
"a",
"full",
"banner",
"with",
"version",
"info",
"the",
"given",
"text",
"and",
"a",
"formatted",
"list",
"of",
"context",
"variables",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L269-L282 |
15,084 | sloria/konch | konch.py | config | def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict... | python | def config(config_dict: typing.Mapping) -> Config:
"""Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use).
"""
logger.debug(f"Updating with {config_dict... | [
"def",
"config",
"(",
"config_dict",
":",
"typing",
".",
"Mapping",
")",
"->",
"Config",
":",
"logger",
".",
"debug",
"(",
"f\"Updating with {config_dict}\"",
")",
"_cfg",
".",
"update",
"(",
"config_dict",
")",
"return",
"_cfg"
] | Configures the konch shell. This function should be called in a
.konchrc file.
:param dict config_dict: Dict that may contain 'context', 'banner', and/or
'shell' (default shell class to use). | [
"Configures",
"the",
"konch",
"shell",
".",
"This",
"function",
"should",
"be",
"called",
"in",
"a",
".",
"konchrc",
"file",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L828-L837 |
15,085 | sloria/konch | konch.py | named_config | def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) ... | python | def named_config(name: str, config_dict: typing.Mapping) -> None:
"""Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file.
"""
names = (
name
if isinstance(name, Iterable) ... | [
"def",
"named_config",
"(",
"name",
":",
"str",
",",
"config_dict",
":",
"typing",
".",
"Mapping",
")",
"->",
"None",
":",
"names",
"=",
"(",
"name",
"if",
"isinstance",
"(",
"name",
",",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"name",
",",
... | Adds a named config to the config registry. The first argument
may either be a string or a collection of strings.
This function should be called in a .konchrc file. | [
"Adds",
"a",
"named",
"config",
"to",
"the",
"config",
"registry",
".",
"The",
"first",
"argument",
"may",
"either",
"be",
"a",
"string",
"or",
"a",
"collection",
"of",
"strings",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L840-L852 |
15,086 | sloria/konch | konch.py | __ensure_directory_in_path | def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory)) | python | def __ensure_directory_in_path(filename: Path) -> None:
"""Ensures that a file's directory is in the Python path.
"""
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory)) | [
"def",
"__ensure_directory_in_path",
"(",
"filename",
":",
"Path",
")",
"->",
"None",
":",
"directory",
"=",
"Path",
"(",
"filename",
")",
".",
"parent",
".",
"resolve",
"(",
")",
"if",
"directory",
"not",
"in",
"sys",
".",
"path",
":",
"logger",
".",
... | Ensures that a file's directory is in the Python path. | [
"Ensures",
"that",
"a",
"file",
"s",
"directory",
"is",
"in",
"the",
"Python",
"path",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L861-L867 |
15,087 | sloria/konch | konch.py | use_file | def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
... | python | def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
"""Load filename as a python file. Import ``filename`` and return it
as a module.
"""
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
... | [
"def",
"use_file",
"(",
"filename",
":",
"typing",
".",
"Union",
"[",
"Path",
",",
"str",
",",
"None",
"]",
",",
"trust",
":",
"bool",
"=",
"False",
")",
"->",
"typing",
".",
"Union",
"[",
"types",
".",
"ModuleType",
",",
"None",
"]",
":",
"config_... | Load filename as a python file. Import ``filename`` and return it
as a module. | [
"Load",
"filename",
"as",
"a",
"python",
"file",
".",
"Import",
"filename",
"and",
"return",
"it",
"as",
"a",
"module",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L898-L954 |
15,088 | sloria/konch | konch.py | resolve_path | def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != s... | python | def resolve_path(filename: Path) -> typing.Union[Path, None]:
"""Find a file by walking up parent directories until the file is found.
Return the absolute path of the file.
"""
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != s... | [
"def",
"resolve_path",
"(",
"filename",
":",
"Path",
")",
"->",
"typing",
".",
"Union",
"[",
"Path",
",",
"None",
"]",
":",
"current",
"=",
"Path",
".",
"cwd",
"(",
")",
"# Stop search at home directory",
"sentinel_dir",
"=",
"Path",
".",
"home",
"(",
")... | Find a file by walking up parent directories until the file is found.
Return the absolute path of the file. | [
"Find",
"a",
"file",
"by",
"walking",
"up",
"parent",
"directories",
"until",
"the",
"file",
"is",
"found",
".",
"Return",
"the",
"absolute",
"path",
"of",
"the",
"file",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L957-L971 |
15,089 | sloria/konch | konch.py | parse_args | def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__) | python | def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
"""Exposes the docopt command-line arguments parser.
Return a dictionary of arguments.
"""
return docopt(__doc__, argv=argv, version=__version__) | [
"def",
"parse_args",
"(",
"argv",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Sequence",
"]",
"=",
"None",
")",
"->",
"typing",
".",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"return",
"docopt",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
",... | Exposes the docopt command-line arguments parser.
Return a dictionary of arguments. | [
"Exposes",
"the",
"docopt",
"command",
"-",
"line",
"arguments",
"parser",
".",
"Return",
"a",
"dictionary",
"of",
"arguments",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1132-L1136 |
15,090 | sloria/konch | konch.py | main | def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
... | python | def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
"""Main entry point for the konch CLI."""
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(args)
... | [
"def",
"main",
"(",
"argv",
":",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Sequence",
"]",
"=",
"None",
")",
"->",
"typing",
".",
"NoReturn",
":",
"args",
"=",
"parse_args",
"(",
"argv",
")",
"if",
"args",
"[",
"\"--debug\"",
"]",
":",
"logging... | Main entry point for the konch CLI. | [
"Main",
"entry",
"point",
"for",
"the",
"konch",
"CLI",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L1139-L1184 |
15,091 | sloria/konch | konch.py | IPythonShell.init_autoreload | def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(... | python | def init_autoreload(mode: int) -> None:
"""Load and initialize the IPython autoreload extension."""
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(... | [
"def",
"init_autoreload",
"(",
"mode",
":",
"int",
")",
"->",
"None",
":",
"from",
"IPython",
".",
"extensions",
"import",
"autoreload",
"ip",
"=",
"get_ipython",
"(",
")",
"# type: ignore # noqa: F821",
"autoreload",
".",
"load_ipython_extension",
"(",
"ip",
")... | Load and initialize the IPython autoreload extension. | [
"Load",
"and",
"initialize",
"the",
"IPython",
"autoreload",
"extension",
"."
] | 15160bd0a0cac967eeeab84794bd6cdd0b5b637d | https://github.com/sloria/konch/blob/15160bd0a0cac967eeeab84794bd6cdd0b5b637d/konch.py#L427-L433 |
15,092 | JamesPHoughton/pysd | pysd/py_backend/vensim/table2py.py | read_tabular | def read_tabular(table_file, sheetname='Sheet1'):
"""
Reads a vensim syntax model which has been formatted as a table.
This is useful in contexts where model building is performed
without the aid of Vensim.
Parameters
----------
table_file: .csv, .tab or .xls(x) file
Table should have... | python | def read_tabular(table_file, sheetname='Sheet1'):
"""
Reads a vensim syntax model which has been formatted as a table.
This is useful in contexts where model building is performed
without the aid of Vensim.
Parameters
----------
table_file: .csv, .tab or .xls(x) file
Table should have... | [
"def",
"read_tabular",
"(",
"table_file",
",",
"sheetname",
"=",
"'Sheet1'",
")",
":",
"if",
"isinstance",
"(",
"table_file",
",",
"str",
")",
":",
"extension",
"=",
"table_file",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if",
"extension",
"i... | Reads a vensim syntax model which has been formatted as a table.
This is useful in contexts where model building is performed
without the aid of Vensim.
Parameters
----------
table_file: .csv, .tab or .xls(x) file
Table should have columns titled as in the table below
| Variable | Equat... | [
"Reads",
"a",
"vensim",
"syntax",
"model",
"which",
"has",
"been",
"formatted",
"as",
"a",
"table",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/vensim/table2py.py#L6-L80 |
15,093 | JamesPHoughton/pysd | pysd/pysd.py | read_xmile | def read_xmile(xmile_file):
""" Construct a model object from `.xmile` file. """
from . import py_backend
from .py_backend.xmile.xmile2py import translate_xmile
py_model_file = translate_xmile(xmile_file)
model = load(py_model_file)
model.xmile_file = xmile_file
return model | python | def read_xmile(xmile_file):
""" Construct a model object from `.xmile` file. """
from . import py_backend
from .py_backend.xmile.xmile2py import translate_xmile
py_model_file = translate_xmile(xmile_file)
model = load(py_model_file)
model.xmile_file = xmile_file
return model | [
"def",
"read_xmile",
"(",
"xmile_file",
")",
":",
"from",
".",
"import",
"py_backend",
"from",
".",
"py_backend",
".",
"xmile",
".",
"xmile2py",
"import",
"translate_xmile",
"py_model_file",
"=",
"translate_xmile",
"(",
"xmile_file",
")",
"model",
"=",
"load",
... | Construct a model object from `.xmile` file. | [
"Construct",
"a",
"model",
"object",
"from",
".",
"xmile",
"file",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/pysd.py#L16-L23 |
15,094 | JamesPHoughton/pysd | pysd/pysd.py | read_vensim | def read_vensim(mdl_file):
"""
Construct a model from Vensim `.mdl` file.
Parameters
----------
mdl_file : <string>
The relative path filename for a raw Vensim `.mdl` file
Returns
-------
model: a PySD class object
Elements from the python model are loaded into the PySD... | python | def read_vensim(mdl_file):
"""
Construct a model from Vensim `.mdl` file.
Parameters
----------
mdl_file : <string>
The relative path filename for a raw Vensim `.mdl` file
Returns
-------
model: a PySD class object
Elements from the python model are loaded into the PySD... | [
"def",
"read_vensim",
"(",
"mdl_file",
")",
":",
"from",
".",
"py_backend",
".",
"vensim",
".",
"vensim2py",
"import",
"translate_vensim",
"from",
".",
"py_backend",
"import",
"functions",
"py_model_file",
"=",
"translate_vensim",
"(",
"mdl_file",
")",
"model",
... | Construct a model from Vensim `.mdl` file.
Parameters
----------
mdl_file : <string>
The relative path filename for a raw Vensim `.mdl` file
Returns
-------
model: a PySD class object
Elements from the python model are loaded into the PySD class and ready to run
Examples
... | [
"Construct",
"a",
"model",
"from",
"Vensim",
".",
"mdl",
"file",
"."
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/pysd.py#L25-L49 |
15,095 | JamesPHoughton/pysd | pysd/py_backend/functions.py | cache | def cache(horizon):
"""
Put a wrapper around a model function
Decorators with parameters are tricky, you have to
essentially create a decorator that returns a decorator,
which itself then returns the function wrapper.
Parameters
----------
horizon: string
- 'step' means cache j... | python | def cache(horizon):
"""
Put a wrapper around a model function
Decorators with parameters are tricky, you have to
essentially create a decorator that returns a decorator,
which itself then returns the function wrapper.
Parameters
----------
horizon: string
- 'step' means cache j... | [
"def",
"cache",
"(",
"horizon",
")",
":",
"def",
"cache_step",
"(",
"func",
")",
":",
"\"\"\" Decorator for caching at a step level\"\"\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"cached",
"(",
"*",
"args",
")",
":",
"\"\"\"Step wise cache function\"\"\"",
"try",
... | Put a wrapper around a model function
Decorators with parameters are tricky, you have to
essentially create a decorator that returns a decorator,
which itself then returns the function wrapper.
Parameters
----------
horizon: string
- 'step' means cache just until the next timestep
... | [
"Put",
"a",
"wrapper",
"around",
"a",
"model",
"function"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L44-L105 |
15,096 | JamesPHoughton/pysd | pysd/py_backend/functions.py | ramp | def ramp(time, slope, start, finish=0):
"""
Implements vensim's and xmile's RAMP function
Parameters
----------
time: function
The current time of modelling
slope: float
The slope of the ramp starting at zero at time start
start: float
Time at which the ramp begins
... | python | def ramp(time, slope, start, finish=0):
"""
Implements vensim's and xmile's RAMP function
Parameters
----------
time: function
The current time of modelling
slope: float
The slope of the ramp starting at zero at time start
start: float
Time at which the ramp begins
... | [
"def",
"ramp",
"(",
"time",
",",
"slope",
",",
"start",
",",
"finish",
"=",
"0",
")",
":",
"t",
"=",
"time",
"(",
")",
"if",
"t",
"<",
"start",
":",
"return",
"0",
"else",
":",
"if",
"finish",
"<=",
"0",
":",
"return",
"slope",
"*",
"(",
"t",... | Implements vensim's and xmile's RAMP function
Parameters
----------
time: function
The current time of modelling
slope: float
The slope of the ramp starting at zero at time start
start: float
Time at which the ramp begins
finish: float
Optional. Time at which the... | [
"Implements",
"vensim",
"s",
"and",
"xmile",
"s",
"RAMP",
"function"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L803-L837 |
15,097 | JamesPHoughton/pysd | pysd/py_backend/functions.py | pulse | def pulse(time, start, duration):
""" Implements vensim's PULSE function
In range [-inf, start) returns 0
In range [start, start + duration) returns 1
In range [start + duration, +inf] returns 0
"""
t = time()
return 1 if start <= t < start + duration else 0 | python | def pulse(time, start, duration):
""" Implements vensim's PULSE function
In range [-inf, start) returns 0
In range [start, start + duration) returns 1
In range [start + duration, +inf] returns 0
"""
t = time()
return 1 if start <= t < start + duration else 0 | [
"def",
"pulse",
"(",
"time",
",",
"start",
",",
"duration",
")",
":",
"t",
"=",
"time",
"(",
")",
"return",
"1",
"if",
"start",
"<=",
"t",
"<",
"start",
"+",
"duration",
"else",
"0"
] | Implements vensim's PULSE function
In range [-inf, start) returns 0
In range [start, start + duration) returns 1
In range [start + duration, +inf] returns 0 | [
"Implements",
"vensim",
"s",
"PULSE",
"function"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L859-L867 |
15,098 | JamesPHoughton/pysd | pysd/py_backend/functions.py | pulse_train | def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... | python | def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... | [
"def",
"pulse_train",
"(",
"time",
",",
"start",
",",
"duration",
",",
"repeat_time",
",",
"end",
")",
":",
"t",
"=",
"time",
"(",
")",
"if",
"start",
"<=",
"t",
"<",
"end",
":",
"return",
"1",
"if",
"(",
"t",
"-",
"start",
")",
"%",
"repeat_time... | Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0 | [
"Implements",
"vensim",
"s",
"PULSE",
"TRAIN",
"function"
] | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L870-L881 |
15,099 | JamesPHoughton/pysd | pysd/py_backend/functions.py | lookup_extrapolation | def lookup_extrapolation(x, xs, ys):
"""
Intermediate values are calculated with linear interpolation between the intermediate points.
Out-of-range values are calculated with linear extrapolation from the last two values at either end.
"""
length = len(xs)
if x < xs[0]:
dx = xs[1] - xs[0... | python | def lookup_extrapolation(x, xs, ys):
"""
Intermediate values are calculated with linear interpolation between the intermediate points.
Out-of-range values are calculated with linear extrapolation from the last two values at either end.
"""
length = len(xs)
if x < xs[0]:
dx = xs[1] - xs[0... | [
"def",
"lookup_extrapolation",
"(",
"x",
",",
"xs",
",",
"ys",
")",
":",
"length",
"=",
"len",
"(",
"xs",
")",
"if",
"x",
"<",
"xs",
"[",
"0",
"]",
":",
"dx",
"=",
"xs",
"[",
"1",
"]",
"-",
"xs",
"[",
"0",
"]",
"dy",
"=",
"ys",
"[",
"1",
... | Intermediate values are calculated with linear interpolation between the intermediate points.
Out-of-range values are calculated with linear extrapolation from the last two values at either end. | [
"Intermediate",
"values",
"are",
"calculated",
"with",
"linear",
"interpolation",
"between",
"the",
"intermediate",
"points",
".",
"Out",
"-",
"of",
"-",
"range",
"values",
"are",
"calculated",
"with",
"linear",
"extrapolation",
"from",
"the",
"last",
"two",
"va... | bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L917-L933 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.