Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
DataObjectStack._deconstruct
(self)
Retain the source objects instead of the direct elements.
Retain the source objects instead of the direct elements.
def _deconstruct(self) -> None: """Retain the source objects instead of the direct elements.""" self._virtual = True sources = [element.source for element in self._elements] if None in sources: raise ValueError("Can't virtualize stack without source information.") sel...
[ "def", "_deconstruct", "(", "self", ")", "->", "None", ":", "self", ".", "_virtual", "=", "True", "sources", "=", "[", "element", ".", "source", "for", "element", "in", "self", ".", "_elements", "]", "if", "None", "in", "sources", ":", "raise", "ValueE...
[ 373, 4 ]
[ 379, 32 ]
python
en
['en', 'en', 'en']
True
DataObjectStack._single_construct
(self, source: Any)
Construct a single DataObject.
Construct a single DataObject.
def _single_construct(self, source: Any) -> DataObject: """Construct a single DataObject.""" return self._type(source)
[ "def", "_single_construct", "(", "self", ",", "source", ":", "Any", ")", "->", "DataObject", ":", "return", "self", ".", "_type", "(", "source", ")" ]
[ 381, 4 ]
[ 383, 33 ]
python
en
['en', 'en', 'en']
True
DataObjectStack.virtual
(self)
If a data stack is virtual, it does only load the data on demand.
If a data stack is virtual, it does only load the data on demand.
def virtual(self) -> bool: """If a data stack is virtual, it does only load the data on demand.""" return self._virtual
[ "def", "virtual", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_virtual" ]
[ 398, 4 ]
[ 400, 28 ]
python
en
['en', 'en', 'en']
True
DataObjectStack.copy
(self, virtual: Optional[bool] = None)
Returns a deepcopy.
Returns a deepcopy.
def copy(self, virtual: Optional[bool] = None): """Returns a deepcopy.""" other = copy.deepcopy(self) if virtual is not None: other.virtual = virtual return other
[ "def", "copy", "(", "self", ",", "virtual", ":", "Optional", "[", "bool", "]", "=", "None", ")", ":", "other", "=", "copy", ".", "deepcopy", "(", "self", ")", "if", "virtual", "is", "not", "None", ":", "other", ".", "virtual", "=", "virtual", "retu...
[ 412, 4 ]
[ 417, 20 ]
python
en
['es', 'pt', 'en']
False
DataObjectStack.extend
(self, other: Union[DataObject, Iterable])
Add new DataObjects to the end of the stack.
Add new DataObjects to the end of the stack.
def extend(self, other: Union[DataObject, Iterable]) -> None: """Add new DataObjects to the end of the stack.""" if isinstance(other, DataObject): elements = [other] if isinstance(other, type(self)): if not self.virtual: elements = other[:] eli...
[ "def", "extend", "(", "self", ",", "other", ":", "Union", "[", "DataObject", ",", "Iterable", "]", ")", "->", "None", ":", "if", "isinstance", "(", "other", ",", "DataObject", ")", ":", "elements", "=", "[", "other", "]", "if", "isinstance", "(", "ot...
[ 465, 4 ]
[ 484, 39 ]
python
en
['en', 'en', 'en']
True
Image.mask
(self)
Set a mask onto the image. TODO
Set a mask onto the image. TODO
def mask(self) -> np.ndarray: """Set a mask onto the image. TODO""" return self._mask
[ "def", "mask", "(", "self", ")", "->", "np", ".", "ndarray", ":", "return", "self", ".", "_mask" ]
[ 640, 4 ]
[ 642, 25 ]
python
en
['en', 'en', 'en']
True
ImageStack.average
(self, avg: int)
Averages over consecutive images in a stack. Parameters ---------- avg : int Number of consecutive image that will be averaged. The total number of images must be dividable by *avg*. Returns ------- ImageStack Stack with averaged imag...
Averages over consecutive images in a stack.
def average(self, avg: int) -> ImageStack: """Averages over consecutive images in a stack. Parameters ---------- avg : int Number of consecutive image that will be averaged. The total number of images must be dividable by *avg*. Returns ------- ...
[ "def", "average", "(", "self", ",", "avg", ":", "int", ")", "->", "ImageStack", ":", "if", "len", "(", "self", ")", "%", "avg", "!=", "0", ":", "raise", "ValueError", "(", "f\"Number of Images in Stack ({len(self)}) is not dividable by {avg}\"", ")", "imgs", "...
[ 767, 4 ]
[ 808, 31 ]
python
en
['en', 'en', 'en']
True
Line.length
(self)
Length of the x and y data.
Length of the x and y data.
def length(self) -> int: """Length of the x and y data.""" return len(self.x)
[ "def", "length", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "x", ")" ]
[ 949, 4 ]
[ 951, 26 ]
python
en
['en', 'en', 'en']
True
Line.area
(self)
Area under the line integrated by simpson rule
Area under the line integrated by simpson rule
def area(self) -> float: "Area under the line integrated by simpson rule" return scipy.integrate.simpson(self.y, self.x)
[ "def", "area", "(", "self", ")", "->", "float", ":", "return", "scipy", ".", "integrate", ".", "simpson", "(", "self", ".", "y", ",", "self", ".", "x", ")" ]
[ 954, 4 ]
[ 956, 54 ]
python
en
['en', 'en', 'en']
True
Line.dataframe
(self)
Pandas Dataframe of the lines x,y data
Pandas Dataframe of the lines x,y data
def dataframe(self) -> pd.DataFrame: """Pandas Dataframe of the lines x,y data""" return pd.DataFrame( data=np.stack([self.x, self.y], axis=1), columns=[ f"{self.xdim} in {self._units['x']}", f"{self.ydim} in {self._units['y']}", ], ...
[ "def", "dataframe", "(", "self", ")", "->", "pd", ".", "DataFrame", ":", "return", "pd", ".", "DataFrame", "(", "data", "=", "np", ".", "stack", "(", "[", "self", ".", "x", ",", "self", ".", "y", "]", ",", "axis", "=", "1", ")", ",", "columns",...
[ 959, 4 ]
[ 967, 9 ]
python
en
['en', 'en', 'en']
True
Line.interpolate
( self, x_data: Union[Number, list[Number], np.ndarray, None] = None, order: Union[str, int] = "cubic", **kwargs, )
Interpolates the x,y data of the Line with a spline of order 'order' Parameters ---------- x_data: Number, list of numbers or 1d numpy array or None x_values at which the interpolation will be evaluated order: str or int When a string must be either "lin...
Interpolates the x,y data of the Line with a spline of order 'order'
def interpolate( self, x_data: Union[Number, list[Number], np.ndarray, None] = None, order: Union[str, int] = "cubic", **kwargs, ) -> Union[np.ndarray, Callable]: """ Interpolates the x,y data of the Line with a spline of order 'order' Parameters ---...
[ "def", "interpolate", "(", "self", ",", "x_data", ":", "Union", "[", "Number", ",", "list", "[", "Number", "]", ",", "np", ".", "ndarray", ",", "None", "]", "=", "None", ",", "order", ":", "Union", "[", "str", ",", "int", "]", "=", "\"cubic\"", "...
[ 969, 4 ]
[ 1007, 27 ]
python
en
['en', 'error', 'th']
False
Line.integral
(self)
Returns the integrated values of a cubic spline evaluated at the x values of the line
Returns the integrated values of a cubic spline evaluated at the x values of the line
def integral(self) -> Line: """Returns the integrated values of a cubic spline evaluated at the x values of the line""" func = self.interpolate() y = np.array([func.integral(self.x[0], x) for x in self.x]) return Line(np.array([self.x, y]))
[ "def", "integral", "(", "self", ")", "->", "Line", ":", "func", "=", "self", ".", "interpolate", "(", ")", "y", "=", "np", ".", "array", "(", "[", "func", ".", "integral", "(", "self", ".", "x", "[", "0", "]", ",", "x", ")", "for", "x", "in",...
[ 1009, 4 ]
[ 1013, 42 ]
python
en
['en', 'en', 'en']
True
Line.derivative
(self)
Returns the derivative of a cubic spline evaluated at the x values of the line
Returns the derivative of a cubic spline evaluated at the x values of the line
def derivative(self) -> Line: """Returns the derivative of a cubic spline evaluated at the x values of the line""" func = self.interpolate() y = np.array([func.derivative()(x) for x in self.x[1:]]) return Line(np.array([self.x[1:], y]))
[ "def", "derivative", "(", "self", ")", "->", "Line", ":", "func", "=", "self", ".", "interpolate", "(", ")", "y", "=", "np", ".", "array", "(", "[", "func", ".", "derivative", "(", ")", "(", "x", ")", "for", "x", "in", "self", ".", "x", "[", ...
[ 1015, 4 ]
[ 1019, 46 ]
python
en
['en', 'en', 'en']
True
Line.smooth
(self, kernel: Union[int, np.ndarray])
Recieves a kernel and convolves the values of the line Parameters ---------- kernel : np.ndarray, int Kernel that will be convolved with the line data. If ``int`` an equaly distributed kernel of size ``kernel`` will be applied. Returns ------- ...
Recieves a kernel and convolves the values of the line
def smooth(self, kernel: Union[int, np.ndarray]) -> Line: """ Recieves a kernel and convolves the values of the line Parameters ---------- kernel : np.ndarray, int Kernel that will be convolved with the line data. If ``int`` an equaly distributed kernel o...
[ "def", "smooth", "(", "self", ",", "kernel", ":", "Union", "[", "int", ",", "np", ".", "ndarray", "]", ")", "->", "Line", ":", "if", "isinstance", "(", "kernel", ",", "int", ")", ":", "kernel", "=", "np", ".", "ones", "(", "kernel", ")", "/", "...
[ 1021, 4 ]
[ 1060, 19 ]
python
en
['en', 'error', 'th']
False
Line.save
(self, fname: str)
Saves the line as .csv Parameters ---------- fname: str Filename of the file to save. If it ends with .csv a csv file of the dataframe representation of the line is saved Otherwise the parent(dataobject) save method is called. Returns ...
Saves the line as .csv
def save(self, fname: str) -> None: """ Saves the line as .csv Parameters ---------- fname: str Filename of the file to save. If it ends with .csv a csv file of the dataframe representation of the line is saved Otherwise the parent(dataobject)...
[ "def", "save", "(", "self", ",", "fname", ":", "str", ")", "->", "None", ":", "if", "fname", ".", "lower", "(", ")", ".", "endswith", "(", "\".csv\"", ")", ":", "self", ".", "dataframe", ".", "to_csv", "(", "fname", ",", "index", "=", "False", ",...
[ 1062, 4 ]
[ 1080, 31 ]
python
en
['en', 'error', 'th']
False
IntensityLine.__init__
(self, stack: ImageStack, roi_: roi.ROI, xaxis: str)
Parameters ---------- stack : ImageStack ImageStack from which the intensities will be extracted roi_ : roi.ROI ROI from within the intensities will be extracted in each image, xaxis : str a string indicates the axis of the dimension along the...
Parameters ---------- stack : ImageStack ImageStack from which the intensities will be extracted roi_ : roi.ROI ROI from within the intensities will be extracted in each image, xaxis : str a string indicates the axis of the dimension along the...
def __init__(self, stack: ImageStack, roi_: roi.ROI, xaxis: str) -> None: """ Parameters ---------- stack : ImageStack ImageStack from which the intensities will be extracted roi_ : roi.ROI ROI from within the intensities will be extracted in each image, ...
[ "def", "__init__", "(", "self", ",", "stack", ":", "ImageStack", ",", "roi_", ":", "roi", ".", "ROI", ",", "xaxis", ":", "str", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "(", "stack", ",", "roi_", ",", "xaxis", ")", ")" ]
[ 1177, 4 ]
[ 1189, 46 ]
python
en
['en', 'error', 'th']
False
IntensityLine.parse
(self, source: tuple[ImageStack, roi.ROI, str])
Applies a ROI to an Imagestack and extracts mean of ROI from each image Parameters ---------- source : tuple[ImageStack, roi.ROI, str] Must be a Tuple of 1. an ImageStack from which the intensities will be extracted, 2. a ROI from within the intensities will...
Applies a ROI to an Imagestack and extracts mean of ROI from each image
def parse(self, source: tuple[ImageStack, roi.ROI, str]) -> dict[str, Any]: """Applies a ROI to an Imagestack and extracts mean of ROI from each image Parameters ---------- source : tuple[ImageStack, roi.ROI, str] Must be a Tuple of 1. an ImageStack from which t...
[ "def", "parse", "(", "self", ",", "source", ":", "tuple", "[", "ImageStack", ",", "roi", ".", "ROI", ",", "str", "]", ")", "->", "dict", "[", "str", ",", "Any", "]", ":", "stack", ",", "roi_", ",", "xaxis", "=", "source", "self", ".", "_source", ...
[ 1191, 4 ]
[ 1229, 9 ]
python
en
['en', 'en', 'en']
True
StitchedLine.__init__
( self, stacks: Union[Sequence[ImageStack], ImageStack], rois: Union[Sequence[roi.ROI], roi.ROI], xaxis: str, )
Parameters ---------- stacks : Sequence[ImageStack] or ImageStack ImageStacks, which will be used for Line extraction rois : Sequence[roi.ROI] or roi.ROI ROIs used for Line extraction. Must be of the same length as ``stacks``. If stacks is a single st...
Parameters ---------- stacks : Sequence[ImageStack] or ImageStack ImageStacks, which will be used for Line extraction rois : Sequence[roi.ROI] or roi.ROI ROIs used for Line extraction. Must be of the same length as ``stacks``. If stacks is a single st...
def __init__( self, stacks: Union[Sequence[ImageStack], ImageStack], rois: Union[Sequence[roi.ROI], roi.ROI], xaxis: str, ) -> None: """ Parameters ---------- stacks : Sequence[ImageStack] or ImageStack ImageStacks, which will be used for L...
[ "def", "__init__", "(", "self", ",", "stacks", ":", "Union", "[", "Sequence", "[", "ImageStack", "]", ",", "ImageStack", "]", ",", "rois", ":", "Union", "[", "Sequence", "[", "roi", ".", "ROI", "]", ",", "roi", ".", "ROI", "]", ",", "xaxis", ":", ...
[ 1252, 4 ]
[ 1279, 47 ]
python
en
['en', 'error', 'th']
False
StitchedLine.parse
(self, source: Sequence[Sequence, Sequence, str])
Extract IntensityLines from Stacks and handle their stitching. Parameters ---------- source : Sequence[Sequence, Sequence, str] List or tuple containing 1. A list or tuple of ImageStacks 2. A list or tuple of ROIs with the same length as the tuple of ImageSt...
Extract IntensityLines from Stacks and handle their stitching.
def parse(self, source: Sequence[Sequence, Sequence, str]) -> dict[str, Any]: """Extract IntensityLines from Stacks and handle their stitching. Parameters ---------- source : Sequence[Sequence, Sequence, str] List or tuple containing 1. A list or tuple of ImageS...
[ "def", "parse", "(", "self", ",", "source", ":", "Sequence", "[", "Sequence", ",", "Sequence", ",", "str", "]", ")", "->", "dict", "[", "str", ",", "Any", "]", ":", "stacks", ",", "rois", ",", "xaxis", "=", "source", "if", "len", "(", "stacks", "...
[ 1281, 4 ]
[ 1330, 9 ]
python
en
['en', 'en', 'en']
True
StitchedLine._stitch_curves
( self, lines: Sequence[IntensityLine] )
Combine x,y values to mulitple lines to one pair of x,y values Parameters ---------- lines : Sequence[IntensityLine] List or tuple of Lines to be stitched together Returns ------- tuple[np.ndarray, np.ndarray] tuple containing the x and y values ...
Combine x,y values to mulitple lines to one pair of x,y values
def _stitch_curves( self, lines: Sequence[IntensityLine] ) -> tuple[np.ndarray, np.ndarray]: """Combine x,y values to mulitple lines to one pair of x,y values Parameters ---------- lines : Sequence[IntensityLine] List or tuple of Lines to be stitched together ...
[ "def", "_stitch_curves", "(", "self", ",", "lines", ":", "Sequence", "[", "IntensityLine", "]", ")", "->", "tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "coeffs", "=", "[", "1", "]", "for", "curr_line", ",", "next_line", "i...
[ 1332, 4 ]
[ 1394, 19 ]
python
en
['en', 'en', 'en']
True
parse_header
(fname, debug=False)
Uncomment the print statements here and in _parse_string_until_null() for easier debugging.
Uncomment the print statements here and in _parse_string_until_null() for easier debugging.
def parse_header(fname, debug=False): """Uncomment the print statements here and in _parse_string_until_null() for easier debugging.""" meta = {} meta_units = {} def parse_block(block, field_dict): for key, (pos, encoding) in field_dict.items(): meta[key] = _parse_bytes(block, po...
[ "def", "parse_header", "(", "fname", ",", "debug", "=", "False", ")", ":", "meta", "=", "{", "}", "meta_units", "=", "{", "}", "def", "parse_block", "(", "block", ",", "field_dict", ")", ":", "for", "key", ",", "(", "pos", ",", "encoding", ")", "in...
[ 704, 0 ]
[ 765, 27 ]
python
en
['en', 'en', 'en']
True
Loadable.__setstate__
(self, state)
Make sure that the path is inserted first.
Make sure that the path is inserted first.
def __setstate__(self, state): """Make sure that the path is inserted first.""" try: ## Is try/except really neccessary? self.path = state.pop("path") except: pass if "fnames" in state: self.fnames = state.pop("fnames") self.__dict__.update(sta...
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "try", ":", "## Is try/except really neccessary?", "self", ".", "path", "=", "state", ".", "pop", "(", "\"path\"", ")", "except", ":", "pass", "if", "\"fnames\"", "in", "state", ":", "self", ".", ...
[ 30, 4 ]
[ 38, 35 ]
python
en
['en', 'en', 'en']
True
LEEMImg.parse_nondat
(self, path)
Use this for other formats than pickle (which is already implemented by Loadable).
Use this for other formats than pickle (which is already implemented by Loadable).
def parse_nondat(self, path): """Use this for other formats than pickle (which is already implemented by Loadable).""" try: data = np.float32(imread(path)) except IOError: # if the object given already is a numpy array: data = path path = "...
[ "def", "parse_nondat", "(", "self", ",", "path", ")", ":", "try", ":", "data", "=", "np", ".", "float32", "(", "imread", "(", "path", ")", ")", "except", "IOError", ":", "# if the object given already is a numpy array:", "data", "=", "path", "path", "=", "...
[ 175, 4 ]
[ 193, 29 ]
python
en
['en', 'en', 'en']
True
LEEMImg.meta
(self)
Dictionary containing all header attributes.
Dictionary containing all header attributes.
def meta(self): """Dictionary containing all header attributes.""" if self._meta is None: self._meta, self._meta_units = parse_header(self.path) return self._meta
[ "def", "meta", "(", "self", ")", ":", "if", "self", ".", "_meta", "is", "None", ":", "self", ".", "_meta", ",", "self", ".", "_meta_units", "=", "parse_header", "(", "self", ".", "path", ")", "return", "self", ".", "_meta" ]
[ 271, 4 ]
[ 275, 25 ]
python
en
['en', 'en', 'en']
True
LEEMImg.meta_units
(self)
Dictionary containing all header attribute units.
Dictionary containing all header attribute units.
def meta_units(self): """Dictionary containing all header attribute units.""" if self._meta_units is None: self._meta, self._meta_units = parse_header(self.path) return self._meta_units
[ "def", "meta_units", "(", "self", ")", ":", "if", "self", ".", "_meta_units", "is", "None", ":", "self", ".", "_meta", ",", "self", ".", "_meta_units", "=", "parse_header", "(", "self", ".", "path", ")", "return", "self", ".", "_meta_units" ]
[ 278, 4 ]
[ 282, 31 ]
python
en
['en', 'en', 'en']
True
LEEMImg.data
(self)
Numpy array containing the image data.
Numpy array containing the image data.
def data(self): """Numpy array containing the image data.""" if self._data is None: self._data = parse_data(self.path) return self._data
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_data", "=", "parse_data", "(", "self", ".", "path", ")", "return", "self", ".", "_data" ]
[ 295, 4 ]
[ 299, 25 ]
python
en
['en', 'en', 'en']
True
LEEMImg.get_unit
(self, field)
Unit string for the specified field.
Unit string for the specified field.
def get_unit(self, field): """Unit string for the specified field.""" try: return self.meta_units[self.attrs[field]] except KeyError: if hasattr(self, field) or self.attrs[field] in self.meta: return self._fallback_units.get(field, "") return "...
[ "def", "get_unit", "(", "self", ",", "field", ")", ":", "try", ":", "return", "self", ".", "meta_units", "[", "self", ".", "attrs", "[", "field", "]", "]", "except", "KeyError", ":", "if", "hasattr", "(", "self", ",", "field", ")", "or", "self", "....
[ 306, 4 ]
[ 313, 21 ]
python
en
['en', 'en', 'en']
True
LEEMImg.get_field_string
(self, field)
Returns a string with the field value and unit.
Returns a string with the field value and unit.
def get_field_string(self, field): """Returns a string with the field value and unit.""" value = getattr(self, field) if value == np.nan: return "NaN" if field == "rel_time": return f"{value:5.0f} {self.get_unit(field)}" if field == "energy": r...
[ "def", "get_field_string", "(", "self", ",", "field", ")", ":", "value", "=", "getattr", "(", "self", ",", "field", ")", "if", "value", "==", "np", ".", "nan", ":", "return", "\"NaN\"", "if", "field", "==", "\"rel_time\"", ":", "return", "f\"{value:5.0f}...
[ 315, 4 ]
[ 330, 60 ]
python
en
['en', 'en', 'en']
True
LEEMImg.rel_time
(self)
Relative time in s (see set_time_origin()). Only makes sense for a stack.
Relative time in s (see set_time_origin()). Only makes sense for a stack.
def rel_time(self): """Relative time in s (see set_time_origin()). Only makes sense for a stack.""" return self.timestamp - self.time_origin
[ "def", "rel_time", "(", "self", ")", ":", "return", "self", ".", "timestamp", "-", "self", ".", "time_origin" ]
[ 345, 4 ]
[ 347, 48 ]
python
en
['en', 'en', 'en']
True
LEEMImg.fov
(self)
Either a positive number in µm, 0 for LEED, or NaN for unknown FoV.
Either a positive number in µm, 0 for LEED, or NaN for unknown FoV.
def fov(self): """Either a positive number in µm, 0 for LEED, or NaN for unknown FoV.""" fov_str = self.meta.get("FoV", "") if "LEED" in fov_str: return 0 try: return float(fov_str.split("µ")[0]) except ValueError: # when the string does not contain a...
[ "def", "fov", "(", "self", ")", ":", "fov_str", "=", "self", ".", "meta", ".", "get", "(", "\"FoV\"", ",", "\"\"", ")", "if", "\"LEED\"", "in", "fov_str", ":", "return", "0", "try", ":", "return", "float", "(", "fov_str", ".", "split", "(", "\"µ\")...
[ 350, 4 ]
[ 358, 25 ]
python
en
['en', 'en', 'en']
True
LEEMImg.averaging
(self)
Number of images that are averaged. 0 means sliding average.
Number of images that are averaged. 0 means sliding average.
def averaging(self): """Number of images that are averaged. 0 means sliding average.""" avg = self.meta.get("Average Images", np.nan) if avg == 255: return 0 elif avg == 0: return 1 return avg
[ "def", "averaging", "(", "self", ")", ":", "avg", "=", "self", ".", "meta", ".", "get", "(", "\"Average Images\"", ",", "np", ".", "nan", ")", "if", "avg", "==", "255", ":", "return", "0", "elif", "avg", "==", "0", ":", "return", "1", "return", "...
[ 361, 4 ]
[ 368, 18 ]
python
en
['en', 'en', 'en']
True
LEEMStack.parse_nondat
(self, path)
Use this for other formats than pickle (which is already implemented by Loadable).
Use this for other formats than pickle (which is already implemented by Loadable).
def parse_nondat(self, path): """Use this for other formats than pickle (which is already implemented by Loadable).""" try: data = np.float32(imread(path)) except IOError: # if the object given already is a numpy array: data = path path = "...
[ "def", "parse_nondat", "(", "self", ",", "path", ")", ":", "try", ":", "data", "=", "np", ".", "float32", "(", "imread", "(", "path", ")", ")", "except", "IOError", ":", "# if the object given already is a numpy array:", "data", "=", "path", "path", "=", "...
[ 433, 4 ]
[ 446, 49 ]
python
en
['en', 'en', 'en']
True
_linalgRealType
(t)
Cast the type t to either double or cdouble.
Cast the type t to either double or cdouble.
def _linalgRealType(t): """Cast the type t to either double or cdouble.""" return double
[ "def", "_linalgRealType", "(", "t", ")", ":", "return", "double" ]
[ 139, 0 ]
[ 141, 17 ]
python
en
['en', 'en', 'en']
True
transpose
(a)
Transpose each matrix in a stack of matrices. Unlike np.transpose, this only swaps the last two axes, rather than all of them Parameters ---------- a : (...,M,N) array_like Returns ------- aT : (...,N,M) ndarray
Transpose each matrix in a stack of matrices.
def transpose(a): """ Transpose each matrix in a stack of matrices. Unlike np.transpose, this only swaps the last two axes, rather than all of them Parameters ---------- a : (...,M,N) array_like Returns ------- aT : (...,N,M) ndarray """ return swapaxes(a, -1, -2)
[ "def", "transpose", "(", "a", ")", ":", "return", "swapaxes", "(", "a", ",", "-", "1", ",", "-", "2", ")" ]
[ 228, 0 ]
[ 243, 30 ]
python
en
['en', 'error', 'th']
False
tensorsolve
(a, b, axes=None)
Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=b.ndim)``. Parameters ---------- a : array_like Coefficient tensor, of ...
Solve the tensor equation ``a x = b`` for x.
def tensorsolve(a, b, axes=None): """ Solve the tensor equation ``a x = b`` for x. It is assumed that all indices of `x` are summed over in the product, together with the rightmost indices of `a`, as is done in, for example, ``tensordot(a, x, axes=b.ndim)``. Parameters ---------- a : a...
[ "def", "tensorsolve", "(", "a", ",", "b", ",", "axes", "=", "None", ")", ":", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "b", "=", "asarray", "(", "b", ")", "an", "=", "a", ".", "ndim", "if", "axes", "is", "not", "None", ":", "allaxe...
[ 252, 0 ]
[ 319, 14 ]
python
en
['en', 'error', 'th']
False
solve
(a, b)
Solve a linear matrix equation, or system of linear scalar equations. Computes the "exact" solution, `x`, of the well-determined, i.e., full rank, linear matrix equation `ax = b`. Parameters ---------- a : (..., M, M) array_like Coefficient matrix. b : {(..., M,), (..., M, K)}, ar...
Solve a linear matrix equation, or system of linear scalar equations.
def solve(a, b): """ Solve a linear matrix equation, or system of linear scalar equations. Computes the "exact" solution, `x`, of the well-determined, i.e., full rank, linear matrix equation `ax = b`. Parameters ---------- a : (..., M, M) array_like Coefficient matrix. b : {(.....
[ "def", "solve", "(", "a", ",", "b", ")", ":", "a", ",", "_", "=", "_makearray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "b", ",", "wrap", "=", "_makearray", "(", "b", ")", "t", ",", "result_t", "...
[ 327, 0 ]
[ 404, 47 ]
python
en
['en', 'error', 'th']
False
tensorinv
(a, ind=2)
Compute the 'inverse' of an N-dimensional array. The result is an inverse for `a` relative to the tensordot operation ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy, ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the tensordot operation. Parameters ------...
Compute the 'inverse' of an N-dimensional array.
def tensorinv(a, ind=2): """ Compute the 'inverse' of an N-dimensional array. The result is an inverse for `a` relative to the tensordot operation ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy, ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the tensordot opera...
[ "def", "tensorinv", "(", "a", ",", "ind", "=", "2", ")", ":", "a", "=", "asarray", "(", "a", ")", "oldshape", "=", "a", ".", "shape", "prod", "=", "1", "if", "ind", ">", "0", ":", "invshape", "=", "oldshape", "[", "ind", ":", "]", "+", "oldsh...
[ 412, 0 ]
[ 476, 32 ]
python
en
['en', 'error', 'th']
False
inv
(a)
Compute the (multiplicative) inverse of a matrix. Given a square matrix `a`, return the matrix `ainv` satisfying ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``. Parameters ---------- a : (..., M, M) array_like Matrix to be inverted. Returns ------- ainv : (..., M, M) n...
Compute the (multiplicative) inverse of a matrix.
def inv(a): """ Compute the (multiplicative) inverse of a matrix. Given a square matrix `a`, return the matrix `ainv` satisfying ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``. Parameters ---------- a : (..., M, M) array_like Matrix to be inverted. Returns ------- a...
[ "def", "inv", "(", "a", ")", ":", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "t", ",", "result_t", "=", "_commonType", "(", "a", ")", "signature", "=", "'D->D'", "if...
[ 486, 0 ]
[ 551, 50 ]
python
en
['en', 'error', 'th']
False
matrix_power
(a, n)
Raise a square matrix to the (integer) power `n`. For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed and then raised to the ``abs(n)``...
Raise a square matrix to the (integer) power `n`.
def matrix_power(a, n): """ Raise a square matrix to the (integer) power `n`. For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed an...
[ "def", "matrix_power", "(", "a", ",", "n", ")", ":", "a", "=", "asanyarray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "try", ":", "n", "=", "operator", ".", "index", "(", "n", ")", "except", "TypeErro...
[ 559, 0 ]
[ 671, 17 ]
python
en
['en', 'error', 'th']
False
cholesky
(a)
Cholesky decomposition. Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`, where `L` is lower-triangular and .H is the conjugate transpose operator (which is the ordinary transpose if `a` is real-valued). `a` must be Hermitian (symmetric if real-valued) and positive-definite....
Cholesky decomposition.
def cholesky(a): """ Cholesky decomposition. Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`, where `L` is lower-triangular and .H is the conjugate transpose operator (which is the ordinary transpose if `a` is real-valued). `a` must be Hermitian (symmetric if real-valued...
[ "def", "cholesky", "(", "a", ")", ":", "extobj", "=", "get_linalg_error_extobj", "(", "_raise_linalgerror_nonposdef", ")", "gufunc", "=", "_umath_linalg", ".", "cholesky_lo", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ...
[ 678, 0 ]
[ 759, 47 ]
python
en
['en', 'error', 'th']
False
qr
(a, mode='reduced')
Compute the qr factorization of a matrix. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is upper-triangular. Parameters ---------- a : array_like, shape (M, N) Matrix to be factored. mode : {'reduced', 'complete', 'r', 'raw', 'full', 'economic'}, optional ...
Compute the qr factorization of a matrix.
def qr(a, mode='reduced'): """ Compute the qr factorization of a matrix. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is upper-triangular. Parameters ---------- a : array_like, shape (M, N) Matrix to be factored. mode : {'reduced', 'complete', 'r', 'raw', 'fu...
[ "def", "qr", "(", "a", ",", "mode", "=", "'reduced'", ")", ":", "if", "mode", "not", "in", "(", "'reduced'", ",", "'complete'", ",", "'r'", ",", "'raw'", ")", ":", "if", "mode", "in", "(", "'f'", ",", "'full'", ")", ":", "# 2013-04-01, 1.8", "msg",...
[ 769, 0 ]
[ 978, 33 ]
python
en
['en', 'error', 'th']
False
eigvals
(a)
Compute the eigenvalues of a general matrix. Main difference between `eigvals` and `eig`: the eigenvectors aren't returned. Parameters ---------- a : (..., M, M) array_like A complex- or real-valued matrix whose eigenvalues will be computed. Returns ------- w : (..., M,) ...
Compute the eigenvalues of a general matrix.
def eigvals(a): """ Compute the eigenvalues of a general matrix. Main difference between `eigvals` and `eig`: the eigenvectors aren't returned. Parameters ---------- a : (..., M, M) array_like A complex- or real-valued matrix whose eigenvalues will be computed. Returns ---...
[ "def", "eigvals", "(", "a", ")", ":", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "_assertFinite", "(", "a", ")", "t", ",", "result_t", "=", "_commonType", "(", "a", ...
[ 985, 0 ]
[ 1072, 41 ]
python
en
['en', 'error', 'th']
False
eigvalsh
(a, UPLO='L')
Compute the eigenvalues of a complex Hermitian or real symmetric matrix. Main difference from eigh: the eigenvectors are not computed. Parameters ---------- a : (..., M, M) array_like A complex- or real-valued matrix whose eigenvalues are to be computed. UPLO : {'L', 'U'}, opt...
Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
def eigvalsh(a, UPLO='L'): """ Compute the eigenvalues of a complex Hermitian or real symmetric matrix. Main difference from eigh: the eigenvectors are not computed. Parameters ---------- a : (..., M, M) array_like A complex- or real-valued matrix whose eigenvalues are to be co...
[ "def", "eigvalsh", "(", "a", ",", "UPLO", "=", "'L'", ")", ":", "UPLO", "=", "UPLO", ".", "upper", "(", ")", "if", "UPLO", "not", "in", "(", "'L'", ",", "'U'", ")", ":", "raise", "ValueError", "(", "\"UPLO argument must be 'L' or 'U'\"", ")", "extobj",...
[ 1080, 0 ]
[ 1170, 52 ]
python
en
['en', 'error', 'th']
False
eig
(a)
Compute the eigenvalues and right eigenvectors of a square array. Parameters ---------- a : (..., M, M) array Matrices for which the eigenvalues and right eigenvectors will be computed Returns ------- w : (..., M) array The eigenvalues, each repeated according to i...
Compute the eigenvalues and right eigenvectors of a square array.
def eig(a): """ Compute the eigenvalues and right eigenvectors of a square array. Parameters ---------- a : (..., M, M) array Matrices for which the eigenvalues and right eigenvectors will be computed Returns ------- w : (..., M) array The eigenvalues, each repe...
[ "def", "eig", "(", "a", ")", ":", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "_assertFinite", "(", "a", ")", "t", ",", "result_t", "=", "_commonType", "(", "a", ")",...
[ 1182, 0 ]
[ 1320, 51 ]
python
en
['en', 'error', 'th']
False
eigh
(a, UPLO='L')
Return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Returns two objects, a 1-D array containing the eigenvalues of `a`, and a 2-D square array or matrix (depending on the input type) of the corresponding eigenvectors (in columns). P...
Return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix.
def eigh(a, UPLO='L'): """ Return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Returns two objects, a 1-D array containing the eigenvalues of `a`, and a 2-D square array or matrix (depending on the input type) of the corresponding eig...
[ "def", "eigh", "(", "a", ",", "UPLO", "=", "'L'", ")", ":", "UPLO", "=", "UPLO", ".", "upper", "(", ")", "if", "UPLO", "not", "in", "(", "'L'", ",", "'U'", ")", ":", "raise", "ValueError", "(", "\"UPLO argument must be 'L' or 'U'\"", ")", "a", ",", ...
[ 1324, 0 ]
[ 1458, 22 ]
python
en
['en', 'error', 'th']
False
svd
(a, full_matrices=True, compute_uv=True, hermitian=False)
Singular Value Decomposition. When `a` is a 2D array, it is factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where `u` and `vh` are 2D unitary arrays and `s` is a 1D array of `a`'s singular values. When `a` is higher-dimensional, SVD is applied in stacked mode as explained below. Paramet...
Singular Value Decomposition.
def svd(a, full_matrices=True, compute_uv=True, hermitian=False): """ Singular Value Decomposition. When `a` is a 2D array, it is factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where `u` and `vh` are 2D unitary arrays and `s` is a 1D array of `a`'s singular values. When `a` is higher-dimensi...
[ "def", "svd", "(", "a", ",", "full_matrices", "=", "True", ",", "compute_uv", "=", "True", ",", "hermitian", "=", "False", ")", ":", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "if", "hermitian", ":", "# note: lapack returns eigenvalues in reverse or...
[ 1468, 0 ]
[ 1649, 16 ]
python
en
['en', 'error', 'th']
False
cond
(x, p=None)
Compute the condition number of a matrix. This function is capable of returning the condition number using one of seven different norms, depending on the value of `p` (see Parameters below). Parameters ---------- x : (..., M, N) array_like The matrix whose condition number is soug...
Compute the condition number of a matrix.
def cond(x, p=None): """ Compute the condition number of a matrix. This function is capable of returning the condition number using one of seven different norms, depending on the value of `p` (see Parameters below). Parameters ---------- x : (..., M, N) array_like The matrix wh...
[ "def", "cond", "(", "x", ",", "p", "=", "None", ")", ":", "x", "=", "asarray", "(", "x", ")", "# in case we have a matrix", "_assertNoEmpty2d", "(", "x", ")", "if", "p", "is", "None", "or", "p", "==", "2", "or", "p", "==", "-", "2", ":", "s", "...
[ 1657, 0 ]
[ 1771, 12 ]
python
en
['en', 'error', 'th']
False
matrix_rank
(M, tol=None, hermitian=False)
Return matrix rank of array using SVD method Rank of the array is the number of singular values of the array that are greater than `tol`. .. versionchanged:: 1.14 Can now operate on stacks of matrices Parameters ---------- M : {(M,), (..., M, N)} array_like Input vector or...
Return matrix rank of array using SVD method
def matrix_rank(M, tol=None, hermitian=False): """ Return matrix rank of array using SVD method Rank of the array is the number of singular values of the array that are greater than `tol`. .. versionchanged:: 1.14 Can now operate on stacks of matrices Parameters ---------- M : ...
[ "def", "matrix_rank", "(", "M", ",", "tol", "=", "None", ",", "hermitian", "=", "False", ")", ":", "M", "=", "asarray", "(", "M", ")", "if", "M", ".", "ndim", "<", "2", ":", "return", "int", "(", "not", "all", "(", "M", "==", "0", ")", ")", ...
[ 1779, 0 ]
[ 1880, 42 ]
python
en
['en', 'error', 'th']
False
pinv
(a, rcond=1e-15, hermitian=False)
Compute the (Moore-Penrose) pseudo-inverse of a matrix. Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all *large* singular values. .. versionchanged:: 1.14 Can now operate on stacks of matrices Parameters ---------- a ...
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
def pinv(a, rcond=1e-15, hermitian=False): """ Compute the (Moore-Penrose) pseudo-inverse of a matrix. Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all *large* singular values. .. versionchanged:: 1.14 Can now operate on stacks...
[ "def", "pinv", "(", "a", ",", "rcond", "=", "1e-15", ",", "hermitian", "=", "False", ")", ":", "a", ",", "wrap", "=", "_makearray", "(", "a", ")", "rcond", "=", "asarray", "(", "rcond", ")", "if", "_isEmpty2d", "(", "a", ")", ":", "m", ",", "n"...
[ 1890, 0 ]
[ 1978, 20 ]
python
en
['en', 'error', 'th']
False
slogdet
(a)
Compute the sign and (natural) logarithm of the determinant of an array. If an array has a very small or very large determinant, then a call to `det` may overflow or underflow. This routine is more robust against such issues, because it computes the logarithm of the determinant rather than the det...
Compute the sign and (natural) logarithm of the determinant of an array.
def slogdet(a): """ Compute the sign and (natural) logarithm of the determinant of an array. If an array has a very small or very large determinant, then a call to `det` may overflow or underflow. This routine is more robust against such issues, because it computes the logarithm of the determinant ...
[ "def", "slogdet", "(", "a", ")", ":", "a", "=", "asarray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "t", ",", "result_t", "=", "_commonType", "(", "a", ")", "real_t", "=", "_realType", "(", "result_t", ...
[ 1985, 0 ]
[ 2068, 23 ]
python
en
['en', 'error', 'th']
False
det
(a)
Compute the determinant of an array. Parameters ---------- a : (..., M, M) array_like Input array to compute determinants for. Returns ------- det : (...) array_like Determinant of `a`. See Also -------- slogdet : Another way to represent the determinant, more...
Compute the determinant of an array.
def det(a): """ Compute the determinant of an array. Parameters ---------- a : (..., M, M) array_like Input array to compute determinants for. Returns ------- det : (...) array_like Determinant of `a`. See Also -------- slogdet : Another way to represent th...
[ "def", "det", "(", "a", ")", ":", "a", "=", "asarray", "(", "a", ")", "_assertRankAtLeast2", "(", "a", ")", "_assertNdSquareness", "(", "a", ")", "t", ",", "result_t", "=", "_commonType", "(", "a", ")", "signature", "=", "'D->D'", "if", "isComplexType"...
[ 2072, 0 ]
[ 2126, 12 ]
python
en
['en', 'error', 'th']
False
lstsq
(a, b, rcond="warn")
r""" Return the least-squares solution to a linear matrix equation. Solves the equation :math:`a x = b` by computing a vector `x` that minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`. The equation may be under-, well-, or over-determined (i.e., the number of linearly independent ro...
r""" Return the least-squares solution to a linear matrix equation.
def lstsq(a, b, rcond="warn"): r""" Return the least-squares solution to a linear matrix equation. Solves the equation :math:`a x = b` by computing a vector `x` that minimizes the squared Euclidean 2-norm :math:`\| b - a x \|^2_2`. The equation may be under-, well-, or over-determined (i.e., the ...
[ "def", "lstsq", "(", "a", ",", "b", ",", "rcond", "=", "\"warn\"", ")", ":", "a", ",", "_", "=", "_makearray", "(", "a", ")", "b", ",", "wrap", "=", "_makearray", "(", "b", ")", "is_1d", "=", "b", ".", "ndim", "==", "1", "if", "is_1d", ":", ...
[ 2136, 0 ]
[ 2289, 41 ]
python
cy
['en', 'cy', 'hi']
False
_multi_svd_norm
(x, row_axis, col_axis, op)
Compute a function of the singular values of the 2-D matrices in `x`. This is a private utility function used by `numpy.linalg.norm()`. Parameters ---------- x : ndarray row_axis, col_axis : int The axes of `x` that hold the 2-D matrices. op : callable This should be either num...
Compute a function of the singular values of the 2-D matrices in `x`.
def _multi_svd_norm(x, row_axis, col_axis, op): """Compute a function of the singular values of the 2-D matrices in `x`. This is a private utility function used by `numpy.linalg.norm()`. Parameters ---------- x : ndarray row_axis, col_axis : int The axes of `x` that hold the 2-D matric...
[ "def", "_multi_svd_norm", "(", "x", ",", "row_axis", ",", "col_axis", ",", "op", ")", ":", "y", "=", "moveaxis", "(", "x", ",", "(", "row_axis", ",", "col_axis", ")", ",", "(", "-", "2", ",", "-", "1", ")", ")", "result", "=", "op", "(", "svd",...
[ 2292, 0 ]
[ 2317, 17 ]
python
en
['en', 'en', 'en']
True
norm
(x, ord=None, axis=None, keepdims=False)
Matrix or vector norm. This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ``ord`` parameter. Parameters ---------- x : array_like Input array. If `axis` is None, `x` mu...
Matrix or vector norm.
def norm(x, ord=None, axis=None, keepdims=False): """ Matrix or vector norm. This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ``ord`` parameter. Parameters ---------- x : a...
[ "def", "norm", "(", "x", ",", "ord", "=", "None", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "x", "=", "asarray", "(", "x", ")", "if", "not", "issubclass", "(", "x", ".", "dtype", ".", "type", ",", "(", "inexact", ",", ...
[ 2325, 0 ]
[ 2562, 66 ]
python
en
['en', 'error', 'th']
False
multi_dot
(arrays)
Compute the dot product of two or more arrays in a single function call, while automatically selecting the fastest evaluation order. `multi_dot` chains `numpy.dot` and uses optimal parenthesization of the matrices [1]_ [2]_. Depending on the shapes of the matrices, this can speed up the multiplica...
Compute the dot product of two or more arrays in a single function call, while automatically selecting the fastest evaluation order.
def multi_dot(arrays): """ Compute the dot product of two or more arrays in a single function call, while automatically selecting the fastest evaluation order. `multi_dot` chains `numpy.dot` and uses optimal parenthesization of the matrices [1]_ [2]_. Depending on the shapes of the matrices, th...
[ "def", "multi_dot", "(", "arrays", ")", ":", "n", "=", "len", "(", "arrays", ")", "# optimization only makes sense for len(arrays) > 2", "if", "n", "<", "2", ":", "raise", "ValueError", "(", "\"Expecting at least two arrays.\"", ")", "elif", "n", "==", "2", ":",...
[ 2572, 0 ]
[ 2680, 21 ]
python
en
['en', 'error', 'th']
False
_multi_dot_three
(A, B, C)
Find the best order for three arrays and do the multiplication. For three arguments `_multi_dot_three` is approximately 15 times faster than `_multi_dot_matrix_chain_order`
Find the best order for three arrays and do the multiplication.
def _multi_dot_three(A, B, C): """ Find the best order for three arrays and do the multiplication. For three arguments `_multi_dot_three` is approximately 15 times faster than `_multi_dot_matrix_chain_order` """ a0, a1b0 = A.shape b1c0, c1 = C.shape # cost1 = cost((AB)C) = a0*a1b0*b1c0...
[ "def", "_multi_dot_three", "(", "A", ",", "B", ",", "C", ")", ":", "a0", ",", "a1b0", "=", "A", ".", "shape", "b1c0", ",", "c1", "=", "C", ".", "shape", "# cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1", "cost1", "=", "a0", "*", "b1c0", "*", "(", "a1...
[ 2683, 0 ]
[ 2701, 32 ]
python
en
['en', 'error', 'th']
False
_multi_dot_matrix_chain_order
(arrays, return_costs=False)
Return a np.array that encodes the optimal order of mutiplications. The optimal order array is then used by `_multi_dot()` to do the multiplication. Also return the cost matrix if `return_costs` is `True` The implementation CLOSELY follows Cormen, "Introduction to Algorithms", Chapter 15.2, ...
Return a np.array that encodes the optimal order of mutiplications.
def _multi_dot_matrix_chain_order(arrays, return_costs=False): """ Return a np.array that encodes the optimal order of mutiplications. The optimal order array is then used by `_multi_dot()` to do the multiplication. Also return the cost matrix if `return_costs` is `True` The implementation CL...
[ "def", "_multi_dot_matrix_chain_order", "(", "arrays", ",", "return_costs", "=", "False", ")", ":", "n", "=", "len", "(", "arrays", ")", "# p stores the dimensions of the matrices", "# Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]", "p", "=", "[", ...
[ 2704, 0 ]
[ 2742, 40 ]
python
en
['en', 'error', 'th']
False
_multi_dot
(arrays, order, i, j)
Actually do the multiplication with the given order.
Actually do the multiplication with the given order.
def _multi_dot(arrays, order, i, j): """Actually do the multiplication with the given order.""" if i == j: return arrays[i] else: return dot(_multi_dot(arrays, order, i, order[i, j]), _multi_dot(arrays, order, order[i, j] + 1, j))
[ "def", "_multi_dot", "(", "arrays", ",", "order", ",", "i", ",", "j", ")", ":", "if", "i", "==", "j", ":", "return", "arrays", "[", "i", "]", "else", ":", "return", "dot", "(", "_multi_dot", "(", "arrays", ",", "order", ",", "i", ",", "order", ...
[ 2745, 0 ]
[ 2751, 65 ]
python
en
['en', 'en', 'en']
True
DebuggingConnector.determine_data_use_amount
(self, overfit_batches: float)
Use less data for debugging purposes
Use less data for debugging purposes
def determine_data_use_amount(self, overfit_batches: float) -> None: """Use less data for debugging purposes""" if overfit_batches > 0: self.trainer.limit_train_batches = overfit_batches self.trainer.limit_val_batches = overfit_batches self.trainer.limit_test_batches ...
[ "def", "determine_data_use_amount", "(", "self", ",", "overfit_batches", ":", "float", ")", "->", "None", ":", "if", "overfit_batches", ">", "0", ":", "self", ".", "trainer", ".", "limit_train_batches", "=", "overfit_batches", "self", ".", "trainer", ".", "lim...
[ 80, 4 ]
[ 85, 61 ]
python
en
['nb', 'en', 'en']
True
token_from_cookie_middleware
(get_response)
Move token in cookie to header.
Move token in cookie to header.
def token_from_cookie_middleware(get_response): """ Move token in cookie to header. """ def middleware(request): token = request.COOKIES.get('token', None) if token is not None: request.META['HTTP_AUTHORIZATION'] = 'Bearer ' + token response = get_response(request) r...
[ "def", "token_from_cookie_middleware", "(", "get_response", ")", ":", "def", "middleware", "(", "request", ")", ":", "token", "=", "request", ".", "COOKIES", ".", "get", "(", "'token'", ",", "None", ")", "if", "token", "is", "not", "None", ":", "request", ...
[ 0, 0 ]
[ 10, 21 ]
python
en
['en', 'en', 'en']
True
DistributedSampler.__iter__
(self)
Deterministically shuffle based on epoch.
Deterministically shuffle based on epoch.
def __iter__(self): """Deterministically shuffle based on epoch.""" if self.shuffle: g = torch.Generator() g.manual_seed(self.epoch) indices = torch.randperm(len(self.dataset), generator=g).tolist() else: indices = torch.arange(len(self.dataset)).t...
[ "def", "__iter__", "(", "self", ")", ":", "if", "self", ".", "shuffle", ":", "g", "=", "torch", ".", "Generator", "(", ")", "g", ".", "manual_seed", "(", "self", ".", "epoch", ")", "indices", "=", "torch", ".", "randperm", "(", "len", "(", "self", ...
[ 16, 4 ]
[ 32, 28 ]
python
en
['en', 'cy', 'en']
True
setup_openblas
(arch=get_arch())
Download and setup an openblas library for building. If successful, the configuration script will find it automatically. Returns ------- msg : str path to extracted files on success, otherwise indicates what went wrong To determine success, do ``os.path.exists(msg)``
Download and setup an openblas library for building. If successful, the configuration script will find it automatically.
def setup_openblas(arch=get_arch()): ''' Download and setup an openblas library for building. If successful, the configuration script will find it automatically. Returns ------- msg : str path to extracted files on success, otherwise indicates what went wrong To determine succes...
[ "def", "setup_openblas", "(", "arch", "=", "get_arch", "(", ")", ")", ":", "_", ",", "tmp", "=", "mkstemp", "(", ")", "if", "not", "arch", ":", "raise", "ValueError", "(", "'unknown architecture'", ")", "typ", "=", "download_openblas", "(", "tmp", ",", ...
[ 88, 0 ]
[ 112, 32 ]
python
en
['en', 'error', 'th']
False
make_init
(dirname)
Create a _distributor_init.py file for OpenBlas
Create a _distributor_init.py file for OpenBlas
def make_init(dirname): ''' Create a _distributor_init.py file for OpenBlas ''' with open(os.path.join(dirname, '_distributor_init.py'), 'wt') as fid: fid.write(textwrap.dedent(""" ''' Helper to preload windows dlls to prevent dll not found errors. Once a DLL ...
[ "def", "make_init", "(", "dirname", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "dirname", ",", "'_distributor_init.py'", ")", ",", "'wt'", ")", "as", "fid", ":", "fid", ".", "write", "(", "textwrap", ".", "dedent", "(", "\"\"...
[ 139, 0 ]
[ 176, 9 ]
python
en
['en', 'error', 'th']
False
test_setup
(arches)
Make sure all the downloadable files exist and can be opened
Make sure all the downloadable files exist and can be opened
def test_setup(arches): ''' Make sure all the downloadable files exist and can be opened ''' for arch in arches: if arch == '': continue try: target = setup_openblas(arch) except: print('Could not setup %s' % arch) raise if ...
[ "def", "test_setup", "(", "arches", ")", ":", "for", "arch", "in", "arches", ":", "if", "arch", "==", "''", ":", "continue", "try", ":", "target", "=", "setup_openblas", "(", "arch", ")", "except", ":", "print", "(", "'Could not setup %s'", "%", "arch", ...
[ 178, 0 ]
[ 192, 21 ]
python
en
['en', 'error', 'th']
False
test_version
(expected_version)
Assert that expected OpenBLAS version is actually available via NumPy
Assert that expected OpenBLAS version is actually available via NumPy
def test_version(expected_version): """ Assert that expected OpenBLAS version is actually available via NumPy """ import numpy import ctypes dll = ctypes.CDLL(numpy.core._multiarray_umath.__file__) get_config = dll.openblas_get_config get_config.restype=ctypes.c_char_p res = get...
[ "def", "test_version", "(", "expected_version", ")", ":", "import", "numpy", "import", "ctypes", "dll", "=", "ctypes", ".", "CDLL", "(", "numpy", ".", "core", ".", "_multiarray_umath", ".", "__file__", ")", "get_config", "=", "dll", ".", "openblas_get_config",...
[ 194, 0 ]
[ 208, 27 ]
python
en
['en', 'error', 'th']
False
test_normalize_image
(img, mcp, dark_counts)
dark_counts_img and mcp_img have the same shape in all fixtures, so it is not tested here!
dark_counts_img and mcp_img have the same shape in all fixtures, so it is not tested here!
def test_normalize_image(img, mcp, dark_counts): """dark_counts_img and mcp_img have the same shape in all fixtures, so it is not tested here! """ if img.data.shape != mcp.data.shape: with pytest.raises(ValueError): img_normed = driftnorm.normalize_image(img, mcp, dark_counts=dark_co...
[ "def", "test_normalize_image", "(", "img", ",", "mcp", ",", "dark_counts", ")", ":", "if", "img", ".", "data", ".", "shape", "!=", "mcp", ".", "data", ".", "shape", ":", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "img_normed", "=", ...
[ 14, 0 ]
[ 26, 46 ]
python
en
['en', 'en', 'en']
True
cast_tensor_type
(inputs, src_type, dst_type)
Recursively convert Tensor in inputs from src_type to dst_type. Args: inputs: Inputs that to be casted. src_type (torch.dtype): Source type. dst_type (torch.dtype): Destination type. Returns: The same type with inputs, but all contained Tensors have been cast.
Recursively convert Tensor in inputs from src_type to dst_type.
def cast_tensor_type(inputs, src_type, dst_type): """Recursively convert Tensor in inputs from src_type to dst_type. Args: inputs: Inputs that to be casted. src_type (torch.dtype): Source type. dst_type (torch.dtype): Destination type. Returns: The same type with inputs, bu...
[ "def", "cast_tensor_type", "(", "inputs", ",", "src_type", ",", "dst_type", ")", ":", "if", "isinstance", "(", "inputs", ",", "torch", ".", "Tensor", ")", ":", "return", "inputs", ".", "to", "(", "dst_type", ")", "elif", "isinstance", "(", "inputs", ",",...
[ 6, 0 ]
[ 32, 17 ]
python
en
['en', 'en', 'en']
True
TrainingStepVariations.training_step
(self, batch, batch_idx, optimizer_idx=None)
Lightning calls this inside the training loop
Lightning calls this inside the training loop
def training_step(self, batch, batch_idx, optimizer_idx=None): """Lightning calls this inside the training loop""" self.training_step_called = True # forward pass x, y = batch x = x.view(x.size(0), -1) y_hat = self(x) # calculate loss loss_train = self.l...
[ "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ",", "optimizer_idx", "=", "None", ")", ":", "self", ".", "training_step_called", "=", "True", "# forward pass", "x", ",", "y", "=", "batch", "x", "=", "x", ".", "view", "(", "x", "."...
[ 27, 4 ]
[ 49, 21 ]
python
en
['en', 'en', 'en']
True
TrainingStepVariations.training_step__multiple_dataloaders
(self, batch, batch_idx, optimizer_idx=None)
Training step for multiple train loaders
Training step for multiple train loaders
def training_step__multiple_dataloaders(self, batch, batch_idx, optimizer_idx=None): """Training step for multiple train loaders""" assert isinstance(batch, dict) assert len(batch) == 2 assert 'a' in batch and 'b' in batch # forward pass x, y = batch['a'] x = x....
[ "def", "training_step__multiple_dataloaders", "(", "self", ",", "batch", ",", "batch_idx", ",", "optimizer_idx", "=", "None", ")", ":", "assert", "isinstance", "(", "batch", ",", "dict", ")", "assert", "len", "(", "batch", ")", "==", "2", "assert", "'a'", ...
[ 60, 4 ]
[ 89, 21 ]
python
en
['en', 'en', 'en']
True
average_precision
( preds: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, pos_label: Optional[int] = None, sample_weights: Optional[Sequence] = None, )
Computes the average precision score. Args: preds: predictions from model (logits or probabilities) target: ground truth values num_classes: integer with number of classes. Not nessesary to provide for binary problems. pos_label: integer determining the positive cla...
Computes the average precision score.
def average_precision( preds: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, pos_label: Optional[int] = None, sample_weights: Optional[Sequence] = None, ) -> Union[List[torch.Tensor], torch.Tensor]: """ Computes the average precision score. Args: preds: p...
[ "def", "average_precision", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "num_classes", ":", "Optional", "[", "int", "]", "=", "None", ",", "pos_label", ":", "Optional", "[", "int", "]", "=", "None", ",", ...
[ 52, 0 ]
[ 98, 92 ]
python
en
['en', 'error', 'th']
False
auroc
( preds: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, pos_label: Optional[int] = None, average: Optional[str] = 'macro', max_fpr: Optional[float] = None, sample_weights: Optional[Sequence] = None, )
Compute `Area Under the Receiver Operating Characteristic Curve (ROC AUC) <https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Further_interpretations>`_ Args: preds: predictions from model (logits or probabilities) target: Ground truth labels num_classes: integer with numb...
Compute `Area Under the Receiver Operating Characteristic Curve (ROC AUC) <https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Further_interpretations>`_
def auroc( preds: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, pos_label: Optional[int] = None, average: Optional[str] = 'macro', max_fpr: Optional[float] = None, sample_weights: Optional[Sequence] = None, ) -> torch.Tensor: """ Compute `Area Under the Receiver ...
[ "def", "auroc", "(", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "num_classes", ":", "Optional", "[", "int", "]", "=", "None", ",", "pos_label", ":", "Optional", "[", "int", "]", "=", "None", ",", "average",...
[ 136, 0 ]
[ 188, 104 ]
python
en
['en', 'en', 'en']
True
Lock._is_expired
(self, createdtime)
Return true if the expiration time is reached, or no value is available.
Return true if the expiration time is reached, or no value is available.
def _is_expired(self, createdtime): """Return true if the expiration time is reached, or no value is available.""" return not self._has_value(createdtime) or ( self.expiretime is not None and time.time() - createdtime > self.expiretime )
[ "def", "_is_expired", "(", "self", ",", "createdtime", ")", ":", "return", "not", "self", ".", "_has_value", "(", "createdtime", ")", "or", "(", "self", ".", "expiretime", "is", "not", "None", "and", "time", ".", "time", "(", ")", "-", "createdtime", "...
[ 67, 4 ]
[ 74, 9 ]
python
en
['en', 'en', 'en']
True
Lock._has_value
(self, createdtime)
Return true if the creation function has proceeded at least once.
Return true if the creation function has proceeded at least once.
def _has_value(self, createdtime): """Return true if the creation function has proceeded at least once.""" return createdtime > 0
[ "def", "_has_value", "(", "self", ",", "createdtime", ")", ":", "return", "createdtime", ">", "0" ]
[ 76, 4 ]
[ 79, 30 ]
python
en
['en', 'en', 'en']
True
HRModule._check_branches
(num_branches, num_blocks, in_channels, num_channels)
Check input to avoid ValueError.
Check input to avoid ValueError.
def _check_branches(num_branches, num_blocks, in_channels, num_channels): """Check input to avoid ValueError.""" if num_branches != len(num_blocks): error_msg = f'NUM_BRANCHES({num_branches}) ' \ f'!= NUM_BLOCKS({len(num_blocks)})' raise ValueError(error_msg) ...
[ "def", "_check_branches", "(", "num_branches", ",", "num_blocks", ",", "in_channels", ",", "num_channels", ")", ":", "if", "num_branches", "!=", "len", "(", "num_blocks", ")", ":", "error_msg", "=", "f'NUM_BRANCHES({num_branches}) '", "f'!= NUM_BLOCKS({len(num_blocks)})...
[ 50, 4 ]
[ 65, 39 ]
python
en
['en', 'fi', 'en']
True
HRModule._make_one_branch
(self, branch_index, block, num_blocks, num_channels, stride=1)
Make one branch.
Make one branch.
def _make_one_branch(self, branch_index, block, num_blocks, num_channels, stride=1): """Make one branch.""" downsample = None if stride != 1 or \ self.in_c...
[ "def", "_make_one_branch", "(", "self", ",", "branch_index", ",", "block", ",", "num_blocks", ",", "num_channels", ",", "stride", "=", "1", ")", ":", "downsample", "=", "None", "if", "stride", "!=", "1", "or", "self", ".", "in_channels", "[", "branch_index...
[ 67, 4 ]
[ 111, 37 ]
python
en
['en', 'kk', 'en']
True
HRModule._make_branches
(self, num_branches, block, num_blocks, num_channels)
Make branches.
Make branches.
def _make_branches(self, num_branches, block, num_blocks, num_channels): """Make branches.""" branches = [] for i in range(num_branches): branches.append( self._make_one_branch(i, block, num_blocks, num_channels)) return nn.ModuleList(branches)
[ "def", "_make_branches", "(", "self", ",", "num_branches", ",", "block", ",", "num_blocks", ",", "num_channels", ")", ":", "branches", "=", "[", "]", "for", "i", "in", "range", "(", "num_branches", ")", ":", "branches", ".", "append", "(", "self", ".", ...
[ 113, 4 ]
[ 121, 38 ]
python
en
['en', 'en', 'en']
False
HRModule._make_fuse_layers
(self)
Make fuse layer.
Make fuse layer.
def _make_fuse_layers(self): """Make fuse layer.""" if self.num_branches == 1: return None num_branches = self.num_branches in_channels = self.in_channels fuse_layers = [] num_out_branches = num_branches if self.multiscale_output else 1 for i in range...
[ "def", "_make_fuse_layers", "(", "self", ")", ":", "if", "self", ".", "num_branches", "==", "1", ":", "return", "None", "num_branches", "=", "self", ".", "num_branches", "in_channels", "=", "self", ".", "in_channels", "fuse_layers", "=", "[", "]", "num_out_b...
[ 123, 4 ]
[ 184, 41 ]
python
en
['en', 'it', 'en']
True
HRModule.forward
(self, x)
Forward function.
Forward function.
def forward(self, x): """Forward function.""" if self.num_branches == 1: return [self.branches[0](x[0])] for i in range(self.num_branches): x[i] = self.branches[i](x[i]) x_fuse = [] for i in range(len(self.fuse_layers)): y = 0 for...
[ "def", "forward", "(", "self", ",", "x", ")", ":", "if", "self", ".", "num_branches", "==", "1", ":", "return", "[", "self", ".", "branches", "[", "0", "]", "(", "x", "[", "0", "]", ")", "]", "for", "i", "in", "range", "(", "self", ".", "num_...
[ 186, 4 ]
[ 203, 21 ]
python
en
['en', 'cy', 'en']
False
cluster_analysis
(X, algorithm="pc-kmeans", **params_)
There are different models to choose from. The following table lists them and on the right, the keyword arguments that they take are listed with the default values. For more information look at the scikit-learn (sk), pyclustering (pc) and ntltk packages online. "sk-birch": "threshold":...
There are different models to choose from. The following table lists them and on the right, the keyword arguments that they take are listed with the default values. For more information look at the scikit-learn (sk), pyclustering (pc) and ntltk packages online.
def cluster_analysis(X, algorithm="pc-kmeans", **params_): """ There are different models to choose from. The following table lists them and on the right, the keyword arguments that they take are listed with the default values. For more information look at the scikit-learn (sk), pyclustering (pc) an...
[ "def", "cluster_analysis", "(", "X", ",", "algorithm", "=", "\"pc-kmeans\"", ",", "*", "*", "params_", ")", ":", "# pylint: disable=too-many-locals", "algorithm", "=", "algorithm", ".", "lower", "(", ")", "constructor", ",", "params", "=", "copy", ".", "deepco...
[ 151, 0 ]
[ 220, 37 ]
python
en
['en', 'error', 'th']
False
smooth_pendry_y
(I, dE, V0i_sq, eps=1e-5, wl=17, p=4, both=True)
I: intensity, dE: gradient of energy V0i_sq: squared elelctron self energy eps: clipping value to avoid division by 0 wl: Savitzky-Golay filter window length p: Savitzky-Golay filter polynom order
I: intensity, dE: gradient of energy V0i_sq: squared elelctron self energy eps: clipping value to avoid division by 0 wl: Savitzky-Golay filter window length p: Savitzky-Golay filter polynom order
def smooth_pendry_y(I, dE, V0i_sq, eps=1e-5, wl=17, p=4, both=True): """ I: intensity, dE: gradient of energy V0i_sq: squared elelctron self energy eps: clipping value to avoid division by 0 wl: Savitzky-Golay filter window length p: Savitzky-Golay filter polynom order """ # pylint: ...
[ "def", "smooth_pendry_y", "(", "I", ",", "dE", ",", "V0i_sq", ",", "eps", "=", "1e-5", ",", "wl", "=", "17", ",", "p", "=", "4", ",", "both", "=", "True", ")", ":", "# pylint: disable=too-many-arguments", "if", "both", ":", "I", "=", "savgol_filter", ...
[ 287, 0 ]
[ 302, 12 ]
python
en
['en', 'error', 'th']
False
plot_clustermap
(clustermap, ax=None, ofile=None, cmap="brg")
Plot 2d numpy array with integer values to colormap.
Plot 2d numpy array with integer values to colormap.
def plot_clustermap(clustermap, ax=None, ofile=None, cmap="brg"): """Plot 2d numpy array with integer values to colormap.""" if ax is None: _, ax = plt.subplots(figsize=(5, 5)) ax.imshow(clustermap, interpolation="none", origin="upper", cmap=cmap) ax.set_xticks([]) ax.set_yticks([]) ax.s...
[ "def", "plot_clustermap", "(", "clustermap", ",", "ax", "=", "None", ",", "ofile", "=", "None", ",", "cmap", "=", "\"brg\"", ")", ":", "if", "ax", "is", "None", ":", "_", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "5", ",",...
[ 361, 0 ]
[ 370, 64 ]
python
en
['en', 'ca', 'en']
True
plot_IVs
(stack, labels, ax=None, ofile=None, mask_outer=0.2, cmap="seismic", legend=None, **kwargs)
Plot IV curves.
Plot IV curves.
def plot_IVs(stack, labels, ax=None, ofile=None, mask_outer=0.2, cmap="seismic", legend=None, **kwargs): """Plot IV curves.""" if ax is None: _, ax = plt.subplots(figsize=(8, 5)) ax.set_xlabel("Energy in eV") ax.set_ylabel("Intensity in a.u.") ax.set_yticks([]) i...
[ "def", "plot_IVs", "(", "stack", ",", "labels", ",", "ax", "=", "None", ",", "ofile", "=", "None", ",", "mask_outer", "=", "0.2", ",", "cmap", "=", "\"seismic\"", ",", "legend", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "N...
[ 412, 0 ]
[ 440, 13 ]
python
en
['en', 'hi-Latn', 'en']
True
plot_IVs2
(energy, IV_curves, ax=None, cmap="seismic")
Plot IV curves.
Plot IV curves.
def plot_IVs2(energy, IV_curves, ax=None, cmap="seismic"): """Plot IV curves.""" if ax is None: _, ax = plt.subplots(figsize=(8, 5)) for i, IV_curve in enumerate(IV_curves): ax.plot(energy, IV_curve, color=plt.get_cmap(cmap)(i / len(IV_curves)))
[ "def", "plot_IVs2", "(", "energy", ",", "IV_curves", ",", "ax", "=", "None", ",", "cmap", "=", "\"seismic\"", ")", ":", "if", "ax", "is", "None", ":", "_", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "(", "8", ",", "5", ")", ")...
[ 442, 0 ]
[ 447, 79 ]
python
en
['en', 'hi-Latn', 'en']
True
find_duplicate
(list)
Find duplication in a list, return a list of duplicated elements
Find duplication in a list, return a list of duplicated elements
def find_duplicate(list): """Find duplication in a list, return a list of duplicated elements""" return [ item for item, counts in _OrderedCounter(list).items() if counts > 1 ]
[ "def", "find_duplicate", "(", "list", ")", ":", "return", "[", "item", "for", "item", ",", "counts", "in", "_OrderedCounter", "(", "list", ")", ".", "items", "(", ")", "if", "counts", ">", "1", "]" ]
[ 90, 0 ]
[ 96, 5 ]
python
en
['en', 'en', 'en']
True
fromarrays
(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None)
create a record array from a (flat) list of arrays >>> x1=np.array([1,2,3,4]) >>> x2=np.array(['a','dd','xyz','12']) >>> x3=np.array([1.1,2,3,4]) >>> r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c') >>> print(r[1]) (2, 'dd', 2.0) # may vary >>> x1[1]=34 >>> r.a array([1, 2,...
create a record array from a (flat) list of arrays
def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a record array from a (flat) list of arrays >>> x1=np.array([1,2,3,4]) >>> x2=np.array(['a','dd','xyz','12']) >>> x3=np.array([1.1,2,3,4]) >>> r = np.co...
[ "def", "fromarrays", "(", "arrayList", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "formats", "=", "None", ",", "names", "=", "None", ",", "titles", "=", "None", ",", "aligned", "=", "False", ",", "byteorder", "=", "None", ")", ":", ...
[ 586, 0 ]
[ 646, 17 ]
python
en
['en', 'en', 'en']
True
fromrecords
(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None)
create a recarray from a list of records in text form The data in the same field can be heterogeneous, they will be promoted to the highest data type. This method is intended for creating smaller record arrays. If used to create large array without formats defined r=fromreco...
create a recarray from a list of records in text form
def fromrecords(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a recarray from a list of records in text form The data in the same field can be heterogeneous, they will be promoted to the highest data type. This me...
[ "def", "fromrecords", "(", "recList", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "formats", "=", "None", ",", "names", "=", "None", ",", "titles", "=", "None", ",", "aligned", "=", "False", ",", "byteorder", "=", "None", ")", ":", "...
[ 648, 0 ]
[ 714, 14 ]
python
en
['en', 'en', 'en']
True
fromstring
(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None)
create a (read-only) record array from binary data contained in a string
create a (read-only) record array from binary data contained in a string
def fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a (read-only) record array from binary data contained in a string""" if dtype is None and formats is None: raise TypeError("fromstring() need...
[ "def", "fromstring", "(", "datastring", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "offset", "=", "0", ",", "formats", "=", "None", ",", "names", "=", "None", ",", "titles", "=", "None", ",", "aligned", "=", "False", ",", "byteorder",...
[ 717, 0 ]
[ 735, 17 ]
python
en
['en', 'en', 'en']
True
fromfile
(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None)
Create an array from binary file data If file is a string or a path-like object then that file is opened, else it is assumed to be a file object. The file object must support random access (i.e. it must have tell and seek methods). >>> from tempfile import TemporaryFile >>> a = np.empty(10,dtype='...
Create an array from binary file data
def fromfile(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None): """Create an array from binary file data If file is a string or a path-like object then that file is opened, else it is assumed to be a file object. The file object must ...
[ "def", "fromfile", "(", "fd", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "offset", "=", "0", ",", "formats", "=", "None", ",", "names", "=", "None", ",", "titles", "=", "None", ",", "aligned", "=", "False", ",", "byteorder", "=", ...
[ 746, 0 ]
[ 818, 17 ]
python
en
['en', 'en', 'en']
True
array
(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True)
Construct a record array from a wide-variety of objects.
Construct a record array from a wide-variety of objects.
def array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True): """Construct a record array from a wide-variety of objects. """ if ((isinstance(obj, (type(None), str)) or isfileobj(obj)) and (formats is No...
[ "def", "array", "(", "obj", ",", "dtype", "=", "None", ",", "shape", "=", "None", ",", "offset", "=", "0", ",", "strides", "=", "None", ",", "formats", "=", "None", ",", "names", "=", "None", ",", "titles", "=", "None", ",", "aligned", "=", "Fals...
[ 820, 0 ]
[ 886, 33 ]
python
en
['en', 'en', 'en']
True
record.pprint
(self)
Pretty-print all fields.
Pretty-print all fields.
def pprint(self): """Pretty-print all fields.""" # pretty-print all fields names = self.dtype.names maxlen = max(len(name) for name in names) fmt = '%% %ds: %%s' % maxlen rows = [fmt % (name, getattr(self, name)) for name in names] return "\n".join(rows)
[ "def", "pprint", "(", "self", ")", ":", "# pretty-print all fields", "names", "=", "self", ".", "dtype", ".", "names", "maxlen", "=", "max", "(", "len", "(", "name", ")", "for", "name", "in", "names", ")", "fmt", "=", "'%% %ds: %%s'", "%", "maxlen", "r...
[ 301, 4 ]
[ 308, 30 ]
python
en
['en', 'mt', 'en']
True
_convert_loaded_hparams
(model_args: dict, hparams_type: Optional[Union[Callable, str]] = None)
Convert hparams according given type in callable or string (past) format.
Convert hparams according given type in callable or string (past) format.
def _convert_loaded_hparams(model_args: dict, hparams_type: Optional[Union[Callable, str]] = None) -> object: """Convert hparams according given type in callable or string (past) format.""" # if not hparams type define if not hparams_type: return model_args # if past checkpoint loaded, convert s...
[ "def", "_convert_loaded_hparams", "(", "model_args", ":", "dict", ",", "hparams_type", ":", "Optional", "[", "Union", "[", "Callable", ",", "str", "]", "]", "=", "None", ")", "->", "object", ":", "# if not hparams type define", "if", "not", "hparams_type", ":"...
[ 247, 0 ]
[ 256, 35 ]
python
en
['en', 'en', 'en']
True
update_hparams
(hparams: dict, updates: dict)
Overrides hparams with new values >>> hparams = {'c': 4} >>> update_hparams(hparams, {'a': {'b': 2}, 'c': 1}) >>> hparams['a']['b'], hparams['c'] (2, 1) >>> update_hparams(hparams, {'a': {'b': 4}, 'c': 7}) >>> hparams['a']['b'], hparams['c'] (4, 7) Args: hparams: the origi...
Overrides hparams with new values
def update_hparams(hparams: dict, updates: dict) -> None: """ Overrides hparams with new values >>> hparams = {'c': 4} >>> update_hparams(hparams, {'a': {'b': 2}, 'c': 1}) >>> hparams['a']['b'], hparams['c'] (2, 1) >>> update_hparams(hparams, {'a': {'b': 4}, 'c': 7}) >>> hparams['a']['b...
[ "def", "update_hparams", "(", "hparams", ":", "dict", ",", "updates", ":", "dict", ")", "->", "None", ":", "for", "k", ",", "v", "in", "updates", ".", "items", "(", ")", ":", "# if missing, add the key", "if", "k", "not", "in", "hparams", ":", "hparams...
[ 259, 0 ]
[ 287, 34 ]
python
en
['en', 'error', 'th']
False
load_hparams_from_tags_csv
(tags_csv: str)
Load hparams from a file. >>> hparams = Namespace(batch_size=32, learning_rate=0.001, data_root='./any/path/here') >>> path_csv = os.path.join('.', 'testing-hparams.csv') >>> save_hparams_to_tags_csv(path_csv, hparams) >>> hparams_new = load_hparams_from_tags_csv(path_csv) >>> vars(hparams) == hpar...
Load hparams from a file.
def load_hparams_from_tags_csv(tags_csv: str) -> Dict[str, Any]: """Load hparams from a file. >>> hparams = Namespace(batch_size=32, learning_rate=0.001, data_root='./any/path/here') >>> path_csv = os.path.join('.', 'testing-hparams.csv') >>> save_hparams_to_tags_csv(path_csv, hparams) >>> hparams_...
[ "def", "load_hparams_from_tags_csv", "(", "tags_csv", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "fs", "=", "get_filesystem", "(", "tags_csv", ")", "if", "not", "fs", ".", "exists", "(", "tags_csv", ")", ":", "rank_zero_warn", "(", ...
[ 290, 0 ]
[ 310, 15 ]
python
en
['en', 'en', 'en']
True
load_hparams_from_yaml
(config_yaml: str, use_omegaconf: bool = True)
Load hparams from a file. Args: config_yaml: Path to config yaml file use_omegaconf: If both `OMEGACONF_AVAILABLE` and `use_omegaconf` are True, the hparams will be converted to `DictConfig` if possible >>> hparams = Namespace(batch_size=32, learning_rate=0.001, dat...
Load hparams from a file.
def load_hparams_from_yaml(config_yaml: str, use_omegaconf: bool = True) -> Dict[str, Any]: """Load hparams from a file. Args: config_yaml: Path to config yaml file use_omegaconf: If both `OMEGACONF_AVAILABLE` and `use_omegaconf` are True, the hparams will be convert...
[ "def", "load_hparams_from_yaml", "(", "config_yaml", ":", "str", ",", "use_omegaconf", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "fs", "=", "get_filesystem", "(", "config_yaml", ")", "if", "not", "fs", ".", "exists", ...
[ 329, 0 ]
[ 359, 18 ]
python
en
['en', 'en', 'en']
True
save_hparams_to_yaml
(config_yaml, hparams: Union[dict, Namespace])
Args: config_yaml: path to new YAML file hparams: parameters to be saved
Args: config_yaml: path to new YAML file hparams: parameters to be saved
def save_hparams_to_yaml(config_yaml, hparams: Union[dict, Namespace]) -> None: """ Args: config_yaml: path to new YAML file hparams: parameters to be saved """ fs = get_filesystem(config_yaml) if not fs.isdir(os.path.dirname(config_yaml)): raise RuntimeError(f"Missing folder...
[ "def", "save_hparams_to_yaml", "(", "config_yaml", ",", "hparams", ":", "Union", "[", "dict", ",", "Namespace", "]", ")", "->", "None", ":", "fs", "=", "get_filesystem", "(", "config_yaml", ")", "if", "not", "fs", ".", "isdir", "(", "os", ".", "path", ...
[ 362, 0 ]
[ 407, 38 ]
python
en
['en', 'error', 'th']
False
ModelIO.load_from_checkpoint
( cls, checkpoint_path: Union[str, IO], map_location: Optional[Union[Dict[str, str], str, torch.device, int, Callable]] = None, hparams_file: Optional[str] = None, strict: bool = True, **kwargs, )
r""" Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to `__init__` in the checkpoint under `hyper_parameters` Any arguments specified through \*args and \*\*kwargs will override args stored in `hyper_parameters`. Args:...
r""" Primary way of loading a model from a checkpoint. When Lightning saves a checkpoint it stores the arguments passed to `__init__` in the checkpoint under `hyper_parameters`
def load_from_checkpoint( cls, checkpoint_path: Union[str, IO], map_location: Optional[Union[Dict[str, str], str, torch.device, int, Callable]] = None, hparams_file: Optional[str] = None, strict: bool = True, **kwargs, ): r""" Primary way of loading a ...
[ "def", "load_from_checkpoint", "(", "cls", ",", "checkpoint_path", ":", "Union", "[", "str", ",", "IO", "]", ",", "map_location", ":", "Optional", "[", "Union", "[", "Dict", "[", "str", ",", "str", "]", ",", "str", ",", "torch", ".", "device", ",", "...
[ 55, 4 ]
[ 156, 20 ]
python
cy
['en', 'cy', 'hi']
False
ModelIO.on_load_checkpoint
(self, checkpoint: Dict[str, Any])
Do something with the checkpoint. Gives model a chance to load something before ``state_dict`` is restored. Args: checkpoint: A dictionary with variables from the checkpoint.
Do something with the checkpoint. Gives model a chance to load something before ``state_dict`` is restored.
def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None: """ Do something with the checkpoint. Gives model a chance to load something before ``state_dict`` is restored. Args: checkpoint: A dictionary with variables from the checkpoint. """
[ "def", "on_load_checkpoint", "(", "self", ",", "checkpoint", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":" ]
[ 207, 4 ]
[ 214, 11 ]
python
en
['en', 'error', 'th']
False
ModelIO.on_save_checkpoint
(self, checkpoint: Dict[str, Any])
Give the model a chance to add something to the checkpoint. ``state_dict`` is already there. Args: checkpoint: A dictionary in which you can save variables to save in a checkpoint. Contents need to be pickleable.
Give the model a chance to add something to the checkpoint. ``state_dict`` is already there.
def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None: """ Give the model a chance to add something to the checkpoint. ``state_dict`` is already there. Args: checkpoint: A dictionary in which you can save variables to save in a checkpoint. Contents...
[ "def", "on_save_checkpoint", "(", "self", ",", "checkpoint", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":" ]
[ 216, 4 ]
[ 224, 11 ]
python
en
['en', 'error', 'th']
False
ModelIO.on_hpc_save
(self, checkpoint: Dict[str, Any])
Hook to do whatever you need right before Slurm manager saves the model. Args: checkpoint: A dictionary in which you can save variables to save in a checkpoint. Contents need to be pickleable.
Hook to do whatever you need right before Slurm manager saves the model.
def on_hpc_save(self, checkpoint: Dict[str, Any]) -> None: """ Hook to do whatever you need right before Slurm manager saves the model. Args: checkpoint: A dictionary in which you can save variables to save in a checkpoint. Contents need to be pickleable. """
[ "def", "on_hpc_save", "(", "self", ",", "checkpoint", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":" ]
[ 229, 4 ]
[ 236, 11 ]
python
en
['en', 'error', 'th']
False
ModelIO.on_hpc_load
(self, checkpoint: Dict[str, Any])
Hook to do whatever you need right before Slurm manager loads the model. Args: checkpoint: A dictionary with variables from the checkpoint.
Hook to do whatever you need right before Slurm manager loads the model.
def on_hpc_load(self, checkpoint: Dict[str, Any]) -> None: """ Hook to do whatever you need right before Slurm manager loads the model. Args: checkpoint: A dictionary with variables from the checkpoint. """
[ "def", "on_hpc_load", "(", "self", ",", "checkpoint", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":" ]
[ 238, 4 ]
[ 244, 11 ]
python
en
['en', 'error', 'th']
False