def test_getCLogger(): # Check if getCLogger returns a CLogger instance assert isinstance(getCLogger('C_TEST'), PRISM_Logger) # Check if getCLogger returns the base logger if not specified assert getCLogger() == logging.root.manager.loggerDict['prism'] # Check if LoggerClass is still default Logger assert logging.getLoggerClass() == logging.Logger
def _get_model_par_seq(self, par_seq, name): """ Converts a provided sequence `par_seq` of model parameter names and indices to a list of indices, removes duplicates and checks if every provided name/index is valid. Parameters ---------- par_seq : 1D array_like of {int, str} A sequence of integers and strings determining which model parameters need to be used for a certain operation. name : str A string stating the name of the variable the result of this method will be stored in. Used for error messages. Returns ------- par_seq_conv : list of int The provided sequence `par_seq` converted to a sorted list of model parameter indices. """ # Do some logging logger = getCLogger('INIT') logger.info("Converting sequence of model parameter names/indices.") # Remove all unwanted characters from the string and split it up par_seq = split_seq(par_seq) # Check elements if they are ints or strings, and if they are valid for i, par_idx in enumerate(par_seq): try: # If par_idx is a string, try to use it as a parameter name if isinstance(par_idx, str): par_seq[i] = self._par_name.index(par_idx) # If not, try to use it as a parameter index else: self._par_name[par_idx] par_seq[i] = par_idx % self._n_par # If any operation above fails, raise error except Exception as error: err_msg = ("Input argument %r[%i] is invalid! (%s)" % (name, i, error)) raise_error(err_msg, InputError, logger) # If everything went without exceptions, check if list is not empty and # remove duplicates if par_seq: par_seq = list(sset(par_seq)) else: err_msg = "Input argument %r is empty!" % (name) raise_error(err_msg, ValueError, logger) # Log end logger.info("Finished converting sequence of model parameter " "names/indices.") # Return it return (par_seq)
def _check_mod_set(self, mod_set, name): """ Checks validity of provided set of model outputs `mod_set` in this :obj:`~ModelLink` instance. Parameters ---------- mod_set : 1D or 2D array_like or dict Model output (set) to validate in this :obj:`~ModelLink` instance. name : str The name of the model output (set), which is used in the error message if the validation fails. Returns ------- mod_set : 1D or 2D :obj:`~numpy.ndarray` object The provided `mod_set` if the validation was successful. If `mod_set` was a dict, it will be converted to a :obj:`~numpy.ndarray` object (sorted on :attr:`~data_idx`). """ # Make logger logger = getCLogger('CHECK') logger.info("Validating provided set of model outputs %r." % (name)) # If mod_set is a dict, try to convert it to a NumPy array if isinstance(mod_set, dict): try: mod_set = np_array([mod_set[idx] for idx in self._data_idx]).T except KeyError as error: err_msg = ( "Input argument %r is missing data identifier '%r'!" % (name, error.args[0])) raise_error(err_msg, KeyError, logger) # Make sure that mod_set is a NumPy array mod_set = np_array(mod_set) # Raise error if mod_set is not 1D or 2D if not (mod_set.ndim == 1 or mod_set.ndim == 2): err_msg = ("Input argument %r is not one-dimensional or " "two-dimensional!" % (name)) raise_error(err_msg, ShapeError, logger) # Raise error if mod_set does not have n_data data values if not (mod_set.shape[-1] == self._n_data): err_msg = ("Input argument %r has incorrect number of data values " "(%i != %i)!" % (name, mod_set.shape[-1], self._n_data)) raise_error(err_msg, ShapeError, logger) # Check if mod_set solely consists out of floats mod_set = check_vals(mod_set, name, 'float') # Log again and return mod_set logger.info("Finished validating provided set of model outputs %r." % (name)) return (mod_set)
def _check_md_var(self, md_var, name): """ Checks validity of provided set of model discrepancy variances `md_var` in this :obj:`~ModelLink` instance. Parameters ---------- md_var : 1D or 2D array_like or dict Model discrepancy variance set to validate in this :obj:`~ModelLink` instance. name : str The name of the model discrepancy set, which is used in the error message if the validation fails. Returns ------- md_var : 2D :obj:`~numpy.ndarray` object The (converted) provided `md_var` if the validation was successful. If `md_var` was a dict, it will be converted to a :obj:`~numpy.ndarray` object. """ # Make logger logger = getCLogger('CHECK') logger.info("Validating provided set of model discrepancy variances " "%r." % (name)) # If md_var is a dict, convert it to a NumPy array if isinstance(md_var, dict): md_var = np_array([md_var[idx] for idx in md_var.keys()]) # Make sure that md_var is a NumPy array md_var = np_array(md_var) # Raise error if md_var is not 1D or 2D if not (md_var.ndim == 1 or md_var.ndim == 2): err_msg = ("Input argument %r is not one-dimensional or " "two-dimensional!" % (name)) raise_error(err_msg, ShapeError, logger) # Check if md_var contains n_data values if not (md_var.shape[0] == self._n_data): err_msg = ("Received array of model discrepancy variances %r has " "incorrect number of data points (%i != %i)!" % (name, md_var.shape[0], self._n_data)) raise ShapeError(err_msg) # Check if single or dual values were given if (md_var.ndim == 1): md_var = np_array([md_var] * 2).T elif (md_var.shape[1] == 2): pass else: err_msg = ("Received array of model discrepancy variances %r has " "incorrect number of values (%i != 2)!" % (name, md_var.shape[1])) raise ShapeError(err_msg) # Check if all values are non-negative floats md_var = check_vals(md_var, 'md_var', 'nneg', 'float') # Log again and return md_var logger.info("Finished validating provided set of model discrepancy " "variances %r." % (name)) return (md_var)
def _check_sam_set(self, sam_set, name): """ Checks validity of provided set of model parameter samples `sam_set` in this :obj:`~ModelLink` instance. Parameters ---------- sam_set : 1D or 2D array_like or dict Parameter/sample set to validate in this :obj:`~ModelLink` instance. name : str The name of the parameter/sample set, which is used in the error message if the validation fails. Returns ------- sam_set : 1D or 2D :obj:`~numpy.ndarray` object The provided `sam_set` if the validation was successful. If `sam_set` was a dict, it will be converted to a :obj:`~numpy.ndarray` object. """ # Make logger logger = getCLogger('CHECK') logger.info("Validating provided set of model parameter samples %r." % (name)) # If sam_set is a dict, convert it to a NumPy array if isinstance(sam_set, dict): sam_set = np_array(sdict(sam_set).values()).T # Make sure that sam_set is a NumPy array sam_set = np_array(sam_set) # Raise error if sam_set is not 1D or 2D if not (sam_set.ndim == 1 or sam_set.ndim == 2): err_msg = ("Input argument %r is not one-dimensional or " "two-dimensional!" % (name)) raise_error(err_msg, ShapeError, logger) # Raise error if sam_set does not have n_par parameter values if not (sam_set.shape[-1] == self._n_par): err_msg = ("Input argument %r has incorrect number of parameters " "(%i != %i)!" % (name, sam_set.shape[-1], self._n_par)) raise_error(err_msg, ShapeError, logger) # Check if sam_set solely consists out of floats sam_set = check_vals(sam_set, name, 'float') # Check if all samples are within parameter space sam_set_2D = np_array(sam_set, ndmin=2) rng = self._par_rng check = np.apply_along_axis( lambda x: ((rng[:, 0] <= x) * (x <= rng[:, 1])).all(), 1, sam_set_2D) # If check is not empty (can be indexed), raise error try: index = np.argwhere(~check)[0] except IndexError: pass else: err_msg = ("Input argument '%s%s' is outside parameter space!" % (name, index if sam_set.ndim != 1 else '')) raise_error(err_msg, ValueError, logger) # Log again and return sam_set logger.info("Finished validating provided set of model parameter " "samples %r." % (name)) return (sam_set)
def start_gui(pipeline_obj): # pragma: no cover # Create a logger logger = getCLogger('GUI') logger.info("Starting %s." % (APP_NAME)) # Import Pipeline class here to avoid an ImportError from prism import Pipeline # Check if provided pipeline_obj is an instance of the Pipeline class if not isinstance(pipeline_obj, Pipeline): err_msg = ("Input argument 'pipeline_obj' must be an instance of the " "Pipeline class!") e13.raise_error(err_msg, TypeError, logger) # Activate worker mode with pipeline_obj.worker_mode: if pipeline_obj._is_controller: # Temporarily switch the backend of MPL cur_backend = mpl.rcParams['backend'] switch_backend('Agg') # Obtain application instance qapp = QW.QApplication.instance() # If qapp is None, create a new one if qapp is None: QW.QApplication.setAttribute(QC.Qt.AA_EnableHighDpiScaling) qapp = QW.QApplication([APP_NAME]) # Set name of application qapp.setApplicationName(APP_NAME) # Hide the 'whats this' tooltip on Windows QW.QApplication.setAttribute( QC.Qt.AA_DisableWindowContextHelpButton) # Make sure that the application quits when last window closes qapp.lastWindowClosed.connect(qapp.quit, QC.Qt.QueuedConnection) # Initialize main window and draw (show) it main_window = MainViewerWindow(pipeline_obj) main_window.show() main_window.raise_() main_window.activateWindow() # Replace KeyboardInterrupt error by system's default handler signal.signal(signal.SIGINT, signal.SIG_DFL) # Start application qapp.exec_() # Delete this application to stop event processing del qapp # Switch back to previous backend switch_backend(cur_backend) # Log that GUI has been closed logger.info("Exited %s." % (APP_NAME)) # Return the main window instance return (main_window)