Example #1
0
def doc_script():
    from cobaya.mpi import is_main_process
    if not is_main_process():
        return
    warn_deprecation()
    # Parse arguments
    import argparse
    parser = argparse.ArgumentParser(
        description="Prints defaults for Cobaya's components.")
    parser.add_argument("component",
                        action="store",
                        nargs="?",
                        default="",
                        metavar="component_name",
                        help="The component whose defaults are requested.")
    kind_opt, kind_opt_ishort = "kind", 0
    parser.add_argument(
        "-" + kind_opt[kind_opt_ishort],
        "--" + kind_opt,
        action="store",
        nargs=1,
        default=None,
        metavar="component_kind",
        help=("Kind of component whose defaults are requested: " +
              ", ".join(['%s' % kind for kind in kinds]) + ". " +
              "Use only when component name is not unique (it would fail)."))
    parser.add_argument("-p",
                        "--python",
                        action="store_true",
                        default=False,
                        help="Request Python instead of YAML.")
    expand_flag, expand_flag_ishort = "expand", 1
    parser.add_argument("-" + expand_flag[expand_flag_ishort],
                        "--" + expand_flag,
                        action="store_true",
                        default=False,
                        help="Expand YAML defaults.")
    arguments = parser.parse_args()
    # Remove plurals (= name of src subfolders), for user-friendliness
    if arguments.component.lower() in subfolders.values():
        arguments.component = next(k for k in subfolders
                                   if arguments.component == subfolders[k])
    # Kind given, list all
    if not arguments.component:
        msg = "Available components: (some may need external code/data)"
        print(msg + "\n" + "-" * len(msg))
        for kind in kinds:
            print("%s:" % kind)
            print(_indent +
                  ("\n" +
                   _indent).join(get_available_internal_class_names(kind)))
        return
    # Kind given: list all components of that kind
    if arguments.component.lower() in kinds:
        print("%s:" % arguments.component.lower())
        print(_indent + ("\n" + _indent).join(
            get_available_internal_class_names(arguments.component.lower())))
        return
    # Otherwise, check if it's a unique component name
    try:
        if arguments.kind:
            arguments.kind = arguments.kind[0].lower()
            if arguments.kind not in kinds:
                print("Kind %r not recognized. Try one of %r" %
                      (arguments.kind, tuple(kinds)))
                raise ValueError
        else:
            arguments.kind = get_kind(arguments.component)
        to_print = get_default_info(arguments.component,
                                    arguments.kind,
                                    return_yaml=not arguments.python,
                                    yaml_expand_defaults=arguments.expand)
        if arguments.python:
            print(pformat({arguments.kind: {arguments.component: to_print}}))
        else:
            print(arguments.kind + ":\n" + _indent + arguments.component +
                  ":\n" + 2 * _indent +
                  ("\n" + 2 * _indent).join(to_print.split("\n")))
            if "!defaults" in to_print:
                print("# This file contains defaults. "
                      "To populate them, use the flag --%s (or -%s)." %
                      (expand_flag, expand_flag[expand_flag_ishort]))
    except Exception:
        if isinstance(Exception, LoggedError.__class__):
            pass
        else:
            if not arguments.kind:
                print("Specify its kind with '--%s [component_kind]'." %
                      kind_opt)
        return 1
    return
