Пример #1
0
 def __init__(
     self,
     oneshot_type: Union[str, OneShotAgent],
     oneshot_params: Dict[str, Any],
     obj: Optional[OneShotAgent] = None,
     name=None,
     type_postfix="",
     ufun=None,
 ):
     if obj:
         self.oneshot_type = get_full_type_name(obj)
         # note that this may not be true and we cannot guarantee that
         # we can instantiate an agent of the same type
         self.oneshot_params = dict()
     else:
         if not oneshot_params:
             oneshot_params = dict()
         self.oneshot_type, self.oneshot_params = (
             get_full_type_name(oneshot_type),
             oneshot_params,
         )
         obj = instantiate(oneshot_type, **oneshot_params)
     super().__init__(obj=obj,
                      name=name,
                      type_postfix=type_postfix,
                      ufun=ufun)
     obj.connect_to_2021_adapter(self)
Пример #2
0
def register_visualizer(type_name: Union[str, Type[NamedObject]], visualizer_name: Union[str, Type[Visualizer]]):
    """
    Registers a visualizer type

    Args:
        type_name: The type for which the visualizer is registered
        visualizer_name: The visualizer type
    """
    VISUALIZERS[get_full_type_name(type_name)] = get_full_type_name(visualizer_name)
Пример #3
0
def visualizer_type(x: Union[str, Type[NamedObject], NamedObject]) -> Optional[Type[Visualizer]]:
    """Finds the type of the visualizer of a given type or object.

    Remarks:

        - If no visualizer is already registered through `register_visualizer` for this type of object, the system will
          try the following in order:
          1. Try to read a class member called "visualizer_type" from the given object/type
          2. Try to add "Visualizer" to the type name and return an object of that type
          3. Return a vase Visualizer object
    """
    if isinstance(x, NamedObject):
        x = x.__class__
    try:
        return get_class(x).visualizer_type()
    except (TypeError, AttributeError):
        pass
    type_name = get_full_type_name(x)
    v = VISUALIZERS.get(type_name, type_name + "Visualizer")
    try:
        return get_class(v)
    except TypeError:
        pass
    try:
        return get_class(v.split(".")[-1])
    except TypeError:
        pass
    return Visualizer
Пример #4
0
 def to_dict(self) -> Dict[str, Any]:
     return {
         "ufuns": [serialize(_) for _ in self.ufuns],
         "weights": self.weights,
         "id": self.id,
         "name": self.name,
         "reserved_value": self.reserved_value,
         PYTHON_CLASS_IDENTIFIER: get_full_type_name(type(self)),
     }
Пример #5
0
def test_builtin_agent_types():
    from negmas.helpers import get_full_type_name

    strs = scml.oneshot.builtin_agent_types(True)
    types = scml.oneshot.builtin_agent_types(False)
    assert len(strs) == len(types)
    assert len(strs) > 0
    assert all([
        get_full_type_name(a).split(".")[-1] == b.split(".")[-1]
        for a, b in zip(types, strs)
    ])
Пример #6
0
def visualizer_type_name(x: Union[str, Type[NamedObject], NamedObject]) -> Optional[Type[Visualizer]]:
    """Finds the type name of the visualizer of a given type or object.

    Remarks:

        - If no visualizer is already registered through `register_visualizer` for this type of object, the system will
          try the following in order:
          1. Try to read a class member called "visualizer_type" from the given object/type
          2. Try to add "Visualizer" to the type name and return an object of that type
          3. Return a vase Visualizer object
    """
    return get_full_type_name(visualizer_type(x))
