def read_in_listfile(fname, lines=1, strip=1, noblank=1, verb=1): """Read in a "listfile", which could have 1 or 2 columns. Return a list of the first column, and if the second column is given, the list of that; if there was only one column in the file, the second list is empty """ L = UTIL.read_text_file(fname, lines=lines, strip=strip, noblank=noblank, verb=verb) L2 = [x.split() for x in L] nrow, ncolmin, ncolmax, is_rag, is_sq \ = UTIL.mat_row_mincol_maxcol_ragged_square(L2) if is_rag: ab.EP("Cannot have a ragged listfile") if not ([1, 2].__contains__(ncolmax)): ab.EP("Need to 1 or 2 cols in listfile, not {}".format(ncolmax)) col0 = [x[0] for x in L2] if ncolmax == 2: col1 = [x[1] for x in L2] else: col1 = [] return col0, col1
def finish_defs(self): """Check a couple things with input. All input files/globs get parsed here. """ if self.in_mat: # replace with actual list of files, because it might just # have been the glob list that was input self.in_mat = UTIL.list_files_by_glob(self.in_mat, sort=True, exit_on_miss=True) if self.in_csv: # replace with CSV file all_csv = UTIL.list_files_by_glob(self.in_csv, sort=True, exit_on_miss=True) if len(all_csv) > 1: ab.EP("Too many files found when globbing with:\n" "\t {}".format(self.in_csv)) else: self.in_csv = all_csv[0] if self.in_listfile: # replace with list file all_listfile = UTIL.list_files_by_glob(self.in_listfile, sort=True, exit_on_miss=True) if len(all_listfile) > 1: ab.EP("Too many files found when globbing with:\n" "\t {}".format(self.in_listfile)) else: self.in_listfile = all_listfile[0]
def check_new_mat2d_with_current(self, Mobj): """Check about info that needs to match if we already have mats in this obj (e.g., nroi, roi_strlabs, roi_intvals, etc.) Output ------ 1 : if nothing exists 2 : if things exist, and this new Mobj is OK to add [exit] : if things are NOT ok """ # trivial case: nothing to check if self.nmat == 0: return 1 # check nroi|size; also, must be square if self.nroi != Mobj.nrow or self.nroi != Mobj.ncol: ab.EP("mismatch in size of current file obj (nroi= {}) " "and new obj (row, col = {}, {})" "".format(self.nroi, Mobj.nrow, Mobj.ncol)) # intvals for ii in range(self.nroi): if self.roi_intvals[ii] != Mobj.col_intvals[ii]: ab.EP("mismatch in intvals of current file obj:\n{}\n" "and those of new obj:\n{}" "".format(self.roi_intvals, Mobj.col_intvals)) # check str labels if self.has_strlabs != Mobj.col_strlabs: ab.EP("mismatch in string labelling in current file obj ({}) " "and new obj ({})" "".format(self.has_strlabs, Mobj.col_strlabs)) # strlabs, if any if self.has_strlabs: for ii in range(self.nroi): if self.roi_strlabs[ii] != Mobj.col_strlabs[ii]: ab.EP("mismatch in strlabs of current file obj:\n{}\n" "and those of new obj:\n{}" "".format(self.roi_strlabs, Mobj.col_strlabs)) # check if a mat2d with this label already exists --> confusion! if self.allmat_labs.__contains__(Mobj.label): ab.EP("current file obj already contains that obj label: {}" "".format(Mobj.label)) # have we survived the gauntlet? return 2
def set_mat(self, M, mform=None, eletype=None, allow_ragged=False): '''Set mat, nrow, ncol Ragged matrices not allowed by default (at present)''' self.mat = [] # reset if type(M) == list or mform == 'LIST': # input M is a list (of lists) of numbers (or strings, # actually, bc eletype can format them) for rrr in M: self.mat.append(rrr) # at this point, elements might be strings still; wait # till after 'if eletype :' below to use values else: ab.EP("Unrecognized input mat format\n") self.set_mat_dims(allow_ragged=allow_ragged) if eletype: self.set_eletype(eletype) #ab.IP("Matrix elements set to be type: {}" # "".format(eletype)) nrow, ncolmin, ncolmax, is_rag, is_sq \ = UTIL.mat_row_mincol_maxcol_ragged_square(self.mat) self.is_ragged = is_rag self.is_square = is_sq # store min and max of ele self.get_mat_min_max()
def set_file_out(self, FF): """Set output file name, and parse for ext (or decide on one, if none is given. """ if not (FF): ab.EP("No output file given for me to work with?") ff_split = FF.split('.') ext = ff_split[-1] if len(ff_split) < 2 or \ not(['bmp', 'emf', 'eps', 'gif', 'jpeg', 'jpg', \ 'pdf', 'pgf', 'png', 'ps', 'raw', 'rgba', \ 'svg', 'svgz', 'tif', 'tiff'].__contains__(ext)) : # fname is just base; need to add our own ext self.ext = rcParams["savefig.format"] self.fout_base = FF self.file_out = '.'.join([self.fout_base, self.ext]) else: # fname is complete # [PT: July 31, 2020] fix joining here, need dot in case # path has dots... self.ext = ext self.fout_base = '.'.join(ff_split[:-1]) self.file_out = '.'.join([self.fout_base, self.ext])
def merge_lists(A, B, empty_one_ok=True, exit_on_empty=True): """Take two lists (of parameters), A and B. If one is empty, just return the other one (set empty_one_ok=False to not have this happen at the start). Otherwise, return the intersection of the 2 lists. If the final result is empty, return empty (default) or set 'exit_on_empty' to error exit. """ if empty_one_ok: if not (A): return copy.deepcopy(B) elif not (B): return copy.deepcopy(A) out = [] for item in A: if B.__contains__(item): out.append(item) else: ab.WP("Item '{}' does not appear in list B.\n" "Continuing without it".format(item)) if out: return out else: if exit_on_empty: ab.EP("No items matched in lists A and B. Exiting.") else: return []
def check_req(self): ''' Check for and point out any missing inputs.''' MISS = 0 if not (self.prefix): ab.EP("missing '{prefix}' value" "".format(**opts_dict), end_exit=False) MISS += 1 if not (self.in_mat) and self.in_listfile == None: ab.EP("Must use at least one of '{in_mat}' or '{in_listfile}" "".format(**opts_dict), end_exit=False) MISS += 1 return MISS
def read_in_cdiflist(fname, lines=1, strip=1, noblank=1, verb=1): """Read in a "cdiflist", which should have 1 number N at the top, and then N rows of 3 values each. Return two items: + the integer N + a list of length N, where each element is a list of 3 floats """ L = UTIL.read_text_file(fname, lines=lines, strip=strip, noblank=noblank, verb=verb) L2 = [x.split() for x in L] # ----------------- get top row value -------------- if len(L2[0]) != 1: ab.EP("Top row is not a single value, though that is expected\n" "for a cdiflist. Instead, it is:\n" "{}".format(' '.join(L2[0]))) try: ntop = int(L2[0][0]) except: ab.EP("Can't read top of cdiflist as an int????") # ------------ get properties of remaining rows ----------- nrow, ncolmin, ncolmax, is_rag, is_sq \ = UTIL.mat_row_mincol_maxcol_ragged_square(L2[1:]) # more checks on size/shape if nrow != ntop: ab.EP("Top number in file is {}, so file should have {} rows total,\n" "but I detect {} rows total".format(ntop, ntop + 1, nrow + 1)) if is_rag: ab.EP("Cannot have a ragged cdiflist") if ncolmax != 3: ab.EP("Need 3 cols throughout most of cdiflist, {}".format(ncolmax)) out = [] for row in L2[1:]: out.append([float(x) for x in row]) return ntop, out
def check_req(self): ''' Check for and point out any missing inputs.''' MISS = 0 if not (self.input): ab.EP("missing '{input}' dset" "".format(**opts_dict), end_exit=False) MISS += 1 if self.vmin and self.vmax: if self.vmax <= self.vmin: ab.EP("Bad cbar range: vmax ({}) <= vmin ({})" "".format(self.vmax, self.vmin), end_exit=False) MISS += 1 return MISS
def open_and_check_GoN(self): if not (os.path.isfile(self.file_inp)): ab.EP("Cannot find grid/netcc/amat file: {}".format(file_inp)) self.set_ext() self.read_in_GoN() self.read_header_GoN() self.read_table_mat_GoN()
def set_row_intvals(self, L): '''input a list of strings; must match number of mat rows''' N = len(L) if N != self.nrow: ab.EP("Number of int vals in list ({}) does not match \n" "number of rows ({})".format(N, self.nrow)) self.row_intvals = [] for x in L: self.row_intvals.append(int(x))
def set_col_strlabs(self, L): '''input a list of strings; must match number of mat cols''' N = len(L) if N != self.ncol: ab.EP("Number of labels in list ({}) does not match \n" "number of cols ({})".format(N, self.ncol)) self.col_strlabs = [] for x in L: self.col_strlabs.append(x)
def read_table_mat_GoN(self): '''Read all the matrix info in the main part of the table each matrix has a "matrix label" part self.nroi, self.nmat as well as string labels and integer ROI values We guess whether matrix element type is int or float based on whether a matrix has any '.' in it or not (respectively). ''' # starting point from which to read, verily idx = self.header_len self.allmat_labs = [] self.allmat = {} while idx < self.data_len: # first, the matrix label line line = [x.strip() for x in self.data[idx].split("#")] mat_lab = line[-1] ab.IP("Getting matrix: {}".format(mat_lab)) self.allmat_labs.append(mat_lab) idx += 1 # then, the matrix lines count_dots = 0 # use this as a way to tell int vs float M = [] for ii in range(self.nroi): count_dots += self.data[idx + ii].count('.') line = [x.strip() for x in self.data[idx + ii].split()] M.append(line) if count_dots: self.allmat[mat_lab] = mat2d(M, label=mat_lab, eletype=float, col_strlabs=self.roi_strlabs, row_strlabs=self.roi_strlabs, col_intvals=self.roi_intvals, row_intvals=self.roi_intvals) else: self.allmat[mat_lab] = mat2d(M, label=mat_lab, eletype=int, col_strlabs=self.roi_strlabs, row_strlabs=self.roi_strlabs, col_intvals=self.roi_intvals, row_intvals=self.roi_intvals) idx += ii + 1 if len(self.allmat_labs) != self.nmat: ab.EP("Mismatch in number of matrix labels {} and\n" "purported number of matrices in the file {}" "".format(self.allmat_labs, self.nmat))
def parse_fulltext_list(self): """ Split up the fulltext that is now a list of strings """ N = len(self.fulltext_list) table_start = int(bool(self.has_header)) if self.has_header: hh = [x.strip() for \ x in self.fulltext_list[0].split(self.delimiter)] tt = [] ltt = [] for ii in range(table_start, N): line = [x.strip() for \ x in self.fulltext_list[ii].split(self.delimiter)] tt.append(line) ltt.append(len(line)) # check lengths for consistency: no raggedness if min(ltt) != max(ltt): ab.EP("Looks like a ragged CSV, with min|max length = {}|{}" "".format(min(ltt), max(ltt))) if self.has_header: if min(ltt) != max(ltt): ab.EP("Looks like a mismatched CSV, with header length = {}\n" "and table length = {}" "".format(max(ltt), len(hh))) # OK to set these values in the obj now self.header = copy.deepcopy(hh) self.table = copy.deepcopy(tt) self.nrow_table = len(self.table) if self.nrow_table: self.ncol_table = len(self.table[0]) # try to categorize each var self.guess_variable_type()
def finish_defs(self): """Check a couple things with input (is exactly 1 file), and sort out prefix if necessary. """ lll = glob.glob(self.input) if not (lll): ab.EP("Could not find file for input: {}" "".format(self.input)) elif len(lll) > 1: ab.EP("Can only have 1 input file; too many for: {}" "".format(self.input)) ifile = lll[0] if not (self.prefix): # if no prefix is entered, get from name of input # [PT: July 31, 2020] fix the regluing iroot = '.'.join(ifile.split('.')[:-1]) if iroot: self.prefix = iroot else: self.prefix = ifile # should never happen
def check_req(self): ''' Check for and point out any missing inputs.''' MISS = 0 if not (self.prefix): ab.EP("missing '{prefix}' value" "".format(**opts_dict), end_exit=False) MISS += 1 if not (self.cdiflist): ab.EP("missing '{cdiflist}' value" "".format(**opts_dict), end_exit=False) MISS += 1 if not (self.bval_max): ab.EP("missing '{bval_max}' value" "".format(**opts_dict), end_exit=False) MISS += 1 return MISS
def set_mat_dims(self, allow_ragged=False): '''Set ncol and nrol of mat in this object. If a ragged matrix is detected, fail by default (or zeropad, if user wants) ''' if not (self.mat): ab.EP("Can't check dimensions of empty mat") #nc, nrmin, nrmax, is_rag, is_sq \ # = UTIL.mat_col_minrow_maxrow_ragged_square(self.mat) nr, ncmin, ncmax, is_rag, is_sq \ = UTIL.mat_row_mincol_maxcol_ragged_square(self.mat) self.nrow = nr if is_rag: if allow_ragged: ab.WP("ragged matrix: min = {}, max = {}\n" "-> am zeropadding".format(ncmin, ncmax)) for ii in range(self.nrow): diff = ncmax - len(self.mat[ii]) if diff: for jj in range(diff): self.mat[ii].append(0) else: ab.EP("ragged matrix: min = {}, max = {}\n" "no flag to allow ragged mats".format(ncmin, ncmax)) self.ncol = ncmax self.nelements = self.nrow * self.ncol ab.IP("mat dims (nrow, ncol): {}, {}".format(self.nrow, self.ncol))
def get_info_from_file_obj(self, FO): """The multi mat is mainly a list of file_grid_netcc objs; FO should be one of those, from which we get much of this info """ if type(FO) != lm2b.file_grid_netcc: ab.EP("Wrong type of input here: need 'lm2b.file_grid_netcc'") self.ftype = FO.ext self.mat_labs = copy.deepcopy(FO.allmat_labs) self.nroi = FO.nroi self.roi_intvals = copy.deepcopy(FO.roi_intvals) if FO.roi_strlabs: self.roi_strlabs = copy.deepcopy(FO.roi_strlabs)
def write_to_file_GoN(self, fname=''): """Write current information to a file on disk. fname can be provided here (gets precedence), or have been provided and stored in the obj previously. """ full_out = self.make_full_out_str_GoN() if fname: ooo = fname elif self.file_out: ooo = self.file_out else: ab.EP("Don't have an output name for this file-- can't write") fff = open(ooo, 'w') fff.write(full_out) fff.close() ab.IP("Wrote {} file: {}".format(self.ext, ooo))
def set_eletype(self, ET): """Set type of each element in the matrix Allowed types are in the 'ok_eletypes' list. """ self.eletype = ET if ET == 'float' or ET == float: for i in range(self.nrow): for j in range(self.ncol): self.mat[i][j] = float(self.mat[i][j]) elif ET == 'int' or ET == int: for i in range(self.nrow): for j in range(self.ncol): self.mat[i][j] = int(self.mat[i][j]) elif ET == 'bool' or ET == bool: for i in range(self.nrow): for j in range(self.ncol): self.mat[i][j] = bool(self.mat[i][j]) else: ab.EP("Don't have element type '{}' in recognized list\n" "for mat elements:\n\t {}" "".format(ET, ", ".join(self.ok_eletypes)))
list_mat, list_ids = lm2t.read_in_listfile(iopts.in_listfile) for fname in list_mat: file_mat = lm2b.file_grid_netcc(fname) multi_mat.add_file(file_mat) elif iopts.in_mat: list_ids = [] # this simplifies coding later for fname in iopts.in_mat: file_mat = lm2b.file_grid_netcc(fname) multi_mat.add_file(file_mat) else: # should not get here ab.EP("No listfile or list of matrices entered??") # this obj contains a lot of info summarizing the matrices mat_info = lm2t.mat_table_guide(multi_mat) # Couple last matrix-related things for later: list of mat # filenames, and inverse dictionary of fnames list_fnames = list(multi_mat.all_fname.values()) dict_all_fname_inv = UTIL.invert_dict(multi_mat.all_fname) # read in CSV (opt) if iopts.in_csv: csv = LCSV.csv_data(iopts.in_csv) csv_ids = csv.get_table_col_by_idx(0) # [0] col is subj IDs # Now, csv.table has the data (all str); csv.header has the
def parse_args(full_argv): """Go through user-entered options and fill an object with the values. These will be used to setup plotting. """ argv = full_argv[1:] Narg = len(argv) if not (Narg): print(help_string) sys.exit(0) # initialize objs iopts = iopts_obj() iopts.full_cmd = full_argv i = 0 while i < Narg: if argv[i] == "{ver}".format(**opts_dict): print(ver) sys.exit(0) elif argv[i] == "{date}".format(**opts_dict): print(date) sys.exit(0) elif argv[i] == "{help}".format(**opts_dict) or \ argv[i] == "{h}".format(**opts_dict) : print(help_string) sys.exit(0) elif argv[i] == "{hview}".format(**opts_dict): prog = os.path.basename(full_argv[0]) cmd = 'apsearch -view_prog_help {}'.format(prog) ab.simple_shell_exec(cmd) sys.exit(0) # ---------- req --------------- # can be a list of many elif argv[i] == "{in_mat}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 while i < Narg: if opts_list.__contains__(argv[i]): i -= 1 break else: iopts.in_mat.append(argv[i]) i += 1 elif argv[i] == "{prefix}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.prefix = argv[i] # ---------- opt --------------- # can be a list of many elif argv[i] == "{pars}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 while i < Narg: if opts_list.__contains__(argv[i]): i -= 1 break else: iopts.pars_list.append(argv[i]) i += 1 elif argv[i] == "{in_csv}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.in_csv = argv[i] elif argv[i] == "{in_listfile}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.in_listfile = argv[i] # --------- finish ------------- else: print("** ERROR: unknown opt: '{}'".format(argv[i])) sys.exit(2) i += 1 if iopts.check_req(): print(" -------------------------------") ab.EP("Problem with input arguments. See detailed whining above.") iopts.finish_defs() return iopts
def parse_args_mat_plot(full_argv): """Go through user-entered options and fill an object with the values. These will be used to setup plotting. """ argv = full_argv[1:] Narg = len(argv) if not (Narg): print(help_string_mat_plot) sys.exit(0) # initialize objs iopts = iopts_to_plot_mat2d() iopts.full_cmd = full_argv i = 0 while i < Narg: if argv[i] == "{ver}".format(**opts_dict): print(ver) sys.exit(0) elif argv[i] == "{date}".format(**opts_dict): print(date) sys.exit(0) elif argv[i] == "{help}".format(**opts_dict) or \ argv[i] == "{h}".format(**opts_dict) : print(help_string_mat_plot) sys.exit(0) elif argv[i] == "{hview}".format(**opts_dict): prog = os.path.basename(full_argv[0]) cmd = 'apsearch -view_prog_help {}'.format(prog) ab.simple_shell_exec(cmd) sys.exit(0) # ---------- req --------------- elif argv[i] == "{input}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.input = argv[i] # ---------- opt --------------- elif argv[i] == "{prefix}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.prefix = argv[i] # can be a list of many elif argv[i] == "{pars}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 while i < Narg: if opts_list.__contains__(argv[i]): i -= 1 break else: iopts.pars_list.append(argv[i]) i += 1 elif argv[i] == "{ftype}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.ftype = argv[i] elif argv[i] == "{dpi}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.dpi = float(argv[i]) elif argv[i] == "{vmin}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.vmin = float(argv[i]) elif argv[i] == "{vmax}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.vmax = float(argv[i]) elif argv[i] == "{fs_xticks}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.fs_xticks = float(argv[i]) elif argv[i] == "{fs_yticks}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.fs_yticks = float(argv[i]) elif argv[i] == "{fs_title}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.fs_title = float(argv[i]) elif argv[i] == "{fs_cbar}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.fs_cbar = float(argv[i]) elif argv[i] == "{cbar_n_intervals}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.cbar_n_intervals = int(argv[i]) elif argv[i] == "{cbar}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.cbar = argv[i] elif argv[i] == "{cbar_width_perc}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.cbar_width_perc = float(argv[i]) elif argv[i] == "{figsize_x}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.figsize_x = float(argv[i]) elif argv[i] == "{figsize_y}".format(**opts_dict): if i >= Narg: ab.ARG_missing_arg(argv[i]) i += 1 iopts.figsize_y = float(argv[i]) elif argv[i] == "{hold_image}".format(**opts_dict): iopts.hold_image = True elif argv[i] == "{tight_layout}".format(**opts_dict): iopts.tight_layout = True elif argv[i] == "{cbar_off}".format(**opts_dict): iopts.cbar_off = True elif argv[i] == "{xticks_off}".format(**opts_dict): iopts.xticks_off = True elif argv[i] == "{yticks_off}".format(**opts_dict): iopts.yticks_off = True # --------- finish ------------- else: print("** ERROR: unknown opt: '{}'".format(argv[i])) sys.exit(2) i += 1 if iopts.check_req(): print(" -------------------------------") ab.EP("Problem with input arguments. See detailed whining above.") iopts.finish_defs() return iopts
M = lm2b.file_grid_netcc(iopts.input) # Make masterlist of parameters to plot if not (iopts.pars_list): list_of_pars = copy.deepcopy(M.allmat_labs) else: list_of_pars = [] for p in iopts.pars_list: if M.allmat_labs.__contains__(p): list_of_pars.append(p) else: ab.WP("Parameter '{}' does not exist in {}; " "continuing with others" "".format(p, iopts.input)) if not (list_of_pars): ab.EP("No parameters to print, even though input file has these:\n" "{}".format(', '.join(M.allmat_labs))) for par in list_of_pars: # Make plot obj Mplot = lm2p.plot_mat2d(M.allmat[par]) # Apply any user-chosen options to plot obj Mplot.apply_iopts(iopts) ab.IP("Plotting: {}".format(par)) # Apply user opts for plotting Mplot.make_plot() sys.exit(0)
def check_new_file_with_current(self, FF): """Check about info that needs to match if we already have files in this obj Output ------ 1 : if nothing exists 2 : if things exist, and this new file FF is OK to add [exit] : if things are NOT ok """ # trivial case: nothing to check if self.nfile == 0: return 1 # since at this point we know there is at least one prior # file, use the [0]th one to compare for properties CC = self.all_file[0] # get from dictionary # check nmat if CC.nmat != FF.nmat: ab.EP("mismatch in number of matrices in current file ({}) " "and new file ({})" "".format(CC.nroi, FF.nroi)) # check nroi/mat if CC.nroi != FF.nroi: ab.EP("mismatch in number of ROIs per mat in current file ({}) " "and new file ({})" "".format(CC.nroi, FF.nroi)) # check str labels if CC.has_strlabs != FF.has_strlabs: ab.EP("mismatch in string labelling in current file ({}) " "and new file ({})" "".format(CC.has_strlabs, FF.has_strlabs)) # check roi intvals for ii in range(CC.nroi): if CC.roi_intvals[ii] != FF.roi_intvals[ii]: ab.EP("mismatch in intvals of current existing file:\n{}\n" "and those of new file:\n{}" "".format(CC.roi_intvals, FF.roi_intvals)) # check ROI strlabs, if any if CC.has_strlabs: for ii in range(CC.nroi): if CC.roi_strlabs[ii] != FF.roi_strlabs[ii]: ab.EP("mismatch in strlabs of existing file:\n{}\n" "and those of new file:\n{}" "".format(CC.roi_strlabs, FF.roi_strlabs)) # check matrix names/types for ii in range(CC.nmat): if CC.allmat_labs[ii] != FF.allmat_labs[ii]: ab.EP("mismatch in matrix labels of existing file:\n{}\n" "and those of new file:\n{}" "".format(CC.allmat_labs, FF.allmat_labs)) # check ext if CC.ext != FF.ext: ab.EP("mismatch in ext in current file ({}) " "and new file ({})" "".format(CC.ext, FF.ext)) # have we survived the gauntlet? return 2
def read_header_GoN(self): ''' Read the header/top part of file, to get: self.nroi, self.nmat as well as string labels and integer ROI values ''' if self.data_len < 3: ab.EP("Can't possibly be grid/netcc/amat file: only {} lines" "".format(self.data_len)) # Now read through each line ('idx'=line number) # Number of ROIs per mat (req) idx = 0 line = [x.strip() for x in self.data[idx].split("#")] if line[-1] == 'Number_of_network_ROIs' or \ line[-1] == 'Number of network ROIs' : self.nroi = int(line[1]) else: ab.EP("Can't recognize line {} format in {}:\n" "{}".format(idx, self.file_inp, line)) # Number of mats in this file (req) idx = 1 line = [x.strip() for x in self.data[idx].split("#")] if line[-1] == 'Number_of_grid_matrices' or \ line[-1] == 'Number of grid matrices' or \ line[-1] == 'Number of netcc matrices' or \ line[-1] == 'Number of amat matrices' : self.nmat = int(line[1]) else: ab.EP("Can't recognize line {} format in {}:\n" "{}".format(idx, self.file_inp, line)) # Check for str labs (opt) idx = 2 line = [x.strip() for x in self.data[idx].split("#")] if line[-1] == head2_str: self.has_strlabs = True idx += 1 self.roi_strlabs = [x.strip() for x in self.data[idx].split()] if self.has_strlabs: idx = 4 else: idx = 2 # ROI integer values (req) self.roi_intvals = [int(x.strip()) for x in self.data[idx].split()] # check lengths nintvals = len(self.roi_intvals) if nintvals != self.nroi: ab.EP("Mismatch in number of int vals labels {} and\n" "purported number of ROIs per mat {}" "".format(nintvals, self.nroi)) if self.has_strlabs: nstrlabs = len(self.roi_strlabs) if nstrlabs != nintvals: ab.EP("Mismatch in number of string labels {} and\n" "ROI int vals {}" "".format(nstrlabs, nintvals)) self.header_len = idx + 1 self.header = self.data[:self.header_len] # consistency check for file nleft_theory = self.nmat * (self.nroi + 1) nleft_reality = self.data_len - self.header_len if nleft_reality < nleft_theory: ab.EP("Too few lines remaining ({}) after reading header,\n" "since we have {} matrices each with {} ROIs\n" "(and a row per mat for the label, needing {} rows total)" "".format(nleft_reality, self.nmat, self.nroi, nleft_theory))