Example #2
0
 def __init__(self):
     super().__init__()
     self.setWindowTitle("Cobaya input generator for Cosmology")
     self.setStyleSheet("* {font-size:%s;}" % font_size)
     # Menu bar for defaults
     self.menubar = QMenuBar()
     defaults_menu = self.menubar.addMenu(
         '&Show defaults and bibliography for a component...')
     menu_actions = {}
     for kind in kinds:
         submenu = defaults_menu.addMenu(subfolders[kind])
         components = get_available_internal_class_names(kind)
         menu_actions[kind] = {}
         for component in components:
             menu_actions[kind][component] = QAction(component, self)
             menu_actions[kind][component].setData((kind, component))
             menu_actions[kind][component].triggered.connect(
                 self.show_defaults)
             submenu.addAction(menu_actions[kind][component])
     # Main layout
     self.menu_layout = QVBoxLayout()
     self.menu_layout.addWidget(self.menubar)
     self.setLayout(self.menu_layout)
     self.layout = QHBoxLayout()
     self.menu_layout.addLayout(self.layout)
     self.layout_left = QVBoxLayout()
     self.layout.addLayout(self.layout_left)
     self.layout_output = QVBoxLayout()
     self.layout.addLayout(self.layout_output)
     # LEFT: Options
     self.options = QWidget()
     self.layout_options = QVBoxLayout()
     self.options.setLayout(self.layout_options)
     self.options_scroll = QScrollArea()
     self.options_scroll.setWidget(self.options)
     self.options_scroll.setWidgetResizable(True)
     self.layout_left.addWidget(self.options_scroll)
     self.combos = dict()
     for group, fields in _combo_dict_text:
         group_box = QGroupBox(group)
         self.layout_options.addWidget(group_box)
         group_layout = QVBoxLayout(group_box)
         for a, desc in fields:
             self.combos[a] = QComboBox()
             # Combo box label only if not single element in group
             if len(fields) > 1:
                 label = QLabel(desc)
                 group_layout.addWidget(label)
             group_layout.addWidget(self.combos[a])
             self.combos[a].addItems([
                 text(k, v) for k, v in getattr(input_database, a).items()
             ])
     # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED
     #                if a == "theory":
     #                    # Add Planck-naming checkbox
     #                    self.planck_names = QCheckBox(
     #                        "Keep common parameter names "
     #                        "(useful for fast CLASS/CAMB switching)")
     #                    group_layout.addWidget(self.planck_names)
     # Connect to refreshers -- needs to be after adding all elements
     for field, combo in self.combos.items():
         if field == "preset":
             combo.currentIndexChanged.connect(self.refresh_preset)
         else:
             combo.currentIndexChanged.connect(self.refresh)
     #        self.planck_names.stateChanged.connect(self.refresh_keep_preset)
     # RIGHT: Output + buttons
     self.display_tabs = QTabWidget()
     self.display = {}
     for k in ["yaml", "python", "bibliography"]:
         self.display[k] = QTextEdit()
         self.display[k].setLineWrapMode(QTextEdit.NoWrap)
         self.display[k].setFontFamily("mono")
         self.display[k].setCursorWidth(0)
         self.display[k].setReadOnly(True)
         self.display_tabs.addTab(self.display[k], k)
     self.display["covmat"] = QWidget()
     covmat_tab_layout = QVBoxLayout()
     self.display["covmat"].setLayout(covmat_tab_layout)
     self.covmat_text = QLabel()
     self.covmat_text.setWordWrap(True)
     self.covmat_table = QTableWidget(0, 0)
     self.covmat_table.setEditTriggers(
         QAbstractItemView.NoEditTriggers)  # ReadOnly!
     covmat_tab_layout.addWidget(self.covmat_text)
     covmat_tab_layout.addWidget(self.covmat_table)
     self.display_tabs.addTab(self.display["covmat"], "covariance matrix")
     self.layout_output.addWidget(self.display_tabs)
     # Buttons
     self.buttons = QHBoxLayout()
     self.save_button = QPushButton('Save as...', self)
     self.copy_button = QPushButton('Copy to clipboard', self)
     self.buttons.addWidget(self.save_button)
     self.buttons.addWidget(self.copy_button)
     self.save_button.released.connect(self.save_file)
     self.copy_button.released.connect(self.copy_clipb)
     self.layout_output.addLayout(self.buttons)
     self.save_dialog = QFileDialog()
     self.save_dialog.setFileMode(QFileDialog.AnyFile)
     self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)
     self.read_settings()
     self.show()
Example #3
0
def doc_script(args=None):
    """Command line script for the documentation."""
    warn_deprecation()
    logger_setup()
    logger = get_logger("doc")
    # Parse arguments
    import argparse
    parser = argparse.ArgumentParser(
        prog="cobaya doc",
        description="Prints defaults for Cobaya's components.")
    parser.add_argument(
        "component",
        action="store",
        nargs="?",
        default="",
        metavar="component_name",
        help=("The component whose defaults are requested. "
              "Pass a component kind (sampler, theory, likelihood) to "
              "list all available (internal) ones, pass nothing to list "
              "all available (internal) components of all kinds."))
    parser.add_argument("-p",
                        "--python",
                        action="store_true",
                        default=False,
                        help="Request Python instead of YAML.")
    expand_flag, expand_flag_ishort = "expand", 1
    parser.add_argument("-" + expand_flag[expand_flag_ishort],
                        "--" + expand_flag,
                        action="store_true",
                        default=False,
                        help="Expand YAML defaults.")
    arguments = parser.parse_args(args)
    # Nothing passed: list all
    if not arguments.component:
        msg = "Available components: (some may need external code/data)"
        print(msg + "\n" + "-" * len(msg))
        for kind in kinds:
            print("%s:" % kind)
            print(_indent +
                  ("\n" +
                   _indent).join(get_available_internal_class_names(kind)))
        return
    # A kind passed (plural or singular): list all of that kind
    if arguments.component.lower() in subfolders.values():
        arguments.component = next(k for k in subfolders
                                   if arguments.component == subfolders[k])
    if arguments.component.lower() in kinds:
        print("%s:" % arguments.component.lower())
        print(_indent + ("\n" + _indent).join(
            get_available_internal_class_names(arguments.component.lower())))
        return
    # Otherwise, try to identify the component
    try:
        cls = get_component_class(arguments.component, logger=logger)
    except ComponentNotFoundError:
        suggestions = similar_internal_class_names(arguments.component)
        logger.error(
            f"Could not identify component '{arguments.component}'. "
            f"Did you mean any of the following? {suggestions} (mind capitalization!)"
        )
        return 1
    to_print = get_default_info(cls,
                                return_yaml=not arguments.python,
                                yaml_expand_defaults=arguments.expand)
    if arguments.python:
        print(pformat({cls.get_kind(): {arguments.component: to_print}}))
    else:
        print(cls.get_kind() + ":\n" + _indent + arguments.component + ":\n" +
              2 * _indent + ("\n" + 2 * _indent).join(to_print.split("\n")))
        if "!defaults" in to_print:
            print("# This file contains defaults. "
                  "To populate them, use the flag --%s (or -%s)." %
                  (expand_flag, expand_flag[expand_flag_ishort]))