hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a932bf8eb6cc85234614310bfca9eee4b755a0f5 | SoonminHwang/pytorch-ssd | vision/utils/box_utils.py | [
"MIT"
] | Python | assign_priors | <not_specific> | def assign_priors(gt_boxes, gt_labels, corner_form_priors,
iou_threshold):
"""Assign ground truth boxes and targets to priors.
Args:
gt_boxes (num_targets, 4): ground truth boxes.
gt_labels (num_targets): labels of targets.
priors (num_priors, 4): corner form priors
... | Assign ground truth boxes and targets to priors.
Args:
gt_boxes (num_targets, 4): ground truth boxes.
gt_labels (num_targets): labels of targets.
priors (num_priors, 4): corner form priors
Returns:
boxes (num_priors, 4): real values for priors.
labels (num_priros): label... | Assign ground truth boxes and targets to priors. | [
"Assign",
"ground",
"truth",
"boxes",
"and",
"targets",
"to",
"priors",
"."
] | def assign_priors(gt_boxes, gt_labels, corner_form_priors,
iou_threshold):
if gt_boxes.shape[0] == 0:
boxes = torch.zeros_like(corner_form_priors)
labels = torch.zeros( corner_form_priors.shape[0], dtype=gt_labels.dtype )
return boxes, labels
ious = iou_of(gt_boxes.unsq... | [
"def",
"assign_priors",
"(",
"gt_boxes",
",",
"gt_labels",
",",
"corner_form_priors",
",",
"iou_threshold",
")",
":",
"if",
"gt_boxes",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"boxes",
"=",
"torch",
".",
"zeros_like",
"(",
"corner_form_priors",
")",
"... | Assign ground truth boxes and targets to priors. | [
"Assign",
"ground",
"truth",
"boxes",
"and",
"targets",
"to",
"priors",
"."
] | [
"\"\"\"Assign ground truth boxes and targets to priors.\n\n Args:\n gt_boxes (num_targets, 4): ground truth boxes.\n gt_labels (num_targets): labels of targets.\n priors (num_priors, 4): corner form priors\n Returns:\n boxes (num_priors, 4): real values for priors.\n labels ... | [
{
"param": "gt_boxes",
"type": null
},
{
"param": "gt_labels",
"type": null
},
{
"param": "corner_form_priors",
"type": null
},
{
"param": "iou_threshold",
"type": null
}
] | {
"returns": [
{
"docstring": "boxes (num_priors, 4): real values for priors.\nlabels (num_priros): labels for priors.",
"docstring_tokens": [
"boxes",
"(",
"num_priors",
"4",
")",
":",
"real",
"values",
"for",
"priors",
... |
a932bf8eb6cc85234614310bfca9eee4b755a0f5 | SoonminHwang/pytorch-ssd | vision/utils/box_utils.py | [
"MIT"
] | Python | hard_negative_mining | <not_specific> | def hard_negative_mining(loss, labels, neg_pos_ratio):
"""
It used to suppress the presence of a large number of negative prediction.
It works on image level not batch level.
For any example/image, it keeps all the positive predictions and
cut the number of negative predictions to make sure the rat... |
It used to suppress the presence of a large number of negative prediction.
It works on image level not batch level.
For any example/image, it keeps all the positive predictions and
cut the number of negative predictions to make sure the ratio
between the negative examples and positive examples is... | It used to suppress the presence of a large number of negative prediction.
It works on image level not batch level.
For any example/image, it keeps all the positive predictions and
cut the number of negative predictions to make sure the ratio
between the negative examples and positive examples is no more
the given rati... | [
"It",
"used",
"to",
"suppress",
"the",
"presence",
"of",
"a",
"large",
"number",
"of",
"negative",
"prediction",
".",
"It",
"works",
"on",
"image",
"level",
"not",
"batch",
"level",
".",
"For",
"any",
"example",
"/",
"image",
"it",
"keeps",
"all",
"the",... | def hard_negative_mining(loss, labels, neg_pos_ratio):
pos_mask = labels > 0
ign_mask = labels == -100
num_pos = pos_mask.long().sum(dim=1, keepdim=True)
num_neg = torch.clamp( num_pos * neg_pos_ratio, min=labels.size(0)*10 )
loss[pos_mask] = -math.inf
loss[ign_mask] = -math.inf
_, inde... | [
"def",
"hard_negative_mining",
"(",
"loss",
",",
"labels",
",",
"neg_pos_ratio",
")",
":",
"pos_mask",
"=",
"labels",
">",
"0",
"ign_mask",
"=",
"labels",
"==",
"-",
"100",
"num_pos",
"=",
"pos_mask",
".",
"long",
"(",
")",
".",
"sum",
"(",
"dim",
"=",... | It used to suppress the presence of a large number of negative prediction. | [
"It",
"used",
"to",
"suppress",
"the",
"presence",
"of",
"a",
"large",
"number",
"of",
"negative",
"prediction",
"."
] | [
"\"\"\"\n It used to suppress the presence of a large number of negative prediction.\n It works on image level not batch level.\n For any example/image, it keeps all the positive predictions and\n cut the number of negative predictions to make sure the ratio\n between the negative examples and posi... | [
{
"param": "loss",
"type": null
},
{
"param": "labels",
"type": null
},
{
"param": "neg_pos_ratio",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "loss",
"type": null,
"docstring": "the loss for each example.",
"docstring_tokens": [
"the",
"loss",
"for",
"each",
"example",
"."
],
"default": null,
"is_optio... |
b11295be394a9cb884b4bb642ee694df65da056a | winnerineast/pai | src/watchdog/src/watchdog.py | [
"MIT"
] | Python | parse_pod_item | <not_specific> | def parse_pod_item(pod, pai_pod_gauge, pai_container_gauge, pai_job_pod_gauge, pods_info):
""" add metrics to pai_pod_gauge or pai_container_gauge if successfully parse pod.
Because we are parsing json outputed by k8s, its format is subjected to change,
we should test if field exists before accessing it to ... | add metrics to pai_pod_gauge or pai_container_gauge if successfully parse pod.
Because we are parsing json outputed by k8s, its format is subjected to change,
we should test if field exists before accessing it to avoid KeyError | add metrics to pai_pod_gauge or pai_container_gauge if successfully parse pod.
Because we are parsing json outputed by k8s, its format is subjected to change,
we should test if field exists before accessing it to avoid KeyError | [
"add",
"metrics",
"to",
"pai_pod_gauge",
"or",
"pai_container_gauge",
"if",
"successfully",
"parse",
"pod",
".",
"Because",
"we",
"are",
"parsing",
"json",
"outputed",
"by",
"k8s",
"its",
"format",
"is",
"subjected",
"to",
"change",
"we",
"should",
"test",
"if... | def parse_pod_item(pod, pai_pod_gauge, pai_container_gauge, pai_job_pod_gauge, pods_info):
pod_name = pod["metadata"]["name"]
namespace = walk_json_field_safe(pod, "metadata", "namespace") or "default"
host_ip = walk_json_field_safe(pod, "status", "hostIP") or "unscheduled"
status = pod["status"]
co... | [
"def",
"parse_pod_item",
"(",
"pod",
",",
"pai_pod_gauge",
",",
"pai_container_gauge",
",",
"pai_job_pod_gauge",
",",
"pods_info",
")",
":",
"pod_name",
"=",
"pod",
"[",
"\"metadata\"",
"]",
"[",
"\"name\"",
"]",
"namespace",
"=",
"walk_json_field_safe",
"(",
"p... | add metrics to pai_pod_gauge or pai_container_gauge if successfully parse pod. | [
"add",
"metrics",
"to",
"pai_pod_gauge",
"or",
"pai_container_gauge",
"if",
"successfully",
"parse",
"pod",
"."
] | [
"\"\"\" add metrics to pai_pod_gauge or pai_container_gauge if successfully parse pod.\n Because we are parsing json outputed by k8s, its format is subjected to change,\n we should test if field exists before accessing it to avoid KeyError \"\"\"",
"# generate pai_containers"
] | [
{
"param": "pod",
"type": null
},
{
"param": "pai_pod_gauge",
"type": null
},
{
"param": "pai_container_gauge",
"type": null
},
{
"param": "pai_job_pod_gauge",
"type": null
},
{
"param": "pods_info",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pod",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pai_pod_gauge",
"type": null,
"docstring": null,
"docstring_to... |
b11295be394a9cb884b4bb642ee694df65da056a | winnerineast/pai | src/watchdog/src/watchdog.py | [
"MIT"
] | Python | try_remove_old_prom_file | null | def try_remove_old_prom_file(path):
""" try to remove old prom file, since old prom file are exposed by node-exporter,
if we do not remove, node-exporter will still expose old metrics """
if os.path.isfile(path):
try:
os.unlink(path)
except Exception as e:
logger.warn... | try to remove old prom file, since old prom file are exposed by node-exporter,
if we do not remove, node-exporter will still expose old metrics | try to remove old prom file, since old prom file are exposed by node-exporter,
if we do not remove, node-exporter will still expose old metrics | [
"try",
"to",
"remove",
"old",
"prom",
"file",
"since",
"old",
"prom",
"file",
"are",
"exposed",
"by",
"node",
"-",
"exporter",
"if",
"we",
"do",
"not",
"remove",
"node",
"-",
"exporter",
"will",
"still",
"expose",
"old",
"metrics"
] | def try_remove_old_prom_file(path):
if os.path.isfile(path):
try:
os.unlink(path)
except Exception as e:
logger.warning("can not remove old prom file %s", path) | [
"def",
"try_remove_old_prom_file",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"path",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"\"can n... | try to remove old prom file, since old prom file are exposed by node-exporter,
if we do not remove, node-exporter will still expose old metrics | [
"try",
"to",
"remove",
"old",
"prom",
"file",
"since",
"old",
"prom",
"file",
"are",
"exposed",
"by",
"node",
"-",
"exporter",
"if",
"we",
"do",
"not",
"remove",
"node",
"-",
"exporter",
"will",
"still",
"expose",
"old",
"metrics"
] | [
"\"\"\" try to remove old prom file, since old prom file are exposed by node-exporter,\n if we do not remove, node-exporter will still expose old metrics \"\"\""
] | [
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
56712c9d76bcf7f47faae7957030915e4d68ba49 | TomaszOdrzygozdz/gym-splendor | agents/multi_process_mcts_agent.py | [
"MIT"
] | Python | finish_game | null | def finish_game(self):
'''When game is finished we need to clear out tree.'''
if self.main_process:
self.mcts_started = False
self.actions_taken_so_far = 0
self.previous_root_state = None
self.previous_game_state = None
self.actions_taken_so_fa... | When game is finished we need to clear out tree. | When game is finished we need to clear out tree. | [
"When",
"game",
"is",
"finished",
"we",
"need",
"to",
"clear",
"out",
"tree",
"."
] | def finish_game(self):
if self.main_process:
self.mcts_started = False
self.actions_taken_so_far = 0
self.previous_root_state = None
self.previous_game_state = None
self.actions_taken_so_far = 0 | [
"def",
"finish_game",
"(",
"self",
")",
":",
"if",
"self",
".",
"main_process",
":",
"self",
".",
"mcts_started",
"=",
"False",
"self",
".",
"actions_taken_so_far",
"=",
"0",
"self",
".",
"previous_root_state",
"=",
"None",
"self",
".",
"previous_game_state",
... | When game is finished we need to clear out tree. | [
"When",
"game",
"is",
"finished",
"we",
"need",
"to",
"clear",
"out",
"tree",
"."
] | [
"'''When game is finished we need to clear out tree.'''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2522584a19c18b7c171881960b79e4833800764b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/envs.py | [
"MIT"
] | Python | clone_state | <not_specific> | def clone_state(self):
"""Returns the current environment state."""
assert self._elapsed_steps is not None, (
'Environment must be reset before the first clone_state().'
)
return TimeLimitWrapperState(
super().clone_state(), self._elapsed_steps) | Returns the current environment state. | Returns the current environment state. | [
"Returns",
"the",
"current",
"environment",
"state",
"."
] | def clone_state(self):
assert self._elapsed_steps is not None, (
'Environment must be reset before the first clone_state().'
)
return TimeLimitWrapperState(
super().clone_state(), self._elapsed_steps) | [
"def",
"clone_state",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_elapsed_steps",
"is",
"not",
"None",
",",
"(",
"'Environment must be reset before the first clone_state().'",
")",
"return",
"TimeLimitWrapperState",
"(",
"super",
"(",
")",
".",
"clone_state",
"(... | Returns the current environment state. | [
"Returns",
"the",
"current",
"environment",
"state",
"."
] | [
"\"\"\"Returns the current environment state.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2522584a19c18b7c171881960b79e4833800764b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/envs.py | [
"MIT"
] | Python | restore_state | <not_specific> | def restore_state(self, state):
"""Restores environment state, returns the observation."""
try:
self._elapsed_steps = state.elapsed_steps
state = state.super_state
except AttributeError:
self._elapsed_steps = 0
return super().restore_state(state) | Restores environment state, returns the observation. | Restores environment state, returns the observation. | [
"Restores",
"environment",
"state",
"returns",
"the",
"observation",
"."
] | def restore_state(self, state):
try:
self._elapsed_steps = state.elapsed_steps
state = state.super_state
except AttributeError:
self._elapsed_steps = 0
return super().restore_state(state) | [
"def",
"restore_state",
"(",
"self",
",",
"state",
")",
":",
"try",
":",
"self",
".",
"_elapsed_steps",
"=",
"state",
".",
"elapsed_steps",
"state",
"=",
"state",
".",
"super_state",
"except",
"AttributeError",
":",
"self",
".",
"_elapsed_steps",
"=",
"0",
... | Restores environment state, returns the observation. | [
"Restores",
"environment",
"state",
"returns",
"the",
"observation",
"."
] | [
"\"\"\"Restores environment state, returns the observation.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "state",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state",
"type": null,
"docstring": null,
"docstring_tokens": ... |
4056182204300f50de41b5906e7bd9bef82467ec | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/action_space_generator_classic.py | [
"MIT"
] | Python | generate_all_legal_trades_classic | List[ActionTradeGems] | def generate_all_legal_trades_classic(state: State) -> List[ActionTradeGems]:
"""Returns the list of all possible actions of trade in a given current_state"""
list_of_actions_trade = []
n_non_empty_stacks = len(state.board.gems_on_board.non_empty_stacks_except_gold())
n_gems_to_get_netto = min(MAX_GEMS_... | Returns the list of all possible actions of trade in a given current_state | Returns the list of all possible actions of trade in a given current_state | [
"Returns",
"the",
"list",
"of",
"all",
"possible",
"actions",
"of",
"trade",
"in",
"a",
"given",
"current_state"
] | def generate_all_legal_trades_classic(state: State) -> List[ActionTradeGems]:
list_of_actions_trade = []
n_non_empty_stacks = len(state.board.gems_on_board.non_empty_stacks_except_gold())
n_gems_to_get_netto = min(MAX_GEMS_ON_HAND - state.active_players_hand().gems_possessed.sum(),
... | [
"def",
"generate_all_legal_trades_classic",
"(",
"state",
":",
"State",
")",
"->",
"List",
"[",
"ActionTradeGems",
"]",
":",
"list_of_actions_trade",
"=",
"[",
"]",
"n_non_empty_stacks",
"=",
"len",
"(",
"state",
".",
"board",
".",
"gems_on_board",
".",
"non_emp... | Returns the list of all possible actions of trade in a given current_state | [
"Returns",
"the",
"list",
"of",
"all",
"possible",
"actions",
"of",
"trade",
"in",
"a",
"given",
"current_state"
] | [
"\"\"\"Returns the list of all possible actions of trade in a given current_state\"\"\"",
"# choose gems to get:",
"# now we have chosen which gems to take, so we need to decide which to return",
"# find gems collection to take:",
"# find possible options of returning gems:",
"# now we create gem collecti... | [
{
"param": "state",
"type": "State"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "state",
"type": "State",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
4056182204300f50de41b5906e7bd9bef82467ec | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/action_space_generator_classic.py | [
"MIT"
] | Python | generate_all_legal_buys_classic | List[ActionBuyCard] | def generate_all_legal_buys_classic(state: State) -> List[ActionBuyCard]:
"""Returns the list of all possible actions of buys in a given current_state"""
list_of_actions_buy = []
discount = state.active_players_hand().discount()
all_cards_can_afford = [card for card in state.board.cards_on_board if
... | Returns the list of all possible actions of buys in a given current_state | Returns the list of all possible actions of buys in a given current_state | [
"Returns",
"the",
"list",
"of",
"all",
"possible",
"actions",
"of",
"buys",
"in",
"a",
"given",
"current_state"
] | def generate_all_legal_buys_classic(state: State) -> List[ActionBuyCard]:
list_of_actions_buy = []
discount = state.active_players_hand().discount()
all_cards_can_afford = [card for card in state.board.cards_on_board if
state.active_players_hand().can_afford_card(card, discount)]... | [
"def",
"generate_all_legal_buys_classic",
"(",
"state",
":",
"State",
")",
"->",
"List",
"[",
"ActionBuyCard",
"]",
":",
"list_of_actions_buy",
"=",
"[",
"]",
"discount",
"=",
"state",
".",
"active_players_hand",
"(",
")",
".",
"discount",
"(",
")",
"all_cards... | Returns the list of all possible actions of buys in a given current_state | [
"Returns",
"the",
"list",
"of",
"all",
"possible",
"actions",
"of",
"buys",
"in",
"a",
"given",
"current_state"
] | [
"\"\"\"Returns the list of all possible actions of buys in a given current_state\"\"\"",
"# we choose combination of other gems:",
"# check if the option satisfies conditions:"
] | [
{
"param": "state",
"type": "State"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "state",
"type": "State",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
8c1b3bac8c6e1ab97d1db6035d117939c317bfa6 | TomaszOdrzygozdz/gym-splendor | archive/dense_models/value_dense_model_v0.py | [
"MIT"
] | Python | create_network | None | def create_network(self, input_size : int = 498, layers_list : List[int] = [800, 800, 800, 800]) -> None:
'''
This method creates network with a specific architecture
:return:
'''
self.set_corrent_session()
entries = Input(shape=(input_size,))
for i, layer_size i... |
This method creates network with a specific architecture
:return:
| This method creates network with a specific architecture | [
"This",
"method",
"creates",
"network",
"with",
"a",
"specific",
"architecture"
] | def create_network(self, input_size : int = 498, layers_list : List[int] = [800, 800, 800, 800]) -> None:
self.set_corrent_session()
entries = Input(shape=(input_size,))
for i, layer_size in enumerate(layers_list):
print(layer_size)
if i == 0:
data_flow = ... | [
"def",
"create_network",
"(",
"self",
",",
"input_size",
":",
"int",
"=",
"498",
",",
"layers_list",
":",
"List",
"[",
"int",
"]",
"=",
"[",
"800",
",",
"800",
",",
"800",
",",
"800",
"]",
")",
"->",
"None",
":",
"self",
".",
"set_corrent_session",
... | This method creates network with a specific architecture | [
"This",
"method",
"creates",
"network",
"with",
"a",
"specific",
"architecture"
] | [
"'''\n This method creates network with a specific architecture\n :return:\n '''",
"#data_flow = Dropout(rate=0.1)(data_flow)"
] | [
{
"param": "self",
"type": null
},
{
"param": "input_size",
"type": "int"
},
{
"param": "layers_list",
"type": "List[int]"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
31b35d668fbcd993e9229925713326c2107c7e29 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/data/data_loader.py | [
"MIT"
] | Python | load_all_cards | Set[Card] | def load_all_cards(file: str = CARDS_DATABASE_FILE) -> Set[Card]:
"""Loads information about cards from file and returns a set of cards."""
set_of_cards = set()
cards_database_file = open(file)
reader = csv.reader(cards_database_file)
_ = next(reader, None)
card_id = 0
for row in reader:
... | Loads information about cards from file and returns a set of cards. | Loads information about cards from file and returns a set of cards. | [
"Loads",
"information",
"about",
"cards",
"from",
"file",
"and",
"returns",
"a",
"set",
"of",
"cards",
"."
] | def load_all_cards(file: str = CARDS_DATABASE_FILE) -> Set[Card]:
set_of_cards = set()
cards_database_file = open(file)
reader = csv.reader(cards_database_file)
_ = next(reader, None)
card_id = 0
for row in reader:
price = GemsCollection({GemColor.BLACK: int(row[2]), GemColor.WHITE: int(... | [
"def",
"load_all_cards",
"(",
"file",
":",
"str",
"=",
"CARDS_DATABASE_FILE",
")",
"->",
"Set",
"[",
"Card",
"]",
":",
"set_of_cards",
"=",
"set",
"(",
")",
"cards_database_file",
"=",
"open",
"(",
"file",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
... | Loads information about cards from file and returns a set of cards. | [
"Loads",
"information",
"about",
"cards",
"from",
"file",
"and",
"returns",
"a",
"set",
"of",
"cards",
"."
] | [
"\"\"\"Loads information about cards from file and returns a set of cards.\"\"\""
] | [
{
"param": "file",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "file",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
31b35d668fbcd993e9229925713326c2107c7e29 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/data/data_loader.py | [
"MIT"
] | Python | load_all_nobles | Set[Noble] | def load_all_nobles(file: str = NOBLES_DATABASE_FILE) -> Set[Noble]:
"""Loads information about nobles from file and returns a set of cards."""
set_of_nobles = set()
nobles_database_file = open(file)
reader = csv.reader(nobles_database_file)
_ = next(reader, None)
noble_id = 100
for row in r... | Loads information about nobles from file and returns a set of cards. | Loads information about nobles from file and returns a set of cards. | [
"Loads",
"information",
"about",
"nobles",
"from",
"file",
"and",
"returns",
"a",
"set",
"of",
"cards",
"."
] | def load_all_nobles(file: str = NOBLES_DATABASE_FILE) -> Set[Noble]:
set_of_nobles = set()
nobles_database_file = open(file)
reader = csv.reader(nobles_database_file)
_ = next(reader, None)
noble_id = 100
for row in reader:
price = GemsCollection({GemColor.BLACK: int(row[1]), GemColor.WH... | [
"def",
"load_all_nobles",
"(",
"file",
":",
"str",
"=",
"NOBLES_DATABASE_FILE",
")",
"->",
"Set",
"[",
"Noble",
"]",
":",
"set_of_nobles",
"=",
"set",
"(",
")",
"nobles_database_file",
"=",
"open",
"(",
"file",
")",
"reader",
"=",
"csv",
".",
"reader",
"... | Loads information about nobles from file and returns a set of cards. | [
"Loads",
"information",
"about",
"nobles",
"from",
"file",
"and",
"returns",
"a",
"set",
"of",
"cards",
"."
] | [
"\"\"\"Loads information about nobles from file and returns a set of cards.\"\"\""
] | [
{
"param": "file",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "file",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
31c094132976fe68910e1e76c9ff31c1248cacb0 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/splendor.py | [
"MIT"
] | Python | step | <not_specific> | def step(self, mode, action: Action, return_observation=True, ensure_correctness = False):
"""
Executes action on the environment. Action is performed on the current state of the game.
The are two modes for is_done: instant_end - the episode ends instantly when any player reaches the number of... |
Executes action on the environment. Action is performed on the current state of the game.
The are two modes for is_done: instant_end - the episode ends instantly when any player reaches the number of
points equal POINTS_TO_WIN and let_all_move - when some player reaches POINTS_TO_WIN we allow... | Executes action on the environment. Action is performed on the current state of the game.
The are two modes for is_done: instant_end - the episode ends instantly when any player reaches the number of
points equal POINTS_TO_WIN and let_all_move - when some player reaches POINTS_TO_WIN we allow all players to move
(till ... | [
"Executes",
"action",
"on",
"the",
"environment",
".",
"Action",
"is",
"performed",
"on",
"the",
"current",
"state",
"of",
"the",
"game",
".",
"The",
"are",
"two",
"modes",
"for",
"is_done",
":",
"instant_end",
"-",
"the",
"episode",
"ends",
"instantly",
"... | def step(self, mode, action: Action, return_observation=True, ensure_correctness = False):
info = {}
if action is not None:
if ensure_correctness:
self.update_actions()
assert self.action_space.contains(action), '{} is not valid action'.format(action)
... | [
"def",
"step",
"(",
"self",
",",
"mode",
",",
"action",
":",
"Action",
",",
"return_observation",
"=",
"True",
",",
"ensure_correctness",
"=",
"False",
")",
":",
"\"\"\"Performs one action on the current current_state of the game. \"\"\"",
"info",
"=",
"{",
"}",
"if... | Executes action on the environment. | [
"Executes",
"action",
"on",
"the",
"environment",
"."
] | [
"\"\"\"\n Executes action on the environment. Action is performed on the current state of the game.\n\n\n The are two modes for is_done: instant_end - the episode ends instantly when any player reaches the number of\n points equal POINTS_TO_WIN and let_all_move - when some player reaches POINTS... | [
{
"param": "self",
"type": null
},
{
"param": "mode",
"type": null
},
{
"param": "action",
"type": "Action"
},
{
"param": "return_observation",
"type": null
},
{
"param": "ensure_correctness",
"type": null
}
] | {
"returns": [
{
"docstring": "observation, reward, is_done, info",
"docstring_tokens": [
"observation",
"reward",
"is_done",
"info"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstri... |
31c094132976fe68910e1e76c9ff31c1248cacb0 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/splendor.py | [
"MIT"
] | Python | render | null | def render(self, mode='human', interactive = True):
"""Creates window if necessary, then renders the current_state of the game """
if self.gui is None:
self.gui = SplendorGUI()
self.gui.interactive = interactive
#clear gui:
#self.gui.clear_all()
#draw curren... | Creates window if necessary, then renders the current_state of the game | Creates window if necessary, then renders the current_state of the game | [
"Creates",
"window",
"if",
"necessary",
"then",
"renders",
"the",
"current_state",
"of",
"the",
"game"
] | def render(self, mode='human', interactive = True):
if self.gui is None:
self.gui = SplendorGUI()
self.gui.interactive = interactive
self.gui.draw_state(self.current_state_of_the_game) | [
"def",
"render",
"(",
"self",
",",
"mode",
"=",
"'human'",
",",
"interactive",
"=",
"True",
")",
":",
"if",
"self",
".",
"gui",
"is",
"None",
":",
"self",
".",
"gui",
"=",
"SplendorGUI",
"(",
")",
"self",
".",
"gui",
".",
"interactive",
"=",
"inter... | Creates window if necessary, then renders the current_state of the game | [
"Creates",
"window",
"if",
"necessary",
"then",
"renders",
"the",
"current_state",
"of",
"the",
"game"
] | [
"\"\"\"Creates window if necessary, then renders the current_state of the game \"\"\"",
"#clear gui:",
"#self.gui.clear_all()",
"#draw current_state"
] | [
{
"param": "self",
"type": null
},
{
"param": "mode",
"type": null
},
{
"param": "interactive",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "mode",
"type": null,
"docstring": null,
"docstring_tokens": [... |
bacb397bf4060ecc5747886ba4b6df903ab504a2 | TomaszOdrzygozdz/gym-splendor | arena/arena.py | [
"MIT"
] | Python | run_one_duel | GameStatisticsDuels | def run_one_duel(self,
mode: str,
list_of_agents: List[Agent],
starting_agent_id: int = 0,
render_game: bool=False,
mpi_communicator = None,
initial_observation = None)-> GameStatisticsDuels:
... | Runs one game between two agents.
:param:
mode: mode of the game (stochastic or deterministic)
list_of_agents: List of agents to play, they will play in the order given by the list
starting_agent_id: Id of the agent who starts the game.
show_game: If True, GUI will appear showin... | Runs one game between two agents. | [
"Runs",
"one",
"game",
"between",
"two",
"agents",
"."
] | def run_one_duel(self,
mode: str,
list_of_agents: List[Agent],
starting_agent_id: int = 0,
render_game: bool=False,
mpi_communicator = None,
initial_observation = None)-> GameStatisticsDuels:
... | [
"def",
"run_one_duel",
"(",
"self",
",",
"mode",
":",
"str",
",",
"list_of_agents",
":",
"List",
"[",
"Agent",
"]",
",",
"starting_agent_id",
":",
"int",
"=",
"0",
",",
"render_game",
":",
"bool",
"=",
"False",
",",
"mpi_communicator",
"=",
"None",
",",
... | Runs one game between two agents. | [
"Runs",
"one",
"game",
"between",
"two",
"agents",
"."
] | [
"\"\"\"Runs one game between two agents.\n :param:\n mode: mode of the game (stochastic or deterministic)\n list_of_agents: List of agents to play, they will play in the order given by the list\n starting_agent_id: Id of the agent who starts the game.\n show_game: If True, GUI wi... | [
{
"param": "self",
"type": null
},
{
"param": "mode",
"type": "str"
},
{
"param": "list_of_agents",
"type": "List[Agent]"
},
{
"param": "starting_agent_id",
"type": "int"
},
{
"param": "render_game",
"type": "bool"
},
{
"param": "mpi_communicator",
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "mode",
"type": "str",
"docstring": null,
"docstring_tokens": ... |
bacb397bf4060ecc5747886ba4b6df903ab504a2 | TomaszOdrzygozdz/gym-splendor | arena/arena.py | [
"MIT"
] | Python | run_many_duels | <not_specific> | def run_many_duels(self,
mode,
list_of_agents: List[Agent],
number_of_games: int,
shuffle_agents: bool = True,
starting_agent_id = 0,
initial_observation = None):
"""Runs ma... | Runs many games on a single process.
:param
list_of_agents: List of agents to play, they will play in the order given by the list.
number_of_games: The number of games to play.
shuffle_agents: If True list of agents (and thus their order in the game will be shuffled after each game).
... | Runs many games on a single process. | [
"Runs",
"many",
"games",
"on",
"a",
"single",
"process",
"."
] | def run_many_duels(self,
mode,
list_of_agents: List[Agent],
number_of_games: int,
shuffle_agents: bool = True,
starting_agent_id = 0,
initial_observation = None):
assert numb... | [
"def",
"run_many_duels",
"(",
"self",
",",
"mode",
",",
"list_of_agents",
":",
"List",
"[",
"Agent",
"]",
",",
"number_of_games",
":",
"int",
",",
"shuffle_agents",
":",
"bool",
"=",
"True",
",",
"starting_agent_id",
"=",
"0",
",",
"initial_observation",
"="... | Runs many games on a single process. | [
"Runs",
"many",
"games",
"on",
"a",
"single",
"process",
"."
] | [
"\"\"\"Runs many games on a single process.\n :param\n list_of_agents: List of agents to play, they will play in the order given by the list.\n number_of_games: The number of games to play.\n shuffle_agents: If True list of agents (and thus their order in the game will be shuffled after ... | [
{
"param": "self",
"type": null
},
{
"param": "mode",
"type": null
},
{
"param": "list_of_agents",
"type": "List[Agent]"
},
{
"param": "number_of_games",
"type": "int"
},
{
"param": "shuffle_agents",
"type": "bool"
},
{
"param": "starting_agent_id",
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "mode",
"type": null,
"docstring": null,
"docstring_tokens": [... |
5bd4d4b3eaae4c33fb21881a72e4e8ddb490fafa | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/shooting.py | [
"MIT"
] | Python | reset | null | def reset(self, env, observation):
"""Reinitializes the agentfor a new environment."""
del observation
assert env.action_space == self._action_space
self._model = env | Reinitializes the agentfor a new environment. | Reinitializes the agentfor a new environment. | [
"Reinitializes",
"the",
"agentfor",
"a",
"new",
"environment",
"."
] | def reset(self, env, observation):
del observation
assert env.action_space == self._action_space
self._model = env | [
"def",
"reset",
"(",
"self",
",",
"env",
",",
"observation",
")",
":",
"del",
"observation",
"assert",
"env",
".",
"action_space",
"==",
"self",
".",
"_action_space",
"self",
".",
"_model",
"=",
"env"
] | Reinitializes the agentfor a new environment. | [
"Reinitializes",
"the",
"agentfor",
"a",
"new",
"environment",
"."
] | [
"\"\"\"Reinitializes the agentfor a new environment.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "observation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "env",
"type": null,
"docstring": null,
"docstring_tokens": []... |
5bd4d4b3eaae4c33fb21881a72e4e8ddb490fafa | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/shooting.py | [
"MIT"
] | Python | act | <not_specific> | def act(self, observation):
"""Runs n_rollouts simulations and chooses the best action."""
assert self._model is not None, (
'Reset ShootingAgent first.'
)
del observation
# TODO(pj): Request network_fn and params here with yield.
network_fn = functools.parti... | Runs n_rollouts simulations and chooses the best action. | Runs n_rollouts simulations and chooses the best action. | [
"Runs",
"n_rollouts",
"simulations",
"and",
"chooses",
"the",
"best",
"action",
"."
] | def act(self, observation):
assert self._model is not None, (
'Reset ShootingAgent first.'
)
del observation
network_fn = functools.partial(networks.DummyNetwork, input_shape=None)
params = None
if self._batch_stepper is None:
self._batch_stepper =... | [
"def",
"act",
"(",
"self",
",",
"observation",
")",
":",
"assert",
"self",
".",
"_model",
"is",
"not",
"None",
",",
"(",
"'Reset ShootingAgent first.'",
")",
"del",
"observation",
"network_fn",
"=",
"functools",
".",
"partial",
"(",
"networks",
".",
"DummyNe... | Runs n_rollouts simulations and chooses the best action. | [
"Runs",
"n_rollouts",
"simulations",
"and",
"chooses",
"the",
"best",
"action",
"."
] | [
"\"\"\"Runs n_rollouts simulations and chooses the best action.\"\"\"",
"# TODO(pj): Request network_fn and params here with yield.",
"# Lazy initialize batch stepper",
"# TODO(pj): Move it to BatchStepper. You should be able to query",
"# BatchStepper for a given number of episodes (by default n_envs).",
... | [
{
"param": "self",
"type": null
},
{
"param": "observation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "observation",
"type": null,
"docstring": null,
"docstring_tok... |
9c37652878816c430b4a5503b57f3eef881d14c3 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/utils/utils_functions.py | [
"MIT"
] | Python | tuple_of_gems_to_gems_collection | GemsCollection | def tuple_of_gems_to_gems_collection(tuple_of_gems: Tuple[GemColor], val = 1, return_val = [1], return_colors = set()) -> GemsCollection:
"""Return a gems collection constructed from the tuple of gems:
Parameters:
_ _ _ _ _ _
tuple_of_gems: Tuple of gems (with possible repetitions).
Returns: A... | Return a gems collection constructed from the tuple of gems:
Parameters:
_ _ _ _ _ _
tuple_of_gems: Tuple of gems (with possible repetitions).
Returns: A gems collections. Example:
(red, red, blue, green) is transformed to GemsCollection({red:2, blue:1, green:1, white:0, black:0, gold:0}). | Return a gems collection constructed from the tuple of gems. | [
"Return",
"a",
"gems",
"collection",
"constructed",
"from",
"the",
"tuple",
"of",
"gems",
"."
] | def tuple_of_gems_to_gems_collection(tuple_of_gems: Tuple[GemColor], val = 1, return_val = [1], return_colors = set()) -> GemsCollection:
gems_dict = {gem_color: 0 for gem_color in GemColor}
for element in tuple_of_gems:
gems_dict[element] += val
for i, element in enumerate(return_colors):
g... | [
"def",
"tuple_of_gems_to_gems_collection",
"(",
"tuple_of_gems",
":",
"Tuple",
"[",
"GemColor",
"]",
",",
"val",
"=",
"1",
",",
"return_val",
"=",
"[",
"1",
"]",
",",
"return_colors",
"=",
"set",
"(",
")",
")",
"->",
"GemsCollection",
":",
"gems_dict",
"="... | Return a gems collection constructed from the tuple of gems: | [
"Return",
"a",
"gems",
"collection",
"constructed",
"from",
"the",
"tuple",
"of",
"gems",
":"
] | [
"\"\"\"Return a gems collection constructed from the tuple of gems:\n Parameters:\n _ _ _ _ _ _\n tuple_of_gems: Tuple of gems (with possible repetitions).\n\n Returns: A gems collections. Example:\n (red, red, blue, green) is transformed to GemsCollection({red:2, blue:1, green:1, white:0, black... | [
{
"param": "tuple_of_gems",
"type": "Tuple[GemColor]"
},
{
"param": "val",
"type": null
},
{
"param": "return_val",
"type": null
},
{
"param": "return_colors",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "tuple_of_gems",
"type": "Tuple[GemColor]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "val",
"type": null,
"docstring": null,
... |
9c37652878816c430b4a5503b57f3eef881d14c3 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/utils/utils_functions.py | [
"MIT"
] | Python | colors_to_gems_collection | GemsCollection | def colors_to_gems_collection(tuple_of_gems) -> GemsCollection:
"""Return a gems collection constructed from list of colors:
Parameters:
_ _ _ _ _ _
tuple_of_gems: Tuple of gems (with possible repetitions).
Returns: A gems collections. Example:
(red, red, blue, green) is transformed to Gem... | Return a gems collection constructed from list of colors:
Parameters:
_ _ _ _ _ _
tuple_of_gems: Tuple of gems (with possible repetitions).
Returns: A gems collections. Example:
(red, red, blue, green) is transformed to GemsCollection({red:2, blue:1, green:1, white:0, black:0, gold:0}). | Return a gems collection constructed from list of colors. | [
"Return",
"a",
"gems",
"collection",
"constructed",
"from",
"list",
"of",
"colors",
"."
] | def colors_to_gems_collection(tuple_of_gems) -> GemsCollection:
gems_dict = {gem_color: 0 for gem_color in GemColor}
for element in tuple_of_gems:
gems_dict[element] += 1
return GemsCollection(gems_dict) | [
"def",
"colors_to_gems_collection",
"(",
"tuple_of_gems",
")",
"->",
"GemsCollection",
":",
"gems_dict",
"=",
"{",
"gem_color",
":",
"0",
"for",
"gem_color",
"in",
"GemColor",
"}",
"for",
"element",
"in",
"tuple_of_gems",
":",
"gems_dict",
"[",
"element",
"]",
... | Return a gems collection constructed from list of colors: | [
"Return",
"a",
"gems",
"collection",
"constructed",
"from",
"list",
"of",
"colors",
":"
] | [
"\"\"\"Return a gems collection constructed from list of colors:\n Parameters:\n _ _ _ _ _ _\n tuple_of_gems: Tuple of gems (with possible repetitions).\n\n Returns: A gems collections. Example:\n (red, red, blue, green) is transformed to GemsCollection({red:2, blue:1, green:1, white:0, black:0,... | [
{
"param": "tuple_of_gems",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "tuple_of_gems",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [
{
"identifier": "_ _ _ _ _ _\n tuple_of_gems",
"type... |
c4e0ca34bc0cd9df2f32496d6fd78a2dadfaf14d | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/networks/keras.py | [
"MIT"
] | Python | train | <not_specific> | def train(self, data_stream):
"""Performs one epoch of training on data prepared by the Trainer.
Args:
data_stream: (Trainer-dependent) Python generator of batches to run
the updates on.
Returns:
dict: Collected metrics, indexed by name.
"""
... | Performs one epoch of training on data prepared by the Trainer.
Args:
data_stream: (Trainer-dependent) Python generator of batches to run
the updates on.
Returns:
dict: Collected metrics, indexed by name.
| Performs one epoch of training on data prepared by the Trainer. | [
"Performs",
"one",
"epoch",
"of",
"training",
"on",
"data",
"prepared",
"by",
"the",
"Trainer",
"."
] | def train(self, data_stream):
dataset = tf.data.Dataset.from_generator(
generator=data_stream,
output_types=(self._model.input.dtype, self._model.output.dtype)
)
history = self._model.fit_generator(dataset, epochs=1, verbose=0,
... | [
"def",
"train",
"(",
"self",
",",
"data_stream",
")",
":",
"dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_generator",
"(",
"generator",
"=",
"data_stream",
",",
"output_types",
"=",
"(",
"self",
".",
"_model",
".",
"input",
".",
"dtype",
... | Performs one epoch of training on data prepared by the Trainer. | [
"Performs",
"one",
"epoch",
"of",
"training",
"on",
"data",
"prepared",
"by",
"the",
"Trainer",
"."
] | [
"\"\"\"Performs one epoch of training on data prepared by the Trainer.\n\n Args:\n data_stream: (Trainer-dependent) Python generator of batches to run\n the updates on.\n\n Returns:\n dict: Collected metrics, indexed by name.\n \"\"\"",
"# WA for bug: http... | [
{
"param": "self",
"type": null
},
{
"param": "data_stream",
"type": null
}
] | {
"returns": [
{
"docstring": "Collected metrics, indexed by name.",
"docstring_tokens": [
"Collected",
"metrics",
"indexed",
"by",
"name",
"."
],
"type": "dict"
}
],
"raises": [],
"params": [
{
"identifier": "self",
... |
c4e0ca34bc0cd9df2f32496d6fd78a2dadfaf14d | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/networks/keras.py | [
"MIT"
] | Python | predict | <not_specific> | def predict(self, inputs):
"""Returns the prediction for a given input.
Args:
inputs: (Agent-dependent) Batch of inputs to run prediction on.
Returns:
Agent-dependent: Network predictions.
"""
return self._model.predict_on_batch(inputs).numpy() | Returns the prediction for a given input.
Args:
inputs: (Agent-dependent) Batch of inputs to run prediction on.
Returns:
Agent-dependent: Network predictions.
| Returns the prediction for a given input. | [
"Returns",
"the",
"prediction",
"for",
"a",
"given",
"input",
"."
] | def predict(self, inputs):
return self._model.predict_on_batch(inputs).numpy() | [
"def",
"predict",
"(",
"self",
",",
"inputs",
")",
":",
"return",
"self",
".",
"_model",
".",
"predict_on_batch",
"(",
"inputs",
")",
".",
"numpy",
"(",
")"
] | Returns the prediction for a given input. | [
"Returns",
"the",
"prediction",
"for",
"a",
"given",
"input",
"."
] | [
"\"\"\"Returns the prediction for a given input.\n\n Args:\n inputs: (Agent-dependent) Batch of inputs to run prediction on.\n\n Returns:\n Agent-dependent: Network predictions.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "inputs",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": "Agent-dependent"
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optio... |
ef9d4eca7db3f69c6c3916908159a8ad0aab3ac7 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/batch_steppers.py | [
"MIT"
] | Python | run_episode_batch | null | def run_episode_batch(self, params, **solve_kwargs): # pylint: disable=missing-param-doc
"""Runs a batch of episodes using the given network parameters.
Args:
params (Network-dependent): Network parameters.
**solve_kwargs (dict): Keyword arguments passed to Agent.solve().
... | Runs a batch of episodes using the given network parameters.
Args:
params (Network-dependent): Network parameters.
**solve_kwargs (dict): Keyword arguments passed to Agent.solve().
Returns:
List of completed episodes (Agent/Trainer-dependent).
| Runs a batch of episodes using the given network parameters. | [
"Runs",
"a",
"batch",
"of",
"episodes",
"using",
"the",
"given",
"network",
"parameters",
"."
] | def run_episode_batch(self, params, **solve_kwargs):
raise NotImplementedError | [
"def",
"run_episode_batch",
"(",
"self",
",",
"params",
",",
"**",
"solve_kwargs",
")",
":",
"raise",
"NotImplementedError"
] | Runs a batch of episodes using the given network parameters. | [
"Runs",
"a",
"batch",
"of",
"episodes",
"using",
"the",
"given",
"network",
"parameters",
"."
] | [
"# pylint: disable=missing-param-doc",
"\"\"\"Runs a batch of episodes using the given network parameters.\n\n Args:\n params (Network-dependent): Network parameters.\n **solve_kwargs (dict): Keyword arguments passed to Agent.solve().\n\n Returns:\n List of completed... | [
{
"param": "self",
"type": null
},
{
"param": "params",
"type": null
}
] | {
"returns": [
{
"docstring": "List of completed episodes (Agent/Trainer-dependent).",
"docstring_tokens": [
"List",
"of",
"completed",
"episodes",
"(",
"Agent",
"/",
"Trainer",
"-",
"dependent",
")",
"."
... |
ef9d4eca7db3f69c6c3916908159a8ad0aab3ac7 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/batch_steppers.py | [
"MIT"
] | Python | _batch_coroutines | <not_specific> | def _batch_coroutines(self, cors):
"""Batches a list of coroutines into one.
Handles waiting for the slowest coroutine and filling blanks in
prediction requests.
"""
# Store the final episodes in a list.
episodes = [None] * len(cors)
def store_transitions(i, cor... | Batches a list of coroutines into one.
Handles waiting for the slowest coroutine and filling blanks in
prediction requests.
| Batches a list of coroutines into one.
Handles waiting for the slowest coroutine and filling blanks in
prediction requests. | [
"Batches",
"a",
"list",
"of",
"coroutines",
"into",
"one",
".",
"Handles",
"waiting",
"for",
"the",
"slowest",
"coroutine",
"and",
"filling",
"blanks",
"in",
"prediction",
"requests",
"."
] | def _batch_coroutines(self, cors):
episodes = [None] * len(cors)
def store_transitions(i, cor):
episodes[i] = yield from cor
while True:
yield None
cors = [store_transitions(i, cor) for(i, cor) in enumerate(cors)]
def all_finished(xs):
... | [
"def",
"_batch_coroutines",
"(",
"self",
",",
"cors",
")",
":",
"episodes",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"cors",
")",
"def",
"store_transitions",
"(",
"i",
",",
"cor",
")",
":",
"episodes",
"[",
"i",
"]",
"=",
"yield",
"from",
"cor",
"wh... | Batches a list of coroutines into one. | [
"Batches",
"a",
"list",
"of",
"coroutines",
"into",
"one",
"."
] | [
"\"\"\"Batches a list of coroutines into one.\n\n Handles waiting for the slowest coroutine and filling blanks in\n prediction requests.\n \"\"\"",
"# Store the final episodes in a list.",
"# End with an infinite stream of Nones, so we don't have",
"# to deal with StopIteration later on."... | [
{
"param": "self",
"type": null
},
{
"param": "cors",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cors",
"type": null,
"docstring": null,
"docstring_tokens": [... |
ef9d4eca7db3f69c6c3916908159a8ad0aab3ac7 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/batch_steppers.py | [
"MIT"
] | Python | run | <not_specific> | def run(self, params, solve_kwargs):
"""Runs the episode using the given network parameters."""
self.network.params = params
episode_cor = self.agent.solve(self.env, **solve_kwargs)
# TODO(pj): This block of code is the same in LocalBatchStepper
... | Runs the episode using the given network parameters. | Runs the episode using the given network parameters. | [
"Runs",
"the",
"episode",
"using",
"the",
"given",
"network",
"parameters",
"."
] | def run(self, params, solve_kwargs):
self.network.params = params
episode_cor = self.agent.solve(self.env, **solve_kwargs)
try:
inputs = next(episode_cor)
while True:
predictions = self.network.predict(inputs... | [
"def",
"run",
"(",
"self",
",",
"params",
",",
"solve_kwargs",
")",
":",
"self",
".",
"network",
".",
"params",
"=",
"params",
"episode_cor",
"=",
"self",
".",
"agent",
".",
"solve",
"(",
"self",
".",
"env",
",",
"**",
"solve_kwargs",
")",
"try",
":"... | Runs the episode using the given network parameters. | [
"Runs",
"the",
"episode",
"using",
"the",
"given",
"network",
"parameters",
"."
] | [
"\"\"\"Runs the episode using the given network parameters.\"\"\"",
"# TODO(pj): This block of code is the same in LocalBatchStepper",
"# too. Move it to the BatchStepper base class."
] | [
{
"param": "self",
"type": null
},
{
"param": "params",
"type": null
},
{
"param": "solve_kwargs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "params",
"type": null,
"docstring": null,
"docstring_tokens":... |
9cf5b92c976de8a096e820ea1a4d62cb6de447c3 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/deck.py | [
"MIT"
] | Python | pop_card | Card | def pop_card(self,
row: Row) -> Card:
"""Pops a card from a given row. Returns this card and removes it from the deck."""
if len(self.decks_dict[row]) > 0:
return self.decks_dict[row].pop(0) | Pops a card from a given row. Returns this card and removes it from the deck. | Pops a card from a given row. Returns this card and removes it from the deck. | [
"Pops",
"a",
"card",
"from",
"a",
"given",
"row",
".",
"Returns",
"this",
"card",
"and",
"removes",
"it",
"from",
"the",
"deck",
"."
] | def pop_card(self,
row: Row) -> Card:
if len(self.decks_dict[row]) > 0:
return self.decks_dict[row].pop(0) | [
"def",
"pop_card",
"(",
"self",
",",
"row",
":",
"Row",
")",
"->",
"Card",
":",
"if",
"len",
"(",
"self",
".",
"decks_dict",
"[",
"row",
"]",
")",
">",
"0",
":",
"return",
"self",
".",
"decks_dict",
"[",
"row",
"]",
".",
"pop",
"(",
"0",
")"
] | Pops a card from a given row. | [
"Pops",
"a",
"card",
"from",
"a",
"given",
"row",
"."
] | [
"\"\"\"Pops a card from a given row. Returns this card and removes it from the deck.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "row",
"type": "Row"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "row",
"type": "Row",
"docstring": null,
"docstring_tokens": [... |
9cf5b92c976de8a096e820ea1a4d62cb6de447c3 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/deck.py | [
"MIT"
] | Python | pop_many_from_one_row | List[Card] | def pop_many_from_one_row(self,
row: Row,
number: int = 4) -> List[Card]:
"""Pops many cards from a given row."""
return [self.pop_card(row) for _ in range(number)] | Pops many cards from a given row. | Pops many cards from a given row. | [
"Pops",
"many",
"cards",
"from",
"a",
"given",
"row",
"."
] | def pop_many_from_one_row(self,
row: Row,
number: int = 4) -> List[Card]:
return [self.pop_card(row) for _ in range(number)] | [
"def",
"pop_many_from_one_row",
"(",
"self",
",",
"row",
":",
"Row",
",",
"number",
":",
"int",
"=",
"4",
")",
"->",
"List",
"[",
"Card",
"]",
":",
"return",
"[",
"self",
".",
"pop_card",
"(",
"row",
")",
"for",
"_",
"in",
"range",
"(",
"number",
... | Pops many cards from a given row. | [
"Pops",
"many",
"cards",
"from",
"a",
"given",
"row",
"."
] | [
"\"\"\"Pops many cards from a given row.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "row",
"type": "Row"
},
{
"param": "number",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "row",
"type": "Row",
"docstring": null,
"docstring_tokens": [... |
9cf5b92c976de8a096e820ea1a4d62cb6de447c3 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/deck.py | [
"MIT"
] | Python | shuffle | None | def shuffle(self) -> None:
"""Shuffles both deck of cards and deck of nobles."""
for list_of_cards in self.decks_dict.values():
random.shuffle(list_of_cards)
random.shuffle(self.deck_of_nobles) | Shuffles both deck of cards and deck of nobles. | Shuffles both deck of cards and deck of nobles. | [
"Shuffles",
"both",
"deck",
"of",
"cards",
"and",
"deck",
"of",
"nobles",
"."
] | def shuffle(self) -> None:
for list_of_cards in self.decks_dict.values():
random.shuffle(list_of_cards)
random.shuffle(self.deck_of_nobles) | [
"def",
"shuffle",
"(",
"self",
")",
"->",
"None",
":",
"for",
"list_of_cards",
"in",
"self",
".",
"decks_dict",
".",
"values",
"(",
")",
":",
"random",
".",
"shuffle",
"(",
"list_of_cards",
")",
"random",
".",
"shuffle",
"(",
"self",
".",
"deck_of_nobles... | Shuffles both deck of cards and deck of nobles. | [
"Shuffles",
"both",
"deck",
"of",
"cards",
"and",
"deck",
"of",
"nobles",
"."
] | [
"\"\"\"Shuffles both deck of cards and deck of nobles.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6a66c51afd8ca57f10f73bbdfbbb8d2362323ecb | TomaszOdrzygozdz/gym-splendor | archive/embedding_average_pool/embedding_average_pool_v0.py | [
"MIT"
] | Python | create_network | None | def create_network(self, input_size : int = 498, layers_list : List[int] = [800, 800, 800, 800]) -> None:
'''
This method creates network with a specific architecture
:return:
'''
#board input:
gems_on_board_input = Input(shape=(36,), name='gems_on_board')
cards_... |
This method creates network with a specific architecture
:return:
| This method creates network with a specific architecture | [
"This",
"method",
"creates",
"network",
"with",
"a",
"specific",
"architecture"
] | def create_network(self, input_size : int = 498, layers_list : List[int] = [800, 800, 800, 800]) -> None:
gems_on_board_input = Input(shape=(36,), name='gems_on_board')
cards_on_board_input_list = [Input(shape=(51,), name='card_{}th'.format(i)) for i in range(12)]
nobles_on_board_list = [Input(s... | [
"def",
"create_network",
"(",
"self",
",",
"input_size",
":",
"int",
"=",
"498",
",",
"layers_list",
":",
"List",
"[",
"int",
"]",
"=",
"[",
"800",
",",
"800",
",",
"800",
",",
"800",
"]",
")",
"->",
"None",
":",
"gems_on_board_input",
"=",
"Input",
... | This method creates network with a specific architecture | [
"This",
"method",
"creates",
"network",
"with",
"a",
"specific",
"architecture"
] | [
"'''\n This method creates network with a specific architecture\n :return:\n '''",
"#board input:",
"#active_player:",
"#TODO: klasa model card_encoder",
"#data_flow = Dropout(rate=0.1)(data_flow)"
] | [
{
"param": "self",
"type": null
},
{
"param": "input_size",
"type": "int"
},
{
"param": "layers_list",
"type": "List[int]"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
c6cd4a21c43800315fd143dab03b6dc7faf42b55 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/base.py | [
"MIT"
] | Python | solve | null | def solve(self, env, init_state=None, time_limit=None):
"""Solves a given environment.
Coroutine, suspends execution for every neural network prediction
request. This enables a very convenient interface for requesting
predictions by the Agent:
def solve(self, env, init_stat... | Solves a given environment.
Coroutine, suspends execution for every neural network prediction
request. This enables a very convenient interface for requesting
predictions by the Agent:
def solve(self, env, init_state=None):
# Planning...
predictions ... | Solves a given environment.
Coroutine, suspends execution for every neural network prediction
request. This enables a very convenient interface for requesting
predictions by the Agent.
def solve(self, env, init_state=None):
Planning
predictions = yield inputs
Planning
predictions = yield inputs
Planning
return episode... | [
"Solves",
"a",
"given",
"environment",
".",
"Coroutine",
"suspends",
"execution",
"for",
"every",
"neural",
"network",
"prediction",
"request",
".",
"This",
"enables",
"a",
"very",
"convenient",
"interface",
"for",
"requesting",
"predictions",
"by",
"the",
"Agent"... | def solve(self, env, init_state=None, time_limit=None):
raise NotImplementedError | [
"def",
"solve",
"(",
"self",
",",
"env",
",",
"init_state",
"=",
"None",
",",
"time_limit",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | Solves a given environment. | [
"Solves",
"a",
"given",
"environment",
"."
] | [
"\"\"\"Solves a given environment.\n\n Coroutine, suspends execution for every neural network prediction\n request. This enables a very convenient interface for requesting\n predictions by the Agent:\n\n def solve(self, env, init_state=None):\n # Planning...\n ... | [
{
"param": "self",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "init_state",
"type": null
},
{
"param": "time_limit",
"type": null
}
] | {
"returns": [
{
"docstring": "A stream of Network inputs requested for inference.",
"docstring_tokens": [
"A",
"stream",
"of",
"Network",
"inputs",
"requested",
"for",
"inference",
"."
],
"type": null
},
{
... |
c6cd4a21c43800315fd143dab03b6dc7faf42b55 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/base.py | [
"MIT"
] | Python | reset | null | def reset(self, env, observation): # pylint: disable=missing-param-doc
"""Resets the agent state.
Called for every new environment to be solved. Overriding is optional.
Args:
env (gym.Env): Environment to solve.
observation (Env-dependent): Initial observation returned... | Resets the agent state.
Called for every new environment to be solved. Overriding is optional.
Args:
env (gym.Env): Environment to solve.
observation (Env-dependent): Initial observation returned by
env.reset().
| Resets the agent state.
Called for every new environment to be solved. Overriding is optional. | [
"Resets",
"the",
"agent",
"state",
".",
"Called",
"for",
"every",
"new",
"environment",
"to",
"be",
"solved",
".",
"Overriding",
"is",
"optional",
"."
] | def reset(self, env, observation): | [
"def",
"reset",
"(",
"self",
",",
"env",
",",
"observation",
")",
":"
] | Resets the agent state. | [
"Resets",
"the",
"agent",
"state",
"."
] | [
"# pylint: disable=missing-param-doc",
"\"\"\"Resets the agent state.\n\n Called for every new environment to be solved. Overriding is optional.\n\n Args:\n env (gym.Env): Environment to solve.\n observation (Env-dependent): Initial observation returned by\n env.... | [
{
"param": "self",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "observation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "env",
"type": null,
"docstring": "Environment to solve.",
"do... |
c6cd4a21c43800315fd143dab03b6dc7faf42b55 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/base.py | [
"MIT"
] | Python | postprocess_transition | <not_specific> | def postprocess_transition(transition):
"""Postprocesses Transitions before passing them to Trainer.
Can be overridden in subclasses to customize data collection.
Called after the episode has finished, so can incorporate any
information known only in the hindsight to the transitions.
... | Postprocesses Transitions before passing them to Trainer.
Can be overridden in subclasses to customize data collection.
Called after the episode has finished, so can incorporate any
information known only in the hindsight to the transitions.
Args:
transition (Transition): ... | Postprocesses Transitions before passing them to Trainer.
Can be overridden in subclasses to customize data collection.
Called after the episode has finished, so can incorporate any
information known only in the hindsight to the transitions. | [
"Postprocesses",
"Transitions",
"before",
"passing",
"them",
"to",
"Trainer",
".",
"Can",
"be",
"overridden",
"in",
"subclasses",
"to",
"customize",
"data",
"collection",
".",
"Called",
"after",
"the",
"episode",
"has",
"finished",
"so",
"can",
"incorporate",
"a... | def postprocess_transition(transition):
return transition | [
"def",
"postprocess_transition",
"(",
"transition",
")",
":",
"return",
"transition"
] | Postprocesses Transitions before passing them to Trainer. | [
"Postprocesses",
"Transitions",
"before",
"passing",
"them",
"to",
"Trainer",
"."
] | [
"\"\"\"Postprocesses Transitions before passing them to Trainer.\n\n Can be overridden in subclasses to customize data collection.\n\n Called after the episode has finished, so can incorporate any\n information known only in the hindsight to the transitions.\n\n Args:\n transi... | [
{
"param": "transition",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "transition",
"type": null,
"docstring": "Transition to postprocess.",
"docstring_tokens": [
"Transition",
... |
c6cd4a21c43800315fd143dab03b6dc7faf42b55 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/base.py | [
"MIT"
] | Python | solve | <not_specific> | def solve(self, env, init_state=None, time_limit=None):
"""Solves a given environment using OnlineAgent.act().
Args:
env (gym.Env): Environment to solve.
init_state (object): Reset the environment to this state.
If None, then do normal gym_open_ai.Env.reset().
... | Solves a given environment using OnlineAgent.act().
Args:
env (gym.Env): Environment to solve.
init_state (object): Reset the environment to this state.
If None, then do normal gym_open_ai.Env.reset().
time_limit (int or None): Maximum number of steps to make... | Solves a given environment using OnlineAgent.act(). | [
"Solves",
"a",
"given",
"environment",
"using",
"OnlineAgent",
".",
"act",
"()",
"."
] | def solve(self, env, init_state=None, time_limit=None):
model_env = env
if time_limit is not None:
env = envs.TimeLimitWrapper(env, time_limit)
if init_state is None:
observation = env.reset()
else:
observation = env.restore_state(init_state)
y... | [
"def",
"solve",
"(",
"self",
",",
"env",
",",
"init_state",
"=",
"None",
",",
"time_limit",
"=",
"None",
")",
":",
"model_env",
"=",
"env",
"if",
"time_limit",
"is",
"not",
"None",
":",
"env",
"=",
"envs",
".",
"TimeLimitWrapper",
"(",
"env",
",",
"t... | Solves a given environment using OnlineAgent.act(). | [
"Solves",
"a",
"given",
"environment",
"using",
"OnlineAgent",
".",
"act",
"()",
"."
] | [
"\"\"\"Solves a given environment using OnlineAgent.act().\n\n Args:\n env (gym.Env): Environment to solve.\n init_state (object): Reset the environment to this state.\n If None, then do normal gym_open_ai.Env.reset().\n time_limit (int or None): Maximum number... | [
{
"param": "self",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "init_state",
"type": null
},
{
"param": "time_limit",
"type": null
}
] | {
"returns": [
{
"docstring": "A stream of Network inputs requested for\ninference.",
"docstring_tokens": [
"A",
"stream",
"of",
"Network",
"inputs",
"requested",
"for",
"inference",
"."
],
"type": "Network-dependent"
... |
0cae31f89c9a0a84dca7f3bc73e1e60d6a24978f | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts_test.py | [
"MIT"
] | Python | rate_new_leaves_tabular | <not_specific> | def rate_new_leaves_tabular(
leaf, observation, model, discount, state_values
):
"""Rates new leaves based on hardcoded values."""
del leaf
del observation
del discount
init_state = model.clone_state()
def rating(action):
(observation, reward, _, _) = model.step(action)
mode... | Rates new leaves based on hardcoded values. | Rates new leaves based on hardcoded values. | [
"Rates",
"new",
"leaves",
"based",
"on",
"hardcoded",
"values",
"."
] | def rate_new_leaves_tabular(
leaf, observation, model, discount, state_values
):
del leaf
del observation
del discount
init_state = model.clone_state()
def rating(action):
(observation, reward, _, _) = model.step(action)
model.restore_state(init_state)
return (reward, sta... | [
"def",
"rate_new_leaves_tabular",
"(",
"leaf",
",",
"observation",
",",
"model",
",",
"discount",
",",
"state_values",
")",
":",
"del",
"leaf",
"del",
"observation",
"del",
"discount",
"init_state",
"=",
"model",
".",
"clone_state",
"(",
")",
"def",
"rating",
... | Rates new leaves based on hardcoded values. | [
"Rates",
"new",
"leaves",
"based",
"on",
"hardcoded",
"values",
"."
] | [
"\"\"\"Rates new leaves based on hardcoded values.\"\"\"",
"# State is the same as observation."
] | [
{
"param": "leaf",
"type": null
},
{
"param": "observation",
"type": null
},
{
"param": "model",
"type": null
},
{
"param": "discount",
"type": null
},
{
"param": "state_values",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "leaf",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "observation",
"type": null,
"docstring": null,
"docstring_tok... |
0cae31f89c9a0a84dca7f3bc73e1e60d6a24978f | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts_test.py | [
"MIT"
] | Python | make_one_level_binary_tree | <not_specific> | def make_one_level_binary_tree(
left_value, right_value, left_reward=0, right_reward=0
):
"""Makes a TabularEnv and rate_new_leaves_fn for a 1-level binary tree."""
# 0, action 0 -> 1 (left)
# 0, action 1 -> 2 (right)
(root_state, left_state, right_state) = (0, 1, 2)
env = testing.TabularEnv(
... | Makes a TabularEnv and rate_new_leaves_fn for a 1-level binary tree. | Makes a TabularEnv and rate_new_leaves_fn for a 1-level binary tree. | [
"Makes",
"a",
"TabularEnv",
"and",
"rate_new_leaves_fn",
"for",
"a",
"1",
"-",
"level",
"binary",
"tree",
"."
] | def make_one_level_binary_tree(
left_value, right_value, left_reward=0, right_reward=0
):
(root_state, left_state, right_state) = (0, 1, 2)
env = testing.TabularEnv(
init_state=root_state,
n_actions=2,
transitions={
root_state: {
0: (left_state, left_rewar... | [
"def",
"make_one_level_binary_tree",
"(",
"left_value",
",",
"right_value",
",",
"left_reward",
"=",
"0",
",",
"right_reward",
"=",
"0",
")",
":",
"(",
"root_state",
",",
"left_state",
",",
"right_state",
")",
"=",
"(",
"0",
",",
"1",
",",
"2",
")",
"env... | Makes a TabularEnv and rate_new_leaves_fn for a 1-level binary tree. | [
"Makes",
"a",
"TabularEnv",
"and",
"rate_new_leaves_fn",
"for",
"a",
"1",
"-",
"level",
"binary",
"tree",
"."
] | [
"\"\"\"Makes a TabularEnv and rate_new_leaves_fn for a 1-level binary tree.\"\"\"",
"# 0, action 0 -> 1 (left)",
"# 0, action 1 -> 2 (right)",
"# state: {action: (state', reward, done)}",
"# Dummy terminal states, made so we can expand left and right.",
"# Dummy terminal states."
] | [
{
"param": "left_value",
"type": null
},
{
"param": "right_value",
"type": null
},
{
"param": "left_reward",
"type": null
},
{
"param": "right_reward",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "left_value",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "right_value",
"type": null,
"docstring": null,
"docstri... |
0cbbb158cc2422058dfe2b4ea5394b6ea7d62a18 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/action_space_generator_fast.py | [
"MIT"
] | Python | generate_all_legal_buys_fast | List[ActionBuyCard] | def generate_all_legal_buys_fast(state: State) -> List[ActionBuyCard]:
"""Returns the list of all possible actions of buys in a given current_state"""
list_of_actions_buy = []
discount = state.active_players_hand().discount()
all_cards_can_afford = [card for card in state.board.cards_on_board if
... | Returns the list of all possible actions of buys in a given current_state | Returns the list of all possible actions of buys in a given current_state | [
"Returns",
"the",
"list",
"of",
"all",
"possible",
"actions",
"of",
"buys",
"in",
"a",
"given",
"current_state"
] | def generate_all_legal_buys_fast(state: State) -> List[ActionBuyCard]:
list_of_actions_buy = []
discount = state.active_players_hand().discount()
all_cards_can_afford = [card for card in state.board.cards_on_board if
state.active_players_hand().can_afford_card(card, discount)] + ... | [
"def",
"generate_all_legal_buys_fast",
"(",
"state",
":",
"State",
")",
"->",
"List",
"[",
"ActionBuyCard",
"]",
":",
"list_of_actions_buy",
"=",
"[",
"]",
"discount",
"=",
"state",
".",
"active_players_hand",
"(",
")",
".",
"discount",
"(",
")",
"all_cards_ca... | Returns the list of all possible actions of buys in a given current_state | [
"Returns",
"the",
"list",
"of",
"all",
"possible",
"actions",
"of",
"buys",
"in",
"a",
"given",
"current_state"
] | [
"\"\"\"Returns the list of all possible actions of buys in a given current_state\"\"\"",
"# we choose combination of other gems:",
"# check if the option satisfies conditions:"
] | [
{
"param": "state",
"type": "State"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "state",
"type": "State",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
34f30cc6a62053ce030bc4931d2283211db43271 | TomaszOdrzygozdz/gym-splendor | arena/deterministic_arena.py | [
"MIT"
] | Python | run_one_duel | GameStatisticsDuels | def run_one_duel(self,
list_of_agents: List[Agent],
starting_agent_id: int = 0,
render_game: bool=False)-> GameStatisticsDuels:
"""Runs one game between two agents.
:param:
list_of_agents: List of agents to play, they will play in th... | Runs one game between two agents.
:param:
list_of_agents: List of agents to play, they will play in the order given by the list
starting_agent_id: Id of the agent who starts the game.
show_game: If True, GUI will appear showing the game. | Runs one game between two agents.
:param:
list_of_agents: List of agents to play, they will play in the order given by the list
starting_agent_id: Id of the agent who starts the game.
show_game: If True, GUI will appear showing the game. | [
"Runs",
"one",
"game",
"between",
"two",
"agents",
".",
":",
"param",
":",
"list_of_agents",
":",
"List",
"of",
"agents",
"to",
"play",
"they",
"will",
"play",
"in",
"the",
"order",
"given",
"by",
"the",
"list",
"starting_agent_id",
":",
"Id",
"of",
"the... | def run_one_duel(self,
list_of_agents: List[Agent],
starting_agent_id: int = 0,
render_game: bool=False)-> GameStatisticsDuels:
self.env.reset()
self.env.set_active_player(starting_agent_id)
self.env.set_players_names([agent.name for... | [
"def",
"run_one_duel",
"(",
"self",
",",
"list_of_agents",
":",
"List",
"[",
"Agent",
"]",
",",
"starting_agent_id",
":",
"int",
"=",
"0",
",",
"render_game",
":",
"bool",
"=",
"False",
")",
"->",
"GameStatisticsDuels",
":",
"self",
".",
"env",
".",
"res... | Runs one game between two agents. | [
"Runs",
"one",
"game",
"between",
"two",
"agents",
"."
] | [
"\"\"\"Runs one game between two agents.\n :param:\n list_of_agents: List of agents to play, they will play in the order given by the list\n starting_agent_id: Id of the agent who starts the game.\n show_game: If True, GUI will appear showing the game. \"\"\"",
"#prepare the game",
... | [
{
"param": "self",
"type": null
},
{
"param": "list_of_agents",
"type": "List[Agent]"
},
{
"param": "starting_agent_id",
"type": "int"
},
{
"param": "render_game",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "list_of_agents",
"type": "List[Agent]",
"docstring": null,
"d... |
34f30cc6a62053ce030bc4931d2283211db43271 | TomaszOdrzygozdz/gym-splendor | arena/deterministic_arena.py | [
"MIT"
] | Python | run_many_duels | <not_specific> | def run_many_duels(self,
list_of_agents: List[Agent],
number_of_games: int,
shuffle_agents: bool = True,
starting_agent_id = 0):
"""Runs many games on a single process.
:param
list_of_agents: List of age... | Runs many games on a single process.
:param
list_of_agents: List of agents to play, they will play in the order given by the list.
number_of_games: The number of games to play.
shuffle_agents: If True list of agents (and thus their order in the game will be shuffled after each game).
... | Runs many games on a single process. | [
"Runs",
"many",
"games",
"on",
"a",
"single",
"process",
"."
] | def run_many_duels(self,
list_of_agents: List[Agent],
number_of_games: int,
shuffle_agents: bool = True,
starting_agent_id = 0):
assert number_of_games > 0, 'Number of games must be positive'
cumulative_results =... | [
"def",
"run_many_duels",
"(",
"self",
",",
"list_of_agents",
":",
"List",
"[",
"Agent",
"]",
",",
"number_of_games",
":",
"int",
",",
"shuffle_agents",
":",
"bool",
"=",
"True",
",",
"starting_agent_id",
"=",
"0",
")",
":",
"assert",
"number_of_games",
">",
... | Runs many games on a single process. | [
"Runs",
"many",
"games",
"on",
"a",
"single",
"process",
"."
] | [
"\"\"\"Runs many games on a single process.\n :param\n list_of_agents: List of agents to play, they will play in the order given by the list.\n number_of_games: The number of games to play.\n shuffle_agents: If True list of agents (and thus their order in the game will be shuffled after ... | [
{
"param": "self",
"type": null
},
{
"param": "list_of_agents",
"type": "List[Agent]"
},
{
"param": "number_of_games",
"type": "int"
},
{
"param": "shuffle_agents",
"type": "bool"
},
{
"param": "starting_agent_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "list_of_agents",
"type": "List[Agent]",
"docstring": "List of agent... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | rate_new_leaves_with_rollouts | <not_specific> | def rate_new_leaves_with_rollouts(
leaf,
observation,
model,
discount,
rollout_agent_class=core.RandomAgent,
rollout_time_limit=100,
):
"""Basic rate_new_leaves_fn based on rollouts with an Agent.
Args:
leaf (TreeNode): Node whose children are to be rated.
observation (n... | Basic rate_new_leaves_fn based on rollouts with an Agent.
Args:
leaf (TreeNode): Node whose children are to be rated.
observation (np.ndarray): Observation received at leaf.
model (gym.Env): Model environment.
discount (float): Discount factor.
rollout_agent_class (type): Ag... | Basic rate_new_leaves_fn based on rollouts with an Agent. | [
"Basic",
"rate_new_leaves_fn",
"based",
"on",
"rollouts",
"with",
"an",
"Agent",
"."
] | def rate_new_leaves_with_rollouts(
leaf,
observation,
model,
discount,
rollout_agent_class=core.RandomAgent,
rollout_time_limit=100,
):
del leaf
agent = rollout_agent_class(model.action_space)
init_state = model.clone_state()
child_ratings = []
for init_action in range(model.... | [
"def",
"rate_new_leaves_with_rollouts",
"(",
"leaf",
",",
"observation",
",",
"model",
",",
"discount",
",",
"rollout_agent_class",
"=",
"core",
".",
"RandomAgent",
",",
"rollout_time_limit",
"=",
"100",
",",
")",
":",
"del",
"leaf",
"agent",
"=",
"rollout_agent... | Basic rate_new_leaves_fn based on rollouts with an Agent. | [
"Basic",
"rate_new_leaves_fn",
"based",
"on",
"rollouts",
"with",
"an",
"Agent",
"."
] | [
"\"\"\"Basic rate_new_leaves_fn based on rollouts with an Agent.\n\n Args:\n leaf (TreeNode): Node whose children are to be rated.\n observation (np.ndarray): Observation received at leaf.\n model (gym.Env): Model environment.\n discount (float): Discount factor.\n rollout_agen... | [
{
"param": "leaf",
"type": null
},
{
"param": "observation",
"type": null
},
{
"param": "model",
"type": null
},
{
"param": "discount",
"type": null
},
{
"param": "rollout_agent_class",
"type": null
},
{
"param": "rollout_time_limit",
"type": null
... | {
"returns": [
{
"docstring": "Network prediction requests.",
"docstring_tokens": [
"Network",
"prediction",
"requests",
"."
],
"type": null
},
{
"docstring": "List of pairs (reward, value) for all actions played from leaf.",
"docstring_t... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | init_graph_node | null | def init_graph_node(self, graph_node=None):
"""Assigns the node's GraphNode, or creates a new one."""
assert self._graph_node is None, 'Graph node initialized twice.'
if graph_node is None:
graph_node = GraphNode(self._init_value)
self._graph_node = graph_node | Assigns the node's GraphNode, or creates a new one. | Assigns the node's GraphNode, or creates a new one. | [
"Assigns",
"the",
"node",
"'",
"s",
"GraphNode",
"or",
"creates",
"a",
"new",
"one",
"."
] | def init_graph_node(self, graph_node=None):
assert self._graph_node is None, 'Graph node initialized twice.'
if graph_node is None:
graph_node = GraphNode(self._init_value)
self._graph_node = graph_node | [
"def",
"init_graph_node",
"(",
"self",
",",
"graph_node",
"=",
"None",
")",
":",
"assert",
"self",
".",
"_graph_node",
"is",
"None",
",",
"'Graph node initialized twice.'",
"if",
"graph_node",
"is",
"None",
":",
"graph_node",
"=",
"GraphNode",
"(",
"self",
"."... | Assigns the node's GraphNode, or creates a new one. | [
"Assigns",
"the",
"node",
"'",
"s",
"GraphNode",
"or",
"creates",
"a",
"new",
"one",
"."
] | [
"\"\"\"Assigns the node's GraphNode, or creates a new one.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "graph_node",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "graph_node",
"type": null,
"docstring": null,
"docstring_toke... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | visit | null | def visit(self, reward, value):
"""Records a visit in the node during backpropagation.
Args:
reward (float): Reward collected when stepping into the node.
value (float or None): Value accumulated on the path out of the
node, or None if value should not be accumul... | Records a visit in the node during backpropagation.
Args:
reward (float): Reward collected when stepping into the node.
value (float or None): Value accumulated on the path out of the
node, or None if value should not be accumulated.
| Records a visit in the node during backpropagation. | [
"Records",
"a",
"visit",
"in",
"the",
"node",
"during",
"backpropagation",
"."
] | def visit(self, reward, value):
self._reward_sum += reward
self._reward_count += 1
if not self.is_terminal and value is not None:
assert self.graph_node is not None, (
'Graph node must be assigned first.'
)
self.graph_node.visit(value) | [
"def",
"visit",
"(",
"self",
",",
"reward",
",",
"value",
")",
":",
"self",
".",
"_reward_sum",
"+=",
"reward",
"self",
".",
"_reward_count",
"+=",
"1",
"if",
"not",
"self",
".",
"is_terminal",
"and",
"value",
"is",
"not",
"None",
":",
"assert",
"self"... | Records a visit in the node during backpropagation. | [
"Records",
"a",
"visit",
"in",
"the",
"node",
"during",
"backpropagation",
"."
] | [
"\"\"\"Records a visit in the node during backpropagation.\n\n Args:\n reward (float): Reward collected when stepping into the node.\n value (float or None): Value accumulated on the path out of the\n node, or None if value should not be accumulated.\n \"\"\"",
"... | [
{
"param": "self",
"type": null
},
{
"param": "reward",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "reward",
"type": null,
"docstring": "Reward collected when stepping... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | quality | <not_specific> | def quality(self, discount):
"""Returns the quality of going into this node in the search tree.
We use it instead of value, so we can handle dense rewards.
Quality(s, a) = reward(s, a) + discount * value(s').
"""
return self._reward_sum / self._reward_count + discount * (
... | Returns the quality of going into this node in the search tree.
We use it instead of value, so we can handle dense rewards.
Quality(s, a) = reward(s, a) + discount * value(s').
| Returns the quality of going into this node in the search tree.
We use it instead of value, so we can handle dense rewards. | [
"Returns",
"the",
"quality",
"of",
"going",
"into",
"this",
"node",
"in",
"the",
"search",
"tree",
".",
"We",
"use",
"it",
"instead",
"of",
"value",
"so",
"we",
"can",
"handle",
"dense",
"rewards",
"."
] | def quality(self, discount):
return self._reward_sum / self._reward_count + discount * (
self._graph_node.value
if self._graph_node is not None else self._init_value
) | [
"def",
"quality",
"(",
"self",
",",
"discount",
")",
":",
"return",
"self",
".",
"_reward_sum",
"/",
"self",
".",
"_reward_count",
"+",
"discount",
"*",
"(",
"self",
".",
"_graph_node",
".",
"value",
"if",
"self",
".",
"_graph_node",
"is",
"not",
"None",... | Returns the quality of going into this node in the search tree. | [
"Returns",
"the",
"quality",
"of",
"going",
"into",
"this",
"node",
"in",
"the",
"search",
"tree",
"."
] | [
"\"\"\"Returns the quality of going into this node in the search tree.\n\n We use it instead of value, so we can handle dense rewards.\n Quality(s, a) = reward(s, a) + discount * value(s').\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "discount",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "discount",
"type": null,
"docstring": null,
"docstring_tokens... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | visit | null | def visit(self, value):
"""Records a visit in the node during backpropagation.
Args:
value (float): Value accumulated on the path out of the node.
"""
self._value_sum += value
self._value_count += 1 | Records a visit in the node during backpropagation.
Args:
value (float): Value accumulated on the path out of the node.
| Records a visit in the node during backpropagation. | [
"Records",
"a",
"visit",
"in",
"the",
"node",
"during",
"backpropagation",
"."
] | def visit(self, value):
self._value_sum += value
self._value_count += 1 | [
"def",
"visit",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_value_sum",
"+=",
"value",
"self",
".",
"_value_count",
"+=",
"1"
] | Records a visit in the node during backpropagation. | [
"Records",
"a",
"visit",
"in",
"the",
"node",
"during",
"backpropagation",
"."
] | [
"\"\"\"Records a visit in the node during backpropagation.\n\n Args:\n value (float): Value accumulated on the path out of the node.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": null,
"docstring": "Value accumulated on the path o... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | _choose_action | <not_specific> | def _choose_action(self, node, visited):
"""Chooses the action to take in a given node based on child qualities.
If avoid_loops is turned on, tries to avoid nodes visited on the path
from the root.
Args:
node (TreeNode): Node to choose an action from.
visited (s... | Chooses the action to take in a given node based on child qualities.
If avoid_loops is turned on, tries to avoid nodes visited on the path
from the root.
Args:
node (TreeNode): Node to choose an action from.
visited (set): Set of GraphNodes visited on the path from the ... | Chooses the action to take in a given node based on child qualities.
If avoid_loops is turned on, tries to avoid nodes visited on the path
from the root. | [
"Chooses",
"the",
"action",
"to",
"take",
"in",
"a",
"given",
"node",
"based",
"on",
"child",
"qualities",
".",
"If",
"avoid_loops",
"is",
"turned",
"on",
"tries",
"to",
"avoid",
"nodes",
"visited",
"on",
"the",
"path",
"from",
"the",
"root",
"."
] | def _choose_action(self, node, visited):
child_qualities = self._rate_children(node)
child_qualities_and_actions = zip(
child_qualities, range(len(child_qualities))
)
if self._avoid_loops:
child_graph_nodes = [child.graph_node for child in node.children]
... | [
"def",
"_choose_action",
"(",
"self",
",",
"node",
",",
"visited",
")",
":",
"child_qualities",
"=",
"self",
".",
"_rate_children",
"(",
"node",
")",
"child_qualities_and_actions",
"=",
"zip",
"(",
"child_qualities",
",",
"range",
"(",
"len",
"(",
"child_quali... | Chooses the action to take in a given node based on child qualities. | [
"Chooses",
"the",
"action",
"to",
"take",
"in",
"a",
"given",
"node",
"based",
"on",
"child",
"qualities",
"."
] | [
"\"\"\"Chooses the action to take in a given node based on child qualities.\n\n If avoid_loops is turned on, tries to avoid nodes visited on the path\n from the root.\n\n Args:\n node (TreeNode): Node to choose an action from.\n visited (set): Set of GraphNodes visited on ... | [
{
"param": "self",
"type": null
},
{
"param": "node",
"type": null
},
{
"param": "visited",
"type": null
}
] | {
"returns": [
{
"docstring": "Action to take.",
"docstring_tokens": [
"Action",
"to",
"take",
"."
],
"type": null
}
],
"raises": [
{
"docstring": "If there's no child not visited before.",
"docstring_tokens": [
"If",
... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | _traverse | <not_specific> | def _traverse(self, root, observation, path):
"""Chooses a path from the root to a leaf in the search tree.
Does not modify the nodes.
Args:
root (TreeNode): Root of the search tree.
observation (np.ndarray): Observation received at root.
path (list): Empty ... | Chooses a path from the root to a leaf in the search tree.
Does not modify the nodes.
Args:
root (TreeNode): Root of the search tree.
observation (np.ndarray): Observation received at root.
path (list): Empty list that will be filled with pairs
(rewa... | Chooses a path from the root to a leaf in the search tree.
Does not modify the nodes. | [
"Chooses",
"a",
"path",
"from",
"the",
"root",
"to",
"a",
"leaf",
"in",
"the",
"search",
"tree",
".",
"Does",
"not",
"modify",
"the",
"nodes",
"."
] | def _traverse(self, root, observation, path):
assert not path, 'Path accumulator should initially be empty.'
path.append((0, root))
visited = {root.graph_node}
node = root
done = False
visited = set()
while not node.is_leaf and not done:
action = self.... | [
"def",
"_traverse",
"(",
"self",
",",
"root",
",",
"observation",
",",
"path",
")",
":",
"assert",
"not",
"path",
",",
"'Path accumulator should initially be empty.'",
"path",
".",
"append",
"(",
"(",
"0",
",",
"root",
")",
")",
"visited",
"=",
"{",
"root"... | Chooses a path from the root to a leaf in the search tree. | [
"Chooses",
"a",
"path",
"from",
"the",
"root",
"to",
"a",
"leaf",
"in",
"the",
"search",
"tree",
"."
] | [
"\"\"\"Chooses a path from the root to a leaf in the search tree.\n\n Does not modify the nodes.\n\n Args:\n root (TreeNode): Root of the search tree.\n observation (np.ndarray): Observation received at root.\n path (list): Empty list that will be filled with pairs\n ... | [
{
"param": "self",
"type": null
},
{
"param": "root",
"type": null
},
{
"param": "observation",
"type": null
},
{
"param": "path",
"type": null
}
] | {
"returns": [
{
"docstring": "Tuple (observation, done, visited), where observation is the\nobservation received in the leaf, done is the \"done\" flag received\nwhen stepping into the leaf and visited is a set of GraphNodes\nvisited on the path. In case of a \"done\", traversal is interrupted.",
"do... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | _expand_leaf | <not_specific> | def _expand_leaf(self, leaf, observation, done, visited):
"""Expands a leaf and returns its quality.
The leaf's new children are assigned initial rewards and values. The
reward and value of the "best" new leaf is then backpropagated.
Only modifies leaf - assigns a GraphNode and adds ch... | Expands a leaf and returns its quality.
The leaf's new children are assigned initial rewards and values. The
reward and value of the "best" new leaf is then backpropagated.
Only modifies leaf - assigns a GraphNode and adds children.
Args:
leaf (TreeNode): Leaf to expand.
... | Expands a leaf and returns its quality.
The leaf's new children are assigned initial rewards and values. The
reward and value of the "best" new leaf is then backpropagated.
Only modifies leaf - assigns a GraphNode and adds children. | [
"Expands",
"a",
"leaf",
"and",
"returns",
"its",
"quality",
".",
"The",
"leaf",
"'",
"s",
"new",
"children",
"are",
"assigned",
"initial",
"rewards",
"and",
"values",
".",
"The",
"reward",
"and",
"value",
"of",
"the",
"\"",
"best",
"\"",
"new",
"leaf",
... | def _expand_leaf(self, leaf, observation, done, visited):
assert leaf.is_leaf
if done:
leaf.is_terminal = True
return 0
already_in_graph = False
if self._graph_mode:
state = self._model.clone_state()
graph_node = self._state_to_graph_node.g... | [
"def",
"_expand_leaf",
"(",
"self",
",",
"leaf",
",",
"observation",
",",
"done",
",",
"visited",
")",
":",
"assert",
"leaf",
".",
"is_leaf",
"if",
"done",
":",
"leaf",
".",
"is_terminal",
"=",
"True",
"return",
"0",
"already_in_graph",
"=",
"False",
"if... | Expands a leaf and returns its quality. | [
"Expands",
"a",
"leaf",
"and",
"returns",
"its",
"quality",
"."
] | [
"\"\"\"Expands a leaf and returns its quality.\n\n The leaf's new children are assigned initial rewards and values. The\n reward and value of the \"best\" new leaf is then backpropagated.\n\n Only modifies leaf - assigns a GraphNode and adds children.\n\n Args:\n leaf (TreeNod... | [
{
"param": "self",
"type": null
},
{
"param": "leaf",
"type": null
},
{
"param": "observation",
"type": null
},
{
"param": "done",
"type": null
},
{
"param": "visited",
"type": null
}
] | {
"returns": [
{
"docstring": "Network prediction requests.",
"docstring_tokens": [
"Network",
"prediction",
"requests",
"."
],
"type": null
},
{
"docstring": "Quality of a chosen child of the expanded leaf, or None if we\nshouldn't backpropaga... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | _backpropagate | null | def _backpropagate(self, value, path):
"""Backpropagates value to the root through path.
Only modifies the rewards and values of nodes on the path.
Args:
value (float or None): Value collected at the leaf, or None if value
should not be backpropagated.
p... | Backpropagates value to the root through path.
Only modifies the rewards and values of nodes on the path.
Args:
value (float or None): Value collected at the leaf, or None if value
should not be backpropagated.
path (list): List of (reward, node) pairs, describi... | Backpropagates value to the root through path.
Only modifies the rewards and values of nodes on the path. | [
"Backpropagates",
"value",
"to",
"the",
"root",
"through",
"path",
".",
"Only",
"modifies",
"the",
"rewards",
"and",
"values",
"of",
"nodes",
"on",
"the",
"path",
"."
] | def _backpropagate(self, value, path):
for (reward, node) in reversed(path):
node.visit(reward, value)
if value is not None:
value = reward + self._discount * value | [
"def",
"_backpropagate",
"(",
"self",
",",
"value",
",",
"path",
")",
":",
"for",
"(",
"reward",
",",
"node",
")",
"in",
"reversed",
"(",
"path",
")",
":",
"node",
".",
"visit",
"(",
"reward",
",",
"value",
")",
"if",
"value",
"is",
"not",
"None",
... | Backpropagates value to the root through path. | [
"Backpropagates",
"value",
"to",
"the",
"root",
"through",
"path",
"."
] | [
"\"\"\"Backpropagates value to the root through path.\n\n Only modifies the rewards and values of nodes on the path.\n\n Args:\n value (float or None): Value collected at the leaf, or None if value\n should not be backpropagated.\n path (list): List of (reward, nod... | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
},
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "value",
"type": null,
"docstring": "Value collected at the leaf, or... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | _run_pass | null | def _run_pass(self, root, observation):
"""Runs a pass of MCTS.
A pass consists of:
1. Tree traversal to find a leaf.
2. Expansion of the leaf, adding its successor states to the tree
and rating them.
3. Backpropagation of the value of the best child o... | Runs a pass of MCTS.
A pass consists of:
1. Tree traversal to find a leaf.
2. Expansion of the leaf, adding its successor states to the tree
and rating them.
3. Backpropagation of the value of the best child of the old leaf.
During leaf expansion, new... | Runs a pass of MCTS.
A pass consists of:
1. Tree traversal to find a leaf.
2. Expansion of the leaf, adding its successor states to the tree
and rating them.
3. Backpropagation of the value of the best child of the old leaf.
During leaf expansion, new children are rated only using
the rate_new_leaves_fn - no actual st... | [
"Runs",
"a",
"pass",
"of",
"MCTS",
".",
"A",
"pass",
"consists",
"of",
":",
"1",
".",
"Tree",
"traversal",
"to",
"find",
"a",
"leaf",
".",
"2",
".",
"Expansion",
"of",
"the",
"leaf",
"adding",
"its",
"successor",
"states",
"to",
"the",
"tree",
"and",... | def _run_pass(self, root, observation):
path = []
try:
(observation, done, visited) = self._traverse(
root, observation, path
)
(_, leaf) = path[-1]
quality = yield from self._expand_leaf(
leaf, observation, done, visited
... | [
"def",
"_run_pass",
"(",
"self",
",",
"root",
",",
"observation",
")",
":",
"path",
"=",
"[",
"]",
"try",
":",
"(",
"observation",
",",
"done",
",",
"visited",
")",
"=",
"self",
".",
"_traverse",
"(",
"root",
",",
"observation",
",",
"path",
")",
"... | Runs a pass of MCTS. | [
"Runs",
"a",
"pass",
"of",
"MCTS",
"."
] | [
"\"\"\"Runs a pass of MCTS.\n\n A pass consists of:\n 1. Tree traversal to find a leaf.\n 2. Expansion of the leaf, adding its successor states to the tree\n and rating them.\n 3. Backpropagation of the value of the best child of the old leaf.\n\n During ... | [
{
"param": "self",
"type": null
},
{
"param": "root",
"type": null
},
{
"param": "observation",
"type": null
}
] | {
"returns": [
{
"docstring": "Network prediction requests.",
"docstring_tokens": [
"Network",
"prediction",
"requests",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": nul... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | reset | null | def reset(self, env, observation):
"""Reinitializes the search tree for a new environment."""
del observation
assert env.action_space == self._action_space
self._model = env
# Initialize root with some reward to avoid division by zero.
self._root = TreeNode(init_reward=0)... | Reinitializes the search tree for a new environment. | Reinitializes the search tree for a new environment. | [
"Reinitializes",
"the",
"search",
"tree",
"for",
"a",
"new",
"environment",
"."
] | def reset(self, env, observation):
del observation
assert env.action_space == self._action_space
self._model = env
self._root = TreeNode(init_reward=0)
self._real_visited = set() | [
"def",
"reset",
"(",
"self",
",",
"env",
",",
"observation",
")",
":",
"del",
"observation",
"assert",
"env",
".",
"action_space",
"==",
"self",
".",
"_action_space",
"self",
".",
"_model",
"=",
"env",
"self",
".",
"_root",
"=",
"TreeNode",
"(",
"init_re... | Reinitializes the search tree for a new environment. | [
"Reinitializes",
"the",
"search",
"tree",
"for",
"a",
"new",
"environment",
"."
] | [
"\"\"\"Reinitializes the search tree for a new environment.\"\"\"",
"# Initialize root with some reward to avoid division by zero."
] | [
{
"param": "self",
"type": null
},
{
"param": "env",
"type": null
},
{
"param": "observation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "env",
"type": null,
"docstring": null,
"docstring_tokens": []... |
38f27e3fd35e2971cf1e49667a03752e571ec3e9 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/stochastic_mcts.py | [
"MIT"
] | Python | act | <not_specific> | def act(self, observation):
"""Runs n_passes MCTS passes and chooses the best action."""
assert self._model is not None, (
'MCTSAgent works only in model-based mode.'
)
self._root_state = self._model.clone_state()
for _ in range(self.n_passes):
yield from ... | Runs n_passes MCTS passes and chooses the best action. | Runs n_passes MCTS passes and chooses the best action. | [
"Runs",
"n_passes",
"MCTS",
"passes",
"and",
"chooses",
"the",
"best",
"action",
"."
] | def act(self, observation):
assert self._model is not None, (
'MCTSAgent works only in model-based mode.'
)
self._root_state = self._model.clone_state()
for _ in range(self.n_passes):
yield from self._run_pass(self._root, observation)
self._real_visited.ad... | [
"def",
"act",
"(",
"self",
",",
"observation",
")",
":",
"assert",
"self",
".",
"_model",
"is",
"not",
"None",
",",
"(",
"'MCTSAgent works only in model-based mode.'",
")",
"self",
".",
"_root_state",
"=",
"self",
".",
"_model",
".",
"clone_state",
"(",
")",... | Runs n_passes MCTS passes and chooses the best action. | [
"Runs",
"n_passes",
"MCTS",
"passes",
"and",
"chooses",
"the",
"best",
"action",
"."
] | [
"\"\"\"Runs n_passes MCTS passes and chooses the best action.\"\"\"",
"# Add the root to visited nodes after running the MCTS passes to ensure",
"# it has a graph node assigned.",
"# Avoid the nodes already visited on the path in the real",
"# environment when choosing an action."
] | [
{
"param": "self",
"type": null
},
{
"param": "observation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "observation",
"type": null,
"docstring": null,
"docstring_tok... |
c9ef1a83b1e82da1c68bed77b30f9bb28b296a80 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/abstract_observation.py | [
"MIT"
] | Python | recreate_state | <not_specific> | def recreate_state(self):
"""Loads observation and return a current_state that agrees with the observation. Warning: this method is ambiguous,
that is, many states can have the same observation (they may differ in the order of hidden cards)."""
state = State(all_cards=StochasticObservation.all_c... | Loads observation and return a current_state that agrees with the observation. Warning: this method is ambiguous,
that is, many states can have the same observation (they may differ in the order of hidden cards). | Loads observation and return a current_state that agrees with the observation. Warning: this method is ambiguous,
that is, many states can have the same observation (they may differ in the order of hidden cards). | [
"Loads",
"observation",
"and",
"return",
"a",
"current_state",
"that",
"agrees",
"with",
"the",
"observation",
".",
"Warning",
":",
"this",
"method",
"is",
"ambiguous",
"that",
"is",
"many",
"states",
"can",
"have",
"the",
"same",
"observation",
"(",
"they",
... | def recreate_state(self):
state = State(all_cards=StochasticObservation.all_cards, all_nobles=StochasticObservation.all_nobles, prepare_state=False)
cards_on_board_names = self.observation_dict['cards_on_board_names']
nobles_on_board_names = self.observation_dict['nobles_on_board_names']
... | [
"def",
"recreate_state",
"(",
"self",
")",
":",
"state",
"=",
"State",
"(",
"all_cards",
"=",
"StochasticObservation",
".",
"all_cards",
",",
"all_nobles",
"=",
"StochasticObservation",
".",
"all_nobles",
",",
"prepare_state",
"=",
"False",
")",
"cards_on_board_na... | Loads observation and return a current_state that agrees with the observation. | [
"Loads",
"observation",
"and",
"return",
"a",
"current_state",
"that",
"agrees",
"with",
"the",
"observation",
"."
] | [
"\"\"\"Loads observation and return a current_state that agrees with the observation. Warning: this method is ambiguous,\n that is, many states can have the same observation (they may differ in the order of hidden cards).\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d057b0de5563b94569c2c9d43017a3f2e7dd9a97 | TomaszOdrzygozdz/gym-splendor | nn_models/dense_q_model_v0.py | [
"MIT"
] | Python | create_network | None | def create_network(self, input_size : int = 597, layers_list : List[int] = [600, 600, 600, 600]) -> None:
'''
This method creates network with a specific architecture
:return:
'''
self.set_corrent_session()
entries = Input(shape=(input_size,))
for i, layer_size i... |
This method creates network with a specific architecture
:return:
| This method creates network with a specific architecture | [
"This",
"method",
"creates",
"network",
"with",
"a",
"specific",
"architecture"
] | def create_network(self, input_size : int = 597, layers_list : List[int] = [600, 600, 600, 600]) -> None:
self.set_corrent_session()
entries = Input(shape=(input_size,))
for i, layer_size in enumerate(layers_list):
print(layer_size)
if i == 0:
data_flow = ... | [
"def",
"create_network",
"(",
"self",
",",
"input_size",
":",
"int",
"=",
"597",
",",
"layers_list",
":",
"List",
"[",
"int",
"]",
"=",
"[",
"600",
",",
"600",
",",
"600",
",",
"600",
"]",
")",
"->",
"None",
":",
"self",
".",
"set_corrent_session",
... | This method creates network with a specific architecture | [
"This",
"method",
"creates",
"network",
"with",
"a",
"specific",
"architecture"
] | [
"'''\n This method creates network with a specific architecture\n :return:\n '''",
"# Pass the file handle in as a lambda function to make it callable"
] | [
{
"param": "self",
"type": null
},
{
"param": "input_size",
"type": "int"
},
{
"param": "layers_list",
"type": "List[int]"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
1c56604204cbbd9a167cc386601a403cf9779c40 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/graphics/splendor_gui.py | [
"MIT"
] | Python | draw_card | None | def draw_card(self,
card: Card,
x_coord: int,
y_coord: int,
draw_buy_button: bool,
draw_reserve_button: bool,
state: State) -> None:
"""Draws a card in the main window.
... | Draws a card in the main window.
Parameters:
_ _ _ _ _ _
card: Card to draw.
x_coord: Horizontal coordinate (from top left corner)
y_coord: Vertical coordinate (from top left corner)
draw_buy_button: Determines if create a buy action button associ... | Draws a card in the main window.
Parameters:
card: Card to draw.
x_coord: Horizontal coordinate (from top left corner)
y_coord: Vertical coordinate (from top left corner)
draw_buy_button: Determines if create a buy action button associated with this card.
draw_reserve_button: Determines if create a reserve action butto... | [
"Draws",
"a",
"card",
"in",
"the",
"main",
"window",
".",
"Parameters",
":",
"card",
":",
"Card",
"to",
"draw",
".",
"x_coord",
":",
"Horizontal",
"coordinate",
"(",
"from",
"top",
"left",
"corner",
")",
"y_coord",
":",
"Vertical",
"coordinate",
"(",
"fr... | def draw_card(self,
card: Card,
x_coord: int,
y_coord: int,
draw_buy_button: bool,
draw_reserve_button: bool,
state: State) -> None:
self.main_canvas.create_rectangle(x_coord, ... | [
"def",
"draw_card",
"(",
"self",
",",
"card",
":",
"Card",
",",
"x_coord",
":",
"int",
",",
"y_coord",
":",
"int",
",",
"draw_buy_button",
":",
"bool",
",",
"draw_reserve_button",
":",
"bool",
",",
"state",
":",
"State",
")",
"->",
"None",
":",
"self",... | Draws a card in the main window. | [
"Draws",
"a",
"card",
"in",
"the",
"main",
"window",
"."
] | [
"\"\"\"Draws a card in the main window.\n\n Parameters:\n _ _ _ _ _ _\n card: Card to draw.\n x_coord: Horizontal coordinate (from top left corner)\n y_coord: Vertical coordinate (from top left corner)\n draw_buy_button: Determines if create a buy ac... | [
{
"param": "self",
"type": null
},
{
"param": "card",
"type": "Card"
},
{
"param": "x_coord",
"type": "int"
},
{
"param": "y_coord",
"type": "int"
},
{
"param": "draw_buy_button",
"type": "bool"
},
{
"param": "draw_reserve_button",
"type": "bool"
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "card",
"type": "Card",
"docstring": null,
"docstring_tokens":... |
1c56604204cbbd9a167cc386601a403cf9779c40 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/graphics/splendor_gui.py | [
"MIT"
] | Python | draw_noble | None | def draw_noble(self,
noble: Noble,
x_coord: int,
y_coord: int) -> None:
"""Draws a noble in the main window.
Parameters:
_ _ _ _ _ _
card: Card to draw.
x_coo... | Draws a noble in the main window.
Parameters:
_ _ _ _ _ _
card: Card to draw.
x_coord: Horizontal coordinate (from top left corner)
y_coord: Vertical coordinate (from top left corner)
draw_buy_button... | Draws a noble in the main window.
Parameters:
card: Card to draw.
x_coord: Horizontal coordinate (from top left corner)
y_coord: Vertical coordinate (from top left corner)
draw_buy_button: Determines if create a buy action button associated with this card.
draw_reserve_button: Determines if create a reserve action butt... | [
"Draws",
"a",
"noble",
"in",
"the",
"main",
"window",
".",
"Parameters",
":",
"card",
":",
"Card",
"to",
"draw",
".",
"x_coord",
":",
"Horizontal",
"coordinate",
"(",
"from",
"top",
"left",
"corner",
")",
"y_coord",
":",
"Vertical",
"coordinate",
"(",
"f... | def draw_noble(self,
noble: Noble,
x_coord: int,
y_coord: int) -> None:
self.main_canvas.create_rectangle(x_coord, y_coord, x_coord + NOBLE_WIDTH,
y_coord + NOBLE_HEIGHT)
for positi... | [
"def",
"draw_noble",
"(",
"self",
",",
"noble",
":",
"Noble",
",",
"x_coord",
":",
"int",
",",
"y_coord",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"main_canvas",
".",
"create_rectangle",
"(",
"x_coord",
",",
"y_coord",
",",
"x_coord",
"+",
"NOB... | Draws a noble in the main window. | [
"Draws",
"a",
"noble",
"in",
"the",
"main",
"window",
"."
] | [
"\"\"\"Draws a noble in the main window.\n\n Parameters:\n _ _ _ _ _ _\n card: Card to draw.\n x_coord: Horizontal coordinate (from top left corner)\n y_coord: Vertical coordinate (from top left corner)\n ... | [
{
"param": "self",
"type": null
},
{
"param": "noble",
"type": "Noble"
},
{
"param": "x_coord",
"type": "int"
},
{
"param": "y_coord",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "noble",
"type": "Noble",
"docstring": null,
"docstring_tokens... |
1c56604204cbbd9a167cc386601a403cf9779c40 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/graphics/splendor_gui.py | [
"MIT"
] | Python | draw_board | None | def draw_board(self,
board: Board,
x_coord: int,
y_coord: int,
state: State) -> None:
"""Draws the board, that is: cards that lie on the table, nobles that lie on the table and coins.
Parameters:
... | Draws the board, that is: cards that lie on the table, nobles that lie on the table and coins.
Parameters:
_ _ _ _ _ _
board: Board to draw.
x_coord: Horizontal coordinate (from left top corner).
y_coord: Vertical coordinate (from left top corner).
... | Draws the board, that is: cards that lie on the table, nobles that lie on the table and coins.
Parameters:
board: Board to draw.
x_coord: Horizontal coordinate (from left top corner).
y_coord: Vertical coordinate (from left top corner).
active_players_hand: The hand of the player that is currently active. This argument... | [
"Draws",
"the",
"board",
"that",
"is",
":",
"cards",
"that",
"lie",
"on",
"the",
"table",
"nobles",
"that",
"lie",
"on",
"the",
"table",
"and",
"coins",
".",
"Parameters",
":",
"board",
":",
"Board",
"to",
"draw",
".",
"x_coord",
":",
"Horizontal",
"co... | def draw_board(self,
board: Board,
x_coord: int,
y_coord: int,
state: State) -> None:
self.board_x_ccord = x_coord
self.board_y_ccord = y_coord
self.main_canvas.create_text(x_coord + BOARD_TIT... | [
"def",
"draw_board",
"(",
"self",
",",
"board",
":",
"Board",
",",
"x_coord",
":",
"int",
",",
"y_coord",
":",
"int",
",",
"state",
":",
"State",
")",
"->",
"None",
":",
"self",
".",
"board_x_ccord",
"=",
"x_coord",
"self",
".",
"board_y_ccord",
"=",
... | Draws the board, that is: cards that lie on the table, nobles that lie on the table and coins. | [
"Draws",
"the",
"board",
"that",
"is",
":",
"cards",
"that",
"lie",
"on",
"the",
"table",
"nobles",
"that",
"lie",
"on",
"the",
"table",
"and",
"coins",
"."
] | [
"\"\"\"Draws the board, that is: cards that lie on the table, nobles that lie on the table and coins.\n Parameters:\n _ _ _ _ _ _\n board: Board to draw.\n x_coord: Horizontal coordinate (from left top corner).\n y_coord: Vertical coordinate (from left top corn... | [
{
"param": "self",
"type": null
},
{
"param": "board",
"type": "Board"
},
{
"param": "x_coord",
"type": "int"
},
{
"param": "y_coord",
"type": "int"
},
{
"param": "state",
"type": "State"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "board",
"type": "Board",
"docstring": null,
"docstring_tokens... |
1c56604204cbbd9a167cc386601a403cf9779c40 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/graphics/splendor_gui.py | [
"MIT"
] | Python | draw_players_hand | None | def draw_players_hand(self,
players_hand: PlayersHand,
x_coord: int,
y_coord: int,
active: bool,
state: State) -> None:
"""Draws a players hands in a given po... | Draws a players hands in a given position.
Parameters:
_ _ _ _ _ _
players_hand: A players hand to draw.
x_coord: Horizontal coordinate (from left top corner).
y_coord: Vertical coordinate (from left top corner).
draw_reserved_buttons: Determines i... | Draws a players hands in a given position.
Parameters:
players_hand: A players hand to draw.
x_coord: Horizontal coordinate (from left top corner).
y_coord: Vertical coordinate (from left top corner).
draw_reserved_buttons: Determines if draw action buy reserved button on reserved cards. | [
"Draws",
"a",
"players",
"hands",
"in",
"a",
"given",
"position",
".",
"Parameters",
":",
"players_hand",
":",
"A",
"players",
"hand",
"to",
"draw",
".",
"x_coord",
":",
"Horizontal",
"coordinate",
"(",
"from",
"left",
"top",
"corner",
")",
".",
"y_coord",... | def draw_players_hand(self,
players_hand: PlayersHand,
x_coord: int,
y_coord: int,
active: bool,
state: State) -> None:
if active:
players_nam... | [
"def",
"draw_players_hand",
"(",
"self",
",",
"players_hand",
":",
"PlayersHand",
",",
"x_coord",
":",
"int",
",",
"y_coord",
":",
"int",
",",
"active",
":",
"bool",
",",
"state",
":",
"State",
")",
"->",
"None",
":",
"if",
"active",
":",
"players_name_f... | Draws a players hands in a given position. | [
"Draws",
"a",
"players",
"hands",
"in",
"a",
"given",
"position",
"."
] | [
"\"\"\"Draws a players hands in a given position.\n Parameters:\n _ _ _ _ _ _\n players_hand: A players hand to draw.\n x_coord: Horizontal coordinate (from left top corner).\n y_coord: Vertical coordinate (from left top corner).\n draw_reserved_butt... | [
{
"param": "self",
"type": null
},
{
"param": "players_hand",
"type": "PlayersHand"
},
{
"param": "x_coord",
"type": "int"
},
{
"param": "y_coord",
"type": "int"
},
{
"param": "active",
"type": "bool"
},
{
"param": "state",
"type": "State"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "players_hand",
"type": "PlayersHand",
"docstring": null,
"doc... |
b021e6765a152fe6b03d79dc60872674deb47e5b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/shooting_test.py | [
"MIT"
] | Python | construct_episodes | <not_specific> | def construct_episodes(actions, rewards):
"""Constructs episodes from actions and rewards nested lists."""
episodes = []
for acts, rews in zip(actions, rewards):
transitions = [
# TODO(koz4k): Initialize using kwargs.
data.Transition(None, act, rew, False, None, {})
... | Constructs episodes from actions and rewards nested lists. | Constructs episodes from actions and rewards nested lists. | [
"Constructs",
"episodes",
"from",
"actions",
"and",
"rewards",
"nested",
"lists",
"."
] | def construct_episodes(actions, rewards):
episodes = []
for acts, rews in zip(actions, rewards):
transitions = [
data.Transition(None, act, rew, False, None, {})
for act, rew in zip(acts[:-1], rews[:-1])]
transitions.append(
data.Transition(None, acts[-1], rew... | [
"def",
"construct_episodes",
"(",
"actions",
",",
"rewards",
")",
":",
"episodes",
"=",
"[",
"]",
"for",
"acts",
",",
"rews",
"in",
"zip",
"(",
"actions",
",",
"rewards",
")",
":",
"transitions",
"=",
"[",
"data",
".",
"Transition",
"(",
"None",
",",
... | Constructs episodes from actions and rewards nested lists. | [
"Constructs",
"episodes",
"from",
"actions",
"and",
"rewards",
"nested",
"lists",
"."
] | [
"\"\"\"Constructs episodes from actions and rewards nested lists.\"\"\"",
"# TODO(koz4k): Initialize using kwargs."
] | [
{
"param": "actions",
"type": null
},
{
"param": "rewards",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "actions",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "rewards",
"type": null,
"docstring": null,
"docstring_toke... |
b021e6765a152fe6b03d79dc60872674deb47e5b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/agents/shooting_test.py | [
"MIT"
] | Python | mock_bstep_class | <not_specific> | def mock_bstep_class():
"""Mock batch stepper class with fixed run_episode_batch return."""
bstep_cls = mock.create_autospec(batch_steppers.LocalBatchStepper)
bstep_cls.return_value.run_episode_batch.return_value = construct_episodes(
actions=[
[0], [0], [0], # Three first episodes acti... | Mock batch stepper class with fixed run_episode_batch return. | Mock batch stepper class with fixed run_episode_batch return. | [
"Mock",
"batch",
"stepper",
"class",
"with",
"fixed",
"run_episode_batch",
"return",
"."
] | def mock_bstep_class():
bstep_cls = mock.create_autospec(batch_steppers.LocalBatchStepper)
bstep_cls.return_value.run_episode_batch.return_value = construct_episodes(
actions=[
[0], [0], [0],
[1], [1], [1],
],
rewards=[
[1], [1], [1],
... | [
"def",
"mock_bstep_class",
"(",
")",
":",
"bstep_cls",
"=",
"mock",
".",
"create_autospec",
"(",
"batch_steppers",
".",
"LocalBatchStepper",
")",
"bstep_cls",
".",
"return_value",
".",
"run_episode_batch",
".",
"return_value",
"=",
"construct_episodes",
"(",
"action... | Mock batch stepper class with fixed run_episode_batch return. | [
"Mock",
"batch",
"stepper",
"class",
"with",
"fixed",
"run_episode_batch",
"return",
"."
] | [
"\"\"\"Mock batch stepper class with fixed run_episode_batch return.\"\"\"",
"# Three first episodes action 0",
"# Three last episodes action 1",
"# Higher mean, action 0",
"# Higher max, action 1"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
c328b7191119cde35fc83cb72b8fad334e44ef17 | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/players_hand.py | [
"MIT"
] | Python | can_afford_card | bool | def can_afford_card(self,
card: Card,
discount: GemsCollection = None) -> bool:
"""Returns true if players_hand can afford card"""
if discount is None:
discount = self.discount()
price_after_discount = card.price % discount
trad... | Returns true if players_hand can afford card | Returns true if players_hand can afford card | [
"Returns",
"true",
"if",
"players_hand",
"can",
"afford",
"card"
] | def can_afford_card(self,
card: Card,
discount: GemsCollection = None) -> bool:
if discount is None:
discount = self.discount()
price_after_discount = card.price % discount
trade = [a - b for a, b in zip(price_after_discount.to_dict(), ... | [
"def",
"can_afford_card",
"(",
"self",
",",
"card",
":",
"Card",
",",
"discount",
":",
"GemsCollection",
"=",
"None",
")",
"->",
"bool",
":",
"if",
"discount",
"is",
"None",
":",
"discount",
"=",
"self",
".",
"discount",
"(",
")",
"price_after_discount",
... | Returns true if players_hand can afford card | [
"Returns",
"true",
"if",
"players_hand",
"can",
"afford",
"card"
] | [
"\"\"\"Returns true if players_hand can afford card\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "card",
"type": "Card"
},
{
"param": "discount",
"type": "GemsCollection"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "card",
"type": "Card",
"docstring": null,
"docstring_tokens":... |
ebb16317904fe5494f7b8afbd10dc329a3234b76 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/utils/mrunner_client.py | [
"MIT"
] | Python | configure_neptune | <not_specific> | def configure_neptune(specification):
"""Configures the Neptune experiment, then returns the Neptune logger."""
if 'NEPTUNE_API_TOKEN' not in os.environ:
raise KeyError('NEPTUNE_API_TOKEN environment variable is not set!')
git_info = specification.get('git_info', None)
if git_info:
git_... | Configures the Neptune experiment, then returns the Neptune logger. | Configures the Neptune experiment, then returns the Neptune logger. | [
"Configures",
"the",
"Neptune",
"experiment",
"then",
"returns",
"the",
"Neptune",
"logger",
"."
] | def configure_neptune(specification):
if 'NEPTUNE_API_TOKEN' not in os.environ:
raise KeyError('NEPTUNE_API_TOKEN environment variable is not set!')
git_info = specification.get('git_info', None)
if git_info:
git_info.commit_date = datetime.datetime.now()
neptune.init(project_qualified_n... | [
"def",
"configure_neptune",
"(",
"specification",
")",
":",
"if",
"'NEPTUNE_API_TOKEN'",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"KeyError",
"(",
"'NEPTUNE_API_TOKEN environment variable is not set!'",
")",
"git_info",
"=",
"specification",
".",
"get",
"(",
... | Configures the Neptune experiment, then returns the Neptune logger. | [
"Configures",
"the",
"Neptune",
"experiment",
"then",
"returns",
"the",
"Neptune",
"logger",
"."
] | [
"\"\"\"Configures the Neptune experiment, then returns the Neptune logger.\"\"\"",
"# Set pwd property with path to experiment."
] | [
{
"param": "specification",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "specification",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
47befba955d139845d683ef02db9cd3dae9c057b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/data/ops.py | [
"MIT"
] | Python | nested_zip | <not_specific> | def nested_zip(xs):
"""Zips a list of pytrees.
Inverse of nested_unzip.
Example:
nested_zip([((1, 2), 3), ((4, 5), 6)]) == (([1, 4], [2, 5]), [3, 6])
"""
assert not _is_leaf(xs)
assert xs
if not _is_leaf(xs[0]):
# Assert that the first levels of the zipped trees are the sam... | Zips a list of pytrees.
Inverse of nested_unzip.
Example:
nested_zip([((1, 2), 3), ((4, 5), 6)]) == (([1, 4], [2, 5]), [3, 6])
| Zips a list of pytrees. | [
"Zips",
"a",
"list",
"of",
"pytrees",
"."
] | def nested_zip(xs):
assert not _is_leaf(xs)
assert xs
if not _is_leaf(xs[0]):
for x in xs:
assert type(x) is type(xs[0]), (
'Cannot zip pytrees of different types: '
'{} and {}.'.format(type(x), type(xs[0]))
)
if _is_namedtuple_instance(xs[... | [
"def",
"nested_zip",
"(",
"xs",
")",
":",
"assert",
"not",
"_is_leaf",
"(",
"xs",
")",
"assert",
"xs",
"if",
"not",
"_is_leaf",
"(",
"xs",
"[",
"0",
"]",
")",
":",
"for",
"x",
"in",
"xs",
":",
"assert",
"type",
"(",
"x",
")",
"is",
"type",
"(",... | Zips a list of pytrees. | [
"Zips",
"a",
"list",
"of",
"pytrees",
"."
] | [
"\"\"\"Zips a list of pytrees.\n\n Inverse of nested_unzip.\n\n Example:\n nested_zip([((1, 2), 3), ((4, 5), 6)]) == (([1, 4], [2, 5]), [3, 6])\n \"\"\"",
"# Assert that the first levels of the zipped trees are the same."
] | [
{
"param": "xs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "xs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "examples",
"docstring": null,
... |
47befba955d139845d683ef02db9cd3dae9c057b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/data/ops.py | [
"MIT"
] | Python | is_last_level | <not_specific> | def is_last_level(x):
"""Returns whether pytree is at the last level (children are leaves)."""
if _is_leaf(x):
return False
if isinstance(x, dict):
vs = x.values()
else:
vs = x
return all(map(_is_leaf, vs)) | Returns whether pytree is at the last level (children are leaves). | Returns whether pytree is at the last level (children are leaves). | [
"Returns",
"whether",
"pytree",
"is",
"at",
"the",
"last",
"level",
"(",
"children",
"are",
"leaves",
")",
"."
] | def is_last_level(x):
if _is_leaf(x):
return False
if isinstance(x, dict):
vs = x.values()
else:
vs = x
return all(map(_is_leaf, vs)) | [
"def",
"is_last_level",
"(",
"x",
")",
":",
"if",
"_is_leaf",
"(",
"x",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"vs",
"=",
"x",
".",
"values",
"(",
")",
"else",
":",
"vs",
"=",
"x",
"return",
"all",
"("... | Returns whether pytree is at the last level (children are leaves). | [
"Returns",
"whether",
"pytree",
"is",
"at",
"the",
"last",
"level",
"(",
"children",
"are",
"leaves",
")",
"."
] | [
"\"\"\"Returns whether pytree is at the last level (children are leaves).\"\"\""
] | [
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
47befba955d139845d683ef02db9cd3dae9c057b | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/data/ops.py | [
"MIT"
] | Python | nested_unzip | <not_specific> | def nested_unzip(x):
"""Uzips a pytree of lists.
Inverse of nested_unzip.
Example:
nested_unzip((([1, 4], [2, 5]), [3, 6])) == [((1, 2), 3), ((4, 5), 6)]
"""
acc = []
try:
i = 0
while True:
acc.append(nested_map(
lambda l: l[i],
... | Uzips a pytree of lists.
Inverse of nested_unzip.
Example:
nested_unzip((([1, 4], [2, 5]), [3, 6])) == [((1, 2), 3), ((4, 5), 6)]
| Uzips a pytree of lists. | [
"Uzips",
"a",
"pytree",
"of",
"lists",
"."
] | def nested_unzip(x):
acc = []
try:
i = 0
while True:
acc.append(nested_map(
lambda l: l[i],
x,
stop_fn=_is_last_level_nonempty,
))
i += 1
except IndexError:
return acc | [
"def",
"nested_unzip",
"(",
"x",
")",
":",
"acc",
"=",
"[",
"]",
"try",
":",
"i",
"=",
"0",
"while",
"True",
":",
"acc",
".",
"append",
"(",
"nested_map",
"(",
"lambda",
"l",
":",
"l",
"[",
"i",
"]",
",",
"x",
",",
"stop_fn",
"=",
"_is_last_lev... | Uzips a pytree of lists. | [
"Uzips",
"a",
"pytree",
"of",
"lists",
"."
] | [
"\"\"\"Uzips a pytree of lists.\n\n Inverse of nested_unzip.\n\n Example:\n nested_unzip((([1, 4], [2, 5]), [3, 6])) == [((1, 2), 3), ((4, 5), 6)]\n \"\"\""
] | [
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "examples",
"docstring": null,
... |
4b8a6acc3026af8f1670c032ba41d0f731426d7e | TomaszOdrzygozdz/gym-splendor | agents/abstract_agent.py | [
"MIT"
] | Python | choose_action | <not_specific> | def choose_action(self, observation : SplendorObservation, previous_actions : List[Action]):
"""This method chooses one action to take, based on the provided observation. This method should not have
access to the original gym_open_ai-splendor environment - you can create your own environment for example... | This method chooses one action to take, based on the provided observation. This method should not have
access to the original gym_open_ai-splendor environment - you can create your own environment for example to do
simulations of game, or have access to environment methods. | This method chooses one action to take, based on the provided observation. This method should not have
access to the original gym_open_ai-splendor environment - you can create your own environment for example to do
simulations of game, or have access to environment methods. | [
"This",
"method",
"chooses",
"one",
"action",
"to",
"take",
"based",
"on",
"the",
"provided",
"observation",
".",
"This",
"method",
"should",
"not",
"have",
"access",
"to",
"the",
"original",
"gym_open_ai",
"-",
"splendor",
"environment",
"-",
"you",
"can",
... | def choose_action(self, observation : SplendorObservation, previous_actions : List[Action]):
if observation.name == 'deterministic':
return self.deterministic_choose_action(observation, previous_actions)
if observation.name == 'stochastic':
return self.stochastic_choose_action(ob... | [
"def",
"choose_action",
"(",
"self",
",",
"observation",
":",
"SplendorObservation",
",",
"previous_actions",
":",
"List",
"[",
"Action",
"]",
")",
":",
"if",
"observation",
".",
"name",
"==",
"'deterministic'",
":",
"return",
"self",
".",
"deterministic_choose_... | This method chooses one action to take, based on the provided observation. | [
"This",
"method",
"chooses",
"one",
"action",
"to",
"take",
"based",
"on",
"the",
"provided",
"observation",
"."
] | [
"\"\"\"This method chooses one action to take, based on the provided observation. This method should not have\n access to the original gym_open_ai-splendor environment - you can create your own environment for example to do\n simulations of game, or have access to environment methods.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "observation",
"type": "SplendorObservation"
},
{
"param": "previous_actions",
"type": "List[Action]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "observation",
"type": "SplendorObservation",
"docstring": null,
... |
4b8c31aefaf9a51a6a4fb20e3b66d0109ee93323 | TomaszOdrzygozdz/gym-splendor | alpaca/alpacka/utils/space.py | [
"MIT"
] | Python | space_iter | <not_specific> | def space_iter(action_space):
"""Returns an iterator over points in a gym_open_ai space."""
try:
return iter(action_space)
except TypeError:
if isinstance(action_space, gym_open_ai.spaces.Discrete):
return iter(range(action_space.n))
else:
raise TypeError('Spa... | Returns an iterator over points in a gym_open_ai space. | Returns an iterator over points in a gym_open_ai space. | [
"Returns",
"an",
"iterator",
"over",
"points",
"in",
"a",
"gym_open_ai",
"space",
"."
] | def space_iter(action_space):
try:
return iter(action_space)
except TypeError:
if isinstance(action_space, gym_open_ai.spaces.Discrete):
return iter(range(action_space.n))
else:
raise TypeError('Space {} does not support iteration.'.format(
type(ac... | [
"def",
"space_iter",
"(",
"action_space",
")",
":",
"try",
":",
"return",
"iter",
"(",
"action_space",
")",
"except",
"TypeError",
":",
"if",
"isinstance",
"(",
"action_space",
",",
"gym_open_ai",
".",
"spaces",
".",
"Discrete",
")",
":",
"return",
"iter",
... | Returns an iterator over points in a gym_open_ai space. | [
"Returns",
"an",
"iterator",
"over",
"points",
"in",
"a",
"gym_open_ai",
"space",
"."
] | [
"\"\"\"Returns an iterator over points in a gym_open_ai space.\"\"\""
] | [
{
"param": "action_space",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "action_space",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
5f1e24410b60effdac041c857a9abac1aa35f04f | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/board.py | [
"MIT"
] | Python | remove_card_from_board_and_refill | None | def remove_card_from_board_and_refill(self, card: Card) -> None:
"""This method removes a card from board and puts a new one (if there is non-empty deck to take from"""
self.cards_on_board.remove(card)
if len(self.deck.decks_dict[card.row]):
self.cards_on_board.add(self.deck.pop_card... | This method removes a card from board and puts a new one (if there is non-empty deck to take from | This method removes a card from board and puts a new one (if there is non-empty deck to take from | [
"This",
"method",
"removes",
"a",
"card",
"from",
"board",
"and",
"puts",
"a",
"new",
"one",
"(",
"if",
"there",
"is",
"non",
"-",
"empty",
"deck",
"to",
"take",
"from"
] | def remove_card_from_board_and_refill(self, card: Card) -> None:
self.cards_on_board.remove(card)
if len(self.deck.decks_dict[card.row]):
self.cards_on_board.add(self.deck.pop_card(card.row)) | [
"def",
"remove_card_from_board_and_refill",
"(",
"self",
",",
"card",
":",
"Card",
")",
"->",
"None",
":",
"self",
".",
"cards_on_board",
".",
"remove",
"(",
"card",
")",
"if",
"len",
"(",
"self",
".",
"deck",
".",
"decks_dict",
"[",
"card",
".",
"row",
... | This method removes a card from board and puts a new one (if there is non-empty deck to take from | [
"This",
"method",
"removes",
"a",
"card",
"from",
"board",
"and",
"puts",
"a",
"new",
"one",
"(",
"if",
"there",
"is",
"non",
"-",
"empty",
"deck",
"to",
"take",
"from"
] | [
"\"\"\"This method removes a card from board and puts a new one (if there is non-empty deck to take from\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "card",
"type": "Card"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "card",
"type": "Card",
"docstring": null,
"docstring_tokens":... |
5f1e24410b60effdac041c857a9abac1aa35f04f | TomaszOdrzygozdz/gym-splendor | gym_splendor_code/envs/mechanics/board.py | [
"MIT"
] | Python | from_dict | null | def from_dict(self, vector):
"""Take player's gems from the board. """
gems = vector['board']['gems_on_board']
self.gems_on_board = GemsCollection({GemColor.GOLD: gems[0], GemColor.RED: gems[1],GemColor.GREEN: gems[2], GemColor.BLUE: gems[3],
GemColor.WHITE: gems[4], Gem... | Take player's gems from the board. | Take player's gems from the board. | [
"Take",
"player",
"'",
"s",
"gems",
"from",
"the",
"board",
"."
] | def from_dict(self, vector):
gems = vector['board']['gems_on_board']
self.gems_on_board = GemsCollection({GemColor.GOLD: gems[0], GemColor.RED: gems[1],GemColor.GREEN: gems[2], GemColor.BLUE: gems[3],
GemColor.WHITE: gems[4], GemColor.BLACK: gems[5]})
cards = vector['boar... | [
"def",
"from_dict",
"(",
"self",
",",
"vector",
")",
":",
"gems",
"=",
"vector",
"[",
"'board'",
"]",
"[",
"'gems_on_board'",
"]",
"self",
".",
"gems_on_board",
"=",
"GemsCollection",
"(",
"{",
"GemColor",
".",
"GOLD",
":",
"gems",
"[",
"0",
"]",
",",
... | Take player's gems from the board. | [
"Take",
"player",
"'",
"s",
"gems",
"from",
"the",
"board",
"."
] | [
"\"\"\"Take player's gems from the board. \"\"\"",
"\"\"\"Puts cards on the board according to previous current_state. \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "vector",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "vector",
"type": null,
"docstring": null,
"docstring_tokens":... |
ae11140e5b9268cd1796ea45393f57ec89ddbfad | TomaszOdrzygozdz/gym-splendor | agents/general_multi_process_mcts_agent.py | [
"MIT"
] | Python | finish_game | null | def finish_game(self):
'''When game is finished we need to clear out tree.'''
self.mcts_started = False
self.actions_taken_so_far = 0
self.previous_root_state = None
self.previous_game_state = None
self.actions_taken_so_far = 0 | When game is finished we need to clear out tree. | When game is finished we need to clear out tree. | [
"When",
"game",
"is",
"finished",
"we",
"need",
"to",
"clear",
"out",
"tree",
"."
] | def finish_game(self):
self.mcts_started = False
self.actions_taken_so_far = 0
self.previous_root_state = None
self.previous_game_state = None
self.actions_taken_so_far = 0 | [
"def",
"finish_game",
"(",
"self",
")",
":",
"self",
".",
"mcts_started",
"=",
"False",
"self",
".",
"actions_taken_so_far",
"=",
"0",
"self",
".",
"previous_root_state",
"=",
"None",
"self",
".",
"previous_game_state",
"=",
"None",
"self",
".",
"actions_taken... | When game is finished we need to clear out tree. | [
"When",
"game",
"is",
"finished",
"we",
"need",
"to",
"clear",
"out",
"tree",
"."
] | [
"'''When game is finished we need to clear out tree.'''"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
c4267977035e70bbfc0dcdf286261fd6f8d6633b | elric91/homeassistant_zigate | zigate/__init__.py | [
"MIT"
] | Python | raw_command | null | def raw_command(call):
"""send a raw command to ZiGate"""
cmd = call.data.get('cmd', '')
data = call.data.get('data', '')
zigate.send_data(cmd, data) | send a raw command to ZiGate | send a raw command to ZiGate | [
"send",
"a",
"raw",
"command",
"to",
"ZiGate"
] | def raw_command(call):
cmd = call.data.get('cmd', '')
data = call.data.get('data', '')
zigate.send_data(cmd, data) | [
"def",
"raw_command",
"(",
"call",
")",
":",
"cmd",
"=",
"call",
".",
"data",
".",
"get",
"(",
"'cmd'",
",",
"''",
")",
"data",
"=",
"call",
".",
"data",
".",
"get",
"(",
"'data'",
",",
"''",
")",
"zigate",
".",
"send_data",
"(",
"cmd",
",",
"d... | send a raw command to ZiGate | [
"send",
"a",
"raw",
"command",
"to",
"ZiGate"
] | [
"\"\"\"send a raw command to ZiGate\"\"\""
] | [
{
"param": "call",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "call",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
c4267977035e70bbfc0dcdf286261fd6f8d6633b | elric91/homeassistant_zigate | zigate/__init__.py | [
"MIT"
] | Python | bind_transport_to_device | null | def bind_transport_to_device(device, protocol_refs):
"""
Bind device and protocol / transport once they are ready
Update the device status @ start
"""
transport = protocol_refs.result()[0]
protocol = protocol_refs.result()[1]
protocol.device = device
device.send_to_transport = trans... |
Bind device and protocol / transport once they are ready
Update the device status @ start
| Bind device and protocol / transport once they are ready
Update the device status @ start | [
"Bind",
"device",
"and",
"protocol",
"/",
"transport",
"once",
"they",
"are",
"ready",
"Update",
"the",
"device",
"status",
"@",
"start"
] | def bind_transport_to_device(device, protocol_refs):
transport = protocol_refs.result()[0]
protocol = protocol_refs.result()[1]
protocol.device = device
device.send_to_transport = transport.write | [
"def",
"bind_transport_to_device",
"(",
"device",
",",
"protocol_refs",
")",
":",
"transport",
"=",
"protocol_refs",
".",
"result",
"(",
")",
"[",
"0",
"]",
"protocol",
"=",
"protocol_refs",
".",
"result",
"(",
")",
"[",
"1",
"]",
"protocol",
".",
"device"... | Bind device and protocol / transport once they are ready
Update the device status @ start | [
"Bind",
"device",
"and",
"protocol",
"/",
"transport",
"once",
"they",
"are",
"ready",
"Update",
"the",
"device",
"status",
"@",
"start"
] | [
"\"\"\"\n Bind device and protocol / transport once they are ready\n Update the device status @ start\n \"\"\""
] | [
{
"param": "device",
"type": null
},
{
"param": "protocol_refs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "device",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "protocol_refs",
"type": null,
"docstring": null,
"docstring... |
0b31ec593bf256fc33a93bad04a828e1b7283c1d | elric91/homeassistant_zigate | sensor/zigate.py | [
"MIT"
] | Python | async_added_to_hass | null | async def async_added_to_hass(self):
"""Handle entity which will be added."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
for attr in iter(state.attributes):
if attr != ATTR_FRIENDLY_NAME:
_LOGGE... | Handle entity which will be added. | Handle entity which will be added. | [
"Handle",
"entity",
"which",
"will",
"be",
"added",
"."
] | async def async_added_to_hass(self):
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
for attr in iter(state.attributes):
if attr != ATTR_FRIENDLY_NAME:
_LOGGER.info('{}: set attribute {} from last state: {}'.... | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"super",
"(",
")",
".",
"async_added_to_hass",
"(",
")",
"state",
"=",
"await",
"self",
".",
"async_get_last_state",
"(",
")",
"if",
"state",
":",
"for",
"attr",
"in",
"iter",
"(",
"s... | Handle entity which will be added. | [
"Handle",
"entity",
"which",
"will",
"be",
"added",
"."
] | [
"\"\"\"Handle entity which will be added.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
bcdfd0001fa449f5844d496ea2a9d7a81860945c | kisuke95/ray | rllib/policy/torch_policy.py | [
"Apache-2.0"
] | Python | extra_compute_grad_fetches | Dict[str, Any] | def extra_compute_grad_fetches(self) -> Dict[str, Any]:
"""Extra values to fetch and return from compute_gradients().
Returns:
Extra fetch dict to be added to the fetch dict of the
`compute_gradients` call.
"""
return {LEARNER_STATS_KEY: {}} | Extra values to fetch and return from compute_gradients().
Returns:
Extra fetch dict to be added to the fetch dict of the
`compute_gradients` call.
| Extra values to fetch and return from compute_gradients(). | [
"Extra",
"values",
"to",
"fetch",
"and",
"return",
"from",
"compute_gradients",
"()",
"."
] | def extra_compute_grad_fetches(self) -> Dict[str, Any]:
return {LEARNER_STATS_KEY: {}} | [
"def",
"extra_compute_grad_fetches",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"LEARNER_STATS_KEY",
":",
"{",
"}",
"}"
] | Extra values to fetch and return from compute_gradients(). | [
"Extra",
"values",
"to",
"fetch",
"and",
"return",
"from",
"compute_gradients",
"()",
"."
] | [
"\"\"\"Extra values to fetch and return from compute_gradients().\n\n Returns:\n Extra fetch dict to be added to the fetch dict of the\n `compute_gradients` call.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "Extra fetch dict to be added to the fetch dict of the\n`compute_gradients` call.",
"docstring_tokens": [
"Extra",
"fetch",
"dict",
"to",
"be",
"added",
"to",
"the",
"fetch",
"dict",
"... |
bcdfd0001fa449f5844d496ea2a9d7a81860945c | kisuke95/ray | rllib/policy/torch_policy.py | [
"Apache-2.0"
] | Python | extra_action_out | Dict[str, TensorType] | def extra_action_out(
self,
input_dict: Dict[str, TensorType],
state_batches: List[TensorType],
model: TorchModelV2,
action_dist: TorchDistributionWrapper,
) -> Dict[str, TensorType]:
"""Returns dict of extra info to include in experience batch.
Args:
... | Returns dict of extra info to include in experience batch.
Args:
input_dict: Dict of model input tensors.
state_batches: List of state tensors.
model: Reference to the model object.
action_dist: Torch action dist object
to get log-probs (e.g. for ... | Returns dict of extra info to include in experience batch. | [
"Returns",
"dict",
"of",
"extra",
"info",
"to",
"include",
"in",
"experience",
"batch",
"."
] | def extra_action_out(
self,
input_dict: Dict[str, TensorType],
state_batches: List[TensorType],
model: TorchModelV2,
action_dist: TorchDistributionWrapper,
) -> Dict[str, TensorType]:
return {} | [
"def",
"extra_action_out",
"(",
"self",
",",
"input_dict",
":",
"Dict",
"[",
"str",
",",
"TensorType",
"]",
",",
"state_batches",
":",
"List",
"[",
"TensorType",
"]",
",",
"model",
":",
"TorchModelV2",
",",
"action_dist",
":",
"TorchDistributionWrapper",
",",
... | Returns dict of extra info to include in experience batch. | [
"Returns",
"dict",
"of",
"extra",
"info",
"to",
"include",
"in",
"experience",
"batch",
"."
] | [
"\"\"\"Returns dict of extra info to include in experience batch.\n\n Args:\n input_dict: Dict of model input tensors.\n state_batches: List of state tensors.\n model: Reference to the model object.\n action_dist: Torch action dist object\n to get lo... | [
{
"param": "self",
"type": null
},
{
"param": "input_dict",
"type": "Dict[str, TensorType]"
},
{
"param": "state_batches",
"type": "List[TensorType]"
},
{
"param": "model",
"type": "TorchModelV2"
},
{
"param": "action_dist",
"type": "TorchDistributionWrapper"
... | {
"returns": [
{
"docstring": "Extra outputs to return in a `compute_actions_from_input_dict()`\ncall (3rd return value).",
"docstring_tokens": [
"Extra",
"outputs",
"to",
"return",
"in",
"a",
"`",
"compute_actions_from_input_dict",
... |
bcdfd0001fa449f5844d496ea2a9d7a81860945c | kisuke95/ray | rllib/policy/torch_policy.py | [
"Apache-2.0"
] | Python | extra_grad_info | Dict[str, TensorType] | def extra_grad_info(self, train_batch: SampleBatch) -> Dict[str, TensorType]:
"""Return dict of extra grad info.
Args:
train_batch: The training batch for which to produce
extra grad info for.
Returns:
The info dict carrying grad info per str key.
... | Return dict of extra grad info.
Args:
train_batch: The training batch for which to produce
extra grad info for.
Returns:
The info dict carrying grad info per str key.
| Return dict of extra grad info. | [
"Return",
"dict",
"of",
"extra",
"grad",
"info",
"."
] | def extra_grad_info(self, train_batch: SampleBatch) -> Dict[str, TensorType]:
return {} | [
"def",
"extra_grad_info",
"(",
"self",
",",
"train_batch",
":",
"SampleBatch",
")",
"->",
"Dict",
"[",
"str",
",",
"TensorType",
"]",
":",
"return",
"{",
"}"
] | Return dict of extra grad info. | [
"Return",
"dict",
"of",
"extra",
"grad",
"info",
"."
] | [
"\"\"\"Return dict of extra grad info.\n\n Args:\n train_batch: The training batch for which to produce\n extra grad info for.\n\n Returns:\n The info dict carrying grad info per str key.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "train_batch",
"type": "SampleBatch"
}
] | {
"returns": [
{
"docstring": "The info dict carrying grad info per str key.",
"docstring_tokens": [
"The",
"info",
"dict",
"carrying",
"grad",
"info",
"per",
"str",
"key",
"."
],
"type": null
}
],
"rai... |
bcdfd0001fa449f5844d496ea2a9d7a81860945c | kisuke95/ray | rllib/policy/torch_policy.py | [
"Apache-2.0"
] | Python | optimizer | Union[List["torch.optim.Optimizer"], "torch.optim.Optimizer"] | def optimizer(
self,
) -> Union[List["torch.optim.Optimizer"], "torch.optim.Optimizer"]:
"""Custom the local PyTorch optimizer(s) to use.
Returns:
The local PyTorch optimizer(s) to use for this Policy.
"""
if hasattr(self, "config"):
optimizers = [
... | Custom the local PyTorch optimizer(s) to use.
Returns:
The local PyTorch optimizer(s) to use for this Policy.
| Custom the local PyTorch optimizer(s) to use. | [
"Custom",
"the",
"local",
"PyTorch",
"optimizer",
"(",
"s",
")",
"to",
"use",
"."
] | def optimizer(
self,
) -> Union[List["torch.optim.Optimizer"], "torch.optim.Optimizer"]:
if hasattr(self, "config"):
optimizers = [
torch.optim.Adam(self.model.parameters(), lr=self.config["lr"])
]
else:
optimizers = [torch.optim.Adam(self.... | [
"def",
"optimizer",
"(",
"self",
",",
")",
"->",
"Union",
"[",
"List",
"[",
"\"torch.optim.Optimizer\"",
"]",
",",
"\"torch.optim.Optimizer\"",
"]",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"config\"",
")",
":",
"optimizers",
"=",
"[",
"torch",
".",
"opti... | Custom the local PyTorch optimizer(s) to use. | [
"Custom",
"the",
"local",
"PyTorch",
"optimizer",
"(",
"s",
")",
"to",
"use",
"."
] | [
"\"\"\"Custom the local PyTorch optimizer(s) to use.\n\n Returns:\n The local PyTorch optimizer(s) to use for this Policy.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "The local PyTorch optimizer(s) to use for this Policy.",
"docstring_tokens": [
"The",
"local",
"PyTorch",
"optimizer",
"(",
"s",
")",
"to",
"use",
"for",
"this",
"Policy",
... |
bcdfd0001fa449f5844d496ea2a9d7a81860945c | kisuke95/ray | rllib/policy/torch_policy.py | [
"Apache-2.0"
] | Python | export_model | None | def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None:
"""Exports the Policy's Model to local directory for serving.
Creates a TorchScript model and saves it.
Args:
export_dir: Local writable directory or filename.
onnx: If given, will export model... | Exports the Policy's Model to local directory for serving.
Creates a TorchScript model and saves it.
Args:
export_dir: Local writable directory or filename.
onnx: If given, will export model in ONNX format. The
value of this parameter set the ONNX OpSet version ... | Exports the Policy's Model to local directory for serving.
Creates a TorchScript model and saves it. | [
"Exports",
"the",
"Policy",
"'",
"s",
"Model",
"to",
"local",
"directory",
"for",
"serving",
".",
"Creates",
"a",
"TorchScript",
"model",
"and",
"saves",
"it",
"."
] | def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None:
self._lazy_tensor_dict(self._dummy_batch)
if "state_in_0" not in self._dummy_batch:
self._dummy_batch["state_in_0"] = self._dummy_batch[
SampleBatch.SEQ_LENS
] = np.array([1.0])
s... | [
"def",
"export_model",
"(",
"self",
",",
"export_dir",
":",
"str",
",",
"onnx",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"_lazy_tensor_dict",
"(",
"self",
".",
"_dummy_batch",
")",
"if",
"\"state_in_0\"",
"not",... | Exports the Policy's Model to local directory for serving. | [
"Exports",
"the",
"Policy",
"'",
"s",
"Model",
"to",
"local",
"directory",
"for",
"serving",
"."
] | [
"\"\"\"Exports the Policy's Model to local directory for serving.\n\n Creates a TorchScript model and saves it.\n\n Args:\n export_dir: Local writable directory or filename.\n onnx: If given, will export model in ONNX format. The\n value of this parameter set the O... | [
{
"param": "self",
"type": null
},
{
"param": "export_dir",
"type": "str"
},
{
"param": "onnx",
"type": "Optional[int]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "export_dir",
"type": "str",
"docstring": "Local writable directory ... |
bcdfd0001fa449f5844d496ea2a9d7a81860945c | kisuke95/ray | rllib/policy/torch_policy.py | [
"Apache-2.0"
] | Python | _multi_gpu_parallel_grad_calc | List[Tuple[List[TensorType], GradInfoDict]] | def _multi_gpu_parallel_grad_calc(
self, sample_batches: List[SampleBatch]
) -> List[Tuple[List[TensorType], GradInfoDict]]:
"""Performs a parallelized loss and gradient calculation over the batch.
Splits up the given train batch into n shards (n=number of this
Policy's devices) and... | Performs a parallelized loss and gradient calculation over the batch.
Splits up the given train batch into n shards (n=number of this
Policy's devices) and passes each data shard (in parallel) through
the loss function using the individual devices' models
(self.model_gpu_towers). Then r... | Performs a parallelized loss and gradient calculation over the batch.
Splits up the given train batch into n shards (n=number of this
Policy's devices) and passes each data shard (in parallel) through
the loss function using the individual devices' models
(self.model_gpu_towers). Then returns each tower's outputs. | [
"Performs",
"a",
"parallelized",
"loss",
"and",
"gradient",
"calculation",
"over",
"the",
"batch",
".",
"Splits",
"up",
"the",
"given",
"train",
"batch",
"into",
"n",
"shards",
"(",
"n",
"=",
"number",
"of",
"this",
"Policy",
"'",
"s",
"devices",
")",
"a... | def _multi_gpu_parallel_grad_calc(
self, sample_batches: List[SampleBatch]
) -> List[Tuple[List[TensorType], GradInfoDict]]:
assert len(self.model_gpu_towers) == len(sample_batches)
lock = threading.Lock()
results = {}
grad_enabled = torch.is_grad_enabled()
def _worke... | [
"def",
"_multi_gpu_parallel_grad_calc",
"(",
"self",
",",
"sample_batches",
":",
"List",
"[",
"SampleBatch",
"]",
")",
"->",
"List",
"[",
"Tuple",
"[",
"List",
"[",
"TensorType",
"]",
",",
"GradInfoDict",
"]",
"]",
":",
"assert",
"len",
"(",
"self",
".",
... | Performs a parallelized loss and gradient calculation over the batch. | [
"Performs",
"a",
"parallelized",
"loss",
"and",
"gradient",
"calculation",
"over",
"the",
"batch",
"."
] | [
"\"\"\"Performs a parallelized loss and gradient calculation over the batch.\n\n Splits up the given train batch into n shards (n=number of this\n Policy's devices) and passes each data shard (in parallel) through\n the loss function using the individual devices' models\n (self.model_gpu... | [
{
"param": "self",
"type": null
},
{
"param": "sample_batches",
"type": "List[SampleBatch]"
}
] | {
"returns": [
{
"docstring": "A list (one item per device) of 2-tuples, each with 1) gradient\nlist and 2) grad info dict.",
"docstring_tokens": [
"A",
"list",
"(",
"one",
"item",
"per",
"device",
")",
"of",
"2",
... |
0759f7d5fcde62771a95cca2d01aa59dbe14532d | kisuke95/ray | doc/source/custom_directives.py | [
"Apache-2.0"
] | Python | fix_xgb_lgbm_docs | null | def fix_xgb_lgbm_docs(app, what, name, obj, options, lines):
"""Fix XGBoost-Ray and LightGBM-Ray docstrings.
For ``app.connect('autodoc-process-docstring')``.
See https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
Removes references to XGBoost ``callback_api`` and sets explicit module
... | Fix XGBoost-Ray and LightGBM-Ray docstrings.
For ``app.connect('autodoc-process-docstring')``.
See https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html
Removes references to XGBoost ``callback_api`` and sets explicit module
references to classes and functions that are named the same way ... |
Removes references to XGBoost ``callback_api`` and sets explicit module
references to classes and functions that are named the same way in both
XGBoost-Ray and LightGBM-Ray. | [
"Removes",
"references",
"to",
"XGBoost",
"`",
"`",
"callback_api",
"`",
"`",
"and",
"sets",
"explicit",
"module",
"references",
"to",
"classes",
"and",
"functions",
"that",
"are",
"named",
"the",
"same",
"way",
"in",
"both",
"XGBoost",
"-",
"Ray",
"and",
... | def fix_xgb_lgbm_docs(app, what, name, obj, options, lines):
def _remove_xgboost_refs(replacements: list):
if name.startswith("xgboost_ray"):
replacements.append((":ref:`callback_api`", "Callback API"))
def _replace_ray_params(replacements: list):
if name.startswith("xgboost_ray"):
... | [
"def",
"fix_xgb_lgbm_docs",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"def",
"_remove_xgboost_refs",
"(",
"replacements",
":",
"list",
")",
":",
"\"\"\"Remove ``callback_api`` ref to XGBoost docs.\n\n Fixes ``unde... | Fix XGBoost-Ray and LightGBM-Ray docstrings. | [
"Fix",
"XGBoost",
"-",
"Ray",
"and",
"LightGBM",
"-",
"Ray",
"docstrings",
"."
] | [
"\"\"\"Fix XGBoost-Ray and LightGBM-Ray docstrings.\n\n For ``app.connect('autodoc-process-docstring')``.\n See https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html\n\n Removes references to XGBoost ``callback_api`` and sets explicit module\n references to classes and functions that are na... | [
{
"param": "app",
"type": null
},
{
"param": "what",
"type": null
},
{
"param": "name",
"type": null
},
{
"param": "obj",
"type": null
},
{
"param": "options",
"type": null
},
{
"param": "lines",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "app",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "what",
"type": null,
"docstring": null,
"docstring_tokens": []... |
0759f7d5fcde62771a95cca2d01aa59dbe14532d | kisuke95/ray | doc/source/custom_directives.py | [
"Apache-2.0"
] | Python | feedback_form_url | <not_specific> | def feedback_form_url(project, page):
"""Create a URL for feedback on a particular page in a project."""
return FEEDBACK_FORM_FMT.format(
title=urllib.parse.quote("[docs] Issue on `{page}.rst`".format(page=page)),
body=urllib.parse.quote(
"# Documentation Problem/Question/Comment\n"
... | Create a URL for feedback on a particular page in a project. | Create a URL for feedback on a particular page in a project. | [
"Create",
"a",
"URL",
"for",
"feedback",
"on",
"a",
"particular",
"page",
"in",
"a",
"project",
"."
] | def feedback_form_url(project, page):
return FEEDBACK_FORM_FMT.format(
title=urllib.parse.quote("[docs] Issue on `{page}.rst`".format(page=page)),
body=urllib.parse.quote(
"# Documentation Problem/Question/Comment\n"
"<!-- Describe your issue/question/comment below. -->\n"
... | [
"def",
"feedback_form_url",
"(",
"project",
",",
"page",
")",
":",
"return",
"FEEDBACK_FORM_FMT",
".",
"format",
"(",
"title",
"=",
"urllib",
".",
"parse",
".",
"quote",
"(",
"\"[docs] Issue on `{page}.rst`\"",
".",
"format",
"(",
"page",
"=",
"page",
")",
"... | Create a URL for feedback on a particular page in a project. | [
"Create",
"a",
"URL",
"for",
"feedback",
"on",
"a",
"particular",
"page",
"in",
"a",
"project",
"."
] | [
"\"\"\"Create a URL for feedback on a particular page in a project.\"\"\""
] | [
{
"param": "project",
"type": null
},
{
"param": "page",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "project",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "page",
"type": null,
"docstring": null,
"docstring_tokens"... |
0759f7d5fcde62771a95cca2d01aa59dbe14532d | kisuke95/ray | doc/source/custom_directives.py | [
"Apache-2.0"
] | Python | download_and_preprocess_ecosystem_docs | <not_specific> | def download_and_preprocess_ecosystem_docs():
"""
This function downloads markdown readme files for various
ecosystem libraries, saves them in specified locations and preprocesses
them before sphinx build starts.
If you have ecosystem libraries that live in a separate repo from Ray,
adding them... |
This function downloads markdown readme files for various
ecosystem libraries, saves them in specified locations and preprocesses
them before sphinx build starts.
If you have ecosystem libraries that live in a separate repo from Ray,
adding them here will allow for their docs to be present in Ray ... | This function downloads markdown readme files for various
ecosystem libraries, saves them in specified locations and preprocesses
them before sphinx build starts.
If you have ecosystem libraries that live in a separate repo from Ray,
adding them here will allow for their docs to be present in Ray docs
without the need... | [
"This",
"function",
"downloads",
"markdown",
"readme",
"files",
"for",
"various",
"ecosystem",
"libraries",
"saves",
"them",
"in",
"specified",
"locations",
"and",
"preprocesses",
"them",
"before",
"sphinx",
"build",
"starts",
".",
"If",
"you",
"have",
"ecosystem"... | def download_and_preprocess_ecosystem_docs():
import urllib.request
import requests
def get_latest_release_tag(repo: str) -> str:
response = requests.get(f"https://api.github.com/repos/{repo}/releases/latest")
return response.json()["tag_name"]
def get_file_from_github(
repo: str... | [
"def",
"download_and_preprocess_ecosystem_docs",
"(",
")",
":",
"import",
"urllib",
".",
"request",
"import",
"requests",
"def",
"get_latest_release_tag",
"(",
"repo",
":",
"str",
")",
"->",
"str",
":",
"\"\"\"repo is just the repo name, eg. ray-project/ray\"\"\"",
"respo... | This function downloads markdown readme files for various
ecosystem libraries, saves them in specified locations and preprocesses
them before sphinx build starts. | [
"This",
"function",
"downloads",
"markdown",
"readme",
"files",
"for",
"various",
"ecosystem",
"libraries",
"saves",
"them",
"in",
"specified",
"locations",
"and",
"preprocesses",
"them",
"before",
"sphinx",
"build",
"starts",
"."
] | [
"\"\"\"\n This function downloads markdown readme files for various\n ecosystem libraries, saves them in specified locations and preprocesses\n them before sphinx build starts.\n\n If you have ecosystem libraries that live in a separate repo from Ray,\n adding them here will allow for their docs to b... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
49f605cf574b9fdfe2646e08ee9a0120d61eaf38 | kisuke95/ray | python/ray/tune/tests/test_sync.py | [
"Apache-2.0"
] | Python | testCloudSyncPeriod | null | def testCloudSyncPeriod(self):
"""Tests that changing SYNC_PERIOD affects syncing frequency."""
tmpdir = tempfile.mkdtemp()
def trainable(config):
for i in range(10):
time.sleep(1)
tune.report(score=i)
def counter(local, remote):
... | Tests that changing SYNC_PERIOD affects syncing frequency. | Tests that changing SYNC_PERIOD affects syncing frequency. | [
"Tests",
"that",
"changing",
"SYNC_PERIOD",
"affects",
"syncing",
"frequency",
"."
] | def testCloudSyncPeriod(self):
tmpdir = tempfile.mkdtemp()
def trainable(config):
for i in range(10):
time.sleep(1)
tune.report(score=i)
def counter(local, remote):
count_file = os.path.join(tmpdir, "count.txt")
if not os.path.e... | [
"def",
"testCloudSyncPeriod",
"(",
"self",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"def",
"trainable",
"(",
"config",
")",
":",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"tune",
".",... | Tests that changing SYNC_PERIOD affects syncing frequency. | [
"Tests",
"that",
"changing",
"SYNC_PERIOD",
"affects",
"syncing",
"frequency",
"."
] | [
"\"\"\"Tests that changing SYNC_PERIOD affects syncing frequency.\"\"\"",
"# This was originally set to 0.5"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
49f605cf574b9fdfe2646e08ee9a0120d61eaf38 | kisuke95/ray | python/ray/tune/tests/test_sync.py | [
"Apache-2.0"
] | Python | testNoSync | null | def testNoSync(self):
"""Sync should not run on a single node."""
def sync_func(source, target):
pass
sync_config = tune.SyncConfig(syncer=sync_func)
with patch.object(CommandBasedClient, "_execute") as mock_sync:
[trial] = tune.run(
"__fake",
... | Sync should not run on a single node. | Sync should not run on a single node. | [
"Sync",
"should",
"not",
"run",
"on",
"a",
"single",
"node",
"."
] | def testNoSync(self):
def sync_func(source, target):
pass
sync_config = tune.SyncConfig(syncer=sync_func)
with patch.object(CommandBasedClient, "_execute") as mock_sync:
[trial] = tune.run(
"__fake",
name="foo",
max_failures... | [
"def",
"testNoSync",
"(",
"self",
")",
":",
"def",
"sync_func",
"(",
"source",
",",
"target",
")",
":",
"pass",
"sync_config",
"=",
"tune",
".",
"SyncConfig",
"(",
"syncer",
"=",
"sync_func",
")",
"with",
"patch",
".",
"object",
"(",
"CommandBasedClient",
... | Sync should not run on a single node. | [
"Sync",
"should",
"not",
"run",
"on",
"a",
"single",
"node",
"."
] | [
"\"\"\"Sync should not run on a single node.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
49f605cf574b9fdfe2646e08ee9a0120d61eaf38 | kisuke95/ray | python/ray/tune/tests/test_sync.py | [
"Apache-2.0"
] | Python | testNoSyncToDriver | null | def testNoSyncToDriver(self):
"""Test that sync to driver is disabled"""
class _Trial:
def __init__(self, id, logdir):
self.id = (id,)
self.logdir = logdir
trial = _Trial("0", "some_dir")
sync_config = tune.SyncConfig(syncer=None)
#... | Test that sync to driver is disabled | Test that sync to driver is disabled | [
"Test",
"that",
"sync",
"to",
"driver",
"is",
"disabled"
] | def testNoSyncToDriver(self):
class _Trial:
def __init__(self, id, logdir):
self.id = (id,)
self.logdir = logdir
trial = _Trial("0", "some_dir")
sync_config = tune.SyncConfig(syncer=None)
callbacks = create_default_callbacks([], sync_config, lo... | [
"def",
"testNoSyncToDriver",
"(",
"self",
")",
":",
"class",
"_Trial",
":",
"def",
"__init__",
"(",
"self",
",",
"id",
",",
"logdir",
")",
":",
"self",
".",
"id",
"=",
"(",
"id",
",",
")",
"self",
".",
"logdir",
"=",
"logdir",
"trial",
"=",
"_Trial... | Test that sync to driver is disabled | [
"Test",
"that",
"sync",
"to",
"driver",
"is",
"disabled"
] | [
"\"\"\"Test that sync to driver is disabled\"\"\"",
"# Create syncer callbacks",
"# Sanity check that we got the syncer callback",
"# Sync function should be false (no sync to driver)",
"# Sync to driver is disabled, so this should be no-op"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | options | <not_specific> | def options(self, **options):
"""Convenience method for executing an actor method call with options.
Same arguments as func._remote(), but returns a wrapped function
that a non-underscore .remote() can be called on.
Examples:
# The following two calls are equivalent.
... | Convenience method for executing an actor method call with options.
Same arguments as func._remote(), but returns a wrapped function
that a non-underscore .remote() can be called on.
Examples:
# The following two calls are equivalent.
>>> actor.my_method._remote(args=[x... | Convenience method for executing an actor method call with options.
Same arguments as func._remote(), but returns a wrapped function
that a non-underscore .remote() can be called on. | [
"Convenience",
"method",
"for",
"executing",
"an",
"actor",
"method",
"call",
"with",
"options",
".",
"Same",
"arguments",
"as",
"func",
".",
"_remote",
"()",
"but",
"returns",
"a",
"wrapped",
"function",
"that",
"a",
"non",
"-",
"underscore",
".",
"remote",... | def options(self, **options):
func_cls = self
class FuncWrapper:
def remote(self, *args, **kwargs):
return func_cls._remote(args=args, kwargs=kwargs, **options)
return FuncWrapper() | [
"def",
"options",
"(",
"self",
",",
"**",
"options",
")",
":",
"func_cls",
"=",
"self",
"class",
"FuncWrapper",
":",
"def",
"remote",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"func_cls",
".",
"_remote",
"(",
"args",
"="... | Convenience method for executing an actor method call with options. | [
"Convenience",
"method",
"for",
"executing",
"an",
"actor",
"method",
"call",
"with",
"options",
"."
] | [
"\"\"\"Convenience method for executing an actor method call with options.\n\n Same arguments as func._remote(), but returns a wrapped function\n that a non-underscore .remote() can be called on.\n\n Examples:\n # The following two calls are equivalent.\n >>> actor.my_meth... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "examples",
"docstring": "The fo... |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | options | <not_specific> | def options(self, **actor_options):
"""Configures and overrides the actor instantiation parameters.
The arguments are the same as those that can be passed
to :obj:`ray.remote`.
Examples:
.. code-block:: python
@ray.remote(num_cpus=2, resources={"CustomResource": 1... | Configures and overrides the actor instantiation parameters.
The arguments are the same as those that can be passed
to :obj:`ray.remote`.
Examples:
.. code-block:: python
@ray.remote(num_cpus=2, resources={"CustomResource": 1})
class Foo:
def m... | Configures and overrides the actor instantiation parameters.
The arguments are the same as those that can be passed
to :obj:`ray.remote`. | [
"Configures",
"and",
"overrides",
"the",
"actor",
"instantiation",
"parameters",
".",
"The",
"arguments",
"are",
"the",
"same",
"as",
"those",
"that",
"can",
"be",
"passed",
"to",
":",
"obj",
":",
"`",
"ray",
".",
"remote",
"`",
"."
] | def options(self, **actor_options):
actor_cls = self
default_options = self._default_options.copy()
default_options.pop("concurrency_groups", None)
updated_options = {**default_options, **actor_options}
ray_option_utils.validate_actor_options(updated_options, in_options=True)
... | [
"def",
"options",
"(",
"self",
",",
"**",
"actor_options",
")",
":",
"actor_cls",
"=",
"self",
"default_options",
"=",
"self",
".",
"_default_options",
".",
"copy",
"(",
")",
"default_options",
".",
"pop",
"(",
"\"concurrency_groups\"",
",",
"None",
")",
"up... | Configures and overrides the actor instantiation parameters. | [
"Configures",
"and",
"overrides",
"the",
"actor",
"instantiation",
"parameters",
"."
] | [
"\"\"\"Configures and overrides the actor instantiation parameters.\n\n The arguments are the same as those that can be passed\n to :obj:`ray.remote`.\n\n Examples:\n\n .. code-block:: python\n\n @ray.remote(num_cpus=2, resources={\"CustomResource\": 1})\n class Foo... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "examples",
"docstring": null,
... |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | bind | <not_specific> | def bind(self, *args, **kwargs):
"""
**Experimental**
For ray DAG building. Implementation and interface subject
to changes.
"""
from ray.experimental.dag.class_node import ClassNode
return ClassNode(
... |
**Experimental**
For ray DAG building. Implementation and interface subject
to changes.
| Experimental
For ray DAG building. Implementation and interface subject
to changes. | [
"Experimental",
"For",
"ray",
"DAG",
"building",
".",
"Implementation",
"and",
"interface",
"subject",
"to",
"changes",
"."
] | def bind(self, *args, **kwargs):
from ray.experimental.dag.class_node import ClassNode
return ClassNode(
actor_cls.__ray_metadata__.modified_class,
args,
kwargs,
updated_options,
) | [
"def",
"bind",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"from",
"ray",
".",
"experimental",
".",
"dag",
".",
"class_node",
"import",
"ClassNode",
"return",
"ClassNode",
"(",
"actor_cls",
".",
"__ray_metadata__",
".",
"modified_class",
... | Experimental
For ray DAG building. | [
"Experimental",
"For",
"ray",
"DAG",
"building",
"."
] | [
"\"\"\"\n **Experimental**\n\n For ray DAG building. Implementation and interface subject\n to changes.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | _remote | <not_specific> | def _remote(self, args=None, kwargs=None, **actor_options):
"""Create an actor.
This method allows more flexibility than the remote method because
resource requirements can be specified and override the defaults in the
decorator.
Args:
args: The arguments to forward... | Create an actor.
This method allows more flexibility than the remote method because
resource requirements can be specified and override the defaults in the
decorator.
Args:
args: The arguments to forward to the actor constructor.
kwargs: The keyword arguments to... | Create an actor.
This method allows more flexibility than the remote method because
resource requirements can be specified and override the defaults in the
decorator. | [
"Create",
"an",
"actor",
".",
"This",
"method",
"allows",
"more",
"flexibility",
"than",
"the",
"remote",
"method",
"because",
"resource",
"requirements",
"can",
"be",
"specified",
"and",
"override",
"the",
"defaults",
"in",
"the",
"decorator",
"."
] | def _remote(self, args=None, kwargs=None, **actor_options):
actor_options.pop("concurrency_groups", None)
if args is None:
args = []
if kwargs is None:
kwargs = {}
meta = self.__ray_metadata__
actor_has_async_methods = (
len(
in... | [
"def",
"_remote",
"(",
"self",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"**",
"actor_options",
")",
":",
"actor_options",
".",
"pop",
"(",
"\"concurrency_groups\"",
",",
"None",
")",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"[",
... | Create an actor. | [
"Create",
"an",
"actor",
"."
] | [
"\"\"\"Create an actor.\n\n This method allows more flexibility than the remote method because\n resource requirements can be specified and override the defaults in the\n decorator.\n\n Args:\n args: The arguments to forward to the actor constructor.\n kwargs: The k... | [
{
"param": "self",
"type": null
},
{
"param": "args",
"type": null
},
{
"param": "kwargs",
"type": null
}
] | {
"returns": [
{
"docstring": "A handle to the newly created actor.",
"docstring_tokens": [
"A",
"handle",
"to",
"the",
"newly",
"created",
"actor",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"ide... |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | bind | <not_specific> | def bind(self, *args, **kwargs):
"""
**Experimental**
For ray DAG building. Implementation and interface subject
to changes.
"""
from ray.experimental.dag.class_node import ClassNode
return ClassNode(
self.__ray_metadata__.modified_class, args, kwarg... |
**Experimental**
For ray DAG building. Implementation and interface subject
to changes.
| Experimental
For ray DAG building. Implementation and interface subject
to changes. | [
"Experimental",
"For",
"ray",
"DAG",
"building",
".",
"Implementation",
"and",
"interface",
"subject",
"to",
"changes",
"."
] | def bind(self, *args, **kwargs):
from ray.experimental.dag.class_node import ClassNode
return ClassNode(
self.__ray_metadata__.modified_class, args, kwargs, self._default_options
) | [
"def",
"bind",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"from",
"ray",
".",
"experimental",
".",
"dag",
".",
"class_node",
"import",
"ClassNode",
"return",
"ClassNode",
"(",
"self",
".",
"__ray_metadata__",
".",
"modified_class",
",",
... | Experimental
For ray DAG building. | [
"Experimental",
"For",
"ray",
"DAG",
"building",
"."
] | [
"\"\"\"\n **Experimental**\n\n For ray DAG building. Implementation and interface subject\n to changes.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | _actor_method_call | <not_specific> | def _actor_method_call(
self,
method_name,
args=None,
kwargs=None,
name="",
num_returns=None,
concurrency_group_name=None,
):
"""Method execution stub for an actor handle.
This is the function that executes when
`actor.method_name.remo... | Method execution stub for an actor handle.
This is the function that executes when
`actor.method_name.remote(*args, **kwargs)` is called. Instead of
executing locally, the method is packaged as a task and scheduled
to the remote actor instance.
Args:
method_name: Th... | Method execution stub for an actor handle.
This is the function that executes when
`actor.method_name.remote(*args, **kwargs)` is called. Instead of
executing locally, the method is packaged as a task and scheduled
to the remote actor instance. | [
"Method",
"execution",
"stub",
"for",
"an",
"actor",
"handle",
".",
"This",
"is",
"the",
"function",
"that",
"executes",
"when",
"`",
"actor",
".",
"method_name",
".",
"remote",
"(",
"*",
"args",
"**",
"kwargs",
")",
"`",
"is",
"called",
".",
"Instead",
... | def _actor_method_call(
self,
method_name,
args=None,
kwargs=None,
name="",
num_returns=None,
concurrency_group_name=None,
):
worker = ray.worker.global_worker
args = args or []
kwargs = kwargs or {}
if self._ray_is_cross_langua... | [
"def",
"_actor_method_call",
"(",
"self",
",",
"method_name",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"name",
"=",
"\"\"",
",",
"num_returns",
"=",
"None",
",",
"concurrency_group_name",
"=",
"None",
",",
")",
":",
"worker",
"=",
"ray"... | Method execution stub for an actor handle. | [
"Method",
"execution",
"stub",
"for",
"an",
"actor",
"handle",
"."
] | [
"\"\"\"Method execution stub for an actor handle.\n\n This is the function that executes when\n `actor.method_name.remote(*args, **kwargs)` is called. Instead of\n executing locally, the method is packaged as a task and scheduled\n to the remote actor instance.\n\n Args:\n ... | [
{
"param": "self",
"type": null
},
{
"param": "method_name",
"type": null
},
{
"param": "args",
"type": null
},
{
"param": "kwargs",
"type": null
},
{
"param": "name",
"type": null
},
{
"param": "num_returns",
"type": null
},
{
"param": "co... | {
"returns": [
{
"docstring": "A list of object refs returned by the remote actor\nmethod.",
"docstring_tokens": [
"A",
"list",
"of",
"object",
"refs",
"returned",
"by",
"the",
"remote",
"actor",
"method",
... |
cdb605fc1fc6acd87803bc58152c9262357532ac | kisuke95/ray | python/ray/actor.py | [
"Apache-2.0"
] | Python | exit_actor | null | def exit_actor():
"""Intentionally exit the current actor.
This function is used to disconnect an actor and exit the worker.
Any ``atexit`` handlers installed in the actor will be run.
Raises:
Exception: An exception is raised if this is a driver or this
worker is not an actor.
... | Intentionally exit the current actor.
This function is used to disconnect an actor and exit the worker.
Any ``atexit`` handlers installed in the actor will be run.
Raises:
Exception: An exception is raised if this is a driver or this
worker is not an actor.
| Intentionally exit the current actor.
This function is used to disconnect an actor and exit the worker.
Any ``atexit`` handlers installed in the actor will be run. | [
"Intentionally",
"exit",
"the",
"current",
"actor",
".",
"This",
"function",
"is",
"used",
"to",
"disconnect",
"an",
"actor",
"and",
"exit",
"the",
"worker",
".",
"Any",
"`",
"`",
"atexit",
"`",
"`",
"handlers",
"installed",
"in",
"the",
"actor",
"will",
... | def exit_actor():
worker = ray.worker.global_worker
if worker.mode == ray.WORKER_MODE and not worker.actor_id.is_nil():
ray.worker.disconnect()
ray.state.state.disconnect()
if worker.core_worker.current_actor_is_asyncio():
raise AsyncioActorExit()
exit = SystemExit(0)... | [
"def",
"exit_actor",
"(",
")",
":",
"worker",
"=",
"ray",
".",
"worker",
".",
"global_worker",
"if",
"worker",
".",
"mode",
"==",
"ray",
".",
"WORKER_MODE",
"and",
"not",
"worker",
".",
"actor_id",
".",
"is_nil",
"(",
")",
":",
"ray",
".",
"worker",
... | Intentionally exit the current actor. | [
"Intentionally",
"exit",
"the",
"current",
"actor",
"."
] | [
"\"\"\"Intentionally exit the current actor.\n\n This function is used to disconnect an actor and exit the worker.\n Any ``atexit`` handlers installed in the actor will be run.\n\n Raises:\n Exception: An exception is raised if this is a driver or this\n worker is not an actor.\n \"\"\... | [] | {
"returns": [],
"raises": [
{
"docstring": "An exception is raised if this is a driver or this\nworker is not an actor.",
"docstring_tokens": [
"An",
"exception",
"is",
"raised",
"if",
"this",
"is",
"a",
"driver",
"or",... |
d6293dca1b77e84f5859f3bac26242fe809d7273 | kisuke95/ray | python/ray/tune/cloud.py | [
"Apache-2.0"
] | Python | save | <not_specific> | def save(self, path: Optional[str] = None, force_download: bool = False):
"""Save trial checkpoint to directory or cloud storage.
If the ``path`` is a local target and the checkpoint already exists
on local storage, the local directory is copied. Else, the checkpoint
is downloaded from ... | Save trial checkpoint to directory or cloud storage.
If the ``path`` is a local target and the checkpoint already exists
on local storage, the local directory is copied. Else, the checkpoint
is downloaded from cloud storage.
If the ``path`` is a cloud target and the checkpoint does not... | Save trial checkpoint to directory or cloud storage.
If the ``path`` is a local target and the checkpoint already exists
on local storage, the local directory is copied. Else, the checkpoint
is downloaded from cloud storage.
If the ``path`` is a cloud target and the checkpoint does not already
exist on local storage, ... | [
"Save",
"trial",
"checkpoint",
"to",
"directory",
"or",
"cloud",
"storage",
".",
"If",
"the",
"`",
"`",
"path",
"`",
"`",
"is",
"a",
"local",
"target",
"and",
"the",
"checkpoint",
"already",
"exists",
"on",
"local",
"storage",
"the",
"local",
"directory",
... | def save(self, path: Optional[str] = None, force_download: bool = False):
temp_dirs = set()
if not path:
if self.cloud_path and self.local_path:
path = self.local_path
elif not self.cloud_path:
raise RuntimeError(
"Cannot save t... | [
"def",
"save",
"(",
"self",
",",
"path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"force_download",
":",
"bool",
"=",
"False",
")",
":",
"temp_dirs",
"=",
"set",
"(",
")",
"if",
"not",
"path",
":",
"if",
"self",
".",
"cloud_path",
"and",... | Save trial checkpoint to directory or cloud storage. | [
"Save",
"trial",
"checkpoint",
"to",
"directory",
"or",
"cloud",
"storage",
"."
] | [
"\"\"\"Save trial checkpoint to directory or cloud storage.\n\n If the ``path`` is a local target and the checkpoint already exists\n on local storage, the local directory is copied. Else, the checkpoint\n is downloaded from cloud storage.\n\n If the ``path`` is a cloud target and the ch... | [
{
"param": "self",
"type": null
},
{
"param": "path",
"type": "Optional[str]"
},
{
"param": "force_download",
"type": "bool"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "path",
"type": "Optional[str]",
"docstring": "Path to save checkpoi... |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | rank_replicas_for_stopping | List["DeploymentReplica"] | def rank_replicas_for_stopping(
all_available_replicas: List["DeploymentReplica"],
) -> List["DeploymentReplica"]:
"""Prioritize replicas that have fewest copies on a node.
This algorithm helps to scale down more intelligently because it can
relinquish node faster. Note that this algorithm doesn't cons... | Prioritize replicas that have fewest copies on a node.
This algorithm helps to scale down more intelligently because it can
relinquish node faster. Note that this algorithm doesn't consider other
deployments or other actors on the same node. See more at
https://github.com/ray-project/ray/issues/20599.
... | Prioritize replicas that have fewest copies on a node.
This algorithm helps to scale down more intelligently because it can
relinquish node faster. Note that this algorithm doesn't consider other
deployments or other actors on the same node. | [
"Prioritize",
"replicas",
"that",
"have",
"fewest",
"copies",
"on",
"a",
"node",
".",
"This",
"algorithm",
"helps",
"to",
"scale",
"down",
"more",
"intelligently",
"because",
"it",
"can",
"relinquish",
"node",
"faster",
".",
"Note",
"that",
"this",
"algorithm"... | def rank_replicas_for_stopping(
all_available_replicas: List["DeploymentReplica"],
) -> List["DeploymentReplica"]:
node_to_replicas = defaultdict(list)
for replica in all_available_replicas:
node_to_replicas[replica.actor_node_id].append(replica)
node_to_replicas.setdefault(None, [])
return ... | [
"def",
"rank_replicas_for_stopping",
"(",
"all_available_replicas",
":",
"List",
"[",
"\"DeploymentReplica\"",
"]",
",",
")",
"->",
"List",
"[",
"\"DeploymentReplica\"",
"]",
":",
"node_to_replicas",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"replica",
"in",
"a... | Prioritize replicas that have fewest copies on a node. | [
"Prioritize",
"replicas",
"that",
"have",
"fewest",
"copies",
"on",
"a",
"node",
"."
] | [
"\"\"\"Prioritize replicas that have fewest copies on a node.\n\n This algorithm helps to scale down more intelligently because it can\n relinquish node faster. Note that this algorithm doesn't consider other\n deployments or other actors on the same node. See more at\n https://github.com/ray-project/ra... | [
{
"param": "all_available_replicas",
"type": "List[\"DeploymentReplica\"]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "all_available_replicas",
"type": "List[\"DeploymentReplica\"]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | start | null | def start(self, deployment_info: DeploymentInfo, version: DeploymentVersion):
"""
Start a new actor for current DeploymentReplica instance.
"""
self._max_concurrent_queries = (
deployment_info.deployment_config.max_concurrent_queries
)
self._graceful_shutdown_... |
Start a new actor for current DeploymentReplica instance.
| Start a new actor for current DeploymentReplica instance. | [
"Start",
"a",
"new",
"actor",
"for",
"current",
"DeploymentReplica",
"instance",
"."
] | def start(self, deployment_info: DeploymentInfo, version: DeploymentVersion):
self._max_concurrent_queries = (
deployment_info.deployment_config.max_concurrent_queries
)
self._graceful_shutdown_timeout_s = (
deployment_info.deployment_config.graceful_shutdown_timeout_s
... | [
"def",
"start",
"(",
"self",
",",
"deployment_info",
":",
"DeploymentInfo",
",",
"version",
":",
"DeploymentVersion",
")",
":",
"self",
".",
"_max_concurrent_queries",
"=",
"(",
"deployment_info",
".",
"deployment_config",
".",
"max_concurrent_queries",
")",
"self",... | Start a new actor for current DeploymentReplica instance. | [
"Start",
"a",
"new",
"actor",
"for",
"current",
"DeploymentReplica",
"instance",
"."
] | [
"\"\"\"\n Start a new actor for current DeploymentReplica instance.\n \"\"\"",
"# it is currently not possible to create a placement group",
"# with no resources (https://github.com/ray-project/ray/issues/20401)",
"# TODO(simon): unify the constructor arguments across language",
"# String depl... | [
{
"param": "self",
"type": null
},
{
"param": "deployment_info",
"type": "DeploymentInfo"
},
{
"param": "version",
"type": "DeploymentVersion"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "deployment_info",
"type": "DeploymentInfo",
"docstring": null,
... |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | update_user_config | null | def update_user_config(self, user_config: Any):
"""
Update user config of existing actor behind current
DeploymentReplica instance.
"""
self._ready_obj_ref = self._actor_handle.reconfigure.remote(user_config) |
Update user config of existing actor behind current
DeploymentReplica instance.
| Update user config of existing actor behind current
DeploymentReplica instance. | [
"Update",
"user",
"config",
"of",
"existing",
"actor",
"behind",
"current",
"DeploymentReplica",
"instance",
"."
] | def update_user_config(self, user_config: Any):
self._ready_obj_ref = self._actor_handle.reconfigure.remote(user_config) | [
"def",
"update_user_config",
"(",
"self",
",",
"user_config",
":",
"Any",
")",
":",
"self",
".",
"_ready_obj_ref",
"=",
"self",
".",
"_actor_handle",
".",
"reconfigure",
".",
"remote",
"(",
"user_config",
")"
] | Update user config of existing actor behind current
DeploymentReplica instance. | [
"Update",
"user",
"config",
"of",
"existing",
"actor",
"behind",
"current",
"DeploymentReplica",
"instance",
"."
] | [
"\"\"\"\n Update user config of existing actor behind current\n DeploymentReplica instance.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user_config",
"type": "Any"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user_config",
"type": "Any",
"docstring": null,
"docstring_to... |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | recover | null | def recover(self):
"""
Recover states in DeploymentReplica instance by fetching running actor
status
"""
logger.debug(
f"Recovering replica {self.replica_tag} for deployment "
f"{self.deployment_name}."
)
self._actor_handle = self.actor_han... |
Recover states in DeploymentReplica instance by fetching running actor
status
| Recover states in DeploymentReplica instance by fetching running actor
status | [
"Recover",
"states",
"in",
"DeploymentReplica",
"instance",
"by",
"fetching",
"running",
"actor",
"status"
] | def recover(self):
logger.debug(
f"Recovering replica {self.replica_tag} for deployment "
f"{self.deployment_name}."
)
self._actor_handle = self.actor_handle
if USE_PLACEMENT_GROUP:
self._placement_group = self.get_placement_group(self._placement_group... | [
"def",
"recover",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Recovering replica {self.replica_tag} for deployment \"",
"f\"{self.deployment_name}.\"",
")",
"self",
".",
"_actor_handle",
"=",
"self",
".",
"actor_handle",
"if",
"USE_PLACEMENT_GROUP",
":",
"se... | Recover states in DeploymentReplica instance by fetching running actor
status | [
"Recover",
"states",
"in",
"DeploymentReplica",
"instance",
"by",
"fetching",
"running",
"actor",
"status"
] | [
"\"\"\"\n Recover states in DeploymentReplica instance by fetching running actor\n status\n \"\"\"",
"# Re-fetch initialization proof",
"# Running actor handle already has all info needed, thus successful",
"# starting simply means retrieving replica version hash from actor"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | check_ready | Tuple[ReplicaStartupStatus, Optional[DeploymentVersion]] | def check_ready(self) -> Tuple[ReplicaStartupStatus, Optional[DeploymentVersion]]:
"""
Check if current replica has started by making ray API calls on
relevant actor / object ref.
Returns:
state (ReplicaStartupStatus):
PENDING_ALLOCATION:
... |
Check if current replica has started by making ray API calls on
relevant actor / object ref.
Returns:
state (ReplicaStartupStatus):
PENDING_ALLOCATION:
- replica is waiting for a worker to start
PENDING_INITIALIZATION
... | Check if current replica has started by making ray API calls on
relevant actor / object ref. | [
"Check",
"if",
"current",
"replica",
"has",
"started",
"by",
"making",
"ray",
"API",
"calls",
"on",
"relevant",
"actor",
"/",
"object",
"ref",
"."
] | def check_ready(self) -> Tuple[ReplicaStartupStatus, Optional[DeploymentVersion]]:
if not self._check_obj_ref_ready(self._allocated_obj_ref):
return ReplicaStartupStatus.PENDING_ALLOCATION, None
replica_ready = self._check_obj_ref_ready(self._ready_obj_ref)
if not replica_ready:
... | [
"def",
"check_ready",
"(",
"self",
")",
"->",
"Tuple",
"[",
"ReplicaStartupStatus",
",",
"Optional",
"[",
"DeploymentVersion",
"]",
"]",
":",
"if",
"not",
"self",
".",
"_check_obj_ref_ready",
"(",
"self",
".",
"_allocated_obj_ref",
")",
":",
"return",
"Replica... | Check if current replica has started by making ray API calls on
relevant actor / object ref. | [
"Check",
"if",
"current",
"replica",
"has",
"started",
"by",
"making",
"ray",
"API",
"calls",
"on",
"relevant",
"actor",
"/",
"object",
"ref",
"."
] | [
"\"\"\"\n Check if current replica has started by making ray API calls on\n relevant actor / object ref.\n\n Returns:\n state (ReplicaStartupStatus):\n PENDING_ALLOCATION:\n - replica is waiting for a worker to start\n PENDING_INITIALI... | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "state (ReplicaStartupStatus):\nPENDING_ALLOCATION:\nreplica is waiting for a worker to start\nPENDING_INITIALIZATION\nreplica reconfigure() haven't returned.\nFAILED:\nreplica __init__() failed.\nSUCCEEDED:\nreplica __init__() and reconfigure() succeeded.\nversion (DeploymentV... |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | graceful_stop | Duration | def graceful_stop(self) -> Duration:
"""Request the actor to exit gracefully.
Returns the timeout after which to kill the actor.
"""
try:
handle = ray.get_actor(
self._actor_name, namespace=self._controller_namespace
)
self._graceful_s... | Request the actor to exit gracefully.
Returns the timeout after which to kill the actor.
| Request the actor to exit gracefully.
Returns the timeout after which to kill the actor. | [
"Request",
"the",
"actor",
"to",
"exit",
"gracefully",
".",
"Returns",
"the",
"timeout",
"after",
"which",
"to",
"kill",
"the",
"actor",
"."
] | def graceful_stop(self) -> Duration:
try:
handle = ray.get_actor(
self._actor_name, namespace=self._controller_namespace
)
self._graceful_shutdown_ref = handle.prepare_for_shutdown.remote()
except ValueError:
pass
return self._grace... | [
"def",
"graceful_stop",
"(",
"self",
")",
"->",
"Duration",
":",
"try",
":",
"handle",
"=",
"ray",
".",
"get_actor",
"(",
"self",
".",
"_actor_name",
",",
"namespace",
"=",
"self",
".",
"_controller_namespace",
")",
"self",
".",
"_graceful_shutdown_ref",
"="... | Request the actor to exit gracefully. | [
"Request",
"the",
"actor",
"to",
"exit",
"gracefully",
"."
] | [
"\"\"\"Request the actor to exit gracefully.\n\n Returns the timeout after which to kill the actor.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | check_stopped | bool | def check_stopped(self) -> bool:
"""Check if the actor has exited."""
try:
handle = ray.get_actor(
self._actor_name, namespace=self._controller_namespace
)
stopped = self._check_obj_ref_ready(self._graceful_shutdown_ref)
if stopped:
... | Check if the actor has exited. | Check if the actor has exited. | [
"Check",
"if",
"the",
"actor",
"has",
"exited",
"."
] | def check_stopped(self) -> bool:
try:
handle = ray.get_actor(
self._actor_name, namespace=self._controller_namespace
)
stopped = self._check_obj_ref_ready(self._graceful_shutdown_ref)
if stopped:
ray.kill(handle, no_restart=True)
... | [
"def",
"check_stopped",
"(",
"self",
")",
"->",
"bool",
":",
"try",
":",
"handle",
"=",
"ray",
".",
"get_actor",
"(",
"self",
".",
"_actor_name",
",",
"namespace",
"=",
"self",
".",
"_controller_namespace",
")",
"stopped",
"=",
"self",
".",
"_check_obj_ref... | Check if the actor has exited. | [
"Check",
"if",
"the",
"actor",
"has",
"exited",
"."
] | [
"\"\"\"Check if the actor has exited.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | _check_active_health_check | ReplicaHealthCheckResponse | def _check_active_health_check(self) -> ReplicaHealthCheckResponse:
"""Check the active health check (if any).
self._health_check_ref will be reset to `None` when the active health
check is deemed to have succeeded or failed. This method *does not*
start a new health check, that's up to... | Check the active health check (if any).
self._health_check_ref will be reset to `None` when the active health
check is deemed to have succeeded or failed. This method *does not*
start a new health check, that's up to the caller.
Returns:
- NONE if there's no active health c... | Check the active health check (if any).
self._health_check_ref will be reset to `None` when the active health
check is deemed to have succeeded or failed. This method *does not
start a new health check, that's up to the caller. | [
"Check",
"the",
"active",
"health",
"check",
"(",
"if",
"any",
")",
".",
"self",
".",
"_health_check_ref",
"will",
"be",
"reset",
"to",
"`",
"None",
"`",
"when",
"the",
"active",
"health",
"check",
"is",
"deemed",
"to",
"have",
"succeeded",
"or",
"failed... | def _check_active_health_check(self) -> ReplicaHealthCheckResponse:
if self._health_check_ref is None:
response = ReplicaHealthCheckResponse.NONE
elif self._check_obj_ref_ready(self._health_check_ref):
try:
ray.get(self._health_check_ref)
response ... | [
"def",
"_check_active_health_check",
"(",
"self",
")",
"->",
"ReplicaHealthCheckResponse",
":",
"if",
"self",
".",
"_health_check_ref",
"is",
"None",
":",
"response",
"=",
"ReplicaHealthCheckResponse",
".",
"NONE",
"elif",
"self",
".",
"_check_obj_ref_ready",
"(",
"... | Check the active health check (if any). | [
"Check",
"the",
"active",
"health",
"check",
"(",
"if",
"any",
")",
"."
] | [
"\"\"\"Check the active health check (if any).\n\n self._health_check_ref will be reset to `None` when the active health\n check is deemed to have succeeded or failed. This method *does not*\n start a new health check, that's up to the caller.\n\n Returns:\n - NONE if there's ... | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "NONE if there's no active health check, or it hasn't returned\nyet and the timeout is not up.\nSUCCEEDED if the active health check succeeded.\nAPP_FAILURE if the active health check failed (or didn't return\nbefore the timeout).\nACTOR_CRASHED if the underlying actor crashed.... |
ab1cc8af10ed239587445b410df0435b41c4631e | kisuke95/ray | python/ray/serve/deployment_state.py | [
"Apache-2.0"
] | Python | _should_start_new_health_check | bool | def _should_start_new_health_check(self) -> bool:
"""Determines if a new health check should be kicked off.
A health check will be started if:
1) There is not already an active health check.
2) It has been more than self._health_check_period_s since the
previous h... | Determines if a new health check should be kicked off.
A health check will be started if:
1) There is not already an active health check.
2) It has been more than self._health_check_period_s since the
previous health check was *started*.
This assumes that self._h... | Determines if a new health check should be kicked off.
A health check will be started if:
1) There is not already an active health check.
2) It has been more than self._health_check_period_s since the
previous health check was *started*.
This assumes that self._health_check_ref is reset to `None` when an
active health... | [
"Determines",
"if",
"a",
"new",
"health",
"check",
"should",
"be",
"kicked",
"off",
".",
"A",
"health",
"check",
"will",
"be",
"started",
"if",
":",
"1",
")",
"There",
"is",
"not",
"already",
"an",
"active",
"health",
"check",
".",
"2",
")",
"It",
"h... | def _should_start_new_health_check(self) -> bool:
if self._health_check_ref is not None:
return False
time_since_last = time.time() - self._last_health_check_time
randomized_period = self._health_check_period_s * random.uniform(0.9, 1.1)
return time_since_last > randomized_pe... | [
"def",
"_should_start_new_health_check",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_health_check_ref",
"is",
"not",
"None",
":",
"return",
"False",
"time_since_last",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_last_health_check_time... | Determines if a new health check should be kicked off. | [
"Determines",
"if",
"a",
"new",
"health",
"check",
"should",
"be",
"kicked",
"off",
"."
] | [
"\"\"\"Determines if a new health check should be kicked off.\n\n A health check will be started if:\n 1) There is not already an active health check.\n 2) It has been more than self._health_check_period_s since the\n previous health check was *started*.\n\n This as... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.