Search is not available for this dataset
text
stringlengths
75
104k
def execute_reliabledictionary(client, application_name, service_name, input_file): """Execute create, update, delete operations on existing reliable dictionaries. carry out create, update and delete operations on existing reliable dictionaries for given application and service. :param application_name: N...
def select_arg_verify(endpoint, cert, key, pem, ca, aad, no_verify): #pylint: disable=invalid-name,too-many-arguments """Verify arguments for select command""" if not (endpoint.lower().startswith('http') or endpoint.lower().startswith('https')): raise CLIError('Endpoint must be HTTP or HTTP...
def select(endpoint, cert=None, key=None, pem=None, ca=None, #pylint: disable=invalid-name, too-many-arguments aad=False, no_verify=False): #pylint: disable-msg=too-many-locals """ Connects to a Service Fabric cluster endpoint. If connecting to secure cluster specify an absolute path to a cer...
def get_aad_token(endpoint, no_verify): #pylint: disable-msg=too-many-locals """Get AAD token""" from azure.servicefabric.service_fabric_client_ap_is import ( ServiceFabricClientAPIs ) from sfctl.auth import ClientCertAuthentication from sfctl.config import set_aad_metadata auth = C...
def _openpyxl_read_xl(xl_path: str): """ Use openpyxl to read an Excel file. """ try: wb = load_workbook(filename=xl_path, read_only=True) except: raise else: return wb
def _check_xl_path(xl_path: str): """ Return the expanded absolute path of `xl_path` if if exists and 'xlrd' or 'openpyxl' depending on which module should be used for the Excel file in `xl_path`. Parameters ---------- xl_path: str Path to an Excel file Returns ------- xl_p...
def read_xl(xl_path: str): """ Return the workbook from the Excel file in `xl_path`.""" xl_path, choice = _check_xl_path(xl_path) reader = XL_READERS[choice] return reader(xl_path)
def get_sheet_list(xl_path: str) -> List: """Return a list with the name of the sheets in the Excel file in `xl_path`. """ wb = read_xl(xl_path) if hasattr(wb, 'sheetnames'): return wb.sheetnames else: return wb.sheet_names()
def concat_sheets(xl_path: str, sheetnames=None, add_tab_names=False): """ Return a pandas DataFrame with the concat'ed content of the `sheetnames` from the Excel file in `xl_path`. Parameters ---------- xl_path: str Path to the Excel file sheetnames: list of str List of ex...
def _check_cols(df, col_names): """ Raise an AttributeError if `df` does not have a column named as an item of the list of strings `col_names`. """ for col in col_names: if not hasattr(df, col): raise AttributeError("DataFrame does not have a '{}' column, got {}.".format(col, ...
def col_values(df, col_name): """ Return a list of not null values from the `col_name` column of `df`.""" _check_cols(df, [col_name]) if 'O' in df[col_name] or pd.np.issubdtype(df[col_name].dtype, str): # if the column is of strings return [nom.lower() for nom in df[pd.notnull(df)][col_name] if not...
def duplicated_rows(df, col_name): """ Return a DataFrame with the duplicated values of the column `col_name` in `df`.""" _check_cols(df, [col_name]) dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])] return dups
def duplicated(values: Sequence): """ Return the duplicated items in `values`""" vals = pd.Series(values) return vals[vals.duplicated()]
def timestamp_with_tzinfo(dt): """ Serialize a date/time value into an ISO8601 text representation adjusted (if needed) to UTC timezone. For instance: >>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391)) '2012-04-10T22:38:20.604391Z' """ utc = tzutc() if dt.tzinfo: ...
def _to_string(data): """ Convert to string all values in `data`. Parameters ---------- data: dict[str]->object Returns ------- string_data: dict[str]->str """ sdata = data.copy() for k, v in data.items(): if isinstance(v, datetime): sdata[k] = timestamp_to_...
def insert_unique(table, data, unique_fields=None, *, raise_if_found=False): """Insert `data` into `table` ensuring that data has unique values in `table` for the fields listed in `unique_fields`. If `raise_if_found` is True, will raise an NotUniqueItemError if another item with the same `unique_fields...
def search_sample(table, sample): """Search for items in `table` that have the same field sub-set values as in `sample`. Parameters ---------- table: tinydb.table sample: dict Sample data Returns ------- search_result: list of dict List of the items found. The list is ...
def search_unique(table, sample, unique_fields=None): """ Search for items in `table` that have the same field sub-set values as in `sample`. Expecting it to be unique, otherwise will raise an exception. Parameters ---------- table: tinydb.table sample: dict Sample data Returns ...
def find_unique(table, sample, unique_fields=None): """Search in `table` an item with the value of the `unique_fields` in the `sample` sample. Check if the the obtained result is unique. If nothing is found will return an empty list, if there is more than one item found, will raise an IndexError. Param...
def _query_sample(sample, operators='__eq__'): """Create a TinyDB query that looks for items that have each field in `sample` with a value compared with the correspondent operation in `operators`. Parameters ---------- sample: dict The sample data operators: str or list of str ...
def _query_data(data, field_names=None, operators='__eq__'): """Create a tinyDB Query object that looks for items that confirms the correspondent operator from `operators` for each `field_names` field values from `data`. Parameters ---------- data: dict The data sample field_names: str...
def _concat_queries(queries, operators='__and__'): """Create a tinyDB Query object that is the concatenation of each query in `queries`. The concatenation operator is taken from `operators`. Parameters ---------- queries: list of tinydb.Query The list of tinydb.Query to be joined. oper...
def _build_query(field_name, field_value, operator='__eq__'): """Create a tinyDB Query object with the format: (where(`field_name`) `operator` `field_value`) Parameters ---------- field_name: str The name of the field to be queried. field_value: The value of the field oper...
def search_by_eid(self, table_name, eid): """Return the element in `table_name` with Object ID `eid`. If None is found will raise a KeyError exception. Parameters ---------- table_name: str The name of the table to look in. eid: int The Object ID...
def insert_unique(self, table_name, data, unique_fields=None, *, raise_if_found=False): """Insert `data` into `table` ensuring that data has unique values in `table` for the fields listed in `unique_fields`. If `raise_if_found` is True, will raise an NotUniqueItemError if another item w...
def search_unique(self, table_name, sample, unique_fields=None): """ Search in `table` an item with the value of the `unique_fields` in the `data` sample. Check if the the obtained result is unique. If nothing is found will return an empty list, if there is more than one item found, will raise a...
def search_sample(self, table_name, sample): """Search for items in `table` that have the same field sub-set values as in `sample`. Parameters ---------- table_name: str sample: dict Sample data Returns ------- search_result: list of dict ...
def is_unique(self, table_name, sample, unique_fields=None): """Return True if an item with the value of `unique_fields` from `data` is unique in the table with `table_name`. False if no sample is found or more than one is found. See function `find_unique` for more details. Par...
def update_unique(self, table_name, fields, data, cond=None, unique_fields=None, *, raise_if_not_found=False): """Update the unique matching element to have a given set of fields. Parameters ---------- table_name: str fields: dict or function[dict -> None]...
def count(self, table_name, sample): """Return the number of items that match the `sample` field values in table `table_name`. Check function search_sample for more details. """ return len(list(search_sample(table=self.table(table_name), samp...
def is_img(obj): """ Check for get_data and get_affine method in an object Parameters ---------- obj: any object Tested object Returns ------- is_img: boolean True if get_data and get_affine methods are present and callable, False otherwise. """ try: ...
def get_data(img): """Get the data in the image without having a side effect on the Nifti1Image object Parameters ---------- img: Nifti1Image Returns ------- np.ndarray """ if hasattr(img, '_data_cache') and img._data_cache is None: # Copy locally the nifti_image to avoid t...
def get_shape(img): """Return the shape of img. Paramerers ----------- img: Returns ------- shape: tuple """ if hasattr(img, 'shape'): shape = img.shape else: shape = img.get_data().shape return shape
def is_valid_coordinate(img, i, j, k): """Return True if the given (i, j, k) voxel grid coordinate values are within the img boundaries. Parameters ---------- @param img: @param i: @param j: @param k: Returns ------- bool """ imgx, imgy, imgz = get_shape(img) return...
def check_img_compatibility(one_img, another_img, only_check_3d=False): """Return true if one_img and another_img have the same shape. False otherwise. If both are nibabel.Nifti1Image will also check for affine matrices. Parameters ---------- one_img: nibabel.Nifti1Image or np.ndarray anot...
def have_same_affine(one_img, another_img, only_check_3d=False): """Return True if the affine matrix of one_img is close to the affine matrix of another_img. False otherwise. Parameters ---------- one_img: nibabel.Nifti1Image another_img: nibabel.Nifti1Image only_check_3d: bool If...
def _make_it_3d(img): """Enforce that img is a 3D img-like object, if it is not, raise a TypeError. i.e., remove dimensions of size 1. Parameters ---------- img: img-like object Returns ------- 3D img-like object """ shape = get_shape(img) if len(shape) == 3: return...
def check_img(image, make_it_3d=False): """Check that image is a proper img. Turn filenames into objects. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1...
def repr_imgs(imgs): """Printing of img or imgs""" if isinstance(imgs, string_types): return imgs if isinstance(imgs, collections.Iterable): return '[{}]'.format(', '.join(repr_imgs(img) for img in imgs)) # try get_filename try: filename = imgs.get_filename() if fil...
def have_same_shape(array1, array2, nd_to_check=None): """ Returns true if array1 and array2 have the same shapes, false otherwise. Parameters ---------- array1: numpy.ndarray array2: numpy.ndarray nd_to_check: int Number of the dimensions to check, i.e., if == 3 then will che...
def have_same_geometry(fname1, fname2): """ @param fname1: string File path of an image @param fname2: string File path of an image @return: bool True if both have the same geometry """ img1shape = nib.load(fname1).get_shape() img2shape = nib.load(fname2).get_shape() return...
def have_same_spatial_geometry(fname1, fname2): """ @param fname1: string File path of an image @param fname2: string File path of an image @return: bool True if both have the same geometry """ img1shape = nib.load(fname1).get_shape() img2shape = nib.load(fname2).get_shape() ...
def dir_match(regex, wd=os.curdir): """Create a list of regex matches that result from the match_regex of all file names within wd. The list of files will have wd as path prefix. @param regex: string @param wd: string working directory @return: """ ls = os.listdir(wd) filt = re...
def recursive_dir_match(folder_path, regex=''): """ Returns absolute paths of folders that match the regex within folder_path and all its children folders. Note: The regex matching is done using the match function of the re module. Parameters ---------- folder_path: string regex: ...
def get_file_list(file_dir, regex=''): """ Creates a list of files that match the search_regex within file_dir. The list of files will have file_dir as path prefix. Parameters ---------- @param file_dir: @param search_regex: Returns: -------- List of paths to files that match ...
def recursive_find_search(folder_path, regex=''): """ Returns absolute paths of files that match the regex within file_dir and all its children folders. Note: The regex matching is done using the search function of the re module. Parameters ---------- folder_path: string regex: st...
def iter_recursive_find(folder_path, *regex): """ Returns absolute paths of files that match the regexs within folder_path and all its children folders. This is an iterator function that will use yield to return each set of file_paths in one iteration. Will only return value if all the strings...
def get_all_files(folder): """ Generator that loops through all absolute paths of the files within folder Parameters ---------- folder: str Root folder start point for recursive search. Yields ------ fpath: str Absolute path of one file in the folders """ for path, dirl...
def recursive_glob(base_directory, regex=''): """ Uses glob to find all files or folders that match the regex starting from the base_directory. Parameters ---------- base_directory: str regex: str Returns ------- files: list """ files = glob(op.join(base_directory, re...
def get_last_file(input_dir, glob_pattern='*', key=op.getctime, reverse=True): """ Return the path to the latest file in `input_dir`. The `key` argument defines which information to use for sorting the list of files, could be: - creation date: os.path.getctime, - modification date: os.path...
def compose_err_msg(msg, **kwargs): """Append key-value pairs to msg, for display. Parameters ---------- msg: string arbitrary message kwargs: dict arbitrary dictionary Returns ------- updated_msg: string msg, with "key: value" appended. Only string values are a...
def group_dicom_files(dicom_file_paths, header_fields): """ Gets a list of DICOM file absolute paths and returns a list of lists of DICOM file paths. Each group contains a set of DICOM files that have exactly the same headers. Parameters ---------- dicom_file_paths: list of str List...
def copy_groups_to_folder(dicom_groups, folder_path, groupby_field_name): """Copy the DICOM file groups to folder_path. Each group will be copied into a subfolder with named given by groupby_field. Parameters ---------- dicom_groups: boyle.dicom.sets.DicomFileSet folder_path: str Path to ...
def calculate_file_distances(dicom_files, field_weights=None, dist_method_cls=None, **kwargs): """ Calculates the DicomFileDistance between all files in dicom_files, using an weighted Levenshtein measure between all field names in field_weights and their corresponding weight...
def fit(self, dcm_file1, dcm_file2): """ Parameters ---------- dcm_file1: str (path to file) or DicomFile or namedtuple dcm_file2: str (path to file) or DicomFile or namedtuple """ self.set_dicom_file1(dcm_file1) self.set_dicom_file2(dcm_file2)
def transform(self): """Check the field values in self.dcmf1 and self.dcmf2 and returns True if all the field values are the same, False otherwise. Returns ------- bool """ if self.dcmf1 is None or self.dcmf2 is None: return np.inf for field_...
def levenshtein_analysis(self, field_weights=None): """ Updates the status of the file clusters comparing the cluster key files with a levenshtein weighted measure using either the header_fields or self.header_fields. Parameters ---------- field_weights: dict of ...
def dist_percentile_threshold(dist_matrix, perc_thr=0.05, k=1): """Thresholds a distance matrix and returns the result. Parameters ---------- dist_matrix: array_like Input array or object that can be converted to an array. perc_thr: float in range of [0,100] Pe...
def get_groups_in_same_folder(self, folder_depth=3): """ Returns a list of 2-tuples with pairs of dicom groups that are in the same folder within given depth. Parameters ---------- folder_depth: int Path depth to check for folder equality. Returns ...
def plot_file_distances(dist_matrix): """ Plots dist_matrix Parameters ---------- dist_matrix: np.ndarray """ import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.matshow(dist_matrix, interpolation='nearest', ...
def merge_groups(self, indices): """Extend the lists within the DICOM groups dictionary. The indices will indicate which list have to be extended by which other list. Parameters ---------- indices: list or tuple of 2 iterables of int, bot having the same len ...
def move_to_folder(self, folder_path, groupby_field_name=None): """Copy the file groups to folder_path. Each group will be copied into a subfolder with named given by groupby_field. Parameters ---------- folder_path: str Path to where copy the DICOM files. grou...
def get_unique_field_values_per_group(self, field_name, field_to_use_as_key=None): """Return a dictionary where the key is the group key file path and the values are sets of unique values of the field name of all DICOM files in the group. Parame...
def get_config_value(name, fallback=None): """Gets a config by name. In the case where the config name is not found, will use fallback value.""" cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) return cli_config.get('servicefabric', name, fallback)
def get_config_bool(name): """Checks if a config value is set to a valid bool value.""" cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) return cli_config.getboolean('servicefabric', name, False)
def set_config_value(name, value): """Set a config by name to a value.""" cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) cli_config.set_value('servicefabric', name, value)
def cert_info(): """Path to certificate related files, either a single file path or a tuple. In the case of no security, returns None.""" sec_type = security_type() if sec_type == 'pem': return get_config_value('pem_path', fallback=None) if sec_type == 'cert': cert_path = get_config...
def set_aad_cache(token, cache): """Set AAD token cache.""" set_config_value('aad_token', jsonpickle.encode(token)) set_config_value('aad_cache', jsonpickle.encode(cache))
def set_aad_metadata(uri, resource, client): """Set AAD metadata.""" set_config_value('authority_uri', uri) set_config_value('aad_resource', resource) set_config_value('aad_client', client)
def set_auth(pem=None, cert=None, key=None, aad=False): """Set certificate usage paths""" if any([cert, key]) and pem: raise ValueError('Cannot specify both pem and cert or key') if any([cert, key]) and not all([cert, key]): raise ValueError('Must specify both cert and key') if pem: ...
def filter_objlist(olist, fieldname, fieldval): """ Returns a list with of the objects in olist that have a fieldname valued as fieldval Parameters ---------- olist: list of objects fieldname: string fieldval: anything Returns ------- list of objets """ return [x for ...
def filter_list(lst, filt): """ Parameters ---------- lst: list filter: function Unary string filter function Returns ------- list List of items that passed the filter Example ------- >>> l = ['12123123', 'N123213'] >>> filt = re.compile('\d*').match...
def match_list(lst, pattern, group_names=[]): """ Parameters ---------- lst: list of str regex: string group_names: list of strings See re.MatchObject group docstring Returns ------- list of strings Filtered list, with the strings that match the pattern """ ...
def append_to_keys(adict, preffix): """ Parameters ---------- adict: preffix: Returns ------- """ return {preffix + str(key): (value if isinstance(value, dict) else value) for key, value in list(adict.items())}
def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. Parameters ---------- string: str Returns ------- boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return ...
def is_regex(string): """ TODO: improve this! Returns True if the given string is considered a regular expression, False otherwise. It will be considered a regex if starts with a non alphabetic character and then correctly compiled by re.compile :param string: str """ is_regex = F...
def is_fnmatch_regex(string): """ Returns True if the given string is considered a fnmatch regular expression, False otherwise. It will look for :param string: str """ is_regex = False regex_chars = ['!', '*', '$'] for c in regex_chars: if string.find(c) > -1: r...
def where_is(strings, pattern, n=1, lookup_func=re.match): """Return index of the nth match found of pattern in strings Parameters ---------- strings: list of str List of strings pattern: str Pattern to be matched nth: int Number of times the match must happen to retur...
def generate_config(output_directory): """ Generate a dcm2nii configuration file that disable the interactive mode. """ if not op.isdir(output_directory): os.makedirs(output_directory) config_file = op.join(output_directory, "config.ini") open_file = open(config_file, "w") open_file...
def add_meta_to_nii(nii_file, dicom_file, dcm_tags=''): """ Add slice duration and acquisition times to the headers of the nifit1 files in `nii_file`. It will add the repetition time of the DICOM file (field: {0x0018, 0x0080, DS, Repetition Time}) to the NifTI file as well as any other tag in `dcm_tags`. ...
def call_dcm2nii(work_dir, arguments=''): """Converts all DICOM files within `work_dir` into one or more NifTi files by calling dcm2nii on this folder. Parameters ---------- work_dir: str Path to the folder that contain the DICOM files arguments: str String containing all the f...
def convert_dcm2nii(input_dir, output_dir, filename): """ Call MRICron's `dcm2nii` to convert the DICOM files inside `input_dir` to Nifti and save the Nifti file in `output_dir` with a `filename` prefix. Parameters ---------- input_dir: str Path to the folder that contains the DICOM files ...
def remove_dcm2nii_underprocessed(filepaths): """ Return a subset of `filepaths`. Keep only the files that have a basename longer than the others with same suffix. This works based on that dcm2nii appends a preffix character for each processing step it does automatically in the DICOM to NifTI conversion...
def dictify(a_named_tuple): """Transform a named tuple into a dictionary""" return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)
def merge_dict_of_lists(adict, indices, pop_later=True, copy=True): """Extend the within a dict of lists. The indices will indicate which list have to be extended by which other list. Parameters ---------- adict: OrderedDict An ordered dictionary of lists indices: list or tuple of 2 it...
def append_dict_values(list_of_dicts, keys=None): """ Return a dict of lists from a list of dicts with the same keys. For each dict in list_of_dicts with look for the values of the given keys and append it to the output dict. Parameters ---------- list_of_dicts: list of dicts keys: lis...
def import_pyfile(filepath, mod_name=None): """ Imports the contents of filepath as a Python module. :param filepath: string :param mod_name: string Name of the module when imported :return: module Imported module """ import sys if sys.version_info.major == 3: import i...
def copy(configfile='', destpath='', overwrite=False, sub_node=''): """Copies the files in the built file tree map to despath. :param configfile: string Path to the FileTreeMap config file :param destpath: string Path to the files destination :param overwrite: bool Overwrite files ...
def get_noneid_references(self): """ Returns ------- ndarray Array of references in self.reflst whose self id is None. """ #return [self.reflst[idx] for idx, idval in enumerate(self) if idval is None] try: nun = np.array(None).astype(self.dtype...
def _print_general_vs_table(self, idset1, idset2): """ :param idset1: :param idset2: """ ref1name = '' set1_hasref = isinstance(idset1, idset_with_reference) if set1_hasref: ref1arr = np.array(idset1.reflst) ref1name = idset1.refname ...
def _print_foreign_repetition_table(self, idset1, idset2): """ :param idset1: :param idset2: """ assert(isinstance(idset1, idset_with_reference)) assert(isinstance(idset2, idset)) reps = idset2.get_repetitions() if len(reps) < 1: return ...
def print_compare_idsets_one_ref(self, idset1_name, idset2_name): """ idset1_name: string key of an idset_with_reference idset2_name: string key of an idset """ try: idset1 = self[idset1_name] idset2 = self[idset2_name] except KeyE...
def convert_sav(inputfile, outputfile=None, method='rpy2', otype='csv'): """ Transforms the input .sav SPSS file into other format. If you don't specify an outputfile, it will use the inputfile and change its extension to .csv """ assert(os.path.isfile(inputfile)) assert(method=='rpy2' or method...
def load_mask(image, allow_empty=True): """Load a Nifti mask volume. Parameters ---------- image: img-like object or boyle.nifti.NeuroImage or str Can either be: - a file path to a Nifti image - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image. ...
def load_mask_data(image, allow_empty=True): """Load a Nifti mask volume and return its data matrix as boolean and affine. Parameters ---------- image: img-like object or boyle.nifti.NeuroImage or str Can either be: - a file path to a Nifti image - any object with get_data() and...
def union_mask(filelist): """ Creates a binarised mask with the union of the files in filelist. Parameters ---------- filelist: list of img-like object or boyle.nifti.NeuroImage or str List of paths to the volume files containing the ROIs. Can either be: - a file path to a N...
def apply_mask(image, mask_img): """Read a Nifti file nii_file and a mask Nifti file. Returns the voxels in nii_file that are within the mask, the mask indices and the mask shape. Parameters ---------- image: img-like object or boyle.nifti.NeuroImage or str Can either be: - a fi...
def apply_mask_4d(image, mask_img): # , smooth_mm=None, remove_nans=True): """Read a Nifti file nii_file and a mask Nifti file. Extract the signals in nii_file that are within the mask, the mask indices and the mask shape. Parameters ---------- image: img-like object or boyle.nifti.NeuroImage ...
def vector_to_volume(arr, mask, order='C'): """Transform a given vector to a volume. This is a reshape function for 3D flattened and maybe masked vectors. Parameters ---------- arr: np.array 1-Dimensional array mask: numpy.ndarray Mask image. Must have 3 dimensions, bool dtype....
def matrix_to_4dvolume(arr, mask, order='C'): """Transform a given vector to a volume. This is a reshape function for 4D flattened masked matrices where the second dimension of the matrix corresponds to the original 4th dimension. Parameters ---------- arr: numpy.array 2D numpy.array ...