class RoomWithOneExit(MultiAgentSimulation):
    size = Int(default_value=100, min=1)
    agent_type = Enum(default_value=Circular, values=(Circular, ThreeCircle))
    body_type = Enum(default_value='adult', values=('adult', ))
    width = Float(default_value=10.0, min=0)
    height = Float(default_value=10.0, min=0)
    exit_width = Float(default_value=1.25, min=0, max=10)
    exit_hall_width = Float(default_value=2.0, min=0)

    def attributes(self):
        orientation = 0.0
        d = dict(target=0,
                 body_type=self.body_type,
                 orientation=orientation,
                 velocity=1.0 * unit_vector(orientation),
                 angular_velocity=0.0,
                 target_direction=unit_vector(orientation),
                 target_orientation=orientation)
        return d

    @default('logic')
    def _default_logic(self):
        return Reset(self) << \
            InsideDomain(self) << (
                Integrator(self) << (
                    Fluctuation(self),
                    Adjusting(self) << (
                        Navigation(self),
                        Orientation(self)
                    ),
                    AgentAgentInteractions(self),
                    AgentObstacleInteractions(self)
                )
            )

    @default('field')
    def _default_field(self):
        return fields.RoomWithOneExit(width=self.width,
                                      height=self.height,
                                      exit_width=self.exit_width,
                                      exit_hall_width=self.exit_hall_width)

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)

        group = AgentGroup(agent_type=self.agent_type,
                           size=self.size,
                           attributes=self.attributes)

        agents.add_non_overlapping_group(
            group, position_gen=self.field.sample_spawn(0))

        return agents
class FourExitsRandomPlacing(MultiAgentSimulation):
    size = Int(default_value=100, min=0, help='Amount of herding agents')
    agent_type = Enum(default_value=Circular, values=(Circular, ThreeCircle))
    body_type = Enum(default_value='adult', values=('adult', ))
    exit_width = Float(default_value=1.25, min=0, max=10)

    def attributes(self):
        def wrapper():
            target = np.random.randint(0, len(self.field.targets))
            orientation = np.random.uniform(-np.pi, np.pi)
            d = dict(target=target,
                     body_type=self.body_type,
                     orientation=orientation,
                     velocity=np.zeros(2),
                     angular_velocity=0.0,
                     target_direction=np.zeros(2),
                     target_orientation=orientation,
                     familiar_exit=np.random.randint(0,
                                                     len(self.field.targets)))
            return d

        return wrapper

    @default('logic')
    def _default_logic(self):
        return Reset(self) << \
            InsideDomain(self) << (
                Integrator(self) << (
                    Fluctuation(self),
                    Adjusting(self) << (
                        Navigation(self),
                        Orientation(self)),
                    AgentAgentInteractions(self),
                    AgentObstacleInteractions(self)))

    @default('field')
    def _default_field(self):
        return fields.FourExitsField(exit_width=self.exit_width)

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)

        group = AgentGroup(agent_type=self.agent_type,
                           size=self.size,
                           attributes=self.attributes())

        agents.add_non_overlapping_group(
            group,
            position_gen=self.field.sample_spawn(0),
            obstacles=geom_to_linear_obstacles(self.field.obstacles))

        return agents
 class MyConf2(Configurable):
     an_enum = Enum(
         "Choice1 choice2".split(),
         allow_none=True,
         default_value="choice2",
         help="Many choices.",
     ).tag(config=True)
class Binding(HasTraits):
    name = Unicode(read_only=True)
    kernel = Enum(SUPPORTED_KERNELS, default_value=DEFAULT_KERNEL)
    mime_type = Unicode()
    connection = Dict()
    state = Enum(
        [
            BindingState.CONNECTED,
            BindingState.DISCONNECTED,
            BindingState.RESTARTED,
            BindingState.CREATING,
            BindingState.ERROR,
        ],
        default_value=BindingState.DISCONNECTED,
    )
    progress = Dict(default_value={"progress": None, "progress_ratio": None})

    def __str__(self):
        conn_info = [
            f"  {key}={value}" for key, value in self.connection.items()
            if value is not None
        ]
        return "\n".join([
            self.name,
            f" {self.state}",
            f" Connection: {self.connection_type}",
            "\n".join(conn_info),
        ])

    @default("mime_type")
    def _default_mime_type(self):
        return MIME_TYPES.get(self.kernel, "unknown")

    @property
    def connection_type(self):
        return self.connection.get("type", BindingConnectionType.SSH)

    def update_progress(self, message: "str", ratio: "float" = None):
        self.progress = {"progress": message, "progress_ratio": ratio}

    def as_dict(self):
        return {
            trait: trait_type.get(self)
            for trait, trait_type in self.traits().items()
        }
class TestAgentInteraction(MultiAgentSimulation):
    start_pos1 = (0, 0)
    start_pos2 = (5, 0)

    width = 20.0
    height = 10.0
    agent_type = Enum(values=(Circular, ThreeCircle), allow_none=True)

    def attributes(self, orientation=0.0):
        d = dict(ratio_rt=0.5882,
                 ratio_rs=0.3725,
                 ratio_ts=0.6275,
                 radius=0.255,
                 target_velocity=1.0,
                 mass=73.5,
                 orientation=orientation,
                 velocity=1.0 * unit_vector(orientation),
                 angular_velocity=0.0,
                 target_direction=unit_vector(orientation),
                 target_orientation=orientation)
        return d

    @default('logic')
    def _default_logic(self):
        return Reset(self) << (Integrator(self) << (
            Fluctuation(self),
            Adjusting(self) << Orientation(self),
            AgentAgentInteractions(self),
        ))

    @default('field')
    def _default_field(self):
        return fields.OutdoorField(width=self.width, height=self.height)

    @observe('agent_type')
    def _observe_agents(self, change):
        if self.agent_type is not None:
            agents = Agents(agent_type=self.agent_type)

            group = AgentGroup(agent_type=self.agent_type,
                               size=1,
                               attributes=partial(self.attributes,
                                                  orientation=0.0))

            agents.add_non_overlapping_group(
                group, position_gen=lambda: self.start_pos1)

            group = AgentGroup(agent_type=self.agent_type,
                               size=1,
                               attributes=partial(self.attributes,
                                                  orientation=np.pi))

            agents.add_non_overlapping_group(
                group, position_gen=lambda: self.start_pos2)

            self.agents = agents
class Outdoor(MultiAgentSimulation):
    r"""Simulation for visualizing collision avoidance."""
    size = Int(default_value=100, min=1)
    agent_type = Enum(default_value=Circular, values=(Circular, ThreeCircle))
    body_type = Enum(default_value='adult', values=('adult', ))
    width = Float(default_value=20.0, min=0)
    height = Float(default_value=20.0, min=0)

    def attributes(self):
        orientation = np.random.uniform(-np.pi, np.pi)
        d = dict(body_type=self.body_type,
                 orientation=orientation,
                 velocity=1.0 * unit_vector(orientation),
                 angular_velocity=0.0,
                 target_direction=unit_vector(orientation),
                 target_orientation=orientation)
        return d

    @default('logic')
    def _default_logic(self):
        return Reset(self) << (Integrator(self) << (
            Fluctuation(self),
            Adjusting(self) << Orientation(self),
            AgentAgentInteractions(self),
        ))

    @default('field')
    def _default_field(self):
        return fields.OutdoorField(width=self.width, height=self.height)

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)

        group = AgentGroup(agent_type=self.agent_type,
                           size=self.size,
                           attributes=self.attributes)

        agents.add_non_overlapping_group(
            group, position_gen=self.field.sample_spawn(0))

        return agents
class TestMovement(MultiAgentSimulation):
    """Test simulation for testing agent movement."""
    size = 1
    width = 20.0
    height = 10.0
    agent_type = Enum(values=(Circular, ThreeCircle), allow_none=True)

    def attributes(self, orientation=0.0):
        d = dict(ratio_rt=0.5882,
                 ratio_rs=0.3725,
                 ratio_ts=0.6275,
                 radius=0.255,
                 target_velocity=1.0,
                 mass=73.5,
                 orientation=orientation,
                 velocity=1.0 * unit_vector(orientation),
                 angular_velocity=0.0,
                 target_direction=unit_vector(orientation),
                 target_orientation=orientation)
        return d

    @default('logic')
    def _default_logic(self):
        return Reset(self) << Integrator(self) << Adjusting(
            self) << Orientation(self)

    @default('field')
    def _default_field(self):
        return fields.OutdoorField(width=self.width, height=self.height)

    @observe('agent_type')
    def _observe_agents(self, change):
        if self.agent_type is not None:
            agents = Agents(agent_type=self.agent_type)

            group = AgentGroup(agent_type=self.agent_type,
                               size=self.size,
                               attributes=self.attributes)

            agents.add_non_overlapping_group(group,
                                             position_gen=lambda: np.array(
                                                 (0, 0)))

            self.agents = agents
class AvoidPillar(Field):
    width = Float(
        default_value=10.0,
        min=0)
    height = Float(
        default_value=20.0,
        min=0)
    pillar_type = Enum(
        values=('ellipse', 'rectangle'),
        default_value='ellipse')
    width_pillar = Float(
        default_value=2.0,
        min=0)
    height_pillar = Float(
        default_value=2.0,
        min=0)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
Example #9
0
 class MyConf(Configurable):
     an_enum = Enum('Choice1 choice2'.split(),
                    help="Many choices.").tag(config=True)
