Пример #1
0
 def __init__(
     self,
     profiles: Dict[int, ConsumptionProfile] = None,
     negotiator_type=DEFAULT_NEGOTIATOR,
     consumption_horizon: Optional[int] = 20,
     immediate_cfp_update: bool = True,
     name=None,
 ):
     super().__init__(name=name)
     self.negotiator_type = get_class(negotiator_type, scope=globals())
     self.profiles: Dict[int, ConsumptionProfile] = defaultdict(
         ConsumptionProfile)
     self.secured_quantities: Dict[int, int] = defaultdict(int)
     if profiles is not None:
         self.set_profiles(profiles=profiles)
     self.consumption_horizon = consumption_horizon
     self.immediate_cfp_update = immediate_cfp_update
Пример #2
0
def builtin_agent_types(as_str=False):
    """
    Returns all built-in agents.

    Args:
        as_str: If true, the full type name will be returned otherwise the
                type object itself.
    """
    from negmas.helpers import get_class

    types = [
        f"scml.scml2019.agents.{_}" for _ in factory_managers.__all__
        if not _.startswith("Java")
    ]
    if as_str:
        return types
    return [get_class(_) for _ in types]
Пример #3
0
    def __init__(
        self,
        *args,
        negotiator_type: Union[SAONegotiator, str] = AspirationNegotiator,
        negotiator_params: Optional[Dict[str, Any]] = None,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)

        # save construction parameters
        self.negotiator_type = get_class(negotiator_type)
        self.negotiator_params = (negotiator_params
                                  if negotiator_params is not None else dict())

        # attributes that will be read during init() from the AWI
        # -------------------------------------------------------
        self.buyer = self.seller = None
Пример #4
0
 def __init__(
     self,
     default_negotiator_type: Union[str, Type[PassThroughNegotiator]] = None,
     default_negotiator_params: Dict[str, Any] = None,
     parent: Union["Controller", "Agent"] = None,
     auto_kill: bool = True,
     **kwargs,
 ):
     super().__init__(**kwargs)
     self._negotiators: Dict[str, NegotiatorInfo] = {}
     if default_negotiator_params is None:
         default_negotiator_params = {}
     if isinstance(default_negotiator_type, str):
         default_negotiator_type = get_class(default_negotiator_type)
     self.__default_negotiator_type = default_negotiator_type
     self.__default_negotiator_params = default_negotiator_params
     self.__parent = parent
     self._auto_kill = auto_kill
Пример #5
0
 def __init__(
     self,
     *args,
     negotiator_type: Union[SAONegotiator, str] = MyUtilityNegotiator,
     negotiator_params: Optional[Dict[str, Any]] = None,
     seller_model_path=NEG_SELL_PATH,
     buyer_model_path=NEG_BUY_PATH,
     **kwargs,
 ):
     super().__init__(*args, **kwargs)
     # TODO: copy into my sync controller!!!!!
     self.negotiator_type = get_class(negotiator_type)
     self.negotiator_params = (negotiator_params
                               if negotiator_params is not None else dict())
     self.neg_history = {True: {}, False: {}}
     self.seller_model = load_seller_neg_model(path=seller_model_path)
     self.buyer_model = load_buyer_neg_model(path=buyer_model_path)
     self.seller_model.eval()
     self.buyer_model.eval()