Пример #7
0
def anac2020_assigner(
    config: List[Dict[str, Any]],
    max_n_worlds: int,
    n_agents_per_competitor: int = 1,
    fair: bool = True,
    competitors: Sequence[Type[Agent]] = (),
    params: Sequence[Dict[str, Any]] = (),
) -> List[List[Dict[str, Any]]]:
    config = config[0]
    competitors = list(
        get_full_type_name(_) if not isinstance(_, str) and _ is not None else _
        for _ in competitors
    )
    n_competitors = len(competitors)
    params = (
        list(params) if params is not None else [dict() for _ in range(n_competitors)]
    )

    try:
        n_permutations = n_competitors
    except ArithmeticError:
        n_permutations = None

    agent_types = config["agent_types"]
    is_default = [_ is not None for _ in agent_types]
    assignable_factories = [i for i, mtype in enumerate(agent_types) if mtype is None]
    shuffle(assignable_factories)
    assignable_factories = (
        np.asarray(assignable_factories)
        .reshape((n_competitors, n_agents_per_competitor))
        .tolist()
    )

    configs = []

    def _copy_config(perm_, c, indx):
        new_config = copy.deepcopy(c)
        new_config["world_params"]["name"] += f".{indx:05d}"
        new_config["is_default"] = is_default
        for (a, p_), assignable in zip(perm_, assignable_factories):
            for factory in assignable:
                new_config["agent_types"][factory] = a
                new_config["agent_params"][factory] = copy.deepcopy(p_)
        return [new_config]

    if n_permutations is not None and max_n_worlds is None:
        k = 0
        permutation = list(zip(competitors, params))
        assert len(permutation) == len(assignable_factories)
        shuffle(permutation)
        perm = permutation
        for __ in range(n_permutations):
            k += 1
            perm = copy.deepcopy(perm)
            perm = perm[-1:] + perm[:-1]
            configs.append(_copy_config(perm, config, k))
    elif max_n_worlds is None:
        raise ValueError(f"Did not give max_n_worlds and cannot find n_permutations.")
    else:
        permutation = list(zip(competitors, params))
        assert len(permutation) == len(assignable_factories)
        if fair:
            n_min = len(assignable_factories)
            n_rounds = int(max_n_worlds // n_min)
            if n_rounds < 1:
                raise ValueError(
                    f"Cannot guarantee fair assignment: n. competitors {len(assignable_factories)}, at least"
                    f" {n_min} runs are needed for fair assignment"
                )
            max_n_worlds = n_rounds * n_min
            k = 0
            for _ in range(n_rounds):
                shuffle(permutation)
                for __ in range(n_min):
                    k += 1
                    perm = copy.deepcopy(permutation)
                    perm = perm[-1:] + perm[:-1]
                    configs.append(_copy_config(perm, config, k))
        else:
            for k in range(max_n_worlds):
                perm = copy.deepcopy(permutation)
                shuffle(perm)
                configs.append(_copy_config(perm, config, k))

    return configs
Пример #8
0
def anac2020_config_generator(
    n_competitors: int,
    n_agents_per_competitor: int,
    agent_names_reveal_type: bool = False,
    non_competitors: Optional[Tuple[Union[str, SCML2020Agent]]] = None,
    non_competitor_params: Optional[Tuple[Dict[str, Any]]] = None,
    compact: bool = True,
    *,
    n_steps: Union[int, Tuple[int, int]] = (50, 100),
    n_processes: Tuple[int, int] = (2, 5),
    min_factories_per_level: int = 2,  # strictly guaranteed
    max_factories_per_level: int = 6,  # not strictly guaranteed
    n_lines: int = 10,
    **kwargs,
) -> List[Dict[str, Any]]:

    if non_competitors is None:
        non_competitors = tuple(DefaultAgent)
    if isinstance(n_processes, Iterable):
        n_processes = tuple(n_processes)
    else:
        n_processes = [n_processes, n_processes]

    n_steps = _intin(n_steps)

    n_processes = randint(*n_processes)
    n_agents = n_agents_per_competitor * n_competitors
    n_default_managers = (
        min(
            n_processes * max_factories_per_level,
            max(0, n_processes * min_factories_per_level),
        )
        - n_agents
    )
    n_defaults = integer_cut(n_default_managers, n_processes, 0)

    n_a_list = integer_cut(n_agents, n_processes, 0)
    for i, n_a in enumerate(n_a_list):
        if n_a + n_defaults[i] < min_factories_per_level:
            n_defaults[i] = min_factories_per_level - n_a
        if n_a + n_defaults[i] > max_factories_per_level and n_defaults[i] > 1:
            n_defaults[i] = max(1, min_factories_per_level - n_a)
    n_f_list = [a + b for a, b in zip(n_defaults, n_a_list)]
    n_factories = sum(n_f_list)

    if non_competitor_params is None:
        non_competitor_params = [{}] * len(non_competitors)

    non_competitors = [get_full_type_name(_) for _ in non_competitors]

    max_def_agents = len(non_competitors) - 1
    agent_types = [None] * n_factories
    manager_params = [None] * n_factories
    first_in_level = 0
    for level in range(n_processes):
        n_d = n_defaults[level]
        n_f = n_f_list[level]
        assert (
            n_d <= n_f
        ), f"Got {n_f} total factories at level {level} out of which {n_d} are default!!"
        for j in range(n_f):
            if j >= n_f - n_d:  # default managers are last managers in the list
                def_indx = randint(0, max_def_agents)
                agent_types[first_in_level + j] = non_competitors[def_indx]
                params_ = copy.deepcopy(non_competitor_params[def_indx])
                if agent_names_reveal_type:
                    params_["name"] = f"_df_{level}_{j}"
                else:
                    params_[
                        "name"
                    ] = (
                        f"_df_{level}_{j}"
                    )  # because I use name to know that this is a default agent in evaluate.
                    # @todo do not use name to identify default agents in evaluation
                manager_params[first_in_level + j] = params_
        first_in_level += n_f

    world_name = unique_name("", add_time=True, rand_digits=4)
    agent_types = [
        get_full_type_name(_) if isinstance(_, SCML2020Agent) else _
        for _ in agent_types
    ]
    world_params = dict(
        name=world_name,
        agent_types=agent_types,
        time_limit=7200 + 3600,
        neg_time_limit=120,
        neg_n_steps=20,
        neg_step_time_limit=10,
        negotiation_speed=21,
        breach_penalty=0.2,
        interest_rate=0.08,
        bankruptcy_limit=1.0,
        initial_balance=None,
        start_negotiations_immediately=False,
        n_agents_per_process=n_f_list,
        n_processes=n_processes,
        n_steps=n_steps,
        n_lines=n_lines,
        compact=compact,
    )
    world_params.update(kwargs)
    config = {
        "world_params": world_params,
        "compact": compact,
        "scoring_context": {},
        "non_competitors": non_competitors,
        "non_competitor_params": non_competitor_params,
        "agent_types": agent_types,
        "agent_params": manager_params,
    }
    config.update(kwargs)
    return [config]
Пример #9
0
def get_agents(
    version: Union[str, int],
    *,
    track: str = "any",
    qualified_only: bool = False,
    finalists_only: bool = False,
    winners_only: bool = False,
    top_only: Optional[Union[int, float]] = None,
    as_class: bool = True,
) -> Tuple[Union[Agent, str]]:
    """
    Gets agent classes/full class names for a version which can either be a competition year (int) or "contrib".

    Args:
        version: Either a competition year (2019, 2020) or the value "contrib" for all other agents
        track: The track (any, collusion, std, sabotage[only for 2019]).
        finalists_only: If true, only agents that were submitted to SCML and passed qualifications will be 
                        returned
        winners_only: If true, only winners of SCML (the given version) will be returned.
        top_only: Either a fraction of finalists or the top n finalists with highest scores in the finals of 
                  SCML
        as_class: If true, the agent classes will be returned otherwise their full class names.
    """
    track = track.lower()
    if isinstance(version, int) and version == 2019:
        if track in ("any", "all") and not winners_only:
            classes = (
                scml2019.FJ2FactoryManager,
                scml2019.RaptFactoryManager,
                scml2019.InsuranceFraudFactoryManager,
                scml2019.SAHAFactoryManager,
                scml2019.CheapBuyerFactoryManager,
                scml2019.NVMFactoryManager,
                scml2019.Monopoly,
                scml2019.PenaltySabotageFactoryManager,
            )
        if track in ("std", "standard", "collusion") and not winners_only:
            classes = (
                scml2019.FJ2FactoryManager,
                scml2019.RaptFactoryManager,
                scml2019.InsuranceFraudFactoryManager,
                scml2019.SAHAFactoryManager,
                scml2019.CheapBuyerFactoryManager,
                scml2019.NVMFactoryManager,
            )
        if track == "sabotage" and not winners_only:
            # track is sabotage. Monopoly and PSFM (to be added)
            classes = (
                scml2019.Monopoly,
                scml2019.PenaltySabotageFactoryManager,
            )
        elif track in ("std", "standard") and winners_only:
            classes = (
                scml2019.InsuranceFraudFactoryManager,
                scml2019.NVMFactoryManager,
                scml2019.SAHAFactoryManager,
            )
        elif track in ("any", "all") and winners_only:
            classes = (
                scml2019.InsuranceFraudFactoryManager,
                scml2019.NVMFactoryManager,
                scml2019.SAHAFactoryManager,
                scml2019.FJ2FactoryManager,
            )
        elif track in ("coll", "collusion") and winners_only:
            classes = (
                scml2019.InsuranceFraudFactoryManager,
                scml2019.NVMFactoryManager,
                scml2019.FJ2FactoryManager,
            )
        elif track in ("sabotage", ) and winners_only:
            classes = tuple()
    elif isinstance(version, int) and version == 2020:
        if track in ("std", "standard") and finalists_only:
            classes = tuple(
                sum(
                    [[f"{_.__name__}.{a}" for a in _.__all__] for _ in (
                        scml2020.team_may,
                        scml2020.team_22,
                        scml2020.team_25,
                        scml2020.team_15,
                        scml2020.a_sengupta,
                        scml2020.monty_hall,
                        scml2020.team_17,
                        scml2020.team_10,
                        scml2020.threadfield,
                        scml2020.team_20,
                        scml2020.biu_th,
                        scml2020.team_32,
                    )],
                    [],
                ))
        elif track in ("coll", "collusion") and finalists_only:
            classes = tuple(
                sum(
                    [[f"{_.__name__}.{a}" for a in _.__all__] for _ in (
                        scml2020.team_17,
                        scml2020.team_may,
                        scml2020.team_25,
                        scml2020.team_15,
                        scml2020.a_sengupta,
                        scml2020.team_20,
                    )],
                    [],
                ))
        elif (track in ("any", "all", "std", "standard", "collusion")
              and not winners_only):
            classes = tuple(
                sum(
                    [[f"{_.__name__}.{a}" for a in _.__all__] for _ in (
                        scml2020.team_may,
                        scml2020.team_22,
                        scml2020.team_25,
                        scml2020.team_15,
                        scml2020.bargent,
                        scml2020.agent0x111,
                        scml2020.a_sengupta,
                        scml2020.past_frauds,
                        scml2020.monty_hall,
                        scml2020.team_19,
                        scml2020.team_17,
                        scml2020.team_10,
                        scml2020.threadfield,
                        scml2020.team_29,
                        scml2020.team_20,
                        scml2020.team_27,
                        scml2020.team_18,
                        scml2020.biu_th,
                        scml2020.team_32,
                    )],
                    [],
                ))
        elif track in ("std", "standard") and winners_only:
            classes = tuple(
                sum(
                    [[f"{_.__name__}.{a}" for a in _.__all__] for _ in (
                        scml2020.team_15,
                        scml2020.team_25,
                    )],
                    [],
                ))
        elif track in ("any", "all") and winners_only:
            classes = tuple(
                sum(
                    [[f"{_.__name__}.{a}" for a in _.__all__] for _ in (
                        scml2020.team_15,
                        scml2020.team_may,
                        scml2020.team_25,
                        scml2020.a_sengupta,
                    )],
                    [],
                ))
        elif track in ("coll", "collusion") and winners_only:
            classes = tuple(
                sum(
                    [[f"{_.__name__}.{a}" for a in _.__all__] for _ in (
                        scml2020.team_may,
                        scml2020.a_sengupta,
                    )],
                    [],
                ))
    elif isinstance(version, str) and version == "contrib":
        classes = tuple()
    else:
        raise ValueError(
            f"The version {version} is unknown. Valid versions are 2019, 2020 (as ints), 'contrib' as a string"
        )
    if not as_class:
        return tuple(get_full_type_name(_) for _ in classes)
    return classes