Example #10
0
class Application(SingletonConfigurable):
    """A singleton application with full configuration support."""

    # The name of the application, will usually match the name of the command
    # line application
    name = Unicode('application')

    # The description of the application that is printed at the beginning
    # of the help.
    description = Unicode('This is an application.')
    # default section descriptions
    option_description = Unicode(option_description)
    keyvalue_description = Unicode(keyvalue_description)
    subcommand_description = Unicode(subcommand_description)

    python_config_loader_class = PyFileConfigLoader
    json_config_loader_class = JSONFileConfigLoader

    # The usage and example string that goes at the end of the help string.
    examples = Unicode()

    # A sequence of Configurable subclasses whose config=True attributes will
    # be exposed at the command line.
    classes = []

    def _classes_inc_parents(self, classes=None):
        """Iterate through configurable classes, including configurable parents

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Children should always be after parents, and each class should only be
        yielded once.
        """
        if classes is None:
            classes = self.classes

        seen = set()
        for c in classes:
            # We want to sort parents before children, so we reverse the MRO
            for parent in reversed(c.mro()):
                if issubclass(parent, Configurable) and (parent not in seen):
                    seen.add(parent)
                    yield parent

    # The version string of this application.
    version = Unicode('0.0')

    # the argv used to initialize the application
    argv = List()

    # Whether failing to load config files should prevent startup
    raise_config_file_errors = Bool(
        TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)

    # The log level for the application
    log_level = Enum(
        (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'),
        default_value=logging.WARN,
        help="Set the log level by value or name.").tag(config=True)

    @observe('log_level')
    @observe_compat
    def _log_level_changed(self, change):
        """Adjust the log level when log_level is set."""
        new = change.new
        if isinstance(new, str):
            new = getattr(logging, new)
            self.log_level = new
        self.log.setLevel(new)

    _log_formatter_cls = LevelFormatter

    log_datefmt = Unicode(
        "%Y-%m-%d %H:%M:%S",
        help="The date format used by logging formatters for %(asctime)s").tag(
            config=True)

    log_format = Unicode(
        "[%(name)s]%(highlevel)s %(message)s",
        help="The Logging format template",
    ).tag(config=True)

    @observe('log_datefmt', 'log_format')
    @observe_compat
    def _log_format_changed(self, change):
        """Change the log formatter when log_format is set."""
        _log_handler = self._get_log_handler()
        if not _log_handler:
            warnings.warn(
                "No Handler found on {self.log}, setting log_format will have no effect",
                RuntimeWarning,
            )
            return
        _log_formatter = self._log_formatter_cls(fmt=self.log_format,
                                                 datefmt=self.log_datefmt)
        _log_handler.setFormatter(_log_formatter)

    @default('log')
    def _log_default(self):
        """Start logging for this application.

        The default is to log to stderr using a StreamHandler, if no default
        handler already exists.  The log level starts at logging.WARN, but this
        can be adjusted by setting the ``log_level`` attribute.
        """
        log = logging.getLogger(self.__class__.__name__)
        log.setLevel(self.log_level)
        log.propagate = False
        _log = log  # copied from Logger.hasHandlers() (new in Python 3.2)
        while _log:
            if _log.handlers:
                return log
            if not _log.propagate:
                break
            else:
                _log = _log.parent
        if sys.executable and sys.executable.endswith('pythonw.exe'):
            # this should really go to a file, but file-logging is only
            # hooked up in parallel applications
            _log_handler = logging.StreamHandler(open(os.devnull, 'w'))
        else:
            _log_handler = logging.StreamHandler()
        _log_formatter = self._log_formatter_cls(fmt=self.log_format,
                                                 datefmt=self.log_datefmt)
        _log_handler.setFormatter(_log_formatter)
        log.addHandler(_log_handler)
        return log

    #: the alias map for configurables
    #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`.
    #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text).
    aliases = {'log-level': 'Application.log_level'}

    # flags for loading Configurables or store_const style flags
    # flags are loaded from this dict by '--key' flags
    # this must be a dict of two-tuples, the first element being the Config/dict
    # and the second being the help string for the flag
    flags = {
        'debug': ({
            'Application': {
                'log_level': logging.DEBUG,
            },
        }, "Set log-level to debug, for the most verbose logging."),
        'show-config': ({
            'Application': {
                'show_config': True,
            },
        }, "Show the application's configuration (human-readable format)"),
        'show-config-json': ({
            'Application': {
                'show_config_json': True,
            },
        }, "Show the application's configuration (json format)"),
    }

    # subcommands for launching other applications
    # if this is not empty, this will be a parent Application
    # this must be a dict of two-tuples,
    # the first element being the application class/import string
    # and the second being the help string for the subcommand
    subcommands = Dict()
    # parse_command_line will initialize a subapp, if requested
    subapp = Instance('traitlets.config.application.Application',
                      allow_none=True)

    # extra command-line arguments that don't set config values
    extra_args = List(Unicode())

    cli_config = Instance(
        Config, (), {},
        help="""The subset of our configuration that came from the command-line

        We re-load this configuration after loading config files,
        to ensure that it maintains highest priority.
        """)

    _loaded_config_files = List()

    show_config = Bool(
        help="Instead of starting the Application, dump configuration to stdout"
    ).tag(config=True)

    show_config_json = Bool(
        help=
        "Instead of starting the Application, dump configuration to stdout (as JSON)"
    ).tag(config=True)

    @observe('show_config_json')
    def _show_config_json_changed(self, change):
        self.show_config = change.new

    @observe('show_config')
    def _show_config_changed(self, change):
        if change.new:
            self._save_start = self.start
            self.start = self.start_show_config

    def __init__(self, **kwargs):
        SingletonConfigurable.__init__(self, **kwargs)
        # Ensure my class is in self.classes, so my attributes appear in command line
        # options and config files.
        cls = self.__class__
        if cls not in self.classes:
            if self.classes is cls.classes:
                # class attr, assign instead of insert
                self.classes = [cls] + self.classes
            else:
                self.classes.insert(0, self.__class__)

    @observe('config')
    @observe_compat
    def _config_changed(self, change):
        super(Application, self)._config_changed(change)
        self.log.debug('Config changed: %r', change.new)

    @catch_config_error
    def initialize(self, argv=None):
        """Do the basic steps to configure me.

        Override in subclasses.
        """
        self.parse_command_line(argv)

    def start(self):
        """Start the app mainloop.

        Override in subclasses.
        """
        if self.subapp is not None:
            return self.subapp.start()

    def start_show_config(self):
        """start function used when show_config is True"""
        config = self.config.copy()
        # exclude show_config flags from displayed config
        for cls in self.__class__.mro():
            if cls.__name__ in config:
                cls_config = config[cls.__name__]
                cls_config.pop('show_config', None)
                cls_config.pop('show_config_json', None)

        if self.show_config_json:
            json.dump(config,
                      sys.stdout,
                      indent=1,
                      sort_keys=True,
                      default=repr)
            # add trailing newline
            sys.stdout.write('\n')
            return

        if self._loaded_config_files:
            print("Loaded config files:")
            for f in self._loaded_config_files:
                print('  ' + f)
            print()

        for classname in sorted(config):
            class_config = config[classname]
            if not class_config:
                continue
            print(classname)
            pformat_kwargs = dict(indent=4, compact=True)

            for traitname in sorted(class_config):
                value = class_config[traitname]
                print('  .{} = {}'.format(
                    traitname,
                    pprint.pformat(value, **pformat_kwargs),
                ))

    def print_alias_help(self):
        """Print the alias parts of the help."""
        print('\n'.join(self.emit_alias_help()))

    def emit_alias_help(self):
        """Yield the lines for alias part of the help."""
        if not self.aliases:
            return

        classdict = {}
        for cls in self.classes:
            # include all parents (up to, but excluding Configurable) in available names
            for c in cls.mro()[:-3]:
                classdict[c.__name__] = c

        for alias, longname in self.aliases.items():
            try:
                if isinstance(longname, tuple):
                    longname, fhelp = longname
                else:
                    fhelp = None
                classname, traitname = longname.split('.', 1)
                cls = classdict[classname]

                trait = cls.class_traits(config=True)[traitname]
                fhelp = cls.class_get_trait_help(trait,
                                                 helptext=fhelp).splitlines()

                if not isinstance(alias, tuple):
                    alias = (alias, )
                alias = sorted(alias, key=len)
                alias = ', '.join(
                    ('--%s' if len(m) > 1 else '-%s') % m for m in alias)

                # reformat first line
                fhelp[0] = fhelp[0].replace('--' + longname, alias)
                for l in fhelp:
                    yield l
                yield indent("Equivalent to: [--%s]" % longname)
            except Exception as ex:
                self.log.error(
                    'Failed collecting help-message for alias %r, due to: %s',
                    alias, ex)
                raise

    def print_flag_help(self):
        """Print the flag part of the help."""
        print('\n'.join(self.emit_flag_help()))

    def emit_flag_help(self):
        """Yield the lines for the flag part of the help."""
        if not self.flags:
            return

        for flags, (cfg, fhelp) in self.flags.items():
            try:
                if not isinstance(flags, tuple):
                    flags = (flags, )
                flags = sorted(flags, key=len)
                flags = ', '.join(
                    ('--%s' if len(m) > 1 else '-%s') % m for m in flags)
                yield flags
                yield indent(dedent(fhelp.strip()))
                cfg_list = ' '.join('--%s.%s=%s' % (clname, prop, val)
                                    for clname, props_dict in cfg.items()
                                    for prop, val in props_dict.items())
                cfg_txt = "Equivalent to: [%s]" % cfg_list
                yield indent(dedent(cfg_txt))
            except Exception as ex:
                self.log.error(
                    'Failed collecting help-message for flag %r, due to: %s',
                    flags, ex)
                raise

    def print_options(self):
        """Print the options part of the help."""
        print('\n'.join(self.emit_options_help()))

    def emit_options_help(self):
        """Yield the lines for the options part of the help."""
        if not self.flags and not self.aliases:
            return
        header = 'Options'
        yield header
        yield '=' * len(header)
        for p in wrap_paragraphs(self.option_description):
            yield p
            yield ''

        for l in self.emit_flag_help():
            yield l
        for l in self.emit_alias_help():
            yield l
        yield ''

    def print_subcommands(self):
        """Print the subcommand part of the help."""
        print('\n'.join(self.emit_subcommands_help()))

    def emit_subcommands_help(self):
        """Yield the lines for the subcommand part of the help."""
        if not self.subcommands:
            return

        header = "Subcommands"
        yield header
        yield '=' * len(header)
        for p in wrap_paragraphs(
                self.subcommand_description.format(app=self.name)):
            yield p
            yield ''
        for subc, (cls, help) in self.subcommands.items():
            yield subc
            if help:
                yield indent(dedent(help.strip()))
        yield ''

    def emit_help_epilogue(self, classes):
        """Yield the very bottom lines of the help message.

        If classes=False (the default), print `--help-all` msg.
        """
        if not classes:
            yield "To see all available configurables, use `--help-all`."
            yield ''

    def print_help(self, classes=False):
        """Print the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        print('\n'.join(self.emit_help(classes=classes)))

    def emit_help(self, classes=False):
        """Yield the help-lines for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        for l in self.emit_description():
            yield l
        for l in self.emit_subcommands_help():
            yield l
        for l in self.emit_options_help():
            yield l

        if classes:
            help_classes = self._classes_with_config_traits()
            if help_classes:
                yield "Class options"
                yield "============="
                for p in wrap_paragraphs(self.keyvalue_description):
                    yield p
                    yield ''

            for cls in help_classes:
                yield cls.class_get_help()
                yield ''
        for l in self.emit_examples():
            yield l

        for l in self.emit_help_epilogue(classes):
            yield l

    def document_config_options(self):
        """Generate rST format documentation for the config options this application

        Returns a multiline string.
        """
        return '\n'.join(c.class_config_rst_doc()
                         for c in self._classes_inc_parents())

    def print_description(self):
        """Print the application description."""
        print('\n'.join(self.emit_description()))

    def emit_description(self):
        """Yield lines with the application description."""
        for p in wrap_paragraphs(self.description or self.__doc__):
            yield p
            yield ''

    def print_examples(self):
        """Print usage and examples (see `emit_examples()`). """
        print('\n'.join(self.emit_examples()))

    def emit_examples(self):
        """Yield lines with the usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        """
        if self.examples:
            yield "Examples"
            yield "--------"
            yield ''
            yield indent(dedent(self.examples.strip()))
            yield ''

    def print_version(self):
        """Print the version string."""
        print(self.version)

    @catch_config_error
    def initialize_subcommand(self, subc, argv=None):
        """Initialize a subcommand with argv."""
        subapp, _ = self.subcommands.get(subc)

        if isinstance(subapp, str):
            subapp = import_item(subapp)

        ## Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430)
        if isinstance(subapp, type) and issubclass(subapp, Application):
            # Clear existing instances before...
            self.__class__.clear_instance()
            # instantiating subapp...
            self.subapp = subapp.instance(parent=self)
        elif callable(subapp):
            # or ask factory to create it...
            self.subapp = subapp(self)
        else:
            raise AssertionError("Invalid mappings for subcommand '%s'!" %
                                 subc)

        # ... and finally initialize subapp.
        self.subapp.initialize(argv)

    def flatten_flags(self):
        """Flatten flags and aliases for loaders, so cl-args override as expected.

        This prevents issues such as an alias pointing to InteractiveShell,
        but a config file setting the same trait in TerminalInteraciveShell
        getting inappropriate priority over the command-line arg.
        Also, loaders expect ``(key: longname)`` and not ````key: (longname, help)`` items.

        Only aliases with exactly one descendent in the class list
        will be promoted.

        """
        # build a tree of classes in our list that inherit from a particular
        # it will be a dict by parent classname of classes in our list
        # that are descendents
        mro_tree = defaultdict(list)
        for cls in self.classes:
            clsname = cls.__name__
            for parent in cls.mro()[1:-3]:
                # exclude cls itself and Configurable,HasTraits,object
                mro_tree[parent.__name__].append(clsname)
        # flatten aliases, which have the form:
        # { 'alias' : 'Class.trait' }
        aliases = {}
        for alias, longname in self.aliases.items():
            if isinstance(longname, tuple):
                longname, _ = longname
            cls, trait = longname.split('.', 1)
            children = mro_tree[cls]
            if len(children) == 1:
                # exactly one descendent, promote alias
                cls = children[0]
            if not isinstance(aliases, tuple):
                alias = (alias, )
            for al in alias:
                aliases[al] = '.'.join([cls, trait])

        # flatten flags, which are of the form:
        # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
        flags = {}
        for key, (flagdict, help) in self.flags.items():
            newflag = {}
            for cls, subdict in flagdict.items():
                children = mro_tree[cls]
                # exactly one descendent, promote flag section
                if len(children) == 1:
                    cls = children[0]

                if cls in newflag:
                    newflag[cls].update(subdict)
                else:
                    newflag[cls] = subdict

            if not isinstance(key, tuple):
                key = (key, )
            for k in key:
                flags[k] = (newflag, help)
        return flags, aliases

    def _create_loader(self, argv, aliases, flags, classes):
        return KVArgParseConfigLoader(argv,
                                      aliases,
                                      flags,
                                      classes=classes,
                                      log=self.log)

    @catch_config_error
    def parse_command_line(self, argv=None):
        """Parse the command line arguments."""
        assert not isinstance(argv, str)
        argv = sys.argv[1:] if argv is None else argv
        self.argv = [cast_unicode(arg) for arg in argv]

        if argv and argv[0] == 'help':
            # turn `ipython help notebook` into `ipython notebook -h`
            argv = argv[1:] + ['-h']

        if self.subcommands and len(argv) > 0:
            # we have subcommands, and one may have been specified
            subc, subargv = argv[0], argv[1:]
            if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
                # it's a subcommand, and *not* a flag or class parameter
                return self.initialize_subcommand(subc, subargv)

        # Arguments after a '--' argument are for the script IPython may be
        # about to run, not IPython iteslf. For arguments parsed here (help and
        # version), we want to only search the arguments up to the first
        # occurrence of '--', which we're calling interpreted_argv.
        try:
            interpreted_argv = argv[:argv.index('--')]
        except ValueError:
            interpreted_argv = argv

        if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')):
            self.print_help('--help-all' in interpreted_argv)
            self.exit(0)

        if '--version' in interpreted_argv or '-V' in interpreted_argv:
            self.print_version()
            self.exit(0)

        # flatten flags&aliases, so cl-args get appropriate priority:
        flags, aliases = self.flatten_flags()
        classes = tuple(self._classes_with_config_traits())
        loader = self._create_loader(argv, aliases, flags, classes=classes)
        try:
            self.cli_config = deepcopy(loader.load_config())
        except SystemExit:
            # traitlets 5: no longer print help output on error
            # help output is huge, and comes after the error
            raise
        self.update_config(self.cli_config)
        # store unparsed args in extra_args
        self.extra_args = loader.extra_args

    @classmethod
    def _load_config_files(cls,
                           basefilename,
                           path=None,
                           log=None,
                           raise_config_file_errors=False):
        """Load config files (py,json) by filename and path.

        yield each config object in turn.
        """

        if not isinstance(path, list):
            path = [path]
        for path in path[::-1]:
            # path list is in descending priority order, so load files backwards:
            pyloader = cls.python_config_loader_class(basefilename + '.py',
                                                      path=path,
                                                      log=log)
            if log:
                log.debug("Looking for %s in %s", basefilename, path
                          or os.getcwd())
            jsonloader = cls.json_config_loader_class(basefilename + '.json',
                                                      path=path,
                                                      log=log)
            loaded = []
            filenames = []
            for loader in [pyloader, jsonloader]:
                config = None
                try:
                    config = loader.load_config()
                except ConfigFileNotFound:
                    pass
                except Exception:
                    # try to get the full filename, but it will be empty in the
                    # unlikely event that the error raised before filefind finished
                    filename = loader.full_filename or basefilename
                    # problem while running the file
                    if raise_config_file_errors:
                        raise
                    if log:
                        log.error("Exception while loading config file %s",
                                  filename,
                                  exc_info=True)
                else:
                    if log:
                        log.debug("Loaded config file: %s",
                                  loader.full_filename)
                if config:
                    for filename, earlier_config in zip(filenames, loaded):
                        collisions = earlier_config.collisions(config)
                        if collisions and log:
                            log.warning(
                                "Collisions detected in {0} and {1} config files."
                                " {1} has higher priority: {2}".format(
                                    filename,
                                    loader.full_filename,
                                    json.dumps(collisions, indent=2),
                                ))
                    yield (config, loader.full_filename)
                    loaded.append(config)
                    filenames.append(loader.full_filename)

    @property
    def loaded_config_files(self):
        """Currently loaded configuration files"""
        return self._loaded_config_files[:]

    @catch_config_error
    def load_config_file(self, filename, path=None):
        """Load config files by filename and path."""
        filename, ext = os.path.splitext(filename)
        new_config = Config()
        for (config, filename) in self._load_config_files(
                filename,
                path=path,
                log=self.log,
                raise_config_file_errors=self.raise_config_file_errors,
        ):
            new_config.merge(config)
            if filename not in self._loaded_config_files:  # only add to list of loaded files if not previously loaded
                self._loaded_config_files.append(filename)
        # add self.cli_config to preserve CLI config priority
        new_config.merge(self.cli_config)
        self.update_config(new_config)

    def _classes_with_config_traits(self, classes=None):
        """
        Yields only classes with configurable traits, and their subclasses.

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Thus, produced sample config-file will contain all classes
        on which a trait-value may be overridden:

        - either on the class owning the trait,
        - or on its subclasses, even if those subclasses do not define
          any traits themselves.
        """
        if classes is None:
            classes = self.classes

        cls_to_config = OrderedDict(
            (cls, bool(cls.class_own_traits(config=True)))
            for cls in self._classes_inc_parents(classes))

        def is_any_parent_included(cls):
            return any(b in cls_to_config and cls_to_config[b]
                       for b in cls.__bases__)

        ## Mark "empty" classes for inclusion if their parents own-traits,
        #  and loop until no more classes gets marked.
        #
        while True:
            to_incl_orig = cls_to_config.copy()
            cls_to_config = OrderedDict(
                (cls, inc_yes or is_any_parent_included(cls))
                for cls, inc_yes in cls_to_config.items())
            if cls_to_config == to_incl_orig:
                break
        for cl, inc_yes in cls_to_config.items():
            if inc_yes:
                yield cl

    def generate_config_file(self, classes=None):
        """generate default config file from Configurables"""
        lines = ["# Configuration file for %s." % self.name]
        lines.append('')
        classes = self.classes if classes is None else classes
        config_classes = list(self._classes_with_config_traits(classes))
        for cls in config_classes:
            lines.append(cls.class_config_section(config_classes))
        return '\n'.join(lines)

    def exit(self, exit_status=0):
        self.log.debug("Exiting application: %s" % self.name)
        sys.exit(exit_status)

    @classmethod
    def launch_instance(cls, argv=None, **kwargs):
        """Launch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        """
        app = cls.instance(**kwargs)
        app.initialize(argv)
        app.start()
Example #11
0
class Application(SingletonConfigurable):
    """A singleton application with full configuration support."""

    # The name of the application, will usually match the name of the command
    # line application
    name = Unicode(u'application')

    # The description of the application that is printed at the beginning
    # of the help.
    description = Unicode(u'This is an application.')
    # default section descriptions
    option_description = Unicode(option_description)
    keyvalue_description = Unicode(keyvalue_description)
    subcommand_description = Unicode(subcommand_description)
    
    python_config_loader_class = PyFileConfigLoader
    json_config_loader_class = JSONFileConfigLoader

    # The usage and example string that goes at the end of the help string.
    examples = Unicode()

    # A sequence of Configurable subclasses whose config=True attributes will
    # be exposed at the command line.
    classes = []
    @property
    def _help_classes(self):
        """Define `App.help_classes` if CLI classes should differ from config file classes"""
        return getattr(self, 'help_classes', self.classes)
    
    @property
    def _config_classes(self):
        """Define `App.config_classes` if config file classes should differ from CLI classes."""
        return getattr(self, 'config_classes', self.classes)

    # The version string of this application.
    version = Unicode(u'0.0')
    
    # the argv used to initialize the application
    argv = List()

    # The log level for the application
    log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'),
                    default_value=logging.WARN,
                    config=True,
                    help="Set the log level by value or name.")
    def _log_level_changed(self, name, old, new):
        """Adjust the log level when log_level is set."""
        if isinstance(new, string_types):
            new = getattr(logging, new)
            self.log_level = new
        self.log.setLevel(new)
    
    _log_formatter_cls = LevelFormatter
    
    log_datefmt = Unicode("%Y-%m-%d %H:%M:%S", config=True,
        help="The date format used by logging formatters for %(asctime)s"
    )
    def _log_datefmt_changed(self, name, old, new):
        self._log_format_changed('log_format', self.log_format, self.log_format)
    
    log_format = Unicode("[%(name)s]%(highlevel)s %(message)s", config=True,
        help="The Logging format template",
    )
    def _log_format_changed(self, name, old, new):
        """Change the log formatter when log_format is set."""
        _log_handler = self.log.handlers[0]
        _log_formatter = self._log_formatter_cls(fmt=new, datefmt=self.log_datefmt)
        _log_handler.setFormatter(_log_formatter)
    

    log = Instance(logging.Logger)
    def _log_default(self):
        """Start logging for this application.

        The default is to log to stderr using a StreamHandler, if no default
        handler already exists.  The log level starts at logging.WARN, but this
        can be adjusted by setting the ``log_level`` attribute.
        """
        log = logging.getLogger(self.__class__.__name__)
        log.setLevel(self.log_level)
        log.propagate = False
        _log = log # copied from Logger.hasHandlers() (new in Python 3.2)
        while _log:
            if _log.handlers:
                return log
            if not _log.propagate:
                break
            else:
                _log = _log.parent
        if sys.executable.endswith('pythonw.exe'):
            # this should really go to a file, but file-logging is only
            # hooked up in parallel applications
            _log_handler = logging.StreamHandler(open(os.devnull, 'w'))
        else:
            _log_handler = logging.StreamHandler()
        _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt)
        _log_handler.setFormatter(_log_formatter)
        log.addHandler(_log_handler)
        return log

    # the alias map for configurables
    aliases = Dict({'log-level' : 'Application.log_level'})

    # flags for loading Configurables or store_const style flags
    # flags are loaded from this dict by '--key' flags
    # this must be a dict of two-tuples, the first element being the Config/dict
    # and the second being the help string for the flag
    flags = Dict()
    def _flags_changed(self, name, old, new):
        """ensure flags dict is valid"""
        for key,value in iteritems(new):
            assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
            assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
            assert isinstance(value[1], string_types), "Bad flag: %r:%s"%(key,value)


    # subcommands for launching other applications
    # if this is not empty, this will be a parent Application
    # this must be a dict of two-tuples,
    # the first element being the application class/import string
    # and the second being the help string for the subcommand
    subcommands = Dict()
    # parse_command_line will initialize a subapp, if requested
    subapp = Instance('traitlets.config.application.Application', allow_none=True)

    # extra command-line arguments that don't set config values
    extra_args = List(Unicode)


    def __init__(self, **kwargs):
        SingletonConfigurable.__init__(self, **kwargs)
        # Ensure my class is in self.classes, so my attributes appear in command line
        # options and config files.
        if self.__class__ not in self.classes:
            self.classes.insert(0, self.__class__)

    def _config_changed(self, name, old, new):
        SingletonConfigurable._config_changed(self, name, old, new)
        self.log.debug('Config changed:')
        self.log.debug(repr(new))

    @catch_config_error
    def initialize(self, argv=None):
        """Do the basic steps to configure me.

        Override in subclasses.
        """
        self.parse_command_line(argv)


    def start(self):
        """Start the app mainloop.

        Override in subclasses.
        """
        if self.subapp is not None:
            return self.subapp.start()

    def print_alias_help(self):
        """Print the alias part of the help."""
        if not self.aliases:
            return

        lines = []
        classdict = {}
        for cls in self._help_classes:
            # include all parents (up to, but excluding Configurable) in available names
            for c in cls.mro()[:-3]:
                classdict[c.__name__] = c

        for alias, longname in iteritems(self.aliases):
            classname, traitname = longname.split('.',1)
            cls = classdict[classname]

            trait = cls.class_traits(config=True)[traitname]
            help = cls.class_get_trait_help(trait).splitlines()
            # reformat first line
            help[0] = help[0].replace(longname, alias) + ' (%s)'%longname
            if len(alias) == 1:
                help[0] = help[0].replace('--%s='%alias, '-%s '%alias)
            lines.extend(help)
        # lines.append('')
        print(os.linesep.join(lines))

    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = []
        for m, (cfg,help) in iteritems(self.flags):
            prefix = '--' if len(m) > 1 else '-'
            lines.append(prefix+m)
            lines.append(indent(dedent(help.strip())))
        # lines.append('')
        print(os.linesep.join(lines))

    def print_options(self):
        if not self.flags and not self.aliases:
            return
        lines = ['Options']
        lines.append('-'*len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.option_description):
            lines.append(p)
            lines.append('')
        print(os.linesep.join(lines))
        self.print_flag_help()
        self.print_alias_help()
        print()

    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-'*len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.subcommand_description.format(
                    app=self.name)):
            lines.append(p)
            lines.append('')
        for subc, (cls, help) in iteritems(self.subcommands):
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print(os.linesep.join(lines))

    def print_help(self, classes=False):
        """Print the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        self.print_description()
        self.print_subcommands()
        self.print_options()

        if classes:
            help_classes = self._help_classes
            if help_classes:
                print("Class parameters")
                print("----------------")
                print()
                for p in wrap_paragraphs(self.keyvalue_description):
                    print(p)
                    print()

            for cls in help_classes:
                cls.class_print_help()
                print()
        else:
            print("To see all available configurables, use `--help-all`")
            print()

        self.print_examples()


    def print_description(self):
        """Print the application description."""
        for p in wrap_paragraphs(self.description):
            print(p)
            print()

    def print_examples(self):
        """Print usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        """
        if self.examples:
            print("Examples")
            print("--------")
            print()
            print(indent(dedent(self.examples.strip())))
            print()

    def print_version(self):
        """Print the version string."""
        print(self.version)

    def update_config(self, config):
        """Fire the traits events when the config is updated."""
        # Save a copy of the current config.
        newconfig = deepcopy(self.config)
        # Merge the new config into the current one.
        newconfig.merge(config)
        # Save the combined config as self.config, which triggers the traits
        # events.
        self.config = newconfig

    @catch_config_error
    def initialize_subcommand(self, subc, argv=None):
        """Initialize a subcommand with argv."""
        subapp,help = self.subcommands.get(subc)

        if isinstance(subapp, string_types):
            subapp = import_item(subapp)

        # clear existing instances
        self.__class__.clear_instance()
        # instantiate
        self.subapp = subapp.instance(config=self.config)
        # and initialize subapp
        self.subapp.initialize(argv)
    
    def flatten_flags(self):
        """flatten flags and aliases, so cl-args override as expected.
        
        This prevents issues such as an alias pointing to InteractiveShell,
        but a config file setting the same trait in TerminalInteraciveShell
        getting inappropriate priority over the command-line arg.

        Only aliases with exactly one descendent in the class list
        will be promoted.
        
        """
        # build a tree of classes in our list that inherit from a particular
        # it will be a dict by parent classname of classes in our list
        # that are descendents
        mro_tree = defaultdict(list)
        for cls in self._help_classes:
            clsname = cls.__name__
            for parent in cls.mro()[1:-3]:
                # exclude cls itself and Configurable,HasTraits,object
                mro_tree[parent.__name__].append(clsname)
        # flatten aliases, which have the form:
        # { 'alias' : 'Class.trait' }
        aliases = {}
        for alias, cls_trait in iteritems(self.aliases):
            cls,trait = cls_trait.split('.',1)
            children = mro_tree[cls]
            if len(children) == 1:
                # exactly one descendent, promote alias
                cls = children[0]
            aliases[alias] = '.'.join([cls,trait])
        
        # flatten flags, which are of the form:
        # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
        flags = {}
        for key, (flagdict, help) in iteritems(self.flags):
            newflag = {}
            for cls, subdict in iteritems(flagdict):
                children = mro_tree[cls]
                # exactly one descendent, promote flag section
                if len(children) == 1:
                    cls = children[0]
                newflag[cls] = subdict
            flags[key] = (newflag, help)
        return flags, aliases

    @catch_config_error
    def parse_command_line(self, argv=None):
        """Parse the command line arguments."""
        argv = sys.argv[1:] if argv is None else argv
        self.argv = [ py3compat.cast_unicode(arg) for arg in argv ]
        
        if argv and argv[0] == 'help':
            # turn `ipython help notebook` into `ipython notebook -h`
            argv = argv[1:] + ['-h']

        if self.subcommands and len(argv) > 0:
            # we have subcommands, and one may have been specified
            subc, subargv = argv[0], argv[1:]
            if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
                # it's a subcommand, and *not* a flag or class parameter
                return self.initialize_subcommand(subc, subargv)

        # Arguments after a '--' argument are for the script IPython may be
        # about to run, not IPython iteslf. For arguments parsed here (help and
        # version), we want to only search the arguments up to the first
        # occurrence of '--', which we're calling interpreted_argv.
        try:
            interpreted_argv = argv[:argv.index('--')]
        except ValueError:
            interpreted_argv = argv

        if any(x in interpreted_argv for x in ('-h', '--help-all', '--help')):
            self.print_help('--help-all' in interpreted_argv)
            self.exit(0)

        if '--version' in interpreted_argv or '-V' in interpreted_argv:
            self.print_version()
            self.exit(0)
        
        # flatten flags&aliases, so cl-args get appropriate priority:
        flags,aliases = self.flatten_flags()
        loader = KVArgParseConfigLoader(argv=argv, aliases=aliases,
                                        flags=flags, log=self.log)
        config = loader.load_config()
        self.update_config(config)
        # store unparsed args in extra_args
        self.extra_args = loader.extra_args

    @classmethod
    def _load_config_files(cls, basefilename, path=None, log=None):
        """Load config files (py,json) by filename and path.

        yield each config object in turn.
        """
        
        if not isinstance(path, list):
            path = [path]
        for path in path[::-1]:
            # path list is in descending priority order, so load files backwards:
            pyloader = cls.python_config_loader_class(basefilename+'.py', path=path, log=log)
            jsonloader = cls.json_config_loader_class(basefilename+'.json', path=path, log=log)
            config = None
            for loader in [pyloader, jsonloader]:
                try:
                    config = loader.load_config()
                except ConfigFileNotFound:
                    pass
                except Exception:
                    # try to get the full filename, but it will be empty in the
                    # unlikely event that the error raised before filefind finished
                    filename = loader.full_filename or basefilename
                    # problem while running the file
                    if log:
                        log.error("Exception while loading config file %s",
                                filename, exc_info=True)
                else:
                    if log:
                        log.debug("Loaded config file: %s", loader.full_filename)
                if config:
                     yield config

        raise StopIteration


    @catch_config_error
    def load_config_file(self, filename, path=None):
        """Load config files by filename and path."""
        filename, ext = os.path.splitext(filename)
        loaded = []
        for config in self._load_config_files(filename, path=path, log=self.log):
            loaded.append(config)
            self.update_config(config)
        if len(loaded) > 1:
            collisions = loaded[0].collisions(loaded[1])
            if collisions:
                self.log.warn("Collisions detected in {0}.py and {0}.json config files."
                              " {0}.json has higher priority: {1}".format(
                              filename, json.dumps(collisions, indent=2),
                ))


    def generate_config_file(self):
        """generate default config file from Configurables"""
        lines = ["# Configuration file for %s." % self.name]
        lines.append('')
        for cls in self._config_classes:
            lines.append(cls.class_config_section())
        return '\n'.join(lines)

    def exit(self, exit_status=0):
        self.log.debug("Exiting application: %s" % self.name)
        sys.exit(exit_status)

    @classmethod
    def launch_instance(cls, argv=None, **kwargs):
        """Launch a global instance of this Application
        
        If a global instance already exists, this reinitializes and starts it
        """
        app = cls.instance(**kwargs)
        app.initialize(argv)
        app.start()
class Hallway(MultiAgentSimulation):
    r"""Hallway

    - Low / medium / high crowd density
    - Overtaking
    - Counterflow
    - Bidirectional flow
    - Unidirectional flow

    """
    size = Int(default_value=50, min=2)
    agent_type = Enum(
        default_value=Circular,
        values=(Circular, ThreeCircle),
    )
    body_type = Enum(default_value='adult', values=('adult', ))
    width = Float(default_value=40.0, min=0)
    height = Float(default_value=5.0, min=0)
    ratio = Float(default_value=1 / 3, min=0, max=1)

    def attributes1(self):
        orientation = 0.0
        return dict(body_type=self.body_type,
                    orientation=orientation,
                    velocity=unit_vector(orientation),
                    angular_velocity=0.0,
                    target_direction=unit_vector(orientation),
                    target_orientation=orientation,
                    target=1)

    def attributes2(self):
        orientation = np.pi
        return dict(body_type=self.body_type,
                    orientation=orientation,
                    velocity=unit_vector(orientation),
                    angular_velocity=0.0,
                    target_direction=unit_vector(orientation),
                    target_orientation=orientation,
                    target=0)

    @default('logic')
    def _default_logic(self):
        return Reset(self) << \
            InsideDomain(self) << (
                Integrator(self) << (
                    Fluctuation(self),
                    Adjusting(self) << (
                        Navigation(self),
                        Orientation(self)
                    ),
                    AgentAgentInteractions(self),
                    AgentObstacleInteractions(self)
                )
            )

    @default('field')
    def _default_field(self):
        return fields.HallwayField(width=self.width,
                                   height=self.height,
                                   ratio=self.ratio)

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)

        group1 = AgentGroup(size=self.size // 2,
                            agent_type=self.agent_type,
                            attributes=self.attributes1)
        group2 = AgentGroup(size=self.size // 2,
                            agent_type=self.agent_type,
                            attributes=self.attributes2)

        agents.add_non_overlapping_group(
            group=group1, position_gen=self.field.sample_spawn(0))
        agents.add_non_overlapping_group(
            group=group2, position_gen=self.field.sample_spawn(1))

        return agents
class FinlandiaTalo2ndFloor(MultiAgentSimulation):
    size_finlandiahall = Int(default_value=200, min=0, max=1700, help='')
    size_foyer = Int(default_value=0, min=0, max=600, help='')
    size_helsinkihall = Int(default_value=200, min=0, max=340, help='')
    size_piazza = Int(default_value=0, min=0, max=600, help='')

    agent_type = Enum(default_value=Circular, values=(Circular, ThreeCircle))
    body_type = Enum(default_value='adult', values=('adult', ))

    def attributes(self, has_target: bool = True, is_follower: bool = False):
        def wrapper():
            rand_target = np.random.randint(0, len(self.field.targets))
            target = rand_target if has_target else NO_TARGET
            orientation = np.random.uniform(-np.pi, np.pi)
            d = dict(target=target,
                     is_leader=not is_follower,
                     is_follower=is_follower,
                     body_type=self.body_type,
                     orientation=orientation,
                     velocity=np.zeros(2),
                     angular_velocity=0.0,
                     target_direction=np.zeros(2),
                     target_orientation=orientation,
                     familiar_exit=np.random.randint(0,
                                                     len(self.field.targets)))
            return d

        return wrapper

    @default('logic')
    def _default_logic(self):
        return Reset(self) << \
               TargetReached(self) << (
                   Integrator(self) << (
                       Fluctuation(self),
                       Adjusting(self) << (
                           Navigation(self) << ExitDetection(
                               self) << LeaderFollower(self),
                           Orientation(self)),
                       AgentAgentInteractions(self),
                       AgentObstacleInteractions(self)))

    @default('field')
    def _default_field(self):
        return FinlandiaTalo2ndFloorField()

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)

        for spawn, name in enumerate(
            ['finlandiahall', 'foyer', 'helsinkihall']):
            group = AgentGroup(agent_type=self.agent_type,
                               size=getattr(self, f'size_{name}'),
                               attributes=self.attributes(has_target=True,
                                                          is_follower=False))

            agents.add_non_overlapping_group(
                group,
                position_gen=self.field.sample_spawn(spawn),
                obstacles=geom_to_linear_obstacles(self.field.obstacles))

        return agents
Example #14
0
class Application(SingletonConfigurable):
    """A singleton application with full configuration support."""

    # The name of the application, will usually match the name of the command
    # line application
    name = Unicode("application")

    # The description of the application that is printed at the beginning
    # of the help.
    description = Unicode("This is an application.")
    # default section descriptions
    option_description = Unicode(option_description)
    keyvalue_description = Unicode(keyvalue_description)
    subcommand_description = Unicode(subcommand_description)

    python_config_loader_class = PyFileConfigLoader
    json_config_loader_class = JSONFileConfigLoader

    # The usage and example string that goes at the end of the help string.
    examples = Unicode()

    # A sequence of Configurable subclasses whose config=True attributes will
    # be exposed at the command line.
    classes: t.List[t.Type[t.Any]] = []

    def _classes_inc_parents(self, classes=None):
        """Iterate through configurable classes, including configurable parents

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Children should always be after parents, and each class should only be
        yielded once.
        """
        if classes is None:
            classes = self.classes

        seen = set()
        for c in classes:
            # We want to sort parents before children, so we reverse the MRO
            for parent in reversed(c.mro()):
                if issubclass(parent, Configurable) and (parent not in seen):
                    seen.add(parent)
                    yield parent

    # The version string of this application.
    version = Unicode("0.0")

    # the argv used to initialize the application
    argv = List()

    # Whether failing to load config files should prevent startup
    raise_config_file_errors = Bool(TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR)

    # The log level for the application
    log_level = Enum(
        (0, 10, 20, 30, 40, 50, "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"),
        default_value=logging.WARN,
        help="Set the log level by value or name.",
    ).tag(config=True)

    _log_formatter_cls = LevelFormatter

    log_datefmt = Unicode(
        "%Y-%m-%d %H:%M:%S", help="The date format used by logging formatters for %(asctime)s"
    ).tag(config=True)

    log_format = Unicode(
        "[%(name)s]%(highlevel)s %(message)s",
        help="The Logging format template",
    ).tag(config=True)

    def get_default_logging_config(self):
        """Return the base logging configuration.

        The default is to log to stderr using a StreamHandler, if no default
        handler already exists.

        The log handler level starts at logging.WARN, but this can be adjusted
        by setting the ``log_level`` attribute.

        The ``logging_config`` trait is merged into this allowing for finer
        control of logging.

        """
        config: t.Dict[str, t.Any] = {
            "version": 1,
            "handlers": {
                "console": {
                    "class": "logging.StreamHandler",
                    "formatter": "console",
                    "level": logging.getLevelName(self.log_level),
                    "stream": "ext://sys.stderr",
                },
            },
            "formatters": {
                "console": {
                    "class": (
                        f"{self._log_formatter_cls.__module__}"
                        f".{self._log_formatter_cls.__name__}"
                    ),
                    "format": self.log_format,
                    "datefmt": self.log_datefmt,
                },
            },
            "loggers": {
                self.__class__.__name__: {
                    "level": "DEBUG",
                    "handlers": ["console"],
                }
            },
            "disable_existing_loggers": False,
        }

        if sys.executable and sys.executable.endswith("pythonw.exe"):
            # disable logging
            # (this should really go to a file, but file-logging is only
            # hooked up in parallel applications)
            del config["handlers"]["loggers"]

        return config

    @observe("log_datefmt", "log_format", "log_level", "logging_config")
    def _observe_logging_change(self, change):
        # convert log level strings to ints
        log_level = self.log_level
        if isinstance(log_level, str):
            self.log_level = getattr(logging, log_level)
        self._configure_logging()

    @observe("log", type="default")
    def _observe_logging_default(self, change):
        self._configure_logging()

    def _configure_logging(self):
        config = self.get_default_logging_config()
        nested_update(config, self.logging_config or {})
        dictConfig(config)
        # make a note that we have configured logging
        self._logging_configured = True

    @default("log")
    def _log_default(self):
        """Start logging for this application."""
        log = logging.getLogger(self.__class__.__name__)
        log.propagate = False
        _log = log  # copied from Logger.hasHandlers() (new in Python 3.2)
        while _log:
            if _log.handlers:
                return log
            if not _log.propagate:
                break
            else:
                _log = _log.parent  # type:ignore[assignment]
        return log

    logging_config = Dict(
        help="""
            Configure additional log handlers.

            The default stderr logs handler is configured by the
            log_level, log_datefmt and log_format settings.

            This configuration can be used to configure additional handlers
            (e.g. to output the log to a file) or for finer control over the
            default handlers.

            If provided this should be a logging configuration dictionary, for
            more information see:
            https://docs.python.org/3/library/logging.config.html#logging-config-dictschema

            This dictionary is merged with the base logging configuration which
            defines the following:

            * A logging formatter intended for interactive use called
              ``console``.
            * A logging handler that writes to stderr called
              ``console`` which uses the formatter ``console``.
            * A logger with the name of this application set to ``DEBUG``
              level.

            This example adds a new handler that writes to a file:

            .. code-block:: python

               c.Application.logging_configuration = {
                   'handlers': {
                       'file': {
                           'class': 'logging.FileHandler',
                           'level': 'DEBUG',
                           'filename': '<path/to/file>',
                       }
                   },
                   'loggers': {
                       '<application-name>': {
                           'level': 'DEBUG',
                           # NOTE: if you don't list the default "console"
                           # handler here then it will be disabled
                           'handlers': ['console', 'file'],
                       },
                   }
               }

        """,
    ).tag(config=True)

    #: the alias map for configurables
    #: Keys might strings or tuples for additional options; single-letter alias accessed like `-v`.
    #: Values might be like "Class.trait" strings of two-tuples: (Class.trait, help-text).
    aliases: t.Dict[str, str] = {"log-level": "Application.log_level"}

    # flags for loading Configurables or store_const style flags
    # flags are loaded from this dict by '--key' flags
    # this must be a dict of two-tuples, the first element being the Config/dict
    # and the second being the help string for the flag
    flags: t.Dict[str, t.Any] = {
        "debug": (
            {
                "Application": {
                    "log_level": logging.DEBUG,
                },
            },
            "Set log-level to debug, for the most verbose logging.",
        ),
        "show-config": (
            {
                "Application": {
                    "show_config": True,
                },
            },
            "Show the application's configuration (human-readable format)",
        ),
        "show-config-json": (
            {
                "Application": {
                    "show_config_json": True,
                },
            },
            "Show the application's configuration (json format)",
        ),
    }

    # subcommands for launching other applications
    # if this is not empty, this will be a parent Application
    # this must be a dict of two-tuples,
    # the first element being the application class/import string
    # and the second being the help string for the subcommand
    subcommands = Dict()
    # parse_command_line will initialize a subapp, if requested
    subapp = Instance("traitlets.config.application.Application", allow_none=True)

    # extra command-line arguments that don't set config values
    extra_args = List(Unicode())

    cli_config = Instance(
        Config,
        (),
        {},
        help="""The subset of our configuration that came from the command-line

        We re-load this configuration after loading config files,
        to ensure that it maintains highest priority.
        """,
    )

    _loaded_config_files = List()

    show_config = Bool(
        help="Instead of starting the Application, dump configuration to stdout"
    ).tag(config=True)

    show_config_json = Bool(
        help="Instead of starting the Application, dump configuration to stdout (as JSON)"
    ).tag(config=True)

    @observe("show_config_json")
    def _show_config_json_changed(self, change):
        self.show_config = change.new

    @observe("show_config")
    def _show_config_changed(self, change):
        if change.new:
            self._save_start = self.start
            self.start = self.start_show_config  # type:ignore[assignment]

    def __init__(self, **kwargs):
        SingletonConfigurable.__init__(self, **kwargs)
        # Ensure my class is in self.classes, so my attributes appear in command line
        # options and config files.
        cls = self.__class__
        if cls not in self.classes:
            if self.classes is cls.classes:
                # class attr, assign instead of insert
                self.classes = [cls] + self.classes
            else:
                self.classes.insert(0, self.__class__)

    @observe("config")
    @observe_compat
    def _config_changed(self, change):
        super()._config_changed(change)
        self.log.debug("Config changed: %r", change.new)

    @catch_config_error
    def initialize(self, argv=None):
        """Do the basic steps to configure me.

        Override in subclasses.
        """
        self.parse_command_line(argv)

    def start(self):
        """Start the app mainloop.

        Override in subclasses.
        """
        if self.subapp is not None:
            return self.subapp.start()

    def start_show_config(self):
        """start function used when show_config is True"""
        config = self.config.copy()
        # exclude show_config flags from displayed config
        for cls in self.__class__.mro():
            if cls.__name__ in config:
                cls_config = config[cls.__name__]
                cls_config.pop("show_config", None)
                cls_config.pop("show_config_json", None)

        if self.show_config_json:
            json.dump(config, sys.stdout, indent=1, sort_keys=True, default=repr)
            # add trailing newline
            sys.stdout.write("\n")
            return

        if self._loaded_config_files:
            print("Loaded config files:")
            for f in self._loaded_config_files:
                print("  " + f)
            print()

        for classname in sorted(config):
            class_config = config[classname]
            if not class_config:
                continue
            print(classname)
            pformat_kwargs: t.Dict[str, t.Any] = dict(indent=4, compact=True)

            for traitname in sorted(class_config):
                value = class_config[traitname]
                print(
                    "  .{} = {}".format(
                        traitname,
                        pprint.pformat(value, **pformat_kwargs),
                    )
                )

    def print_alias_help(self):
        """Print the alias parts of the help."""
        print("\n".join(self.emit_alias_help()))

    def emit_alias_help(self):
        """Yield the lines for alias part of the help."""
        if not self.aliases:
            return

        classdict = {}
        for cls in self.classes:
            # include all parents (up to, but excluding Configurable) in available names
            for c in cls.mro()[:-3]:
                classdict[c.__name__] = c

        for alias, longname in self.aliases.items():
            try:
                if isinstance(longname, tuple):
                    longname, fhelp = longname
                else:
                    fhelp = None
                classname, traitname = longname.split(".")[-2:]
                longname = classname + "." + traitname
                cls = classdict[classname]

                trait = cls.class_traits(config=True)[traitname]
                fhelp = cls.class_get_trait_help(trait, helptext=fhelp).splitlines()

                if not isinstance(alias, tuple):
                    alias = (alias,)  # type:ignore[assignment]
                alias = sorted(alias, key=len)  # type:ignore[assignment]
                alias = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in alias)

                # reformat first line
                fhelp[0] = fhelp[0].replace("--" + longname, alias)
                yield from fhelp
                yield indent("Equivalent to: [--%s]" % longname)
            except Exception as ex:
                self.log.error("Failed collecting help-message for alias %r, due to: %s", alias, ex)
                raise

    def print_flag_help(self):
        """Print the flag part of the help."""
        print("\n".join(self.emit_flag_help()))

    def emit_flag_help(self):
        """Yield the lines for the flag part of the help."""
        if not self.flags:
            return

        for flags, (cfg, fhelp) in self.flags.items():
            try:
                if not isinstance(flags, tuple):
                    flags = (flags,)  # type:ignore[assignment]
                flags = sorted(flags, key=len)  # type:ignore[assignment]
                flags = ", ".join(("--%s" if len(m) > 1 else "-%s") % m for m in flags)
                yield flags
                yield indent(dedent(fhelp.strip()))
                cfg_list = " ".join(
                    f"--{clname}.{prop}={val}"
                    for clname, props_dict in cfg.items()
                    for prop, val in props_dict.items()
                )
                cfg_txt = "Equivalent to: [%s]" % cfg_list
                yield indent(dedent(cfg_txt))
            except Exception as ex:
                self.log.error("Failed collecting help-message for flag %r, due to: %s", flags, ex)
                raise

    def print_options(self):
        """Print the options part of the help."""
        print("\n".join(self.emit_options_help()))

    def emit_options_help(self):
        """Yield the lines for the options part of the help."""
        if not self.flags and not self.aliases:
            return
        header = "Options"
        yield header
        yield "=" * len(header)
        for p in wrap_paragraphs(self.option_description):
            yield p
            yield ""

        yield from self.emit_flag_help()
        yield from self.emit_alias_help()
        yield ""

    def print_subcommands(self):
        """Print the subcommand part of the help."""
        print("\n".join(self.emit_subcommands_help()))

    def emit_subcommands_help(self):
        """Yield the lines for the subcommand part of the help."""
        if not self.subcommands:
            return

        header = "Subcommands"
        yield header
        yield "=" * len(header)
        for p in wrap_paragraphs(self.subcommand_description.format(app=self.name)):
            yield p
            yield ""
        for subc, (_, help) in self.subcommands.items():
            yield subc
            if help:
                yield indent(dedent(help.strip()))
        yield ""

    def emit_help_epilogue(self, classes):
        """Yield the very bottom lines of the help message.

        If classes=False (the default), print `--help-all` msg.
        """
        if not classes:
            yield "To see all available configurables, use `--help-all`."
            yield ""

    def print_help(self, classes=False):
        """Print the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        print("\n".join(self.emit_help(classes=classes)))

    def emit_help(self, classes=False):
        """Yield the help-lines for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        yield from self.emit_description()
        yield from self.emit_subcommands_help()
        yield from self.emit_options_help()

        if classes:
            help_classes = self._classes_with_config_traits()
            if help_classes:
                yield "Class options"
                yield "============="
                for p in wrap_paragraphs(self.keyvalue_description):
                    yield p
                    yield ""

            for cls in help_classes:
                yield cls.class_get_help()
                yield ""
        yield from self.emit_examples()

        yield from self.emit_help_epilogue(classes)

    def document_config_options(self):
        """Generate rST format documentation for the config options this application

        Returns a multiline string.
        """
        return "\n".join(c.class_config_rst_doc() for c in self._classes_inc_parents())

    def print_description(self):
        """Print the application description."""
        print("\n".join(self.emit_description()))

    def emit_description(self):
        """Yield lines with the application description."""
        for p in wrap_paragraphs(self.description or self.__doc__ or ""):
            yield p
            yield ""

    def print_examples(self):
        """Print usage and examples (see `emit_examples()`)."""
        print("\n".join(self.emit_examples()))

    def emit_examples(self):
        """Yield lines with the usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        """
        if self.examples:
            yield "Examples"
            yield "--------"
            yield ""
            yield indent(dedent(self.examples.strip()))
            yield ""

    def print_version(self):
        """Print the version string."""
        print(self.version)

    @catch_config_error
    def initialize_subcommand(self, subc, argv=None):
        """Initialize a subcommand with argv."""
        subapp, _ = self.subcommands.get(subc)

        if isinstance(subapp, str):
            subapp = import_item(subapp)

        # Cannot issubclass() on a non-type (SOhttp://stackoverflow.com/questions/8692430)
        if isinstance(subapp, type) and issubclass(subapp, Application):
            # Clear existing instances before...
            self.__class__.clear_instance()
            # instantiating subapp...
            self.subapp = subapp.instance(parent=self)
        elif callable(subapp):
            # or ask factory to create it...
            self.subapp = subapp(self)  # type:ignore[call-arg]
        else:
            raise AssertionError("Invalid mappings for subcommand '%s'!" % subc)

        # ... and finally initialize subapp.
        self.subapp.initialize(argv)

    def flatten_flags(self):
        """Flatten flags and aliases for loaders, so cl-args override as expected.

        This prevents issues such as an alias pointing to InteractiveShell,
        but a config file setting the same trait in TerminalInteraciveShell
        getting inappropriate priority over the command-line arg.
        Also, loaders expect ``(key: longname)`` and not ````key: (longname, help)`` items.

        Only aliases with exactly one descendent in the class list
        will be promoted.

        """
        # build a tree of classes in our list that inherit from a particular
        # it will be a dict by parent classname of classes in our list
        # that are descendents
        mro_tree = defaultdict(list)
        for cls in self.classes:
            clsname = cls.__name__
            for parent in cls.mro()[1:-3]:
                # exclude cls itself and Configurable,HasTraits,object
                mro_tree[parent.__name__].append(clsname)
        # flatten aliases, which have the form:
        # { 'alias' : 'Class.trait' }
        aliases: t.Dict[str, str] = {}
        for alias, longname in self.aliases.items():
            if isinstance(longname, tuple):
                longname, _ = longname
            cls, trait = longname.split(".", 1)  # type:ignore[assignment]
            children = mro_tree[cls]  # type:ignore[index]
            if len(children) == 1:
                # exactly one descendent, promote alias
                cls = children[0]  # type:ignore[assignment]
            if not isinstance(aliases, tuple):
                alias = (alias,)  # type:ignore[assignment]
            for al in alias:
                aliases[al] = ".".join([cls, trait])  # type:ignore[list-item]

        # flatten flags, which are of the form:
        # { 'key' : ({'Cls' : {'trait' : value}}, 'help')}
        flags = {}
        for key, (flagdict, help) in self.flags.items():
            newflag: t.Dict[t.Any, t.Any] = {}
            for cls, subdict in flagdict.items():
                children = mro_tree[cls]  # type:ignore[index]
                # exactly one descendent, promote flag section
                if len(children) == 1:
                    cls = children[0]  # type:ignore[assignment]

                if cls in newflag:
                    newflag[cls].update(subdict)
                else:
                    newflag[cls] = subdict

            if not isinstance(key, tuple):
                key = (key,)  # type:ignore[assignment]
            for k in key:
                flags[k] = (newflag, help)
        return flags, aliases

    def _create_loader(self, argv, aliases, flags, classes):
        return KVArgParseConfigLoader(argv, aliases, flags, classes=classes, log=self.log)

    @catch_config_error
    def parse_command_line(self, argv=None):
        """Parse the command line arguments."""
        assert not isinstance(argv, str)
        argv = sys.argv[1:] if argv is None else argv
        self.argv = [cast_unicode(arg) for arg in argv]

        if argv and argv[0] == "help":
            # turn `ipython help notebook` into `ipython notebook -h`
            argv = argv[1:] + ["-h"]

        if self.subcommands and len(argv) > 0:
            # we have subcommands, and one may have been specified
            subc, subargv = argv[0], argv[1:]
            if re.match(r"^\w(\-?\w)*$", subc) and subc in self.subcommands:
                # it's a subcommand, and *not* a flag or class parameter
                return self.initialize_subcommand(subc, subargv)

        # Arguments after a '--' argument are for the script IPython may be
        # about to run, not IPython iteslf. For arguments parsed here (help and
        # version), we want to only search the arguments up to the first
        # occurrence of '--', which we're calling interpreted_argv.
        try:
            interpreted_argv = argv[: argv.index("--")]
        except ValueError:
            interpreted_argv = argv

        if any(x in interpreted_argv for x in ("-h", "--help-all", "--help")):
            self.print_help("--help-all" in interpreted_argv)
            self.exit(0)

        if "--version" in interpreted_argv or "-V" in interpreted_argv:
            self.print_version()
            self.exit(0)

        # flatten flags&aliases, so cl-args get appropriate priority:
        flags, aliases = self.flatten_flags()
        classes = tuple(self._classes_with_config_traits())
        loader = self._create_loader(argv, aliases, flags, classes=classes)
        try:
            self.cli_config = deepcopy(loader.load_config())
        except SystemExit:
            # traitlets 5: no longer print help output on error
            # help output is huge, and comes after the error
            raise
        self.update_config(self.cli_config)
        # store unparsed args in extra_args
        self.extra_args = loader.extra_args

    @classmethod
    def _load_config_files(cls, basefilename, path=None, log=None, raise_config_file_errors=False):
        """Load config files (py,json) by filename and path.

        yield each config object in turn.
        """

        if not isinstance(path, list):
            path = [path]
        for path in path[::-1]:
            # path list is in descending priority order, so load files backwards:
            pyloader = cls.python_config_loader_class(basefilename + ".py", path=path, log=log)
            if log:
                log.debug("Looking for %s in %s", basefilename, path or os.getcwd())
            jsonloader = cls.json_config_loader_class(basefilename + ".json", path=path, log=log)
            loaded: t.List[t.Any] = []
            filenames: t.List[str] = []
            for loader in [pyloader, jsonloader]:
                config = None
                try:
                    config = loader.load_config()
                except ConfigFileNotFound:
                    pass
                except Exception:
                    # try to get the full filename, but it will be empty in the
                    # unlikely event that the error raised before filefind finished
                    filename = loader.full_filename or basefilename
                    # problem while running the file
                    if raise_config_file_errors:
                        raise
                    if log:
                        log.error("Exception while loading config file %s", filename, exc_info=True)
                else:
                    if log:
                        log.debug("Loaded config file: %s", loader.full_filename)
                if config:
                    for filename, earlier_config in zip(filenames, loaded):
                        collisions = earlier_config.collisions(config)
                        if collisions and log:
                            log.warning(
                                "Collisions detected in {0} and {1} config files."
                                " {1} has higher priority: {2}".format(
                                    filename,
                                    loader.full_filename,
                                    json.dumps(collisions, indent=2),
                                )
                            )
                    yield (config, loader.full_filename)
                    loaded.append(config)
                    filenames.append(loader.full_filename)

    @property
    def loaded_config_files(self):
        """Currently loaded configuration files"""
        return self._loaded_config_files[:]

    @catch_config_error
    def load_config_file(self, filename, path=None):
        """Load config files by filename and path."""
        filename, ext = os.path.splitext(filename)
        new_config = Config()
        for (config, filename) in self._load_config_files(
            filename,
            path=path,
            log=self.log,
            raise_config_file_errors=self.raise_config_file_errors,
        ):
            new_config.merge(config)
            if (
                filename not in self._loaded_config_files
            ):  # only add to list of loaded files if not previously loaded
                self._loaded_config_files.append(filename)
        # add self.cli_config to preserve CLI config priority
        new_config.merge(self.cli_config)
        self.update_config(new_config)

    def _classes_with_config_traits(self, classes=None):
        """
        Yields only classes with configurable traits, and their subclasses.

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Thus, produced sample config-file will contain all classes
        on which a trait-value may be overridden:

        - either on the class owning the trait,
        - or on its subclasses, even if those subclasses do not define
          any traits themselves.
        """
        if classes is None:
            classes = self.classes

        cls_to_config = OrderedDict(
            (cls, bool(cls.class_own_traits(config=True)))
            for cls in self._classes_inc_parents(classes)
        )

        def is_any_parent_included(cls):
            return any(b in cls_to_config and cls_to_config[b] for b in cls.__bases__)

        # Mark "empty" classes for inclusion if their parents own-traits,
        #  and loop until no more classes gets marked.
        #
        while True:
            to_incl_orig = cls_to_config.copy()
            cls_to_config = OrderedDict(
                (cls, inc_yes or is_any_parent_included(cls))
                for cls, inc_yes in cls_to_config.items()
            )
            if cls_to_config == to_incl_orig:
                break
        for cl, inc_yes in cls_to_config.items():
            if inc_yes:
                yield cl

    def generate_config_file(self, classes=None):
        """generate default config file from Configurables"""
        lines = ["# Configuration file for %s." % self.name]
        lines.append("")
        classes = self.classes if classes is None else classes
        config_classes = list(self._classes_with_config_traits(classes))
        for cls in config_classes:
            lines.append(cls.class_config_section(config_classes))
        return "\n".join(lines)

    def close_handlers(self):
        if getattr(self, "_logging_configured", False):
            # don't attempt to close handlers unless they have been opened
            # (note accessing self.log.handlers will create handlers if they
            # have not yet been initialised)
            for handler in self.log.handlers:
                with suppress(Exception):
                    handler.close()
            self._logging_configured = False

    def exit(self, exit_status=0):
        self.log.debug("Exiting application: %s" % self.name)
        self.close_handlers()
        sys.exit(exit_status)

    def __del__(self):
        self.close_handlers()

    @classmethod
    def launch_instance(cls, argv=None, **kwargs):
        """Launch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        """
        app = cls.instance(**kwargs)
        app.initialize(argv)
        app.start()
Example #15
0
 class MyConf2(Configurable):
     an_enum = Enum('Choice1 choice2'.split(),
                    allow_none=True,
                    default_value='choice2',
                    help="Many choices.").tag(config=True)
Example #16
0
class ComplexFloor(MultiAgentSimulation):

    agent_type = Enum(default_value=Circular, values=(Circular, ThreeCircle))
    body_type = Enum(default_value='adult', values=('adult', ))

    def attributes(self,
                   familiar,
                   has_target: bool = True,
                   is_follower: bool = True):
        def wrapper():
            target = familiar if has_target else NO_TARGET
            orientation = np.random.uniform(-np.pi, np.pi)
            d = dict(
                target=target,
                is_leader=not is_follower,
                is_follower=is_follower,
                body_type=self.body_type,
                orientation=orientation,
                velocity=np.zeros(2),
                angular_velocity=0.0,
                target_direction=np.zeros(2),
                target_orientation=orientation,
                familiar_exit=familiar,
            )
            return d

        return wrapper

    def attributes_leader(self,
                          target_iter,
                          has_target: bool = True,
                          is_follower: bool = False):
        def wrapper():
            target = next(target_iter)
            orientation = np.random.uniform(-np.pi, np.pi)
            d = dict(
                target=target,
                is_leader=not is_follower,
                is_follower=is_follower,
                body_type=self.body_type,
                orientation=orientation,
                velocity=np.zeros(2),
                angular_velocity=0.0,
                target_direction=np.zeros(2),
                target_orientation=orientation,
                familiar_exit=4,
            )
            return d

        return wrapper

    @default('logic')
    def _default_logic(self):
        return Reset(self) << \
               TargetReached(self) << (
                   Integrator(self) << (
                       #Fluctuation(self),
                       Adjusting(self) << (
                           Navigation(self) << LeaderFollower(self),
                           Orientation(self)),
                       AgentAgentInteractions(self),
                       AgentObstacleInteractions(self)))

    @default('field')
    def _default_field(self):
        return ComplexFloorField()

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)
        return agents
Example #17
0
class ComplexFloor(MultiAgentSimulation):
    # def __init__(self, kokeilu):
    #    self.kokeilu = kokeilu

    size_spawn_left = Int(
        default_value=50, min=0, max=200, help='')
    size_spawn_lower = Int(
        default_value=50, min=0, max=200, help='')
    size_spawn_right = Int(
        default_value=50, min=0, max=200, help='')
    size_spawn_upper = Int(
        default_value=50, min=0, max=200, help='')
    size_leader = Int(
        default_value=0, min=0, max=6, help='')

    agent_type = Enum(
        default_value=Circular,
        values=(Circular, ThreeCircle))
    body_type = Enum(
        default_value='adult',
        values=('adult',))

    # CHECK THE GUIDE GENERATOR FUNCTION
    # A helper function to create spawn points for leaders out of their cell coordinates.
    # The input is the array of leader spawn cells and the number of leaders in the simulation.
    # def generate_leader_pos(cell, n_lead, seed_number):
    def generate_leader_pos(self, cell, n_lead):

        # FIRST THE DATA HAS TO BE CREATED
        # Load data of followers
        followers = np.load('complex/spawn_complex.npy')
        follower_positions = followers['position']
        follower_radii = followers['radius']

        # Minimal radius of a guide (the same value given in agents.py to the guides).
        max_r = 0.27

        # Number of times spawned leaders are allowed to overlap each other before the program is
        # terminated.
        overlaps = 10000

        # Import Complex floor field
        field = ComplexFloor().field

        # Bound box representing the room.
        width = 90
        height = 90

        # Create a grid structure over the room geometry.
        # Cell size in the grid, determines the resolution of the micro-macro converted data
        cell_size = 2
        m = np.round(width / cell_size)
        n = np.round(height / cell_size)
        m = m.astype(int)
        n = n.astype(int)
        X = np.linspace(0, width, m + 1)
        Y = np.linspace(0, height, n + 1)
        hlines = [((x1, yi), (x2, yi)) for x1, x2 in zip(X[:-1], X[1:]) for yi in Y]
        vlines = [((xi, y1), (xi, y2)) for y1, y2 in zip(Y[:-1], Y[1:]) for xi in X]
        grids = list(polygonize(MultiLineString(hlines + vlines)))

        # Leaders' spawn areas
        leader_spawns = []

        # Leader's spawn points
        spawn_points = []

        # Loop through the cells and calculate intersections with spawn areas.
        for i in range(n_lead):

            poly = field.domain.intersection(grids[cell[i]])
            if not poly.is_empty:
                leader_spawns.append(poly)

        # Import obstacles
        obstacles = field.obstacles

        # Spawn a random position from the starting area.
        # Loop through all the leaders.
        # (1) Take into account that there might be obstacles in the spawn areas, and take also
        # into account that agents have a buffer radius.
        # (2) If the spawn area is a MultiPolygon, loop through the polygons in a MultiPolygon. Create a
        # mesh grid of the spawn area with Delaunay triangulation.
        # (2.1) Spawn a random point from the mesh grid.
        # (2.2) Check that the position doesn't interfere with other agents' positions
        # (2.3) Set the Boolean value for if the leader is initially inside the Finlandiahall
        # (this is needed for the movement simulation).
        # (3) If the spawn area is not a MultiPolygon, just directly create a mesh grid of the spawn area
        # with Delaunay triangulation.
        # (3.1) Spawn a random point from the mesh grid.
        # (3.2) Check that the position doesn't interfere with other agents' positions
        # (3.3) Set the Boolean value for if the leader is initially inside the Finlandiahall (this is
        # is needed for the movement simulation).
        for i in range(n_lead):
            seed = 0
            # (1)
            n_spawnpoints = len(spawn_points)
            geom = leader_spawns[i] - obstacles.buffer(max_r)
            j = 0  # set overlaps counter to zero
            # (2)
            if isinstance(geom, MultiPolygon):
                n_polygons = len(geom)
                for j in range(n_polygons):
                    vertices = np.asarray(geom[j].convex_hull.exterior)
                    delaunay = Delaunay(vertices)
                    mesh = vertices[delaunay.simplices]
                    if j == 0:
                        meshes = mesh
                    else:
                        meshes = np.concatenate((mesh, meshes), axis=0)
                # Computes cumulative sum of the areas of the triangle mesh.
                weights = triangle_area_cumsum(meshes)
                weights /= weights[-1]

                while j < overlaps:
                    seed += 1
                    distances = []  # temporarily store distances from the spawned point to the previously spawned
                    n_overlaps = 0  # for each attempt to position the guide, set number of overlaps to zero
                    # (2.1) Spawn a random point for the guide.
                    np.random.seed(seed)
                    x = np.random.random()
                    k = np.searchsorted(weights, x)
                    a, b, c = meshes[k]
                    spawn_point = random_sample_triangle(a, b, c)
                    # spawn_point = random_sample_triangle(a, b, c, seed)
                    # (2.2)
                    if n_spawnpoints != 0:  # if there are no other spawned guides skip this step
                        for k in range(0, n_spawnpoints):
                            d = length(spawn_point - spawn_points[k])
                            h = d - 2 * max_r
                            distances.append(h)
                        distances_array = distances
                        distances_array = np.asarray(distances_array)
                        n_overlaps += len(np.where(distances_array < 0)[0])
                    for obstacle in obstacles:
                        obstacle = list(obstacle.coords)
                        n_obstacle_points = len(obstacle)
                        for k in range(0, n_obstacle_points):
                            if k == n_obstacle_points - 1:
                                h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),
                                                            np.asarray(obstacle[0]))
                            else:
                                h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),
                                                            np.asarray(obstacle[k + 1]))
                            if h < 0.0:
                                n_overlaps += 1
                    for agent in range(len(follower_radii)):
                        h, _ = distance_circles(follower_positions[agent], follower_radii[agent], spawn_point, max_r)
                        if h < 0.0:
                            n_overlaps += 1

                    if n_overlaps == 0:
                        # (2.3)
                        # Append the point to spawn points
                        spawn_points.append([spawn_point[0], spawn_point[1]])
                        # print("Guide spawned")
                        # sys.stdout.flush()
                        break
                    j += 1
                    if j == overlaps:
                        raise Exception('Leaders do not fit in the cell')
                        # (3)
            else:
                vertices = np.asarray(geom.convex_hull.exterior)
                delaunay = Delaunay(vertices)
                mesh = vertices[delaunay.simplices]
                weights = triangle_area_cumsum(mesh)
                weights /= weights[-1]

                while j < overlaps:
                    seed += 1
                    distances = []  # temporarily store distances from the spawned point to the previously spawned
                    n_overlaps = 0  # for each attempt to position the guide, set number of overlaps to zero
                    # (3.1) Spawn a random point for the guide
                    np.random.seed(seed)
                    x = np.random.random()
                    k = np.searchsorted(weights, x)
                    a, b, c = mesh[k]
                    spawn_point = random_sample_triangle(a, b, c)
                    # spawn_point = random_sample_triangle(a, b, c, seed)
                    if n_spawnpoints != 0:
                        for k in range(0, n_spawnpoints):
                            d = length(spawn_point - spawn_points[k])
                            h = d - 2 * max_r
                            distances.append(h)
                        distances_array = distances
                        distances_array = np.asarray(distances_array)
                        n_overlaps += len(np.where(distances_array < 0)[0])
                    for obstacle in obstacles:
                        obstacle = list(obstacle.coords)
                        n_obstacle_points = len(obstacle)
                        for k in range(0, n_obstacle_points):
                            if k == n_obstacle_points - 1:
                                h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),
                                                            np.asarray(obstacle[0]))
                            else:
                                h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),
                                                            np.asarray(obstacle[k + 1]))
                            if h < 0.0:
                                n_overlaps += 1
                    for agent in range(len(follower_radii)):
                        h, _ = distance_circles(follower_positions[agent], follower_radii[agent], spawn_point, max_r)
                        if h < 0.0:
                            n_overlaps += 1

                    if n_overlaps == 0:
                        # (3.3)
                        # Append the point to spawn points
                        spawn_points.append([spawn_point[0], spawn_point[1]])
                        # print("Guide spawned")
                        # sys.stdout.flush()
                        break
                    j += 1
                    if j == overlaps:
                        raise Exception('Leaders do not fit in the cell')
        return spawn_points

    # CHECK ATTRIBUTES
    def attributes(self, familiar, has_target: bool = True, is_follower: bool = True):
        def wrapper():
            target = familiar if has_target else NO_TARGET
            orientation = np.random.uniform(-np.pi, np.pi)
            d = dict(
                target=target,
                is_leader=not is_follower,
                is_follower=is_follower,
                body_type=self.body_type,
                orientation=orientation,
                velocity=np.zeros(2),
                angular_velocity=0.0,
                target_direction=np.zeros(2),
                target_orientation=orientation,
                familiar_exit=familiar,
            )
            return d

        return wrapper

    def attributes_leader(self, target_iter, has_target: bool = True, is_follower: bool = False):
        def wrapper():
            target = next(target_iter)
            orientation = np.random.uniform(-np.pi, np.pi)
            d = dict(
                target=target,
                is_leader=not is_follower,
                is_follower=is_follower,
                body_type=self.body_type,
                orientation=orientation,
                velocity=np.zeros(2),
                angular_velocity=0.0,
                target_direction=np.zeros(2),
                target_orientation=orientation,
                familiar_exit=4,
            )
            return d

        return wrapper

    @default('logic')
    def _default_logic(self):
        return Reset(self) << \
               TargetReached(self) << (
                   Integrator(self) << (
                       #Fluctuation(self),
                       Adjusting(self) << (
                           Navigation(self) << LeaderFollower(self),
                           Orientation(self)),
                       AgentAgentInteractions(self),
                       AgentObstacleInteractions(self)))

    @default('field')
    def _default_field(self):
        return ComplexFloorField()

    @default('agents')
    def _default_agents(self):
        agents = Agents(agent_type=self.agent_type)

        # Generate iterators for group of leaders.
        #target_exits = [0,1,0]
        #cells = [913,695,652]
        target_exits = []
        cells = []
        n_guides = len(target_exits)

        speed_left = "fast"
        speed_lower = "fast"
        speed_right = "fast"
        speed_upper = "fast"

        # Exiting agents in left spawn
        group_follower_spawn_left = AgentGroup(
            agent_type=self.agent_type,
            size=getattr(self, 'size_spawn_left'),
            attributes=self.attributes(familiar=2, has_target=True, is_follower=True))

        agents.add_non_overlapping_group(
            speed_left,
            "spawn_left",
            group_follower_spawn_left,
            position_gen=False,
            position_iter=iter([]),
            spawn=0,
            obstacles=geom_to_linear_obstacles(self.field.obstacles))

        # Exiting agents in lower spawn
        group_follower_spawn_lower = AgentGroup(
            agent_type=self.agent_type,
            size=getattr(self, 'size_spawn_lower'),
            attributes=self.attributes(familiar=3, has_target=True, is_follower=True))

        agents.add_non_overlapping_group(
            speed_lower,
            "spawn_lower",
            group_follower_spawn_lower,
            position_gen=False,
            position_iter=iter([]),
            spawn=0,
            obstacles=geom_to_linear_obstacles(self.field.obstacles))

        # Exiting agents in right spawn
        group_follower_spawn_right = AgentGroup(
            agent_type=self.agent_type,
            size=getattr(self, 'size_spawn_right'),
            attributes=self.attributes(familiar=0, has_target=True, is_follower=True))

        agents.add_non_overlapping_group(
            speed_right,
            "spawn_right",
            group_follower_spawn_right,
            position_gen=False,
            position_iter=iter([]),
            spawn=2,
            obstacles=geom_to_linear_obstacles(self.field.obstacles))

        # Exiting agents in upper spawn
        group_follower_spawn_upper = AgentGroup(
            agent_type=self.agent_type,
            size=getattr(self, 'size_spawn_upper'),
            attributes=self.attributes(familiar=1, has_target=True, is_follower=True))

        agents.add_non_overlapping_group(
            speed_upper,
            "spawn_upper",
            group_follower_spawn_upper,
            position_gen=False,
            position_iter=iter([]),
            spawn=3,
            obstacles=geom_to_linear_obstacles(self.field.obstacles))

        if n_guides != 0:
            init_pos = self.generate_leader_pos(cells, n_guides)
            print(init_pos)
            # init_pos = [[8, 6]]
            target_exits = iter(target_exits)
            init_pos = iter(init_pos)

            # Guides in Variance Dilemma
            group_leader = AgentGroup(
                agent_type=self.agent_type,
                size=n_guides,
                attributes=self.attributes_leader(target_iter=target_exits, has_target=True, is_follower=False))

            agents.add_non_overlapping_group(
                "group_leader",
                group_leader,
                position_gen=True,
                position_iter=init_pos,
                spawn=0,
                obstacles=geom_to_linear_obstacles(self.field.obstacles))

        return agents