Пример #6
0
    def __init__(
        self,
        *args,
        negotiator_type: Union[SAONegotiator, str] = AspirationNegotiator,
        negotiator_params: Optional[Dict[str, Any]] = None,
        **kwargs,
    ):
        super().__init__(*args, execution_fraction=0.3, **kwargs)
        # super().__init__(*args, execution_fraction=0.5, **kwargs)
        # save construction parameters
        self.negotiator_type = get_class(negotiator_type)
        self.negotiator_params = (
            negotiator_params if negotiator_params is not None else dict()
        )

        # attributes that will be read during init() from the AWI
        # -------------------------------------------------------
        self.buyers = self.sellers = None
        """Buyer controllers and seller controllers. Each of them is responsible of covering the
Пример #7
0
 def __init__(
     self,
     *args,
     negotiator_type: Union[SAONegotiator, str] = AspirationNegotiator,
     negotiator_params: Optional[Dict[str, Any]] = None,
     horizon=5,
     predicted_demand: Union[int, np.ndarray] = None,
     predicted_supply: Union[int, np.ndarray] = None,
     agreement_fraction: float = 0.5,
     adapt_prices: bool = False,
     **kwargs,
 ):
     super().__init__(*args, **kwargs)
     self.adapt_prices = adapt_prices
     self.predicted_demand = predicted_demand
     self.predicted_supply = predicted_supply
     self.negotiator_type = get_class(negotiator_type)
     self.negotiator_params = (
         negotiator_params if negotiator_params is not None else dict()
     )
     self.horizon = horizon
     self.exogenous_horizon = None
     self.input_product: int = -1
     self.output_product: int = -1
     self.process: int = -1
     self.pcost: int = -1
     self.n_inputs: int = -1
     self.n_outputs: int = -1
     self.supplies_needed: np.ndarray = None
     self.sales_needed: np.ndarray = None
     self.input_cost: np.ndarray = None
     self.output_price: np.ndarray = None
     self.supplies_secured: np.ndarray = None
     self.sales_secured: np.ndarray = None
     self.production_needed = None
     self.production_secured = None
     self.production_factor = 1
     self.buyers = self.sellers = None
     self.catalog_n_equivalent = 0
     self.supplies_negotiating = None
     self.sales_negotiating = None
     self.agreement_fraction = agreement_fraction
     self.use_exogenous_contracts = True
Пример #8
0
 def __init__(
     self,
     default_negotiator_type: Union[str,
                                    Type[PassThroughNegotiator]] = None,
     default_negotiator_params: Dict[str, Any] = None,
     parent: Union["Controller", "Agent"] = None,
     auto_kill: bool = True,
     name: str = None,
     ufun: "UtilityFunction" = None,
 ):
     super().__init__(name=name, ufun=ufun)
     self._negotiators: Dict[str, Tuple["PassThroughNegotiator", Any]] = {}
     if default_negotiator_params is None:
         default_negotiator_params = {}
     if isinstance(default_negotiator_type, str):
         default_negotiator_type = get_class(default_negotiator_type)
     self.__default_negotiator_type = default_negotiator_type
     self.__default_negotiator_params = default_negotiator_params
     self.__parent = parent
     self._auto_kill = auto_kill
Пример #9
0
    def make_world(self, config=None) -> TrainWorld:
        # configuration, for Scenario scml
        if config is None:
            agent_types = [
                get_class(agent_type, ) for agent_type in TRAINING_AGENT_TYPES
            ]
            n_steps = N_STEPS
            world_configuration = SCML2020World.generate(
                agent_types=agent_types, n_steps=n_steps)
        else:
            world_configuration = SCML2020World.generate(
                agent_types=config['agent_types'],
                agent_params=config['agent_params'][:-2],
                n_steps=config['n_steps'])

        world = TrainWorld(configuration=world_configuration)

        if config is None:
            self.reset_world(world)

        return world
    def __init__(
        self,
        *args,
        data,
        plan,
        awi,
        agent,
        negotiator_type: Union[SAONegotiator, str] = AspirationNegotiator,
        negotiator_params: Optional[Dict[str, Any]] = None,
        **kwargs,
    ):
        self.data = data
        self.plan = plan
        self.awi = awi
        self.agent = agent

        self.negotiator_type = get_class(negotiator_type)
        self.negotiator_params = (
            negotiator_params if negotiator_params is not None else dict()
        )

        self._horizon = 5  # TODO: Decide this value
Пример #11
0
    def create_negotiator(
        self,
        negotiator_type: Union[str, Type[PassThroughNegotiator]] = None,
        name: str = None,
        cntxt: Any = None,
        **kwargs,
    ) -> PassThroughNegotiator:
        """
        Creates a negotiator passing it the context

        Args:
            negotiator_type: Type of the negotiator to be created
            name: negotiator name
            cntxt: The context to be associated with this negotiator. It will not be passed to the negotiator
            constructor.
            **kwargs: any key-value pairs to be passed to the negotiator constructor

        Returns:

            PassThroughNegotiator: The negotiator to be controlled

        """
        if negotiator_type is None:
            negotiator_type = self.__default_negotiator_type
        elif isinstance(negotiator_type, str):
            negotiator_type = get_class(negotiator_type)
        if negotiator_type is None:
            raise ValueError(
                "No negotiator type is passed and no default negotiator type is defined for this "
                "controller")
        args = self.__default_negotiator_params
        if kwargs:
            args.update(kwargs)
        new_negotiator = negotiator_type(name=name, parent=self, **args)
        if new_negotiator is not None:
            self._negotiators[new_negotiator.id] = (new_negotiator, cntxt)
        return new_negotiator
Пример #12
0
 def __init__(
     self,
     name=None,
     simulator_type: Union[str,
                           Type[FactorySimulator]] = FastFactorySimulator,
     scheduler_type: Union[str, Type[Scheduler]] = GreedyScheduler,
     scheduler_params: Optional[Dict[str, Any]] = None,
     optimism: float = 0.0,
     negotiator_type: Union[str, Type[Negotiator]] = DEFAULT_NEGOTIATOR,
     negotiator_params: Optional[Dict[str, Any]] = None,
     n_retrials=5,
     use_consumer=True,
     reactive=False,
     sign_only_guaranteed_contracts=True,
     riskiness=0.0,
     max_insurance_premium: float = 0.1,
     my_reports=[],
     not_fm=[],
     mean_score: float = 1000.0,
     bought={},
     sold={},
 ):
     self.my_reports = []
     self.not_fm = []
     self.mean_score: float = 1000.0
     self.bought = bought
     self.sold = sold
     super().__init__(name=name, simulator_type=simulator_type)
     self.negotiator_type = get_class(negotiator_type, scope=globals())
     self.negotiator_params = (negotiator_params
                               if negotiator_params is not None else {})
     self.optimism = optimism
     self.ufun_factory: Union[Type[NegotiatorUtility],
                              Callable[[Any, Any], NegotiatorUtility]]
     if optimism < 1e-6:
         self.ufun_factory = PessimisticNegotiatorUtility
     elif optimism > 1 - 1e-6:
         self.ufun_factory = OptimisticNegotiatorUtility
     else:
         self.ufun_factory: NegotiatorUtility = lambda agent, annotation: AveragingNegotiatorUtility(
             agent=agent, annotation=annotation, optimism=self.optimism)
     if max_insurance_premium < 0.0:
         warnings.warn(
             f"Negative max insurance ({max_insurance_premium}) is deprecated. Set max_insurance_premium = inf "
             f"for always buying and max_insurance_premium = 0.0 for never buying. Will continue assuming inf"
         )
         max_insurance_premium = float("inf")
     self.max_insurance_premium = max_insurance_premium
     self.n_retrials = n_retrials
     self.n_neg_trials: Dict[str, int] = defaultdict(int)
     self.consumer = None
     self.use_consumer = use_consumer
     self.reactive = reactive
     self.sign_only_guaranteed_contracts = sign_only_guaranteed_contracts
     self.contract_schedules: Dict[str, ScheduleInfo] = {}
     self.riskiness = riskiness
     self.negotiation_margin = int(
         round(n_retrials * max(0.0, 1.0 - riskiness)))
     self.scheduler_type: Type[Scheduler] = get_class(scheduler_type,
                                                      scope=globals())
     self.scheduler: Scheduler = None
     self.scheduler_params: Dict[
         str,
         Any] = scheduler_params if scheduler_params is not None else {}
Пример #13
0
def anac2019_world(competitors: Sequence[Union[str,
                                               Type[FactoryManager]]] = (),
                   randomize: bool = True,
                   log_file_name: str = None,
                   name: str = None,
                   agent_names_reveal_type: bool = False,
                   n_intermediate: Tuple[int, int] = (1, 4),
                   n_miners=5,
                   n_factories_per_level=11,
                   n_consumers=5,
                   n_lines_per_factory=10,
                   guaranteed_contracts=False,
                   use_consumer=True,
                   max_insurance_premium=100,
                   n_retrials=5,
                   negotiator_type: str = 'negmas.sao.AspirationNegotiator',
                   transportation_delay=0,
                   default_signing_delay=0,
                   max_storage=sys.maxsize,
                   consumption_horizon=15,
                   consumption=(3, 5),
                   negotiation_speed=21,
                   neg_time_limit=60 * 4,
                   neg_n_steps=20,
                   n_steps=100,
                   time_limit=60 * 90,
                   n_default_per_level: int = 5) -> SCMLWorld:
    """
    Creates a world compatible with the ANAC 2019 competition. Note that

    Args:
        name: World name to use
        agent_names_reveal_type: If true, a snake_case version of the agent_type will prefix agent names
        randomize: If true, managers are assigned to factories randomly otherwise in the order
        they are giving (cycling).
        n_intermediate:
        n_default_per_level:
        competitors: A list of class names for the competitors
        n_miners: number of miners of the single raw material
        n_factories_per_level: number of factories at every production level
        n_consumers: number of consumers of the final product
        n_steps: number of simulation steps
        n_lines_per_factory: number of lines in each factory
        negotiation_speed: The number of negotiation steps per simulation step. None means infinite
        default_signing_delay: The number of simulation between contract conclusion and signature
        neg_n_steps: The maximum number of steps of a single negotiation (that is double the number of rounds)
        neg_time_limit: The total time-limit of a single negotiation
        time_limit: The total time-limit of the simulation
        transportation_delay: The transportation delay
        n_retrials: The number of retrials the `Miner` and `GreedyFactoryManager` will try if negotiations fail
        max_insurance_premium: The maximum insurance premium accepted by `GreedyFactoryManager` (-1 to disable)
        use_consumer: If true, the `GreedyFactoryManager` will use an internal consumer for buying its needs
        guaranteed_contracts: If true, the `GreedyFactoryManager` will only sign contracts that it can guaratnee not to
        break.
        consumption_horizon: The number of steps for which `Consumer` publishes `CFP` s
        consumption: The consumption schedule will be sampled from a uniform distribution with these limits inclusive
        log_file_name: File name to store the logs
        negotiator_type: The negotiation factory used to create all negotiators
        max_storage: maximum storage capacity for all factory negmas If None then it is unlimited


    Returns:
        SCMLWorld ready to run

    Remarks:

        - Every production level n has one process only that takes n steps to complete


    """
    competitors = list(competitors)
    if n_factories_per_level == n_default_per_level and len(competitors) > 0:
        raise ValueError(
            f'All factories in all levels are occupied by the default factory manager. Either decrease'
            f' n_default_per_level ({n_default_per_level}) or increase n_factories_per_level '
            f' ({n_factories_per_level})')
    if isinstance(n_intermediate, Iterable):
        n_intermediate = list(n_intermediate)
    else:
        n_intermediate = [n_intermediate, n_intermediate]
    max_insurance_premium = None if max_insurance_premium < 0 else max_insurance_premium
    n_competitors = len(competitors)
    n_intermediate_levels_min = int(
        math.ceil(n_competitors /
                  (n_factories_per_level - n_default_per_level))) - 1
    if n_intermediate_levels_min > n_intermediate[1]:
        raise ValueError(
            f'Need {n_intermediate_levels_min} intermediate levels to run {n_competitors} competitors'
        )
    n_intermediate[0] = max(n_intermediate_levels_min, n_intermediate[0])
    competitors = [
        get_class(c) if isinstance(c, str) else c for c in competitors
    ]
    if len(competitors) < 1:
        competitors.append(GreedyFactoryManager)
    world = SCMLWorld.single_path_world(
        log_file_name=log_file_name,
        n_steps=n_steps,
        agent_names_reveal_type=agent_names_reveal_type,
        negotiation_speed=negotiation_speed,
        n_intermediate_levels=randint(*n_intermediate),
        n_miners=n_miners,
        n_consumers=n_consumers,
        n_factories_per_level=n_factories_per_level,
        consumption=consumption,
        consumer_kwargs={
            'negotiator_type': negotiator_type,
            'consumption_horizon': consumption_horizon
        },
        miner_kwargs={
            'negotiator_type': negotiator_type,
            'n_retrials': n_retrials
        },
        manager_kwargs={
            'negotiator_type': negotiator_type,
            'n_retrials': n_retrials,
            'sign_only_guaranteed_contracts': guaranteed_contracts,
            'use_consumer': use_consumer,
            'max_insurance_premium': max_insurance_premium
        },
        transportation_delay=transportation_delay,
        time_limit=time_limit,
        neg_time_limit=neg_time_limit,
        neg_n_steps=neg_n_steps,
        default_signing_delay=default_signing_delay,
        n_lines_per_factory=n_lines_per_factory,
        max_storage=max_storage,
        manager_types=competitors,
        n_default_per_level=n_default_per_level,
        randomize=randomize,
        name=name)

    return world