text
stringlengths
18
773k
def __name_unit_regex(word): """ Split a name and unit that are bunched together (i.e. '250m') :param str word: :return str str: """ value = "" unit = "" r = re.findall(re_name_unit, word) try: value = r[0][0] except IndexError ...
def __split_name_unit(self, line): """ Split a string that has value and unit as one. :param str line: :return str str: """ vals = [] unit = '' if line != '' or line != ' ': # If there are parenthesis, remove them line = line.replac...
def __str_cleanup(line): """ Remove the unnecessary characters in the line that we don't want :param str line: :return str: """ if '#' in line: line = line.replace("#", "") line = line.strip() if '-----------' in line: line = ''...
def __slice_key_val(line): """ Get the key and value items from a line by looking for and lines that have a ":" :param str line: :return str str: Key, Value """ position = line.find(":") # If value is -1, that means the item was not found in the string. if...
def __create_coordinates(self, lat, lon, elev): """ GeoJSON standard: Use to determine 2-point or 4-point coordinates :param list lat: :param list lon: :return dict: """ # Sort lat an lon in numerical order lat.sort() lon.sort() geo...
def __geo_multipoint(lat, lon, elev): """ GeoJSON standard: Create a geoJson MultiPoint-type dictionary :param list lat: :param list lon: :return dict: """ logger_noaa_lpd.info("enter geo_multipoint") geo_dict = OrderedDict() geometry_dict ...
def __geo_point(lat, lon, elev): """ GeoJSON standard: Create a geoJson Point-type dictionary :param list lat: :param list lon: :return dict: """ logger_noaa_lpd.info("enter geo_point") coordinates = [] geo_dict = OrderedDict() geom...
def __reorganize_doi(temp_pub): """ Create a valid bib json entry for the DOI information. "DOI" is technically the only valid DOI key, but there are sometimes a doi_id and doi_url entry. Check for all three and compare them, then keep whichever seems best. :param dict temp_pub: ...
def __create_chron_cols(metadata): """ Use to collected chron metadata to create the chron columns :param dict metadata: key: variable, val: unit (optional) :return list: list of one dict per column """ chron_col_list = [] chron_col_ct = 1 for variableName...
def __reorganize_chron_header(line): """ Reorganize the list of variables. If there are units given, log them. :param str line: :return dict: key: variable, val: units (optional) """ d = {} # Header variables should be tab-delimited. Use regex to split by tabs ...
def __reorganize_authors(authors): """ Separate the string of authors and put it into a BibJSON compliant list :param str authors: :return list: List of dictionaries of author names. """ # String SHOULD be semi-colon separated names. l = [] s = authors.spl...
def fix_doi(L): """ DOIs are commonly stored in the BibJson format under "identifier". We want to move these to the root of the publication under "doi". Make the reassignments necessary and also remove duplicate and unwanted Doi/DOI keys. :param dict L: Metadata :return dict L: Metdata "...
def get_lipd_version(L): """ Check what version of LiPD this file is using. If none is found, assume it's using version 1.0 :param dict L: Metadata :return float: """ version = 1.0 _keys = ["LipdVersion", "LiPDVersion", "lipdVersion", "liPDVersion"] for _key in _keys: if _key in ...
def update_lipd_version(L): """ Metadata is indexed by number at this step. Use the current version number to determine where to start updating from. Use "chain versioning" to make it modular. If a file is a few versions behind, convert to EACH version until reaching current. If a file is one versi...
def update_lipd_v1_1(d): """ Update LiPD v1.0 to v1.1 - chronData entry is a list that allows multiple tables - paleoData entry is a list that allows multiple tables - chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables - Added 'lipdVersion' key :pa...
def update_lipd_v1_3(d): """ Update LiPD v1.2 to v1.3 - Added 'createdBy' key - Top-level folder inside LiPD archives are named "bag". (No longer <datasetname>) - .jsonld file is now generically named 'metadata.jsonld' (No longer <datasetname>.lpd ) - All "paleo" and "chron" prefixes are removed...
def update_lipd_v1_3_names(d): """ Update the key names and merge interpretation data :param dict d: Metadata :return dict d: Metadata """ try: if isinstance(d, dict): for k, v in d.items(): # dive down for dictionaries d[k] = update_lipd_v1_3_...
def update_lipd_v1_3_structure(d): """ Update the structure for summary and ensemble tables :param dict d: Metadata :return dict d: Metadata """ for key in ["paleoData", "chronData"]: if key in d: for entry1 in d[key]: if "model" in entry1: ...
def merge_csv_metadata(d, csvs): """ Using the given metadata dictionary, retrieve CSV data from CSV files, and insert the CSV values into their respective metadata columns. Checks for both paleoData and chronData tables. :param dict d: Metadata :return dict: Modified metadata dictionary """ ...
def _merge_csv_section(sections, pc, csvs): """ Add csv data to all paleo data tables :param dict sections: Metadata :return dict sections: Metadata """ logger_csvs.info("enter merge_csv_section") try: # Loop through each table_data in paleoData for _name, _section in secti...
def _merge_csv_model(models, pc, csvs): """ Add csv data to each column in chron model :param dict models: Metadata :return dict models: Metadata """ logger_csvs.info("enter merge_csv_model") try: for _name, _model in models.items(): if "summaryTable" in _model: ...
def _merge_csv_column(table, csvs): """ Add csv data to each column in a list of columns :param dict table: Table metadata :param str crumbs: Hierarchy crumbs :param str pc: Paleo or Chron table type :return dict: Table metadata with csv "values" entry :return bool ensemble: Ensemble data o...
def read_csv_from_file(filename): """ Opens the target CSV file and creates a dictionary with one list for each CSV column. :param str filename: :return list of lists: column values """ logger_csvs.info("enter read_csv_from_file") d = {} l = [] try: logger_csvs.info("open fi...
def write_csv_to_file(d): """ Writes columns of data to a target CSV file. :param dict d: A dictionary containing one list for every data column. Keys: int, Values: list :return None: """ logger_csvs.info("enter write_csv_to_file") try: for filename, data in d.items(): ...
def get_csv_from_metadata(dsn, d): """ Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files. :param str dsn: Dataset name :param dict d: Metadata :return dict _csvs: Csv """ logger_csvs.info("enter get_csv_from_metadata") _csvs = OrderedD...
def _get_csv_from_section(sections, crumbs, csvs): """ Get table name, variable name, and column values from paleo metadata :param dict sections: Metadata :param str crumbs: Crumbs :param dict csvs: Csv :return dict sections: Metadata :return dict csvs: Csv """ logger_csvs.info("ent...
def _get_csv_from_model(models, crumbs, csvs): """ Get csv from model data :param dict models: Metadata :param str crumbs: Crumbs :param dict csvs: Csv :return dict models: Metadata :return dict csvs: Csv """ logger_csvs.info("enter get_csv_from_model: {}".format(crumbs)) _idx =...
def _get_csv_from_columns(table, filename, csvs): """ Search a data tables for column values. Return a dict of column values :param dict d: Table data :return dict: Column values. ref by var name """ csvs[filename] = OrderedDict() try: if "columns" in table: try: ...
def _get_filename(table): """ Get the filename from a data table. If it doesn't exist, create a new one based on table hierarchy in metadata file. format: <dataSetName>.<section><idx><table><idx>.csv example: ODP1098B.Chron1.ChronMeasurementTable.csv :param dict table: Table data :param str cru...
def _reorder_csv(d, filename=""): """ Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD column number alignment. { "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } } :param dict d: csv data :param str filenam...
def _is_numeric_data(ll): """ List of lists of csv values data :param list ll: :return bool: True, all lists are numeric lists, False, data contains at least one numeric list. """ for l in ll: try: if any(math.isnan(float(i)) or isinstance(i, str) for i in l): ...
def _merge_ensemble(ensemble, col_nums, col_vals): """ The second column is not typical. "number" is a list of column numbers and "values" is an array of column values. Before we can write this to csv, it has to match the format the writer expects. :param dict ensemble: First column data :param ...
def get_validator_format(L): """ Format the LIPD data in the layout that the Lipd.net validator accepts. '_format' example: [ {"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...}, {"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...}, .....
def create_detailed_results(result): """ Use the result from the API call to create an organized single string output for printing to the console. :param dict result: Results from API call for one file :return str string: Organized results for printing """ string = "" # Validation Response ...
def display_results(results, detailed=False): """ Display the results from the validator in a brief or detailed output :param list results: API results, sorted by dataset name (multiple) :param bool detailed: Detailed results on or off :return none: """ # print("\nVALIDATOR RESULTS") # ...
def call_validator_api(dsn, api_data): """ Single call to the lipd.net validator API 'api_data' format: [ {"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...}, {"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...}, ... ] Result f...
def procces_filters(all_needs, current_needlist): """ Filters all needs with given configuration :param current_needlist: needlist object, which stores all filters :param all_needs: List of all needs inside document :return: list of needs, which passed the filters """ if current_needlist[...
def filter_needs(needs, filter_string="", filter_parts=True, merge_part_with_parent=True): """ Filters given needs based on a given filter string. Returns all needs, which pass the given filter. :param merge_part_with_parent: If True, need_parts inherit options from their parent need :param filter_...
def filter_single_need(need, filter_string=""): """ Checks if a single need/need_part passes a filter_string :param need: need or need_part :param filter_string: string, which is used as input for eval() :return: True, if need as passed the filter_string, else False """ filter_context = nee...
def get_logging_level(debug): """Returns logging level based on boolean""" level = logging.INFO if debug: level = logging.DEBUG return level
def run_spec(spec, benchmark_hosts, result_hosts=None, output_fmt=None, logfile_info=None, logfile_result=None, action=None, fail_if=None, sample_mode='reservoir'): """Run a spec file, executing the statements on...
def download_from_url(src_url, dst_dir): """ Use the given URL and destination to download and save a file :param str src_url: Direct URL to lipd file download :param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd :return none: """ dst_pat...
def doi_main(files): """ Main function that controls the script. Take in directory containing the .lpd file(s). Loop for each file. :return None: """ logger_doi_main.info("enter doi_main") print("Found {0} {1} file(s)".format(str(len(files[".lpd"])), 'LiPD')) force = prompt_force() for ...
def process_lpd(name, dir_tmp): """ Opens up json file, invokes doi_resolver, closes file, updates changelog, cleans directory, and makes new bag. :param str name: Name of current .lpd file :param str dir_tmp: Path to tmp directory :return none: """ logger_doi_main.info("enter process_lpd") ...
def prompt_force(): """ Ask the user if they want to force update files that were previously resolved :return bool: response """ logger_doi_main.info("enter prompt_force") count = 0 print("Do you want to force updates for previously resolved files? (y/n)") while True: force = inp...
def process_needtables(app, doctree, fromdocname): """ Replace all needtables nodes with a tale of filtered noded. :param app: :param doctree: :param fromdocname: :return: """ env = app.builder.env for node in doctree.traverse(Needtable): if not app.config.needs_include_nee...
def get_sections(need_info): """Gets the hierarchy of the section nodes as a list starting at the section of the current need and then its parent sections""" sections = [] current_node = need_info['target_node'] while current_node: if isinstance(current_node, nodes.section): titl...
def purge_needs(app, env, docname): """ Gets executed, if a doc file needs to be purged/ read in again. So this code delete all found needs for the given docname. """ if not hasattr(env, 'needs_all_needs'): return env.needs_all_needs = {key: need for key, need in env.needs_all_needs.item...
def add_sections(app, doctree, fromdocname): """Add section titles to the needs as additional attributes that can be used in tables and filters""" needs = getattr(app.builder.env, 'needs_all_needs', {}) for key, need_info in needs.items(): sections = get_sections(need_info) need_info['se...
def process_need_nodes(app, doctree, fromdocname): """ Event handler to add title meta data (status, tags, links, ...) information to the Need node. :param app: :param doctree: :param fromdocname: :return: """ if not app.config.needs_include_needs: for node in doctree.traverse(N...
def create_back_links(env): """ Create back-links in all found needs. But do this only once, as all needs are already collected and this sorting is for all needs and not only for the ones of the current document. :param env: sphinx enviroment :return: None """ if env.needs_workflow['bac...
def construct_headline(need_data, app): """ Constructs the node-structure for the headline/title container :param need_data: need_info container :return: node """ # need title calculation title_type = '{}: '.format(need_data["type_name"]) title_headline = need_data["title"] title_id ...
def construct_meta(need_data, env): """ Constructs the node-structure for the status container :param need_data: need_info container :return: node """ hide_options = env.config.needs_hide_options if not isinstance(hide_options, list): raise SphinxError('Config parameter needs_hide_o...
def _fix_list_dyn_func(list): """ This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;". Example: `link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts: #. link_a #. [[copy('links' #. need_id)]] This function...
def html_visit(self, node): """ Visitor method for Need-node of builder 'html'. Does only wrap the Need-content into an extra <div> with class=need """ self.body.append(self.starttag(node, 'div', '', CLASS='need'))
def merge_extra_options(self, needs_info): """Add any extra options introduced via options_ext to needs_info""" extra_keys = set(self.options.keys()).difference(set(needs_info.keys())) for key in extra_keys: needs_info[key] = self.options[key] # Finally add all not used extr...
def merge_global_options(self, needs_info): """Add all global defined options to needs_info""" global_options = getattr(self.env.app.config, 'needs_global_options', None) if global_options is None: return for key, value in global_options.items(): # If key already...
def _get_full_title(self): """Determines the title for the need in order of precedence: directive argument, first sentence of requirement (if `:title_from_content:` was set, and '' if no title is to be derived.""" if len(self.arguments) > 0: # a title was passed if 'title_fr...
def process_needlist(app, doctree, fromdocname): """ Replace all needlist nodes with a list of the collected needs. Augment each need with a backlink to the original location. """ env = app.builder.env for node in doctree.traverse(Needlist): if not app.config.needs_include_needs: ...
def parse_version(version: str) -> tuple: """Parse a string formatted X[.Y.Z] version number into a tuple >>> parse_version('10.2.3') (10, 2, 3) >>> parse_version('12') (12, 0, 0) """ if not version: return None parts = version.split('.') missing = 3 - len(parts) return...
def parse_table(fq_table: str) -> Tuple[str, str]: """Parse a tablename into tuple(<schema>, <table>). Schema defaults to doc if the table name doesn't contain a schema. >>> parse_table('x.users') ('x', 'users') >>> parse_table('users') ('doc', 'users') """ parts = fq_table.split('.')...
def as_bulk_queries(queries, bulk_size): """Group a iterable of (stmt, args) by stmt into (stmt, bulk_args). bulk_args will be a list of the args grouped by stmt. len(bulk_args) will be <= bulk_size """ stmt_dict = defaultdict(list) for stmt, args in queries: bulk_args = stmt_dict[stmt...
def get_lines(filename: str) -> Iterator[str]: """Create an iterator that returns the lines of a utf-8 encoded file.""" if filename.endswith('.gz'): with gzip.open(filename, 'r') as f: for line in f: yield line.decode('utf-8') else: with open(filename, 'r', encodi...
def as_statements(lines: Iterator[str]) -> Iterator[str]: """Create an iterator that transforms lines into sql statements. Statements within the lines must end with ";" The last statement will be included even if it does not end in ';' >>> list(as_statements(['select * from', '-- comments are filtered...
def break_iterable(iterable, pred): """Break a iterable on the item that matches the predicate into lists. The item that matched the predicate is not included in the result. >>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3)) [[1, 2], [4]] """ sublist = [] for i in iterable: i...
def create_bag(dir_bag): """ Create a Bag out of given files. :param str dir_bag: Directory that contains csv, jsonld, and changelog files. :return obj: Bag """ logger_bagit.info("enter create_bag") # if not dir_bag: # dir_bag = os.getcwd() try: bag = bagit.make_bag(dir_b...
def open_bag(dir_bag): """ Open Bag at the given path :param str dir_bag: Path to Bag :return obj: Bag """ logger_bagit.info("enter open_bag") try: bag = bagit.Bag(dir_bag) logger_bagit.info("opened bag") return bag except Exception as e: print("Error: fai...
def validate_md5(bag): """ Check if Bag is valid :param obj bag: Bag :return None: """ logger_bagit.info("validate_md5") if bag.is_valid(): print("Valid md5") # for path, fixity in bag.entries.items(): # print("path:{}\nmd5:{}\n".format(path, fixity["md5"])) e...
def resolved_flag(bag): """ Check DOI flag in bag.info to see if doi_resolver has been previously run :param obj bag: Bag :return bool: Flag """ if 'DOI-Resolved' in bag.info: logger_bagit.info("bagit resolved_flag: true") return True logger_bagit.info("bagit resolved_flag: f...
def finish_bag(dir_bag): """ Closing steps for creating a bag :param obj dir_bag: :return None: """ logger_bagit.info("enter finish_bag") # Create a bag for the 3 files new_bag = create_bag(dir_bag) open_bag(dir_bag) new_bag.save(manifests=True) logger_bagit.info("exit finish...
def _ask_how_many(): """ Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode. :return str: Path or none """ batch = True invalid = True _option = "" try: while invalid: print("\nChoose a loading option:\n1. ...
def browse_dialog_dir(): """ Open up a GUI browse dialog window and let to user pick a target directory. :return str: Target directory path """ _go_to_package() logger_directory.info("enter browse_dialog") _path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False) ...
def browse_dialog_file(): """ Open up a GUI browse dialog window and let to user select one or more files :return str _path: Target directory path :return list _files: List of selected files """ logger_directory.info("enter browse_dialog") # We make files a list, because the user can multi...
def check_file_age(filename, days): """ Check if the target file has an older creation date than X amount of time. i.e. One day: 60*60*24 :param str filename: Target filename :param int days: Limit in number of days :return bool: True - older than X time, False - not older than X time """ ...
def collect_metadata_files(cwd, new_files, existing_files): """ Collect all files from a given path. Separate by file type, and return one list for each type If 'files' contains specific :param str cwd: Directory w/ target files :param list new_files: Specific new files to load :param dict exist...
def collect_metadata_file(full_path): """ Create the file metadata and add it to the appropriate section by file-type :param str full_path: :param dict existing_files: :return dict existing files: """ fne = os.path.basename(full_path) fn = os.path.splitext(fne)[0] obj = {"full_path":...
def dir_cleanup(dir_bag, dir_data): """ Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with the data files, so we don't need the other text files and such. :param str dir_bag: Path to root of Bag :param str dir_data: Path to Bag /data subdi...
def filename_from_path(path): """ Extract the file name from a given file path. :param str path: File path :return str: File name with extension """ head, tail = ntpath.split(path) return head, tail or ntpath.basename(head)
def find_files(): """ Search for the directory containing jsonld and csv files. chdir and then quit. :return none: """ _dir = os.getcwd() _files = os.listdir() # Look for a jsonld file for _file in _files: if _file.endswith(".jsonld"): return os.getcwd() # No json...
def get_filenames_generated(d, name="", csvs=""): """ Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that originated in the LiPD file (that possibly don't follow the naming standard) :param dict d: Data :param str name: LiPD dataset name to...
def get_filenames_in_lipd(path, name=""): """ List all the files contained in the LiPD archive. Bagit, JSON, and CSV :param str path: Directory to be listed :param str name: LiPD dataset name, if you want to prefix it to show file hierarchy :return list: Filenames found """ _filenames = [] ...
def get_src_or_dst(mode, path_type): """ User sets the path to a LiPD source location :param str mode: "read" or "write" mode :param str path_type: "directory" or "file" :return str path: dir path to files :return list files: files chosen """ logger_directory.info("enter set_src_or_dst")...
def get_src_or_dst_prompt(mode): """ String together the proper prompt based on the mode :param str mode: "read" or "write" :return str prompt: The prompt needed """ _words = {"read": "from", "write": "to"} # print(os.getcwd()) prompt = "Where would you like to {} your file(s) {}?\n" \ ...
def get_src_or_dst_path(prompt, count): """ Let the user choose a path, and store the value. :return str _path: Target directory :return str count: Counter for attempted prompts """ _path = "" print(prompt) option = input("Option: ") print("\n") if option == '1': # Set th...
def list_files(x, path=""): """ Lists file(s) in given path of the X type. :param str x: File extension that we are interested in. :param str path: Path, if user would like to check a specific directory outside of the CWD :return list of str: File name(s) to be worked on """ logger_directory...
def rm_files_in_dir(path): """ Removes all files within a directory, but does not delete the directory :param str path: Target directory :return none: """ for f in os.listdir(path): try: os.remove(f) except PermissionError: os.chmod(f, 0o777) t...
def rm_file_if_exists(path, filename): """ Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton. :param str filename: Filename :param str path: Directory :return none: """ _full_path = os.path.join(path, filename) if os.path.exists(_...
def regenerate(location='http://www.iana.org/assignments/language-subtag-registry', filename=None, default_encoding='utf-8'): """ Generate the languages Python module. """ paren = re.compile('\([^)]*\)') # Get the language list. data = urllib2.urlopen(location) if ('content-t...
def give_repr(cls): # pragma: no cover r"""Patch a class to give it a generic __repr__ method that works by inspecting the instance dictionary. Parameters ---------- cls: type The class to add a generic __repr__ to. Returns ------- cls: type The passed class is returne...
def newton(power_sum, elementary_symmetric_polynomial, order): r''' Given two lists of values, the first list being the `power sum`s of a polynomial, and the second being expressions of the roots of the polynomial as found by Viete's Formula, use information from the longer list to fill out the shor...
def vietes(coefficients): r''' Given the coefficients of a polynomial of a single variable, compute an elementary symmetric polynomial of the roots of the input polynomial by Viete's Formula: .. math:: \sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n} ...
def max_variants(composition): """Calculates the maximum number of isotopic variants that could be produced by a composition. Parameters ---------- composition : Mapping Any Mapping type where keys are element symbols and values are integers Returns ------- max_n_variants :...
def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON): ''' Compute a peak list representing the theoretical isotopic cluster for `composition`. Parameters ---------- composition : Mapping Any Mapping type where keys are element symbols and values are integers ...
def call(): """Execute command line helper.""" args = get_arguments() # Set up logging if args.debug: log_level = logging.DEBUG elif args.quiet: log_level = logging.WARN else: log_level = logging.INFO setup_logging(log_level) skybell = None try: # ...
def trimim( fims, affine=None, scale=2, divdim = 8**2, int_order=0, fmax = 0.05, outpath='', fname='', fcomment='', store_avg=False, store_img_intrmd=False, store_img=False, i...
def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2): ''' Separable kernels for convolution executed on the GPU device The outputted kernels are in this order: z, y, x ''' xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5) ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2...
def iyang(imgIn, krnl, imgSeg, Cnt, itr=5): '''partial volume correction using iterative Yang method imgIn: input image which is blurred due to the PSF of the scanner krnl: shift invariant kernel of the PSF imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer number...
def pvc_iyang( petin, mridct, Cnt, pvcroi, krnl, itr=5, tool='niftyreg', faff='', outpath='', fcomment='', store_img=False, store_rois=False, ): ''' Perform partial volume (PVC) correction of PET data (petin) using M...
def ct2mu(im): '''HU units to 511keV PET mu-values https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf C. Burger, et al., PET attenuation coefficients from CT images, ''' # convert nans to -1024 for the HU values only im[np.isnan(im)] = -1024 # constants muwat...
def centre_mass_img(imdct): ''' Calculate the centre of mass of an image along each axes (x,y,z), separately. Arguments: imdct - the image dictionary with the image and header data. Output the list of the centre of mass for each axis. ''' #> initialise centre of mass arr...