code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def parse_passage(obj: dict) -> BioCPassage: passage = BioCPassage() passage.offset = obj['offset'] passage.infons = obj['infons'] if 'text' in obj: passage.text = obj['text'] for sentence in obj['sentences']: passage.add_sentence(parse_sentence(sentence)) for annot...
Deserialize a dict obj to a BioCPassage object
null
null
null
def parse_doc(obj: dict) -> BioCDocument: doc = BioCDocument() doc.id = obj['id'] doc.infons = obj['infons'] for passage in obj['passages']: doc.add_passage(parse_passage(passage)) for annotation in obj['annotations']: doc.add_annotation(parse_annotation(annotation)) ...
Deserialize a dict obj to a BioCDocument object
null
null
null
def load(fp, **kwargs) -> BioCCollection: obj = json.load(fp, **kwargs) return parse_collection(obj)
Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a BioCCollection object Args: fp: a file containing a JSON document **kwargs: Returns: BioCCollection: a collection
null
null
null
def loads(s: str, **kwargs) -> BioCCollection: obj = json.loads(s, **kwargs) return parse_collection(obj)
Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a BioCCollection object. Args: s(str): **kwargs: Returns: BioCCollection: a collection
null
null
null
''' Okay this worker is going build graphs from PCAP Bro output logs ''' # Grab the Bro log handles from the input bro_logs = input_data['pcap_bro'] # Weird log if 'weird_log' in bro_logs: stream = self.workbench.stream_sample(bro_logs['weird_log']) self...
def execute(self, input_data)
Okay this worker is going build graphs from PCAP Bro output logs
8.181881
5.623092
1.45505
''' Build up a graph (nodes and edges from a Bro http.log) ''' print 'Entering http_log_graph...' for row in list(stream): # Skip '-' hosts if (row['id.orig_h'] == '-'): continue # Add the originating host self.add_node(row['id.or...
def http_log_graph(self, stream)
Build up a graph (nodes and edges from a Bro http.log)
4.418089
3.493823
1.264543
''' Build up a graph (nodes and edges from a Bro dns.log) ''' for row in list(stream): # dataframes['files_log'][['md5','mime_type','missing_bytes','rx_hosts','source','tx_hosts']] # If the mime-type is interesting add the uri and the host->uri->host relationships ...
def files_log_graph(self, stream)
Build up a graph (nodes and edges from a Bro dns.log)
5.994499
5.117964
1.171266
self.on_create = on_create self.on_modify = on_modify self.on_delete = on_delete
def register_callbacks(self, on_create, on_modify, on_delete)
Register callbacks for file creation, modification, and deletion
1.726397
1.580189
1.092526
# Grab all the timestamp info before = self._file_timestamp_info(self.path) while True: gevent.sleep(1) after = self._file_timestamp_info(self.path) added = [fname for fname in after.keys() if fname not in before.keys()] removed...
def _start_monitoring(self)
Internal method that monitors the directory for changes
2.791372
2.599555
1.073788
files = [os.path.join(path, fname) for fname in os.listdir(path) if '.py' in fname] return dict ([(fname, os.path.getmtime(fname)) for fname in files])
def _file_timestamp_info(self, path)
Grab all the timestamps for the files in the directory
3.43659
3.078362
1.11637
''' Recursively traverse the yara/rules directory for rules ''' # Try to find the yara rules directory relative to the worker my_dir = os.path.dirname(os.path.realpath(__file__)) yara_rule_path = os.path.join(my_dir, 'yara/rules') if not os.path.exists(yara_rule_path): ...
def get_rules_from_disk(self)
Recursively traverse the yara/rules directory for rules
4.599134
3.856747
1.19249
''' yara worker execute method ''' raw_bytes = input_data['sample']['raw_bytes'] matches = self.rules.match_data(raw_bytes) # The matches data is organized in the following way # {'filename1': [match_list], 'filename2': [match_list]} # match_list = list of match ...
def execute(self, input_data)
yara worker execute method
6.185658
5.712306
1.082865
for i in xrange(0, len(data), chunk_size): yield data[i:i+chunk_size]
def chunks(data, chunk_size)
Yield chunk_size chunks from data.
1.739353
1.834413
0.94818
# Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Upload the files into workbench my_file = os.path.join(os.path.dirname(os...
def run()
This client pushes a file into Workbench.
3.903727
3.657221
1.067403
''' Recursively traverse the yara/rules directory for rules ''' # Try to find the yara rules directory relative to the worker my_dir = os.path.dirname(os.path.realpath(__file__)) yara_rule_path = os.path.join(my_dir, 'yara/rules') if not os.path.exists(yara_rule_path): raise RuntimeError('y...
def get_rules_from_disk()
Recursively traverse the yara/rules directory for rules
4.551302
3.859456
1.17926
''' Write the PCAPs to disk for Bro to process and return the pcap filenames ''' # Setup the pcap in the input data for processing by Bro. The input # may be either an individual sample or a sample set. file_list = [] if 'sample' in input_data: raw_bytes = input_data...
def setup_pcap_inputs(self, input_data)
Write the PCAPs to disk for Bro to process and return the pcap filenames
3.062682
2.666074
1.148761
''' Execute ''' # Get the bro script path (workers/bro/__load__.bro) script_path = self.bro_script_dir # Create a temporary directory with self.goto_temp_directory() as temp_dir: # Get the pcap inputs (filenames) print 'pcap_bro: Setting up PCAP inputs....
def execute(self, input_data)
Execute
4.024778
4.062498
0.990715
''' Bro subprocess manager ''' try: sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE) except OSError: raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args)) out...
def subprocess_manager(self, exec_args)
Bro subprocess manager
3.888631
3.510527
1.107706
rh.printSysLog("Enter getVM.getDirectory") parms = ["-T", rh.userid] results = invokeSMCLI(rh, "Image_Query_DM", parms) if results['overallRC'] == 0: results['response'] = re.sub('\*DVHOPT.*', '', results['response']) rh.printLn("N", results['response']) else: # SMAPI A...
def getDirectory(rh)
Get the virtual machine's directory statements. Input: Request Handle with the following properties: function - 'CMDVM' subfunction - 'CMD' userid - userid of the virtual machine Output: Request Handle updated with the results. Return code - 0: ok, no...
6.771434
6.395376
1.058802
rh.printSysLog("Enter getVM.getStatus, userid: " + rh.userid) results = isLoggedOn(rh, rh.userid) if results['rc'] != 0: # Uhoh, can't determine if guest is logged on or not rh.updateResults(results) rh.printSysLog("Exit getVM.getStatus, rc: " + str(rh.r...
def getStatus(rh)
Get the basic status of a virtual machine. Input: Request Handle with the following properties: function - 'CMDVM' subfunction - 'CMD' userid - userid of the virtual machine Output: Request Handle updated with the results. Return code - 0: ok, non-zer...
2.931704
2.912444
1.006613
raw_data = raw_data.split('\n') # clear blank lines data = [] for i in raw_data: i = i.strip(' \n') if i == '': continue else: data.append(i) # process data into one list of dicts results = [] for i in range(0, len(data), 5): temp...
def extract_fcp_data(raw_data, status)
extract data from smcli System_WWPN_Query output. Input: raw data returned from smcli Output: data extracted would be like: 'status:Free \n fcp_dev_no:1D2F\n physical_wwpn:C05076E9928051D1\n channel_path_id:8B\n npiv_wwpn': 'NONE'\n status:Free\n fcp_dev_no:1D2...
3.507899
3.618464
0.969444
rh.printSysLog("Enter changeVM.dedicate") parms = ["-T", rh.userid] hideList = [] results = invokeSMCLI(rh, "System_WWPN_Query", parms, hideInLog=hideList) if results['overallRC'] != 0: # SMAPI API failed. ...
def fcpinfo(rh)
Get fcp info and filter by the status. Input: Request Handle with the following properties: function - 'GETVM' subfunction - 'FCPINFO' userid - userid of the virtual machine parms['status'] - The status for filter results. Output: Request Han...
7.605082
7.244258
1.049808
if getattr(self, '_no_auto_update', None) is not None: return self._no_auto_update else: self._no_auto_update = utils._TempBool() return self._no_auto_update
def _no_auto_update_getter(self)
:class:`bool`. Boolean controlling whether the :meth:`start_update` method is automatically called by the :meth:`update` method Examples -------- You can disable the automatic update via >>> with data.no_auto_update: ... data.update(time=1) ... data.start_update() ...
3.457296
5.989491
0.577227
coord = np.asarray(coord) deltas = 0.5 * (coord[1:] - coord[:-1]) first = coord[0] - deltas[0] last = coord[-1] + deltas[-1] return np.r_[[first], coord[:-1] + deltas, [last]]
def _infer_interval_breaks(coord)
>>> _infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) Taken from xarray.plotting.plot module
2.462292
2.517552
0.97805
if VARIABLELABEL in arr.dims: return arr.coords[VARIABLELABEL].tolist() else: return arr.name
def _get_variable_names(arr)
Return the variable names of an array
8.415313
8.122106
1.0361
try: return OrderedDict(arr_names) except (ValueError, TypeError): # ValueError for cyordereddict, TypeError for collections.OrderedDict pass if arr_names is None: arr_names = repeat('arr{0}') elif isstring(arr_names): arr_names = repeat(arr_names) dims =...
def setup_coords(arr_names=None, sort=[], dims={}, **kwargs)
Sets up the arr_names dictionary for the plot Parameters ---------- arr_names: string, list of strings or dictionary Set the unique array names of the resulting arrays and (optionally) dimensions. - if string: same as list of strings (see below). Strings may include {0} w...
2.843084
2.773205
1.025198
if isinstance(arr, slice): return arr if len(arr) == 1: return slice(arr[0], arr[0] + 1) step = np.unique(arr[1:] - arr[:-1]) if len(step) == 1: return slice(arr[0], arr[-1] + step[0], step[0])
def to_slice(arr)
Test whether `arr` is an integer array that can be replaced by a slice Parameters ---------- arr: numpy.array Numpy integer array Returns ------- slice or None If `arr` could be converted to an array, this is returned, otherwise `None` is returned See Also ----...
1.94505
2.332369
0.833937
try: values = coord.values except AttributeError: values = coord if values.ndim == 0: return base_index.get_loc(values[()]) if len(values) == len(base_index) and (values == base_index).all(): return slice(None) values = np.array(list(map(lambda i: base_index.get_...
def get_index_from_coord(coord, base_index)
Function to return the coordinate as integer, integer array or slice If `coord` is zero-dimensional, the corresponding integer in `base_index` will be supplied. Otherwise it is first tried to return a slice, if that does not work an integer array with the corresponding indices is returned. Parameters ...
3.395286
2.763098
1.228797
def median(arr): return arr.min() + (arr.max() - arr.min())/2 import re from pandas import Index t_pattern = t_format for fmt, patt in t_patterns.items(): t_pattern = t_pattern.replace(fmt, patt) t_pattern = re.compile(t_pattern) time = list(range(len(files))) for i,...
def get_tdata(t_format, files)
Get the time information from file names Parameters ---------- t_format: str The string that can be used to get the time information in the files. Any numeric datetime format string (e.g. %Y, %m, %H) can be used, but not non-numeric strings like %b, etc. See [1]_ for the datetime fo...
3.226792
3.18058
1.01453
to_update = {} for v, obj in six.iteritems(ds.variables): units = obj.attrs.get('units', obj.encoding.get('units', None)) if units == 'day as %Y%m%d.%f' and np.issubdtype( obj.dtype, np.datetime64): to_update[v] = xr.Variable( obj.dims, AbsoluteTi...
def to_netcdf(ds, *args, **kwargs)
Store the given dataset as a netCDF file This functions works essentially the same as the usual :meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time units Parameters ---------- ds: xarray.Dataset The dataset to store %(xarray.Dataset.to_netcdf.parameters)s
3.479432
3.446348
1.0096
try: f = store.ds.file except AttributeError: return None try: return f.path except AttributeError: return None
def _get_fname_nio(store)
Try to get the file name from the NioDataStore store
4.84796
4.027171
1.203813
from tempfile import NamedTemporaryFile # if already specified, return that filename if ds.psy._filename is not None: return tuple([ds.psy._filename] + list(ds.psy.data_store)) def dump_nc(): # make sure that the data store is not closed by providing a # write argument ...
def get_filename_ds(ds, dump=True, paths=None, **kwargs)
Return the filename of the corresponding to a dataset This method returns the path to the `ds` or saves the dataset if there exists no filename Parameters ---------- ds: xarray.Dataset The dataset you want the path information for dump: bool If True and the dataset has not been...
3.575435
3.493121
1.023565
# use the absolute path name (is saver when saving the project) if isstring(filename_or_obj) and osp.exists(filename_or_obj): filename_or_obj = osp.abspath(filename_or_obj) if engine == 'gdal': from psyplot.gdal_store import GdalStore filename_or_obj = GdalStore(filename_or_obj)...
def open_dataset(filename_or_obj, decode_cf=True, decode_times=True, decode_coords=True, engine=None, gridfile=None, **kwargs)
Open an instance of :class:`xarray.Dataset`. This method has the same functionality as the :func:`xarray.open_dataset` method except that is supports an additional 'gdal' engine to open gdal Rasters (e.g. GeoTiffs) and that is supports absolute time units like ``'day as %Y%m%d.%f'`` (if `decode_cf` and...
3.578451
3.603738
0.992983
if t_format is not None or engine == 'gdal': if isinstance(paths, six.string_types): paths = sorted(glob(paths)) if not paths: raise IOError('no files to open') if t_format is not None: time, paths = get_tdata(t_format, paths) kwargs['concat_dim'] = t...
def open_mfdataset(paths, decode_cf=True, decode_times=True, decode_coords=True, engine=None, gridfile=None, t_format=None, **kwargs)
Open multiple files as a single dataset. This function is essentially the same as the :func:`xarray.open_mfdataset` function but (as the :func:`open_dataset`) supports additional decoding and the ``'gdal'`` engine. You can further specify the `t_format` parameter to get the time information from th...
3.800411
3.633559
1.04592
if isinstance(fname, xr.Dataset): return fname if not isstring(fname): try: # test iterable fname[0] except TypeError: pass else: if store_mod is not None and store_cls is not None: if isstring(store_mod): ...
def _open_ds_from_store(fname, store_mod=None, store_cls=None, **kwargs)
Open a dataset and return it
2.577351
2.50097
1.030541
if func is None: self._connections = [] else: self._connections.remove(func)
def disconnect(self, func=None)
Disconnect a function call to the signal. If None, all connections are disconnected
3.729108
2.935303
1.270434
try: return self._logger except AttributeError: name = '%s.%s' % (self.__module__, self.__class__.__name__) self._logger = logging.getLogger(name) self.logger.debug('Initializing...') return self._logger
def logger(self)
:class:`logging.Logger` of this instance
2.859803
2.776111
1.030147
for decoder_cls in cls._registry: if decoder_cls.can_decode(ds, var): return decoder_cls(ds) return CFDecoder(ds)
def get_decoder(cls, ds, var)
Class method to get the right decoder class that can decode the given dataset and variable Parameters ---------- %(CFDecoder.can_decode.parameters)s Returns ------- CFDecoder The decoder for the given dataset that can decode the variable ...
4.43944
4.691948
0.946183
def add_attrs(obj): if 'coordinates' in obj.attrs: extra_coords.update(obj.attrs['coordinates'].split()) obj.encoding['coordinates'] = obj.attrs.pop('coordinates') if 'bounds' in obj.attrs: extra_coords.add(obj.attrs['bounds']) ...
def decode_coords(ds, gridfile=None)
Sets the coordinates and bounds in a dataset This static method sets those coordinates and bounds that are marked marked in the netCDF attributes as coordinates in :attr:`ds` (without deleting them from the variable attributes because this information is necessary for visualizing the da...
2.786827
2.722317
1.023697
warn("The 'is_triangular' method is depreceated and will be removed " "soon! Use the 'is_unstructured' method!", DeprecationWarning, stacklevel=1) return str(var.attrs.get('grid_type')) == 'unstructured' or \ self._check_triangular_bounds(var)[0]
def is_triangular(self, var)
Test if a variable is on a triangular grid This method first checks the `grid_type` attribute of the variable (if existent) whether it is equal to ``"unstructered"``, then it checks whether the bounds are not two-dimensional. Parameters ---------- var: xarray.Variable o...
6.041553
5.100167
1.184579
if coords is None: coords = self.ds.coords axis = axis.lower() get_coord = self.get_x if axis == 'x' else self.get_y coord = get_coord(var, coords=coords) if coord is not None: bounds = self._get_coord_cell_node_coord(coord, coords, nans, ...
def get_cell_node_coord(self, var, coords=None, axis='x', nans=None)
Checks whether the bounds in the variable attribute are triangular Parameters ---------- var: xarray.Variable or xarray.DataArray The variable to check coords: dict Coordinates to use. If None, the coordinates of the dataset in the :attr:`ds` attribut...
3.657977
3.587956
1.019516
bounds = coord.attrs.get('bounds') if bounds is not None: bounds = self.ds.coords.get(bounds) if bounds is not None: if coords is not None: bounds = bounds.sel(**{ key: coords[key] for key in set(coords).int...
def _get_coord_cell_node_coord(self, coord, coords=None, nans=None, var=None)
Get the boundaries of an unstructed coordinate Parameters ---------- coord: xr.Variable The coordinate whose bounds should be returned %(CFDecoder.get_cell_node_coord.parameters.no_var|axis)s Returns ------- %(CFDecoder.get_cell_node_coord.returns)s
3.261508
3.121249
1.044937
# !!! WILL BE REMOVED IN THE NEAR FUTURE! !!! bounds = self.get_cell_node_coord(var, coords, axis=axis, nans=nans) if bounds is not None: return bounds.shape[-1] == 3, bounds else: return None, None
def _check_triangular_bounds(self, var, coords=None, axis='x', nans=None)
Checks whether the bounds in the variable attribute are triangular Parameters ---------- %(CFDecoder.get_cell_node_coord.parameters)s Returns ------- bool or None True, if unstructered, None if it could not be determined xarray.Coordinate or None ...
6.648739
5.225376
1.272394
if str(var.attrs.get('grid_type')) == 'unstructured': return True xcoord = self.get_x(var) if xcoord is not None: bounds = self._get_coord_cell_node_coord(xcoord) if bounds is not None and bounds.shape[-1] > 2: return True
def is_unstructured(self, var)
Test if a variable is on an unstructered grid Parameters ---------- %(CFDecoder.is_triangular.parameters)s Returns ------- %(CFDecoder.is_triangular.returns)s Notes ----- Currently this is the same as :meth:`is_triangular` method, but may ...
5.104945
5.933268
0.860393
xcoord = self.get_x(var) return xcoord is not None and xcoord.ndim == 2
def is_circumpolar(self, var)
Test if a variable is on a circumpolar grid Parameters ---------- %(CFDecoder.is_triangular.parameters)s Returns ------- %(CFDecoder.is_triangular.returns)s
7.655764
8.942276
0.856131
axis = axis.lower() if axis not in list('xyzt'): raise ValueError("Axis must be one of X, Y, Z, T, not {0}".format( axis)) # we first check for the dimensions and then for the coordinates # attribute coords = coords or self.ds.coords c...
def get_variable_by_axis(self, var, axis, coords=None)
Return the coordinate matching the specified axis This method uses to ``'axis'`` attribute in coordinates to return the corresponding coordinate of the given variable Possible types -------------- var: xarray.Variable The variable to get the dimension for ax...
4.129968
3.118812
1.324212
coords = coords or self.ds.coords coord = self.get_variable_by_axis(var, 'x', coords) if coord is not None: return coord return coords.get(self.get_xname(var))
def get_x(self, var, coords=None)
Get the x-coordinate of a variable This method searches for the x-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'X', otherwise it looks whether there is an intersection between the :attr:`x` attribute and the variabl...
4.671911
5.084524
0.918849
if coords is not None: coord = self.get_variable_by_axis(var, 'x', coords) if coord is not None and coord.name in var.dims: return coord.name dimlist = list(self.x.intersection(var.dims)) if dimlist: if len(dimlist) > 1: ...
def get_xname(self, var, coords=None)
Get the name of the x-dimension This method gives the name of the x-dimension (which is not necessarily the name of the coordinate if the variable has a coordinate attribute) Parameters ---------- var: xarray.Variables The variable to get the dimension for c...
4.586169
4.967404
0.923253
coords = coords or self.ds.coords coord = self.get_variable_by_axis(var, 'y', coords) if coord is not None: return coord return coords.get(self.get_yname(var))
def get_y(self, var, coords=None)
Get the y-coordinate of a variable This method searches for the y-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'Y', otherwise it looks whether there is an intersection between the :attr:`y` attribute and the variabl...
4.606286
5.052008
0.911773
if coords is not None: coord = self.get_variable_by_axis(var, 'y', coords) if coord is not None and coord.name in var.dims: return coord.name dimlist = list(self.y.intersection(var.dims)) if dimlist: if len(dimlist) > 1: ...
def get_yname(self, var, coords=None)
Get the name of the y-dimension This method gives the name of the y-dimension (which is not necessarily the name of the coordinate if the variable has a coordinate attribute) Parameters ---------- var: xarray.Variables The variable to get the dimension for c...
4.539111
4.780725
0.949461
coords = coords or self.ds.coords coord = self.get_variable_by_axis(var, 'z', coords) if coord is not None: return coord zname = self.get_zname(var) if zname is not None: return coords.get(zname) return None
def get_z(self, var, coords=None)
Get the vertical (z-) coordinate of a variable This method searches for the z-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'Z', otherwise it looks whether there is an intersection between the :attr:`z` attribute and...
3.361269
3.569762
0.941595
if coords is not None: coord = self.get_variable_by_axis(var, 'z', coords) if coord is not None and coord.name in var.dims: return coord.name dimlist = list(self.z.intersection(var.dims)) if dimlist: if len(dimlist) > 1: ...
def get_zname(self, var, coords=None)
Get the name of the z-dimension This method gives the name of the z-dimension (which is not necessarily the name of the coordinate if the variable has a coordinate attribute) Parameters ---------- var: xarray.Variables The variable to get the dimension for c...
4.751306
4.856053
0.97843
coords = coords or self.ds.coords coord = self.get_variable_by_axis(var, 't', coords) if coord is not None: return coord dimlist = list(self.t.intersection(var.dims).intersection(coords)) if dimlist: if len(dimlist) > 1: warn("Foun...
def get_t(self, var, coords=None)
Get the time coordinate of a variable This method searches for the time coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'T', otherwise it looks whether there is an intersection between the :attr:`t` attribute and the v...
4.262014
4.101015
1.039258
if coords is not None: coord = self.get_variable_by_axis(var, 't', coords) if coord is not None and coord.name in var.dims: return coord.name dimlist = list(self.t.intersection(var.dims)) if dimlist: if len(dimlist) > 1: ...
def get_tname(self, var, coords=None)
Get the name of the t-dimension This method gives the name of the time dimension Parameters ---------- var: xarray.Variables The variable to get the dimension for coords: dict The coordinates to use for checking the axis attribute. If None, t...
4.775713
4.758289
1.003662
if coords is None: coords = arr.coords else: coords = { label: coord for label, coord in six.iteritems(arr.coords) if label in coords} ret = self.get_coord_idims(coords) # handle the coordinates that are not in the dataset ...
def get_idims(self, arr, coords=None)
Get the coordinates in the :attr:`ds` dataset as int or slice This method returns a mapping from the coordinate names of the given `arr` to an integer, slice or an array of integer that represent the coordinates in the :attr:`ds` dataset and can be used to extract the given `arr` via th...
5.067259
5.430932
0.933037
ret = dict( (label, get_index_from_coord(coord, self.ds.indexes[label])) for label, coord in six.iteritems(coords) if label in self.ds.indexes) return ret
def get_coord_idims(self, coords)
Get the slicers for the given coordinates from the base dataset This method converts `coords` to slicers (list of integers or ``slice`` objects) Parameters ---------- coords: dict A subset of the ``ds.coords`` attribute of the base dataset :attr:`ds` ...
4.667817
6.29367
0.741668
if 'bounds' in coord.attrs: bounds = self.ds.coords[coord.attrs['bounds']] if ignore_shape: return bounds.values.ravel() if not bounds.shape[:-1] == coord.shape: bounds = self.ds.isel(**self.get_idims(coord)) try: ...
def get_plotbounds(self, coord, kind=None, ignore_shape=False)
Get the bounds of a coordinate This method first checks the ``'bounds'`` attribute of the given `coord` and if it fails, it calculates them. Parameters ---------- coord: xarray.Coordinate The coordinate to get the bounds for kind: str The interpo...
5.001845
4.985853
1.003208
if bounds.shape[:-1] != coord.shape or bounds.shape[-1] != 2: raise ValueError( "Cannot interprete bounds with shape {0} for {1} " "coordinate with shape {2}.".format( bounds.shape, coord.name, coord.shape)) ret = np.zeros(tuple(m...
def _get_plotbounds_from_cf(coord, bounds)
Get plot bounds from the bounds stored as defined by CFConventions Parameters ---------- coord: xarray.Coordinate The coordinate to get the bounds for bounds: xarray.DataArray The bounds as inferred from the attributes of the given `coord` Returns ...
3.258615
3.352461
0.972007
warn("The 'get_triangles' method is depreceated and will be removed " "soon! Use the 'get_cell_node_coord' method!", DeprecationWarning, stacklevel=stacklevel) from matplotlib.tri import Triangulation def get_vertices(axis): bounds = self._check_tr...
def get_triangles(self, var, coords=None, convert_radian=True, copy=False, src_crs=None, target_crs=None, nans=None, stacklevel=1)
Get the triangles for the variable Parameters ---------- var: xarray.Variable or xarray.DataArray The variable to use coords: dict Alternative coordinates to use. If None, the coordinates of the :attr:`ds` dataset are used convert_radian: bool...
3.059773
3.077356
0.994286
if coord.ndim == 1: return _infer_interval_breaks(coord) elif coord.ndim == 2: from scipy.interpolate import interp2d kind = kind or rcParams['decoder.interp_kind'] y, x = map(np.arange, coord.shape) new_x, new_y = map(_infer_interval_...
def _infer_interval_breaks(coord, kind=None)
Interpolate the bounds from the data in coord Parameters ---------- %(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s Returns ------- %(CFDecoder.get_plotbounds.returns)s Notes ----- this currently only works for rectilinear grids
3.180117
2.9761
1.068552
if decode_coords: ds = cls.decode_coords(ds, gridfile=gridfile) if decode_times: for k, v in six.iteritems(ds.variables): # check for absolute time units and make sure the data is not # already decoded via dtype check if v....
def _decode_ds(cls, ds, gridfile=None, decode_coords=True, decode_times=True)
Static method to decode coordinates and time informations This method interpretes absolute time informations (stored with units ``'day as %Y%m%d.%f'``) and coordinates Parameters ---------- %(CFDecoder.decode_coords.parameters)s decode_times : bool, optional ...
4.322372
4.052949
1.066476
for decoder_cls in cls._registry + [CFDecoder]: ds = decoder_cls._decode_ds(ds, *args, **kwargs) return ds
def decode_ds(cls, ds, *args, **kwargs)
Static method to decode coordinates and time informations This method interpretes absolute time informations (stored with units ``'day as %Y%m%d.%f'``) and coordinates Parameters ---------- %(CFDecoder._decode_ds.parameters)s Returns ------- xarray.Data...
6.359455
7.001426
0.908308
method_mapping = {'x': self.get_xname, 'z': self.get_zname, 't': self.get_tname} dims = dict(dims) if self.is_unstructured(var): # we assume a one-dimensional grid method_mapping['y'] = self.get_xname else: method_mapping['y'] =...
def correct_dims(self, var, dims={}, remove=True)
Expands the dimensions to match the dims in the variable Parameters ---------- var: xarray.Variable The variable to get the data for dims: dict a mapping from dimension to the slices remove: bool If True, dimensions in `dims` that are not in t...
3.3641
3.49132
0.963561
dims = dict(dims) name_map = {self.get_xname(var, self.ds.coords): 'x', self.get_yname(var, self.ds.coords): 'y', self.get_zname(var, self.ds.coords): 'z', self.get_tname(var, self.ds.coords): 't'} dims = dict(dims) for...
def standardize_dims(self, var, dims={})
Replace the coordinate names through x, y, z and t Parameters ---------- var: xarray.Variable The variable to use the dimensions of dims: dict The dictionary to use for replacing the original dimensions Returns ------- dict Th...
2.255096
2.48025
0.909221
mesh = var.attrs.get('mesh') if mesh is None: return None if coords is None: coords = self.ds.coords return coords.get(mesh, self.ds.coords.get(mesh))
def get_mesh(self, var, coords=None)
Get the mesh variable for the given `var` Parameters ---------- var: xarray.Variable The data source whith the ``'mesh'`` attribute coords: dict The coordinates to use. If None, the coordinates of the dataset of this decoder is used Returns ...
3.467265
3.366903
1.029808
warn("The 'get_triangles' method is depreceated and will be removed " "soon! Use the 'get_cell_node_coord' method!", DeprecationWarning, stacklevel=stacklevel) from matplotlib.tri import Triangulation if coords is None: coords = self.ds.coords ...
def get_triangles(self, var, coords=None, convert_radian=True, copy=False, src_crs=None, target_crs=None, nans=None, stacklevel=1)
Get the of the given coordinate. Parameters ---------- %(CFDecoder.get_triangles.parameters)s Returns ------- %(CFDecoder.get_triangles.returns)s Notes ----- If the ``'location'`` attribute is set to ``'node'``, a delaunay triangulation ...
3.058662
3.157098
0.968821
if coords is None: coords = self.ds.coords idims = self.get_coord_idims(coords) def get_coord(coord): coord = coords.get(coord, self.ds.coords.get(coord)) return coord.isel(**{d: sl for d, sl in idims.items() if d in...
def get_cell_node_coord(self, var, coords=None, axis='x', nans=None)
Checks whether the bounds in the variable attribute are triangular Parameters ---------- %(CFDecoder.get_cell_node_coord.parameters)s Returns ------- %(CFDecoder.get_cell_node_coord.returns)s
3.857191
3.803599
1.01409
extra_coords = set(ds.coords) for var in six.itervalues(ds.variables): if 'mesh' in var.attrs: mesh = var.attrs['mesh'] if mesh not in extra_coords: extra_coords.add(mesh) try: mesh_var =...
def decode_coords(ds, gridfile=None)
Reimplemented to set the mesh variables as coordinates Parameters ---------- %(CFDecoder.decode_coords.parameters)s Returns ------- %(CFDecoder.decode_coords.returns)s
2.403378
2.408097
0.99804
def get_coord(coord): return coords.get(coord, self.ds.coords.get(coord)) return list(map(get_coord, coord.attrs.get('node_coordinates', '').split()[:2]))
def get_nodes(self, coord, coords)
Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates
7.3327
6.099957
1.20209
if coords is None: coords = self.ds.coords # first we try the super class ret = super(UGridDecoder, self).get_x(var, coords) # but if that doesn't work because we get the variable name in the # dimension of `var`, we use the means of the triangles if ...
def get_x(self, var, coords=None)
Get the centers of the triangles in the x-dimension Parameters ---------- %(CFDecoder.get_y.parameters)s Returns ------- %(CFDecoder.get_y.returns)s
6.067614
5.98863
1.013189
if self._plot is None: import psyplot.project as psy self._plot = psy.DataArrayPlotter(self) return self._plot
def plot(self)
An object to visualize this data object To make a 2D-plot with the :mod:`psy-simple <psy_simple.plugin>` plugin, you can just type .. code-block:: python plotter = da.psy.plot.plot2d() It will create a new :class:`psyplot.plotter.Plotter` instance with the extract...
11.526074
5.899919
1.953599
self.replot = self.replot or replot if self.plotter is not None: self.plotter._register_update(replot=self.replot, fmt=fmt, force=force, todefault=todefault)
def _register_update(self, replot=False, fmt={}, force=False, todefault=False)
Register new formatoptions for updating Parameters ---------- replot: bool Boolean that determines whether the data specific formatoptions shall be updated in any case or not. Note, if `dims` is not empty or any coordinate keyword is in ``**kwargs``, this wil...
2.909458
3.263959
0.891389
if self.plotter is not None: return self.plotter.start_update(draw=draw, queues=queues)
def start_update(self, draw=None, queues=None)
Conduct the formerly registered updates This method conducts the updates that have been registered via the :meth:`update` method. You can call this method if the :attr:`no_auto_update` attribute of this instance and the `auto_update` parameter in the :meth:`update` method has been set t...
3.352404
4.437854
0.755411
fmt = dict(fmt) fmt.update(kwargs) self._register_update(replot=replot, fmt=fmt, force=force, todefault=todefault) if not self.no_auto_update or auto_update: self.start_update(draw=draw)
def update(self, fmt={}, replot=False, draw=None, auto_update=False, force=False, todefault=False, **kwargs)
Update the coordinates and the plot This method updates all arrays in this list with the given coordinate values and formatoptions. Parameters ---------- %(InteractiveBase._register_update.parameters)s auto_update: bool Boolean determining whether or not the...
4.415153
4.457347
0.990534
return set.intersection(*map( set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self)))
def dims_intersect(self)
Dimensions of the arrays in this list that are used in all arrays
9.135562
6.757304
1.351954
ret = set() for arr in self: if isinstance(arr, InteractiveList): ret.update(arr.names) else: ret.add(arr.name) return ret
def names(self)
Set of the variable in this list
4.333111
3.925256
1.103905
return [ _get_variable_names(arr) if not isinstance(arr, ArrayList) else arr.all_names for arr in self]
def all_names(self)
The variable names for each of the arrays in this list
12.148347
7.457188
1.629079
return [ _get_dims(arr) if not isinstance(arr, ArrayList) else arr.all_dims for arr in self]
def all_dims(self)
The dimensions for each of the arrays in this list
11.013177
7.833019
1.405994
return [ arr.psy.decoder.is_unstructured(arr) if not isinstance(arr, ArrayList) else arr.is_unstructured for arr in self]
def is_unstructured(self)
A boolean for each array whether it is unstructured or not
16.14706
12.032623
1.34194
return set.intersection(*map( set, (getattr(arr, 'coords_intersect', arr.coords) for arr in self) ))
def coords_intersect(self)
Coordinates of the arrays in this list that are used in all arrays
8.650472
6.613419
1.308018
return self.__class__( (arr for arr in self if arr.psy.plotter is not None), auto_update=bool(self.auto_update))
def with_plotter(self)
The arrays in this instance that are visualized with a plotter
11.108092
8.337036
1.332379
return list(chain.from_iterable( ([arr] if not isinstance(arr, InteractiveList) else arr.arrays for arr in self)))
def arrays(self)
A list of all the :class:`xarray.DataArray` instances in this list
10.212137
9.626505
1.060835
name_in_me = arr.psy.arr_name in self.arr_names if not name_in_me: return arr, False elif name_in_me and not self._contains_array(arr): if new_name is False: raise ValueError( "Array name %s is already in use! Set the `new_name...
def rename(self, arr, new_name=True)
Rename an array to find a name that isn't already in the list Parameters ---------- arr: InteractiveBase A :class:`InteractiveArray` or :class:`InteractiveList` instance whose name shall be checked new_name: bool or str If False, and the ``arr_name`` ...
4.716822
4.152928
1.135782
if not deep: return self.__class__(self[:], attrs=self.attrs.copy(), auto_update=not bool(self.no_auto_update)) else: return self.__class__( [arr.psy.copy(deep) for arr in self], attrs=self.attrs.copy(), a...
def copy(self, deep=False)
Returns a copy of the list Parameters ---------- deep: bool If False (default), only the list is copied and not the contained arrays, otherwise the contained arrays are deep copied
4.668001
4.997078
0.934146
def filter_ignores(item): return item[0] not in ignore_keys and isinstance(item[1], dict) if 'fname' in data: return {tuple( [data['fname'], data['store']] + ([data.get('concat_dim')] if concat_dim else []))} return set(chain(*map(...
def _get_dsnames(cls, data, ignore_keys=['attrs', 'plotter', 'ds'], concat_dim=False)
Recursive method to get all the file names out of a dictionary `data` created with the :meth`array_info` method
4.197016
4.162265
1.008349
ds_description = {'ds', 'fname', 'num', 'arr', 'store'} if 'ds' in data: # make sure that the data set has a number assigned to it data['ds'].psy.num keys_in_data = ds_description.intersection(data) if keys_in_data: return {key: data[key] for ...
def _get_ds_descriptions_unsorted( cls, data, ignore_keys=['attrs', 'plotter'], nums=None)
Recursive method to get all the file names or datasets out of a dictionary `data` created with the :meth`array_info` method
4.102643
4.082073
1.005039
tnames = set() for arr in self: if isinstance(arr, InteractiveList): tnames.update(arr.get_tnames()) else: tnames.add(arr.psy.decoder.get_tname( next(arr.psy.iter_base_variables), arr.coords)) return tnames - {N...
def _get_tnames(self)
Get the name of the time coordinate of the objects in this list
8.153724
7.299322
1.117052
for arr in self: arr.psy._register_update(method=method, replot=replot, dims=dims, fmt=fmt, force=force, todefault=todefault)
def _register_update(self, method='isel', replot=False, dims={}, fmt={}, force=False, todefault=False)
Register new dimensions and formatoptions for updating. The keywords are the same as for each single array Parameters ---------- %(InteractiveArray._register_update.parameters)s
4.404492
4.185662
1.052281
def worker(arr): results[arr.psy.arr_name] = arr.psy.start_update( draw=False, queues=queues) if len(self) == 0: return results = {} threads = [Thread(target=worker, args=(arr,), name='update_%s' % arr.psy.arr_na...
def start_update(self, draw=None)
Conduct the registered plot updates This method starts the updates from what has been registered by the :meth:`update` method. You can call this method if you did not set the `auto_update` parameter when calling the :meth:`update` method to True and when the :attr:`no_auto_update` attri...
3.876366
3.743712
1.035434
dims = dict(dims) fmt = dict(fmt) vars_and_coords = set(chain( self.dims, self.coords, ['name', 'x', 'y', 'z', 't'])) furtherdims, furtherfmt = utils.sort_kwargs(kwargs, vars_and_coords) dims.update(furtherdims) fmt.update(furtherfmt) self._r...
def update(self, method='isel', dims={}, fmt={}, replot=False, auto_update=False, draw=None, force=False, todefault=False, enable_post=None, **kwargs)
Update the coordinates and the plot This method updates all arrays in this list with the given coordinate values and formatoptions. Parameters ---------- %(InteractiveArray._register_update.parameters)s %(InteractiveArray.update.parameters.auto_update)s %(ArrayL...
4.614866
4.285024
1.076976
for fig in set(chain(*map( lambda arr: arr.psy.plotter.figs2draw, self.with_plotter))): self.logger.debug("Drawing figure %s", fig.number) fig.canvas.draw() for arr in self: if arr.psy.plotter is not None: arr.psy.plotter._figs...
def draw(self)
Draws all the figures in this instance
5.880327
5.784645
1.016541
arr = self(arr_name=val.psy.arr_name)[0] is_not_list = any( map(lambda a: not isinstance(a, InteractiveList), [arr, val])) is_list = any(map(lambda a: isinstance(a, InteractiveList), [arr, val])) # if one is an InteractiveLis...
def _contains_array(self, val)
Checks whether exactly this array is in the list
5.257689
4.952793
1.06156
names = self.arr_names counter = counter or iter(range(1000)) try: new_name = next( filter(lambda n: n not in names, map(fmt_str.format, counter))) except StopIteration: raise ValueError( "{0} already...
def next_available_name(self, fmt_str='arr{0}', counter=None)
Create a new array out of the given format string Parameters ---------- format_str: str The base string to use. ``'{0}'`` will be replaced by a counter counter: iterable An iterable where the numbers should be drawn from. If None, ``range(100)`` is us...
3.758454
4.04369
0.929462
arr, renamed = self.rename(value, new_name) if renamed is not None: super(ArrayList, self).append(value)
def append(self, value, new_name=False)
Append a new array to the list Parameters ---------- value: InteractiveBase The data object to append to this list %(ArrayList.rename.parameters.new_name)s Raises ------ %(ArrayList.rename.raises)s See Also -------- list.appe...
8.493489
9.226703
0.920534
# extend those arrays that aren't alredy in the list super(ArrayList, self).extend(t[0] for t in filter( lambda t: t[1] is not None, ( self.rename(arr, new_name) for arr in iterable)))
def extend(self, iterable, new_name=False)
Add further arrays from an iterable to this list Parameters ---------- iterable Any iterable that contains :class:`InteractiveBase` instances %(ArrayList.rename.parameters.new_name)s Raises ------ %(ArrayList.rename.raises)s See Also ...
7.981792
8.220078
0.971012
name = arr if isinstance(arr, six.string_types) else arr.psy.arr_name if arr not in self: raise ValueError( "Array {0} not in the list".format(name)) for i, arr in enumerate(self): if arr.psy.arr_name == name: del self[i] ...
def remove(self, arr)
Removes an array from the list Parameters ---------- arr: str or :class:`InteractiveBase` The array name or the data object in this list to remove Raises ------ ValueError If no array with the specified array name is in the list
3.623214
3.546096
1.021747
ret = super(self.__class__, self)._njobs or [0] ret[0] += 1 return ret
def _njobs(self)
%(InteractiveBase._njobs)s
9.016028
6.60785
1.364442
ArrayList._register_update(self, method=method, dims=dims) InteractiveBase._register_update(self, fmt=fmt, todefault=todefault, replot=bool(dims) or replot, force=force)
def _register_update(self, method='isel', replot=False, dims={}, fmt={}, force=False, todefault=False)
Register new dimensions and formatoptions for updating Parameters ---------- %(InteractiveArray._register_update.parameters)s
6.172769
6.5573
0.941358
if queues is not None: queues[0].get() try: for arr in self: arr.psy.start_update(draw=False) self.onupdate.emit() except Exception: self._finish_all(queues) raise if queues is not None: queu...
def start_update(self, draw=None, queues=None)
Conduct the formerly registered updates This method conducts the updates that have been registered via the :meth:`update` method. You can call this method if the :attr:`auto_update` attribute of this instance is True and the `auto_update` parameter in the :meth:`update` method has been ...
5.399488
6.667485
0.809824
plotter = kwargs.pop('plotter', None) make_plot = kwargs.pop('make_plot', True) instance = super(InteractiveList, cls).from_dataset(*args, **kwargs) if plotter is not None: plotter.initialize_plot(instance, make_plot=make_plot) return instance
def from_dataset(cls, *args, **kwargs)
Create an InteractiveList instance from the given base dataset Parameters ---------- %(ArrayList.from_dataset.parameters.no_plotter)s plotter: psyplot.plotter.Plotter The plotter instance that is used to visualize the data in this list make_plot: bool ...
3.192577
2.210412
1.444336