Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Based on the snippet: <|code_start|>"""Lobby."""
# pylint: disable=invalid-name, bad-continuation
# Player inputs in the lobby, and several host settings.
lobby = "lobby"/Struct(
If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(5)),
If(lambda ctx: find_save_version(ctx) >= 20.06, Padding(9)),
Array(8, "teams"/Byte), # team number selected by each player
If(lambda ctx: ctx._.version not in (Version.DE, Version.HD),
Padding(1),
),
Peek("reveal_map_id"/Int32ul),
<|code_end|>
, predict the immediate next line with the help of imports:
from construct import Array, Byte, Bytes, Flag, Int32ul, Padding, Peek, Struct, If, Computed, Embedded, Int32sl
from mgz.enums import GameTypeEnum, RevealMapEnum
from mgz.util import Version, find_save_version
and context (classes, functions, sometimes code) from other files:
# Path: mgz/enums.py
# def GameTypeEnum(ctx):
# """Game Type Enumeration."""
# return Enum(
# ctx,
# RM=0,
# Regicide=1,
# DM=2,
# Scenario=3,
# Campaign=4,
# KingOfTheHill=5,
# WonderRace=6,
# DefendTheWonder=7,
# TurboRandom=8,
# CaptureTheRelic=10,
# SuddenDeath=11,
# BattleRoyale=12,
# EmpireWars=13
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | RevealMapEnum("reveal_map"/Int32ul), |
Given the code snippet: <|code_start|>"""Lobby."""
# pylint: disable=invalid-name, bad-continuation
# Player inputs in the lobby, and several host settings.
lobby = "lobby"/Struct(
If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(5)),
If(lambda ctx: find_save_version(ctx) >= 20.06, Padding(9)),
Array(8, "teams"/Byte), # team number selected by each player
<|code_end|>
, generate the next line using the imports in this file:
from construct import Array, Byte, Bytes, Flag, Int32ul, Padding, Peek, Struct, If, Computed, Embedded, Int32sl
from mgz.enums import GameTypeEnum, RevealMapEnum
from mgz.util import Version, find_save_version
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/enums.py
# def GameTypeEnum(ctx):
# """Game Type Enumeration."""
# return Enum(
# ctx,
# RM=0,
# Regicide=1,
# DM=2,
# Scenario=3,
# Campaign=4,
# KingOfTheHill=5,
# WonderRace=6,
# DefendTheWonder=7,
# TurboRandom=8,
# CaptureTheRelic=10,
# SuddenDeath=11,
# BattleRoyale=12,
# EmpireWars=13
# )
#
# def RevealMapEnum(ctx):
# """Reveal Map Enumeration."""
# return Enum(
# ctx,
# normal=0,
# explored=1,
# all_visible=2,
# no_fog=3,
# )
#
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | If(lambda ctx: ctx._.version not in (Version.DE, Version.HD), |
Based on the snippet: <|code_start|>"""Determine dataset."""
def resolve_hd_version(hd, save_version):
"""Best guess at HD version."""
if hd.version == 1006:
if 'test_57' in hd and hd.test_57.is_57:
return '5.7'
else:
return '5.8'
if hd.version == 1005:
return '>=5.0,<5.7'
if hd.version == 1004:
return '4.8'
if save_version >= 12.36:
return '>=4.6,<4.8'
return None
def get_dataset_data(header):
"""Get dataset."""
sample = header.initial.players[0].attributes.player_stats
mod = None
if 'mod' in sample:
mod = (sample.mod.get('id'), sample.mod.get('version'))
_, ref = get_dataset(header.version, mod)
<|code_end|>
, predict the immediate next line with the help of imports:
import mgz
from mgz.util import Version
from mgz.reference import get_dataset
and context (classes, functions, sometimes code) from other files:
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# Path: mgz/reference.py
# def get_dataset(version, mod):
# """Fetch dataset reference data."""
# if version is Version.DE:
# dataset_id = 100
# elif version is Version.HD:
# dataset_id = 300
# elif mod:
# dataset_id = mod[0]
# else:
# dataset_id = 0
# return dataset_id, json.loads(pkgutil.get_data(REF_PACKAGE, f'data/datasets/{dataset_id}.json'))
. Output only the next line. | if header.version == Version.DE: |
Given snippet: <|code_start|>"""Determine dataset."""
def resolve_hd_version(hd, save_version):
"""Best guess at HD version."""
if hd.version == 1006:
if 'test_57' in hd and hd.test_57.is_57:
return '5.7'
else:
return '5.8'
if hd.version == 1005:
return '>=5.0,<5.7'
if hd.version == 1004:
return '4.8'
if save_version >= 12.36:
return '>=4.6,<4.8'
return None
def get_dataset_data(header):
"""Get dataset."""
sample = header.initial.players[0].attributes.player_stats
mod = None
if 'mod' in sample:
mod = (sample.mod.get('id'), sample.mod.get('version'))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import mgz
from mgz.util import Version
from mgz.reference import get_dataset
and context:
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# Path: mgz/reference.py
# def get_dataset(version, mod):
# """Fetch dataset reference data."""
# if version is Version.DE:
# dataset_id = 100
# elif version is Version.HD:
# dataset_id = 300
# elif mod:
# dataset_id = mod[0]
# else:
# dataset_id = 0
# return dataset_id, json.loads(pkgutil.get_data(REF_PACKAGE, f'data/datasets/{dataset_id}.json'))
which might include code, classes, or functions. Output only the next line. | _, ref = get_dataset(header.version, mod) |
Here is a snippet: <|code_start|> hd_string(data)
data.read(8)
guid = data.read(16)
lobby = hd_string(data)
mod = hd_string(data)
data.read(8)
hd_string(data)
data.read(4)
return dict(
players=players,
guid=str(uuid.UUID(bytes=guid)),
lobby=lobby.decode('utf-8'),
mod=mod.decode('utf-8'),
map_id=map_id,
difficulty_id=difficulty_id
)
def decompress(data):
"""Decompress header bytes."""
prefix_size = 8
header_len, _ = unpack('<II', data)
zlib_header = data.read(header_len - prefix_size)
return io.BytesIO(zlib.decompress(zlib_header, wbits=ZLIB_WBITS))
def parse_version(header, data):
"""Parse and compute game version."""
log = unpack('<I', data)
game, save = unpack('<7sxf', header)
<|code_end|>
. Write the next line using the current file imports:
import io
import hashlib
import re
import struct
import uuid
import zlib
from mgz.util import get_version, Version
and context from other files:
# Path: mgz/util.py
# def get_version(game_version, save_version, log_version):
# """Get version based on version fields."""
# if game_version == 'VER 9.3':
# return Version.AOK
# if game_version == 'VER 9.4':
# if log_version == 3:
# return Version.AOC10
# if log_version == 5 or save_version >= 12.97:
# return Version.DE
# if save_version >= 12.36:
# return Version.HD
# if log_version == 4:
# return Version.AOC10C
# return Version.AOC
# if game_version == 'VER 9.8':
# return Version.USERPATCH12
# if game_version == 'VER 9.9':
# return Version.USERPATCH13
# if game_version == 'VER 9.A':
# return Version.USERPATCH14RC2
# if game_version in ['VER 9.B', 'VER 9.C', 'VER 9.D']:
# return Version.USERPATCH14
# if game_version in ['VER 9.E', 'VER 9.F']:
# return Version.USERPATCH15
# if game_version == 'MCP 9.F':
# return Version.MCP
# if log_version is not None or game_version != 'VER 9.4':
# raise ValueError('unsupported version: {}, {}, {}'.format(game_version, save_version, log_version))
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
, which may include functions, classes, or code. Output only the next line. | version = get_version(game.decode('ascii'), round(save, 2), log) |
Continue the code snippet: <|code_start|> if not offset:
match = REGEXES[player_number].search(data, pos)
end = data.find(BLOCK_END, pos) - pos + len(BLOCK_END)
if match is None:
break
offset = match.start() - pos
while end + 8 < offset:
end += data.find(BLOCK_END, pos + end) - (pos + end) + len(BLOCK_END)
if end + 8 == offset:
break
pos += offset
# Speed optimization: Skip specified fixed-length objects.
test = data[pos:pos + 4]
for fingerprint, offset in SKIP_OBJECTS:
if test == fingerprint:
break
else:
objects.append(dict(parse_object(data, pos), index=index))
offset = None
pos += 31
return objects, pos + end
def parse_mod(header, num_players, version):
"""Parse Userpatch mod version."""
cur = header.tell()
name_length = unpack(f'<xx{num_players}x36x5xh', header)
resources = unpack(f'<{name_length + 1}xIx', header)
values = unpack(f'<{resources}f', header)
header.seek(cur)
<|code_end|>
. Use current file imports:
import io
import hashlib
import re
import struct
import uuid
import zlib
from mgz.util import get_version, Version
and context (classes, functions, or code) from other files:
# Path: mgz/util.py
# def get_version(game_version, save_version, log_version):
# """Get version based on version fields."""
# if game_version == 'VER 9.3':
# return Version.AOK
# if game_version == 'VER 9.4':
# if log_version == 3:
# return Version.AOC10
# if log_version == 5 or save_version >= 12.97:
# return Version.DE
# if save_version >= 12.36:
# return Version.HD
# if log_version == 4:
# return Version.AOC10C
# return Version.AOC
# if game_version == 'VER 9.8':
# return Version.USERPATCH12
# if game_version == 'VER 9.9':
# return Version.USERPATCH13
# if game_version == 'VER 9.A':
# return Version.USERPATCH14RC2
# if game_version in ['VER 9.B', 'VER 9.C', 'VER 9.D']:
# return Version.USERPATCH14
# if game_version in ['VER 9.E', 'VER 9.F']:
# return Version.USERPATCH15
# if game_version == 'MCP 9.F':
# return Version.MCP
# if log_version is not None or game_version != 'VER 9.4':
# raise ValueError('unsupported version: {}, {}, {}'.format(game_version, save_version, log_version))
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
. Output only the next line. | if version is Version.USERPATCH15: |
Based on the snippet: <|code_start|> "wonder_high"/Float32l,
"total_tribute_sent"/Float32l,
"convert_min_adj"/Float32l,
"convert_max_adj"/Float32l,
"convert_resist_min_adj"/Float32l,
"convert_resist_max_adj"/Float32l,
"convert_building_min"/Float32l,
"convert_building_max"/Float32l,
"convert_building_chance"/Float32l,
"spies"/Float32l,
"value_wonders_castles"/Float32l,
"food_score"/Float32l,
"wood_score"/Float32l,
"stone_score"/Float32l,
"gold_score"/Float32l,
Embedded(If(lambda ctx: find_save_version(ctx) >= 11.76, Struct(
"wood_bonus0"/Float32l,
"food_bonus0"/Float32l,
"relic_rate"/Float32l,
"heresy"/Float32l,
"theocracy"/Float32l,
"crenellations"/Float32l,
"construction_rate_mod"/Float32l,
"hun_wonder_bonus"/Float32l,
"spies_discount"/Float32l,
))),
Embedded(If(lambda ctx: find_version(ctx) in (Version.DE, Version.HD), Struct(
Array(this._._.num_header_data - 198, Float32l)
))),
Embedded(If(lambda ctx: find_version(ctx) in [Version.USERPATCH15, Version.MCP], Struct(
<|code_end|>
, predict the immediate next line with the help of imports:
from construct import Embedded, Float32l, If, Struct, this, Array
from mgz.util import ModVersionAdapter, Version, find_version, find_save_version
and context (classes, functions, sometimes code) from other files:
# Path: mgz/util.py
# class ModVersionAdapter(Adapter):
# """Parse mod version."""
#
# def _decode(self, obj, context):
# """Decode mod."""
# number = int(obj)
# mod_id = int(number / 1000)
# mod_version = '.'.join(list(str(number % 1000)))
# return {
# 'id': mod_id,
# 'name': const.MODS.get(mod_id, 'Unknown Mod'),
# 'version': mod_version
# }
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | ModVersionAdapter("mod"/Float32l), |
Continue the code snippet: <|code_start|> "total_kill_and_raze_worth"/Float32l,
"total_tribute_recvd"/Float32l,
"total_value_of_razings"/Float32l,
"castle_high"/Float32l,
"wonder_high"/Float32l,
"total_tribute_sent"/Float32l,
"convert_min_adj"/Float32l,
"convert_max_adj"/Float32l,
"convert_resist_min_adj"/Float32l,
"convert_resist_max_adj"/Float32l,
"convert_building_min"/Float32l,
"convert_building_max"/Float32l,
"convert_building_chance"/Float32l,
"spies"/Float32l,
"value_wonders_castles"/Float32l,
"food_score"/Float32l,
"wood_score"/Float32l,
"stone_score"/Float32l,
"gold_score"/Float32l,
Embedded(If(lambda ctx: find_save_version(ctx) >= 11.76, Struct(
"wood_bonus0"/Float32l,
"food_bonus0"/Float32l,
"relic_rate"/Float32l,
"heresy"/Float32l,
"theocracy"/Float32l,
"crenellations"/Float32l,
"construction_rate_mod"/Float32l,
"hun_wonder_bonus"/Float32l,
"spies_discount"/Float32l,
))),
<|code_end|>
. Use current file imports:
from construct import Embedded, Float32l, If, Struct, this, Array
from mgz.util import ModVersionAdapter, Version, find_version, find_save_version
and context (classes, functions, or code) from other files:
# Path: mgz/util.py
# class ModVersionAdapter(Adapter):
# """Parse mod version."""
#
# def _decode(self, obj, context):
# """Decode mod."""
# number = int(obj)
# mod_id = int(number / 1000)
# mod_version = '.'.join(list(str(number % 1000)))
# return {
# 'id': mod_id,
# 'name': const.MODS.get(mod_id, 'Unknown Mod'),
# 'version': mod_version
# }
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | Embedded(If(lambda ctx: find_version(ctx) in (Version.DE, Version.HD), Struct( |
Next line prediction: <|code_start|> "total_kill_and_raze_worth"/Float32l,
"total_tribute_recvd"/Float32l,
"total_value_of_razings"/Float32l,
"castle_high"/Float32l,
"wonder_high"/Float32l,
"total_tribute_sent"/Float32l,
"convert_min_adj"/Float32l,
"convert_max_adj"/Float32l,
"convert_resist_min_adj"/Float32l,
"convert_resist_max_adj"/Float32l,
"convert_building_min"/Float32l,
"convert_building_max"/Float32l,
"convert_building_chance"/Float32l,
"spies"/Float32l,
"value_wonders_castles"/Float32l,
"food_score"/Float32l,
"wood_score"/Float32l,
"stone_score"/Float32l,
"gold_score"/Float32l,
Embedded(If(lambda ctx: find_save_version(ctx) >= 11.76, Struct(
"wood_bonus0"/Float32l,
"food_bonus0"/Float32l,
"relic_rate"/Float32l,
"heresy"/Float32l,
"theocracy"/Float32l,
"crenellations"/Float32l,
"construction_rate_mod"/Float32l,
"hun_wonder_bonus"/Float32l,
"spies_discount"/Float32l,
))),
<|code_end|>
. Use current file imports:
(from construct import Embedded, Float32l, If, Struct, this, Array
from mgz.util import ModVersionAdapter, Version, find_version, find_save_version)
and context including class names, function names, or small code snippets from other files:
# Path: mgz/util.py
# class ModVersionAdapter(Adapter):
# """Parse mod version."""
#
# def _decode(self, obj, context):
# """Decode mod."""
# number = int(obj)
# mod_id = int(number / 1000)
# mod_version = '.'.join(list(str(number % 1000)))
# return {
# 'id': mod_id,
# 'name': const.MODS.get(mod_id, 'Unknown Mod'),
# 'version': mod_version
# }
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | Embedded(If(lambda ctx: find_version(ctx) in (Version.DE, Version.HD), Struct( |
Next line prediction: <|code_start|> "p4_tribute_recvd"/Float32l,
"p5_tribute_recvd"/Float32l,
"p6_tribute_recvd"/Float32l,
"p7_tribute_recvd"/Float32l,
"p8_tribute_recvd"/Float32l,
"current_unit_worth"/Float32l,
"current_building_worth"/Float32l,
"total_food_gathered"/Float32l,
"total_wood_gathered"/Float32l,
"total_stone_gathered"/Float32l,
"total_gold_gathered"/Float32l,
"total_kill_and_raze_worth"/Float32l,
"total_tribute_recvd"/Float32l,
"total_value_of_razings"/Float32l,
"castle_high"/Float32l,
"wonder_high"/Float32l,
"total_tribute_sent"/Float32l,
"convert_min_adj"/Float32l,
"convert_max_adj"/Float32l,
"convert_resist_min_adj"/Float32l,
"convert_resist_max_adj"/Float32l,
"convert_building_min"/Float32l,
"convert_building_max"/Float32l,
"convert_building_chance"/Float32l,
"spies"/Float32l,
"value_wonders_castles"/Float32l,
"food_score"/Float32l,
"wood_score"/Float32l,
"stone_score"/Float32l,
"gold_score"/Float32l,
<|code_end|>
. Use current file imports:
(from construct import Embedded, Float32l, If, Struct, this, Array
from mgz.util import ModVersionAdapter, Version, find_version, find_save_version)
and context including class names, function names, or small code snippets from other files:
# Path: mgz/util.py
# class ModVersionAdapter(Adapter):
# """Parse mod version."""
#
# def _decode(self, obj, context):
# """Decode mod."""
# number = int(obj)
# mod_id = int(number / 1000)
# mod_version = '.'.join(list(str(number % 1000)))
# return {
# 'id': mod_id,
# 'name': const.MODS.get(mod_id, 'Unknown Mod'),
# 'version': mod_version
# }
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
. Output only the next line. | Embedded(If(lambda ctx: find_save_version(ctx) >= 11.76, Struct( |
Given snippet: <|code_start|> language = None
encoding = 'unknown'
name = 'Unknown'
for pair in ENCODING_MARKERS:
marker = pair[0]
test_encoding = pair[1]
e_m = marker.encode(test_encoding)
for line in instructions.split(b'\n'):
pos = line.find(e_m)
if pos > -1:
encoding = test_encoding
name = line[pos+len(e_m):].decode(encoding).replace('.rms', '')
language = pair[2]
break
# disambiguate certain languages
if not language:
language = 'unknown'
for pair in LANGUAGE_MARKERS:
if instructions.find(pair[0].encode(pair[1])) > -1:
language = pair[2]
break
if encoding == 'unknown':
raise ValueError('could not detect encoding')
return encoding, language, name
def lookup_name(map_id, name, version, reference):
"""Lookup base game map if applicable."""
custom = True
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import mgz
from mgz.util import Version
and context:
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
which might include code, classes, or functions. Output only the next line. | is_de = version == Version.DE |
Given the code snippet: <|code_start|>"""Replay."""
# pylint: disable=invalid-name
# Basic information about the recorded game
replay = "replay"/Struct(
"old_time"/Int32ul,
"world_time"/Int32ul,
"old_world_time"/Int32ul,
"game_speed_id"/Int32ul, # world_time_delta
"world_time_delta_seconds"/Int32ul,
"timer"/Float32l,
"game_speed_float"/Float32l,
"temp_pause"/Byte,
"next_object_id"/Int32ul,
"next_reusable_object_id"/Int32sl,
"random_seed"/Int32ul,
"random_seed_2"/Int32ul,
"rec_player"/Int16ul, # id of the rec owner
"num_players"/Byte, # including gaia
<|code_end|>
, generate the next line using the imports in this file:
from construct import Array, Byte, Flag, Float32l, Int16ul, Int32sl, Int32ul, Padding, Struct, If, Embedded
from mgz.util import Version
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/util.py
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
. Output only the next line. | Embedded(If(lambda ctx: ctx._.version != Version.AOK, Struct( |
Predict the next line for this snippet: <|code_start|> "time"/Int32ul,
)
# Disabled techs, units, and buildings.
disables = "disables"/Struct(
Padding(4),
Padding(64),
If(lambda ctx: ctx._._.version != Version.DE,
Struct(
Array(16, "num_disabled_techs"/Int32ul),
Array(16, Array(30, Padding(4))),
Array(16, "num_disabled_units"/Int32ul),
Array(16, Array(30, Padding(4))),
Array(16, "num_disabled_buildings"/Int32ul),
Array(16, Array(20, Padding(4))),
)
),
If(lambda ctx: ctx._._.version == Version.DE, Bytes(196)),
If(lambda ctx: ctx._._.version == Version.HD, Bytes(644)),
"padding"/Bytes(12)
)
# Game settings.
game_settings = "game_settings"/Struct(
Array(16, AgeEnum("starting_ages"/Int32sl)),
"hd"/If(lambda ctx: find_version(ctx) == Version.HD, Bytes(16)),
Padding(4),
Padding(8),
"map_id"/If(lambda ctx: ctx._._.version != Version.AOK, Int32ul),
Peek("difficulty_id"/Int32ul),
<|code_end|>
with the help of current file imports:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context from other files:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
, which may contain function names, class names, or code. Output only the next line. | DifficultyEnum("difficulty"/Int32ul), |
Continue the code snippet: <|code_start|> )
),
If(lambda ctx: ctx._._.version == Version.DE, Bytes(196)),
If(lambda ctx: ctx._._.version == Version.HD, Bytes(644)),
"padding"/Bytes(12)
)
# Game settings.
game_settings = "game_settings"/Struct(
Array(16, AgeEnum("starting_ages"/Int32sl)),
"hd"/If(lambda ctx: find_version(ctx) == Version.HD, Bytes(16)),
Padding(4),
Padding(8),
"map_id"/If(lambda ctx: ctx._._.version != Version.AOK, Int32ul),
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"lock_teams"/Int32ul,
If(lambda ctx: ctx._._.version == Version.DE,
Struct(
Padding(29),
If(lambda ctx: find_save_version(ctx) >= 13.07, Padding(1)),
If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(132)),
If(lambda ctx: find_save_version(ctx) >= 20.06, Padding(1)),
If(lambda ctx: find_save_version(ctx) >= 20.16, Padding(4)),
If(lambda ctx: find_save_version(ctx) >= 25.02, Padding(4*16)),
If(lambda ctx: find_save_version(ctx) >= 25.06, Padding(4))
)
),
Array(9, "player_info"/Struct(
"data_ref"/Int32ul,
<|code_end|>
. Use current file imports:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context (classes, functions, or code) from other files:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
. Output only the next line. | PlayerTypeEnum("type"/Int32ul), |
Given the code snippet: <|code_start|> Padding(4),
"explored"/Int32ul,
Padding(4),
"all"/Int32ul,
"mode"/Int32ul,
"score"/Int32ul,
"time"/Int32ul,
)
# Disabled techs, units, and buildings.
disables = "disables"/Struct(
Padding(4),
Padding(64),
If(lambda ctx: ctx._._.version != Version.DE,
Struct(
Array(16, "num_disabled_techs"/Int32ul),
Array(16, Array(30, Padding(4))),
Array(16, "num_disabled_units"/Int32ul),
Array(16, Array(30, Padding(4))),
Array(16, "num_disabled_buildings"/Int32ul),
Array(16, Array(20, Padding(4))),
)
),
If(lambda ctx: ctx._._.version == Version.DE, Bytes(196)),
If(lambda ctx: ctx._._.version == Version.HD, Bytes(644)),
"padding"/Bytes(12)
)
# Game settings.
game_settings = "game_settings"/Struct(
<|code_end|>
, generate the next line using the imports in this file:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
. Output only the next line. | Array(16, AgeEnum("starting_ages"/Int32sl)), |
Using the snippet: <|code_start|># Game settings.
game_settings = "game_settings"/Struct(
Array(16, AgeEnum("starting_ages"/Int32sl)),
"hd"/If(lambda ctx: find_version(ctx) == Version.HD, Bytes(16)),
Padding(4),
Padding(8),
"map_id"/If(lambda ctx: ctx._._.version != Version.AOK, Int32ul),
Peek("difficulty_id"/Int32ul),
DifficultyEnum("difficulty"/Int32ul),
"lock_teams"/Int32ul,
If(lambda ctx: ctx._._.version == Version.DE,
Struct(
Padding(29),
If(lambda ctx: find_save_version(ctx) >= 13.07, Padding(1)),
If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(132)),
If(lambda ctx: find_save_version(ctx) >= 20.06, Padding(1)),
If(lambda ctx: find_save_version(ctx) >= 20.16, Padding(4)),
If(lambda ctx: find_save_version(ctx) >= 25.02, Padding(4*16)),
If(lambda ctx: find_save_version(ctx) >= 25.06, Padding(4))
)
),
Array(9, "player_info"/Struct(
"data_ref"/Int32ul,
PlayerTypeEnum("type"/Int32ul),
"name"/PascalString(lengthfield="name_length"/Int32ul)
)),
Padding(36),
Padding(4),
IfThenElse(lambda ctx: ctx._._.version == Version.DE,
Struct(
<|code_end|>
, determine the next line of code. You have imports:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context (class names, function names, or code) available:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
. Output only the next line. | If(lambda ctx: find_save_version(ctx) < 13.34, Find(b'\x9a\x99\x99\x99\x99\x99\x01\x40', None)), # double: 2.2 |
Given snippet: <|code_start|>"""Scenario."""
# pylint: disable=invalid-name, bad-continuation
# Scenario header.
scenario_header = "scenario_header"/Struct(
"next_uid"/Int32ul,
"scenario_version"/Float32l,
Array(16, "names"/String(256)),
Array(16, "player_ids"/Int32ul),
Array(16, "player_data"/Struct(
"active"/Int32ul,
"human"/Int32ul,
"civilization"/Int32ul,
"constant"/Int32ul, # 0x04 0x00 0x00 0x00
)),
Padding(5),
"elapsed_time"/Float32l,
"scenario_filename"/PascalString(lengthfield="scenario_filename_length"/Int16ul),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
which might include code, classes, or functions. Output only the next line. | If(lambda ctx: ctx._._.version == Version.DE, Struct( |
Given the code snippet: <|code_start|>"""Scenario."""
# pylint: disable=invalid-name, bad-continuation
# Scenario header.
scenario_header = "scenario_header"/Struct(
"next_uid"/Int32ul,
"scenario_version"/Float32l,
Array(16, "names"/String(256)),
Array(16, "player_ids"/Int32ul),
Array(16, "player_data"/Struct(
"active"/Int32ul,
"human"/Int32ul,
"civilization"/Int32ul,
"constant"/Int32ul, # 0x04 0x00 0x00 0x00
)),
Padding(5),
"elapsed_time"/Float32l,
"scenario_filename"/PascalString(lengthfield="scenario_filename_length"/Int16ul),
If(lambda ctx: ctx._._.version == Version.DE, Struct(
Padding(64),
<|code_end|>
, generate the next line using the imports in this file:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context (functions, classes, or occasionally code) from other files:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
. Output only the next line. | If(lambda ctx: find_save_version(ctx) >= 13.34, Padding(64)) |
Using the snippet: <|code_start|> "explored"/Int32ul,
Padding(4),
"all"/Int32ul,
"mode"/Int32ul,
"score"/Int32ul,
"time"/Int32ul,
)
# Disabled techs, units, and buildings.
disables = "disables"/Struct(
Padding(4),
Padding(64),
If(lambda ctx: ctx._._.version != Version.DE,
Struct(
Array(16, "num_disabled_techs"/Int32ul),
Array(16, Array(30, Padding(4))),
Array(16, "num_disabled_units"/Int32ul),
Array(16, Array(30, Padding(4))),
Array(16, "num_disabled_buildings"/Int32ul),
Array(16, Array(20, Padding(4))),
)
),
If(lambda ctx: ctx._._.version == Version.DE, Bytes(196)),
If(lambda ctx: ctx._._.version == Version.HD, Bytes(644)),
"padding"/Bytes(12)
)
# Game settings.
game_settings = "game_settings"/Struct(
Array(16, AgeEnum("starting_ages"/Int32sl)),
<|code_end|>
, determine the next line of code. You have imports:
from construct import (Array, Float32l, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Peek, String, Struct, Bytes, If, IfThenElse)
from mgz.enums import DifficultyEnum, PlayerTypeEnum, AgeEnum
from mgz.util import Find, Version, find_save_version, find_version
and context (class names, function names, or code) available:
# Path: mgz/enums.py
# def DifficultyEnum(ctx):
# """Difficulty Enumeration."""
# return Enum(
# ctx,
# hardest=0,
# hard=1,
# moderate=2,
# standard=3,
# easiest=4,
# extreme=5,
# unknown=6
# )
#
# def PlayerTypeEnum(ctx):
# """Player Type Enumeration."""
# return Enum(
# ctx,
# absent=0,
# closed=1,
# human=2,
# eliminated=3,
# computer=4,
# cyborg=5,
# spectator=6
# )
#
# def AgeEnum(ctx):
# """Age Enumeration."""
# return Enum(
# ctx,
# what=-2,
# unset=-1,
# dark=0,
# feudal=1,
# castle=2,
# imperial=3,
# postimperial=4,
# dmpostimperial=6,
# default='unknown'
# )
#
# Path: mgz/util.py
# class Find(Construct):
# """Find bytes, and read past them."""
#
# __slots__ = ["find", "max_length"]
#
# def __init__(self, find, max_length):
# """Initiallize."""
# Construct.__init__(self)
# if not isinstance(find, list):
# find = [find]
# self.find = find
# self.max_length = max_length
#
# def _parse(self, stream, context, path):
# """Parse stream to find a given byte string."""
# start = stream.tell()
# read_bytes = ""
# if self.max_length:
# read_bytes = stream.read(self.max_length)
# else:
# read_bytes = stream.read()
# candidates = []
# for f in self.find:
# match = re.search(f, read_bytes)
# if not match:
# continue
# candidates.append(match.end())
# if not candidates:
# raise RuntimeError('could not find bytes: {}'.format(f))
# choice = min(candidates)
# stream.seek(start + choice)
# return choice
#
# class Version(Enum):
# """Version enumeration.
#
# Using consts from https://github.com/goto-bus-stop/recanalyst/blob/master/src/Model/Version.php
# for consistency.
# """
# AOK = 1
# AOC = 4
# AOC10 = 5
# AOC10C = 8
# USERPATCH12 = 12
# USERPATCH13 = 13
# USERPATCH14 = 11
# USERPATCH15 = 20
# DE = 21
# USERPATCH14RC2 = 22
# MCP = 30
# HD = 19
#
# def find_save_version(ctx):
# """Find save version."""
# if 'save_version' not in ctx:
# return find_save_version(ctx._)
# return ctx.save_version
#
# def find_version(ctx):
# """Find version."""
# if 'version' not in ctx:
# return find_version(ctx._)
# return ctx.version
. Output only the next line. | "hd"/If(lambda ctx: find_version(ctx) == Version.HD, Bytes(16)), |
Predict the next line after this snippet: <|code_start|>
military = "military"/Struct(
"score"/Int16ul,
"units_killed"/Int16ul,
"hit_points_killed"/Int16ul,
"units_lost"/Int16ul,
"buildings_razed"/Int16ul,
"hit_points_razed"/Int16ul,
"buildings_lost"/Int16ul,
"units_converted"/Int16ul
)
economy = "economy"/Struct(
"score"/Int16ul,
Padding(2),
"food_collected"/Int32ul,
"wood_collected"/Int32ul,
"stone_collected"/Int32ul,
"gold_collected"/Int32ul,
"tribute_sent"/Int16ul,
"tribute_received"/Int16ul,
"trade_gold"/Int16ul,
"relic_gold"/Int16ul
)
technology = "technology"/Struct(
"score"/Int16ul,
Padding(2),
Peek("feudal_time_int"/Int32sl),
<|code_end|>
using the current file's imports:
from construct import (Array, Byte, Flag, Int16ul, Int32sl, Int32ul, Padding,
Peek, Struct, Bytes)
from mgz.util import TimeSecAdapter
and any relevant context from other files:
# Path: mgz/util.py
# class TimeSecAdapter(Adapter):
# """Conversion to readable time."""
#
# def _decode(self, obj, context):
# """Decode timestamp to string."""
# return convert_to_timestamp(obj)
. Output only the next line. | TimeSecAdapter("feudal_time"/Int32sl), |
Next line prediction: <|code_start|> return space.solution(sv)
queue = deque([sv])
while queue and (elapsed_time(space.start_time) < max_time) and (space.iterations < max_iterations):
cv = pop(queue)
space.iterations += 1
if debug is not None:
debug(cv)
while cv.generate(): # TODO: generate_all
pass
if cv.h_cost is None:
break
for nv in cv.unexplored(): # TODO - should reverse order for DFS
if nv.contained(goal):
return space.solution(nv)
queue.append(nv)
return space.failure()
##################################################
def dfs(*args):
return simple_search(lambda queue: queue.pop(), *args)
def bfs(*args):
return simple_search(lambda queue: queue.popleft(), *args)
def srandom_walk(*args):
<|code_end|>
. Use current file imports:
(from collections import deque
from .utils import pop_random, pop_rrt
from ..state_space import StateSpace
from misc.functions import elapsed_time)
and context including class names, function names, or small code snippets from other files:
# Path: planner/progression/utils.py
# def pop_random(queue):
# queue.rotate(randint(0, len(queue) - 1))
# return queue.popleft()
#
# def pop_rrt(distance, sample, goal_sample=None, goal_probability=DEFAULT_GOAL_PROBABILITY):
# return lambda queue: pop_min(
# queue, lambda sv: distance(sv.state, sample_target(
# sample, goal_sample=goal_sample, goal_probability=goal_probability)))
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
. Output only the next line. | return simple_search(pop_random, *args) |
Using the snippet: <|code_start|> if debug is not None:
debug(cv)
while cv.generate(): # TODO: generate_all
pass
if cv.h_cost is None:
break
for nv in cv.unexplored(): # TODO - should reverse order for DFS
if nv.contained(goal):
return space.solution(nv)
queue.append(nv)
return space.failure()
##################################################
def dfs(*args):
return simple_search(lambda queue: queue.pop(), *args)
def bfs(*args):
return simple_search(lambda queue: queue.popleft(), *args)
def srandom_walk(*args):
return simple_search(pop_random, *args)
def srrt(start, goal, generator, max_time, max_iterations, max_generations, max_cost, max_length, debug,
distance, sample, goal_sample, goal_probability):
<|code_end|>
, determine the next line of code. You have imports:
from collections import deque
from .utils import pop_random, pop_rrt
from ..state_space import StateSpace
from misc.functions import elapsed_time
and context (class names, function names, or code) available:
# Path: planner/progression/utils.py
# def pop_random(queue):
# queue.rotate(randint(0, len(queue) - 1))
# return queue.popleft()
#
# def pop_rrt(distance, sample, goal_sample=None, goal_probability=DEFAULT_GOAL_PROBABILITY):
# return lambda queue: pop_min(
# queue, lambda sv: distance(sv.state, sample_target(
# sample, goal_sample=goal_sample, goal_probability=goal_probability)))
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
. Output only the next line. | return simple_search(pop_rrt(distance, sample, goal_sample, goal_probability), start, goal, generator, |
Continue the code snippet: <|code_start|>
def simple_search(pop, start, goal, generator, max_time, max_iterations, max_generations, max_cost, max_length, debug):
space = StateSpace(generator, start, 1, max_generations, max_cost, max_length)
sv = space.root
if sv.contained(goal):
return space.solution(sv)
queue = deque([sv])
<|code_end|>
. Use current file imports:
from collections import deque
from .utils import pop_random, pop_rrt
from ..state_space import StateSpace
from misc.functions import elapsed_time
and context (classes, functions, or code) from other files:
# Path: planner/progression/utils.py
# def pop_random(queue):
# queue.rotate(randint(0, len(queue) - 1))
# return queue.popleft()
#
# def pop_rrt(distance, sample, goal_sample=None, goal_probability=DEFAULT_GOAL_PROBABILITY):
# return lambda queue: pop_min(
# queue, lambda sv: distance(sv.state, sample_target(
# sample, goal_sample=goal_sample, goal_probability=goal_probability)))
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
. Output only the next line. | while queue and (elapsed_time(space.start_time) < max_time) and (space.iterations < max_iterations): |
Given snippet: <|code_start|>
def safe_next(generator, i=None):
if i is None:
values = list(islice(generator, 1))
if len(values) == 0: return None
return values[0]
return list(islice(generator, i))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import Iterator
from itertools import islice
from .numerical import INF
and context:
# Path: misc/numerical.py
# INF = float('inf')
which might include code, classes, or functions. Output only the next line. | def take(iterable, n=INF): |
Continue the code snippet: <|code_start|> self.active = False
for source_vertex, edge in self.sources:
edge.update_inactive()
#if source_vertex is not None:
# source_vertex.update_inactive()
def update_inactive(self): # TODO - this is really slow. Only search if not greedy and reached?
if not self.active: return
self.active = False # Temporarily set to inactive
for connector in self.connectors:
connector.update_inactive()
if connector.active:
self.active = True
return
#for sink_vertex, _ in self.sinks:
# sink_vertex.update_inactive()
# if sink_vertex.active:
# self.active = True
# return
# Cannot find active parent node
self.set_inactive()
"""
def __str__(self):
return 'V(' + str(self.substate) + ')'
__repr__ = __str__
def node_str(self):
#if len(self.substate) == 0: # If this happens, there is a problem...
# return 'EmptySet'
<|code_end|>
. Use current file imports:
from .utils import *
from misc.objects import str_object
from misc.functions import flatten
and context (classes, functions, or code) from other files:
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
#
# Path: misc/functions.py
# def flatten(iterable_of_iterables):
# return (item for iterables in iterable_of_iterables for item in iterables)
. Output only the next line. | return '\n'.join([str_object(variable) + '=' + str_object(value) for variable, value in self.substate]) |
Based on the snippet: <|code_start|> modified_operator = deepcopy(operator)
modified_operator.original = operator
for v, val in operator.cond():
if v not in operator.effects: # NOTE - adds operator image
modified_operator.effects[v] = val
if hierarchy((v, val), operator) > level:
del modified_operator.conditions[v]
modified_operators.append(modified_operator)
plan, state_space = subsearch(start, goal, modified_operators)
#print(plan.length)
if plan is None:
return None, None
state = start
sequence = []
#for operator in plan.operators + [goal]: # TODO - should I assume that the last operator achieves the goal or not?
for modified_operator in plan.operators:
operator = modified_operator.original
if state not in operator:
#print(state, operator)
#print()
subplan, subdata = fixed_search(state, Goal(operator.conditions), operators, subsearch, hierarchy, level=level+1)
if subplan is None:
return None, None
state = subplan.get_states()[-1]
sequence += subplan.operators
if operator != goal:
state = operator(state)
sequence.append(operator)
<|code_end|>
, predict the immediate next line with the help of imports:
from planner.state_space import Plan
from sas.states import Goal
from copy import deepcopy
and context (classes, functions, sometimes code) from other files:
# Path: planner/state_space.py
# class Plan(object):
# def __init__(self, start, operators):
# self.start = start
# self.operators = operators
# @property
# def cost(self):
# if not self.operators:
# return 0
# return sum(operator.cost for operator in self.operators)
# @property
# def length(self):
# return len(self.operators)
# @property
# def priority(self):
# return Priority(self.cost, self.length)
# def __iter__(self):
# return iter(self.operators)
# def get_states(self):
# states = [self.start]
# for operator in self.operators:
# #assert states[-1] in operator
# #states.append(operator(states[-1]))
# states.append(operator.apply(states[-1]))
# return states
# def get_derived_states(self, axioms):
# states = [self.start]
# derived_state, axiom_plan = derive_predicates(states[-1], axioms)
# derived_states = [derived_state]
# axiom_plans = [axiom_plan]
# for operator in self.operators:
# assert derived_states[-1] in operator
# states.append(operator.apply(states[-1]))
# derived_state, axiom_plan = derive_predicates(states[-1], axioms)
# derived_states.append(derived_state)
# axiom_plans.append(axiom_plan)
# return derived_states, axiom_plans
# def __str__(self):
# s = '{name} | Cost: {self.cost} | Length {self.length}'.format(name=self.__class__.__name__, self=self)
# for i, operator in enumerate(self.operators):
# s += str_line('\n%d | '%(i+1), operator)
# return s
# __repr__ = __str__
#
# Path: sas/states.py
# class Goal(PartialState): # TODO: unify PartialState and Goal
# def __init__(self, values, test=lambda state: True):
# self.conditions = values
# self.test = test
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.cond())))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
. Output only the next line. | return Plan(start, sequence), None # TODO - merge state-spaces |
Here is a snippet: <|code_start|>
def fixed_search(start, goal, operators, subsearch, hierarchy, level=0):
# Modify operators wrt hierarchy but not goal?
# Can always modify operators to produce additional effects from the projected preconditions
modified_operators = []
#for operator in operators + [goal]: # TODO - include goal
for operator in operators:
modified_operator = deepcopy(operator)
modified_operator.original = operator
for v, val in operator.cond():
if v not in operator.effects: # NOTE - adds operator image
modified_operator.effects[v] = val
if hierarchy((v, val), operator) > level:
del modified_operator.conditions[v]
modified_operators.append(modified_operator)
plan, state_space = subsearch(start, goal, modified_operators)
#print(plan.length)
if plan is None:
return None, None
state = start
sequence = []
#for operator in plan.operators + [goal]: # TODO - should I assume that the last operator achieves the goal or not?
for modified_operator in plan.operators:
operator = modified_operator.original
if state not in operator:
#print(state, operator)
#print()
<|code_end|>
. Write the next line using the current file imports:
from planner.state_space import Plan
from sas.states import Goal
from copy import deepcopy
and context from other files:
# Path: planner/state_space.py
# class Plan(object):
# def __init__(self, start, operators):
# self.start = start
# self.operators = operators
# @property
# def cost(self):
# if not self.operators:
# return 0
# return sum(operator.cost for operator in self.operators)
# @property
# def length(self):
# return len(self.operators)
# @property
# def priority(self):
# return Priority(self.cost, self.length)
# def __iter__(self):
# return iter(self.operators)
# def get_states(self):
# states = [self.start]
# for operator in self.operators:
# #assert states[-1] in operator
# #states.append(operator(states[-1]))
# states.append(operator.apply(states[-1]))
# return states
# def get_derived_states(self, axioms):
# states = [self.start]
# derived_state, axiom_plan = derive_predicates(states[-1], axioms)
# derived_states = [derived_state]
# axiom_plans = [axiom_plan]
# for operator in self.operators:
# assert derived_states[-1] in operator
# states.append(operator.apply(states[-1]))
# derived_state, axiom_plan = derive_predicates(states[-1], axioms)
# derived_states.append(derived_state)
# axiom_plans.append(axiom_plan)
# return derived_states, axiom_plans
# def __str__(self):
# s = '{name} | Cost: {self.cost} | Length {self.length}'.format(name=self.__class__.__name__, self=self)
# for i, operator in enumerate(self.operators):
# s += str_line('\n%d | '%(i+1), operator)
# return s
# __repr__ = __str__
#
# Path: sas/states.py
# class Goal(PartialState): # TODO: unify PartialState and Goal
# def __init__(self, values, test=lambda state: True):
# self.conditions = values
# self.test = test
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.cond())))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
, which may include functions, classes, or code. Output only the next line. | subplan, subdata = fixed_search(state, Goal(operator.conditions), operators, subsearch, hierarchy, level=level+1) |
Given snippet: <|code_start|>
def random_policy(current_vertex):
edges = current_vertex.get_successors()
if not edges:
return None # current_vertex
return random.choice(edges)
def greedy_policy(current_vertex, weight=1, shuffle=True):
# TODO: function that returns the policy
# TODO: use evaluators
edges = current_vertex.get_successors()
if not edges:
return None
if shuffle:
edges = randomize(edges)
return min(edges, key=lambda e: e.cost + weight*e.sink.get_h_cost())
##################################################
def random_walk(start, goal, generator, _=None, policy=random_policy, max_steps=INF, debug=None, **kwargs):
space = StateSpace(generator, start, max_extensions=INF, **kwargs)
current_vertex = space.root
edge_path = []
while space.is_active() and len(edge_path) < max_steps:
#current_vertex.generate_all()
space.new_iteration(current_vertex)
if debug is not None:
debug(current_vertex)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import math
import numpy
from planner.state_space import test_goal, test_parent_operator, StateSpace, Solution, Plan
from misc.numerical import INF
from misc.functions import randomize
and context:
# Path: planner/state_space.py
# IS_SAFE = True # http://www.fast-downward.org/Doc/Evaluator
# class Plan(object):
# class Vertex(object):
# class Edge(object):
# class StateSpace(object):
# def __init__(self, start, operators):
# def cost(self):
# def length(self):
# def priority(self):
# def __iter__(self):
# def get_states(self):
# def get_derived_states(self, axioms):
# def __str__(self):
# def test_goal(vertex, goal):
# def test_parent_operator(sink_vertex):
# def __init__(self, state, state_space):
# def num_unexplored(self):
# def reset_path(self):
# def priority(self):
# def relax(self, edge):
# def get_children(self):
# def contained(self, partial_state):
# def enumerated(self):
# def get_h_cost(self):
# def get_successors(self):
# def is_dead_end(self):
# def evaluate(self):
# def extend_state_space(self):
# def generate(self):
# def generate_all(self):
# def has_unexplored(self):
# def unexplored(self):
# def dump(self):
# def __str__(self):
# def __init__(self, source, sink, operator, state_space):
# def path_cost(self):
# def path_length(self):
# def priority(self):
# def is_parent(self): # TODO: what was the purpose of this?
# def evaluate_test(self):
# def __str__(self):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# def has_state(self, state):
# def get_state(self, state):
# def __iter__(self):
# def __len__(self):
# def new_iteration(self, vertex):
# def is_active(self):
# def extend(self, vertex, operator):
# def retrace(self, vertex):
# def plan(self, vertex):
# def solution(self, vertex):
# def failure(self):
# def time_elapsed(self):
# def __repr__(self):
# def dump(self):
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/functions.py
# def randomize(sequence):
# shuffle(sequence)
# return sequence
which might include code, classes, or functions. Output only the next line. | if test_goal(current_vertex, goal): |
Predict the next line for this snippet: <|code_start|>
def random_policy(current_vertex):
edges = current_vertex.get_successors()
if not edges:
return None # current_vertex
return random.choice(edges)
def greedy_policy(current_vertex, weight=1, shuffle=True):
# TODO: function that returns the policy
# TODO: use evaluators
edges = current_vertex.get_successors()
if not edges:
return None
if shuffle:
edges = randomize(edges)
return min(edges, key=lambda e: e.cost + weight*e.sink.get_h_cost())
##################################################
def random_walk(start, goal, generator, _=None, policy=random_policy, max_steps=INF, debug=None, **kwargs):
<|code_end|>
with the help of current file imports:
import random
import math
import numpy
from planner.state_space import test_goal, test_parent_operator, StateSpace, Solution, Plan
from misc.numerical import INF
from misc.functions import randomize
and context from other files:
# Path: planner/state_space.py
# IS_SAFE = True # http://www.fast-downward.org/Doc/Evaluator
# class Plan(object):
# class Vertex(object):
# class Edge(object):
# class StateSpace(object):
# def __init__(self, start, operators):
# def cost(self):
# def length(self):
# def priority(self):
# def __iter__(self):
# def get_states(self):
# def get_derived_states(self, axioms):
# def __str__(self):
# def test_goal(vertex, goal):
# def test_parent_operator(sink_vertex):
# def __init__(self, state, state_space):
# def num_unexplored(self):
# def reset_path(self):
# def priority(self):
# def relax(self, edge):
# def get_children(self):
# def contained(self, partial_state):
# def enumerated(self):
# def get_h_cost(self):
# def get_successors(self):
# def is_dead_end(self):
# def evaluate(self):
# def extend_state_space(self):
# def generate(self):
# def generate_all(self):
# def has_unexplored(self):
# def unexplored(self):
# def dump(self):
# def __str__(self):
# def __init__(self, source, sink, operator, state_space):
# def path_cost(self):
# def path_length(self):
# def priority(self):
# def is_parent(self): # TODO: what was the purpose of this?
# def evaluate_test(self):
# def __str__(self):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# def has_state(self, state):
# def get_state(self, state):
# def __iter__(self):
# def __len__(self):
# def new_iteration(self, vertex):
# def is_active(self):
# def extend(self, vertex, operator):
# def retrace(self, vertex):
# def plan(self, vertex):
# def solution(self, vertex):
# def failure(self):
# def time_elapsed(self):
# def __repr__(self):
# def dump(self):
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/functions.py
# def randomize(sequence):
# shuffle(sequence)
# return sequence
, which may contain function names, class names, or code. Output only the next line. | space = StateSpace(generator, start, max_extensions=INF, **kwargs) |
Given the code snippet: <|code_start|>def random_policy(current_vertex):
edges = current_vertex.get_successors()
if not edges:
return None # current_vertex
return random.choice(edges)
def greedy_policy(current_vertex, weight=1, shuffle=True):
# TODO: function that returns the policy
# TODO: use evaluators
edges = current_vertex.get_successors()
if not edges:
return None
if shuffle:
edges = randomize(edges)
return min(edges, key=lambda e: e.cost + weight*e.sink.get_h_cost())
##################################################
def random_walk(start, goal, generator, _=None, policy=random_policy, max_steps=INF, debug=None, **kwargs):
space = StateSpace(generator, start, max_extensions=INF, **kwargs)
current_vertex = space.root
edge_path = []
while space.is_active() and len(edge_path) < max_steps:
#current_vertex.generate_all()
space.new_iteration(current_vertex)
if debug is not None:
debug(current_vertex)
if test_goal(current_vertex, goal):
operator_path = [edge.operator for edge in edge_path]
plan = Plan(start, operator_path)
<|code_end|>
, generate the next line using the imports in this file:
import random
import math
import numpy
from planner.state_space import test_goal, test_parent_operator, StateSpace, Solution, Plan
from misc.numerical import INF
from misc.functions import randomize
and context (functions, classes, or occasionally code) from other files:
# Path: planner/state_space.py
# IS_SAFE = True # http://www.fast-downward.org/Doc/Evaluator
# class Plan(object):
# class Vertex(object):
# class Edge(object):
# class StateSpace(object):
# def __init__(self, start, operators):
# def cost(self):
# def length(self):
# def priority(self):
# def __iter__(self):
# def get_states(self):
# def get_derived_states(self, axioms):
# def __str__(self):
# def test_goal(vertex, goal):
# def test_parent_operator(sink_vertex):
# def __init__(self, state, state_space):
# def num_unexplored(self):
# def reset_path(self):
# def priority(self):
# def relax(self, edge):
# def get_children(self):
# def contained(self, partial_state):
# def enumerated(self):
# def get_h_cost(self):
# def get_successors(self):
# def is_dead_end(self):
# def evaluate(self):
# def extend_state_space(self):
# def generate(self):
# def generate_all(self):
# def has_unexplored(self):
# def unexplored(self):
# def dump(self):
# def __str__(self):
# def __init__(self, source, sink, operator, state_space):
# def path_cost(self):
# def path_length(self):
# def priority(self):
# def is_parent(self): # TODO: what was the purpose of this?
# def evaluate_test(self):
# def __str__(self):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# def has_state(self, state):
# def get_state(self, state):
# def __iter__(self):
# def __len__(self):
# def new_iteration(self, vertex):
# def is_active(self):
# def extend(self, vertex, operator):
# def retrace(self, vertex):
# def plan(self, vertex):
# def solution(self, vertex):
# def failure(self):
# def time_elapsed(self):
# def __repr__(self):
# def dump(self):
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/functions.py
# def randomize(sequence):
# shuffle(sequence)
# return sequence
. Output only the next line. | return Solution(plan, space) |
Given the code snippet: <|code_start|>
def random_policy(current_vertex):
edges = current_vertex.get_successors()
if not edges:
return None # current_vertex
return random.choice(edges)
def greedy_policy(current_vertex, weight=1, shuffle=True):
# TODO: function that returns the policy
# TODO: use evaluators
edges = current_vertex.get_successors()
if not edges:
return None
if shuffle:
edges = randomize(edges)
return min(edges, key=lambda e: e.cost + weight*e.sink.get_h_cost())
##################################################
def random_walk(start, goal, generator, _=None, policy=random_policy, max_steps=INF, debug=None, **kwargs):
space = StateSpace(generator, start, max_extensions=INF, **kwargs)
current_vertex = space.root
edge_path = []
while space.is_active() and len(edge_path) < max_steps:
#current_vertex.generate_all()
space.new_iteration(current_vertex)
if debug is not None:
debug(current_vertex)
if test_goal(current_vertex, goal):
operator_path = [edge.operator for edge in edge_path]
<|code_end|>
, generate the next line using the imports in this file:
import random
import math
import numpy
from planner.state_space import test_goal, test_parent_operator, StateSpace, Solution, Plan
from misc.numerical import INF
from misc.functions import randomize
and context (functions, classes, or occasionally code) from other files:
# Path: planner/state_space.py
# IS_SAFE = True # http://www.fast-downward.org/Doc/Evaluator
# class Plan(object):
# class Vertex(object):
# class Edge(object):
# class StateSpace(object):
# def __init__(self, start, operators):
# def cost(self):
# def length(self):
# def priority(self):
# def __iter__(self):
# def get_states(self):
# def get_derived_states(self, axioms):
# def __str__(self):
# def test_goal(vertex, goal):
# def test_parent_operator(sink_vertex):
# def __init__(self, state, state_space):
# def num_unexplored(self):
# def reset_path(self):
# def priority(self):
# def relax(self, edge):
# def get_children(self):
# def contained(self, partial_state):
# def enumerated(self):
# def get_h_cost(self):
# def get_successors(self):
# def is_dead_end(self):
# def evaluate(self):
# def extend_state_space(self):
# def generate(self):
# def generate_all(self):
# def has_unexplored(self):
# def unexplored(self):
# def dump(self):
# def __str__(self):
# def __init__(self, source, sink, operator, state_space):
# def path_cost(self):
# def path_length(self):
# def priority(self):
# def is_parent(self): # TODO: what was the purpose of this?
# def evaluate_test(self):
# def __str__(self):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# def has_state(self, state):
# def get_state(self, state):
# def __iter__(self):
# def __len__(self):
# def new_iteration(self, vertex):
# def is_active(self):
# def extend(self, vertex, operator):
# def retrace(self, vertex):
# def plan(self, vertex):
# def solution(self, vertex):
# def failure(self):
# def time_elapsed(self):
# def __repr__(self):
# def dump(self):
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/functions.py
# def randomize(sequence):
# shuffle(sequence)
# return sequence
. Output only the next line. | plan = Plan(start, operator_path) |
Continue the code snippet: <|code_start|>
def random_policy(current_vertex):
edges = current_vertex.get_successors()
if not edges:
return None # current_vertex
return random.choice(edges)
def greedy_policy(current_vertex, weight=1, shuffle=True):
# TODO: function that returns the policy
# TODO: use evaluators
edges = current_vertex.get_successors()
if not edges:
return None
if shuffle:
edges = randomize(edges)
return min(edges, key=lambda e: e.cost + weight*e.sink.get_h_cost())
##################################################
<|code_end|>
. Use current file imports:
import random
import math
import numpy
from planner.state_space import test_goal, test_parent_operator, StateSpace, Solution, Plan
from misc.numerical import INF
from misc.functions import randomize
and context (classes, functions, or code) from other files:
# Path: planner/state_space.py
# IS_SAFE = True # http://www.fast-downward.org/Doc/Evaluator
# class Plan(object):
# class Vertex(object):
# class Edge(object):
# class StateSpace(object):
# def __init__(self, start, operators):
# def cost(self):
# def length(self):
# def priority(self):
# def __iter__(self):
# def get_states(self):
# def get_derived_states(self, axioms):
# def __str__(self):
# def test_goal(vertex, goal):
# def test_parent_operator(sink_vertex):
# def __init__(self, state, state_space):
# def num_unexplored(self):
# def reset_path(self):
# def priority(self):
# def relax(self, edge):
# def get_children(self):
# def contained(self, partial_state):
# def enumerated(self):
# def get_h_cost(self):
# def get_successors(self):
# def is_dead_end(self):
# def evaluate(self):
# def extend_state_space(self):
# def generate(self):
# def generate_all(self):
# def has_unexplored(self):
# def unexplored(self):
# def dump(self):
# def __str__(self):
# def __init__(self, source, sink, operator, state_space):
# def path_cost(self):
# def path_length(self):
# def priority(self):
# def is_parent(self): # TODO: what was the purpose of this?
# def evaluate_test(self):
# def __str__(self):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# def has_state(self, state):
# def get_state(self, state):
# def __iter__(self):
# def __len__(self):
# def new_iteration(self, vertex):
# def is_active(self):
# def extend(self, vertex, operator):
# def retrace(self, vertex):
# def plan(self, vertex):
# def solution(self, vertex):
# def failure(self):
# def time_elapsed(self):
# def __repr__(self):
# def dump(self):
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/functions.py
# def randomize(sequence):
# shuffle(sequence)
# return sequence
. Output only the next line. | def random_walk(start, goal, generator, _=None, policy=random_policy, max_steps=INF, debug=None, **kwargs): |
Given snippet: <|code_start|>
def random_policy(current_vertex):
edges = current_vertex.get_successors()
if not edges:
return None # current_vertex
return random.choice(edges)
def greedy_policy(current_vertex, weight=1, shuffle=True):
# TODO: function that returns the policy
# TODO: use evaluators
edges = current_vertex.get_successors()
if not edges:
return None
if shuffle:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import math
import numpy
from planner.state_space import test_goal, test_parent_operator, StateSpace, Solution, Plan
from misc.numerical import INF
from misc.functions import randomize
and context:
# Path: planner/state_space.py
# IS_SAFE = True # http://www.fast-downward.org/Doc/Evaluator
# class Plan(object):
# class Vertex(object):
# class Edge(object):
# class StateSpace(object):
# def __init__(self, start, operators):
# def cost(self):
# def length(self):
# def priority(self):
# def __iter__(self):
# def get_states(self):
# def get_derived_states(self, axioms):
# def __str__(self):
# def test_goal(vertex, goal):
# def test_parent_operator(sink_vertex):
# def __init__(self, state, state_space):
# def num_unexplored(self):
# def reset_path(self):
# def priority(self):
# def relax(self, edge):
# def get_children(self):
# def contained(self, partial_state):
# def enumerated(self):
# def get_h_cost(self):
# def get_successors(self):
# def is_dead_end(self):
# def evaluate(self):
# def extend_state_space(self):
# def generate(self):
# def generate_all(self):
# def has_unexplored(self):
# def unexplored(self):
# def dump(self):
# def __str__(self):
# def __init__(self, source, sink, operator, state_space):
# def path_cost(self):
# def path_length(self):
# def priority(self):
# def is_parent(self): # TODO: what was the purpose of this?
# def evaluate_test(self):
# def __str__(self):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# def has_state(self, state):
# def get_state(self, state):
# def __iter__(self):
# def __len__(self):
# def new_iteration(self, vertex):
# def is_active(self):
# def extend(self, vertex, operator):
# def retrace(self, vertex):
# def plan(self, vertex):
# def solution(self, vertex):
# def failure(self):
# def time_elapsed(self):
# def __repr__(self):
# def dump(self):
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/functions.py
# def randomize(sequence):
# shuffle(sequence)
# return sequence
which might include code, classes, or functions. Output only the next line. | edges = randomize(edges) |
Here is a snippet: <|code_start|>Node = namedtuple('Node', ['cost', 'operators'])
"""
class Node(Set, object):
def __init__(self, operators):
self.operators = operators
self.cost = self._cost()
def __contains__(self, operator):
return operator in self.operators
def __iter__(self):
return iter(self.operators)
def __len__(self):
return len(self.operators)
def _cost(self):
return sum(operator.cost for operator in self.operators)
# https://docs.python.org/2/library/stdtypes.html#set.union
# set.union
class UnitNode(Node):
def _cost(self):
return len(self.operators)
"""
# TODO - merge process that attempts to reason about operators that accomplish each others goals by extending union
def relaxed_plan(state, goal, operators, unit=False, greedy=True):
variable_nodes = defaultdict(dict)
operator_nodes = {}
conditions = defaultdict(lambda: defaultdict(list))
unsatisfied = {}
<|code_end|>
. Write the next line using the current file imports:
from misc.utils import *
from misc.priority_queue import PriorityQueue
and context from other files:
# Path: misc/priority_queue.py
# class PriorityQueue(StableQueue):
# def __init__(self, array=[]):
# super(PriorityQueue, self).__init__()
# self.queue = list(map(lambda x: self.new_node(*x), array))
# heapify(self.queue)
# def peek(self):
# return self.queue[0].element
# def push(self, priority, element):
# heappush(self.queue, self.new_node(priority, element))
# def pop(self):
# return heappop(self.queue).element
# def empty(self):
# return len(self) == 0
# def __len__(self):
# return len(self.queue)
# def __repr__(self):
# #order = self.queue
# order = sorted(self.queue)
# return '{}{}'.format(self.__class__.__name__, order)
, which may include functions, classes, or code. Output only the next line. | queue = PriorityQueue() |
Continue the code snippet: <|code_start|>
class Clear(Literal): pass
class OnTable(Literal): pass
class ArmEmpty(Literal): pass
class Holding(Literal): pass
class On(Literal): pass
<|code_end|>
. Use current file imports:
from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations
and context (classes, functions, or code) from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | class Pick(Action): |
Based on the snippet: <|code_start|> self.conditions = {Holding(obj)}
self.effects = {Clear(obj), OnTable(obj), ArmEmpty(),
~Holding(obj)}
class Stack(Action):
def __init__(self, obj, under_obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Holding(obj), Clear(under_obj)}
self.effects = {Clear(obj), ArmEmpty(), On(obj, under_obj),
~Holding(obj), ~Clear(under_obj)}
class Unstack(Action):
def __init__(self, obj, under_obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Clear(obj), ArmEmpty(), On(obj, under_obj)}
self.effects = {Holding(obj), Clear(under_obj),
~Clear(obj), ~ArmEmpty(), ~On(obj, under_obj)}
###########################################################################
def line_stack_blocks(n=10, height=5):
height = max(height, 0)
n = max(height, n)
blocks = ['Block{}'.format(i) for i in range(1, n+1)]
operators = [Pick(item) for item in blocks] + \
[Place(item) for item in blocks] + \
[Unstack(*item) for item in permutations(blocks, 2)] + \
[Stack(*item) for item in permutations(blocks, 2)]
<|code_end|>
, predict the immediate next line with the help of imports:
from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations
and context (classes, functions, sometimes code) from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | initial = State({OnTable(block) for block in blocks} | |
Predict the next line after this snippet: <|code_start|> def __init__(self, obj, under_obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Holding(obj), Clear(under_obj)}
self.effects = {Clear(obj), ArmEmpty(), On(obj, under_obj),
~Holding(obj), ~Clear(under_obj)}
class Unstack(Action):
def __init__(self, obj, under_obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Clear(obj), ArmEmpty(), On(obj, under_obj)}
self.effects = {Holding(obj), Clear(under_obj),
~Clear(obj), ~ArmEmpty(), ~On(obj, under_obj)}
###########################################################################
def line_stack_blocks(n=10, height=5):
height = max(height, 0)
n = max(height, n)
blocks = ['Block{}'.format(i) for i in range(1, n+1)]
operators = [Pick(item) for item in blocks] + \
[Place(item) for item in blocks] + \
[Unstack(*item) for item in permutations(blocks, 2)] + \
[Stack(*item) for item in permutations(blocks, 2)]
initial = State({OnTable(block) for block in blocks} |
{Clear(block) for block in blocks} |
{ArmEmpty()})
tower = blocks[:height]
<|code_end|>
using the current file's imports:
from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations
and any relevant context from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | goal = PartialState({OnTable(blocks[0]), ArmEmpty()} | |
Next line prediction: <|code_start|> self.effects = {Clear(obj), ArmEmpty(), On(obj, under_obj),
~Holding(obj), ~Clear(under_obj)}
class Unstack(Action):
def __init__(self, obj, under_obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Clear(obj), ArmEmpty(), On(obj, under_obj)}
self.effects = {Holding(obj), Clear(under_obj),
~Clear(obj), ~ArmEmpty(), ~On(obj, under_obj)}
###########################################################################
def line_stack_blocks(n=10, height=5):
height = max(height, 0)
n = max(height, n)
blocks = ['Block{}'.format(i) for i in range(1, n+1)]
operators = [Pick(item) for item in blocks] + \
[Place(item) for item in blocks] + \
[Unstack(*item) for item in permutations(blocks, 2)] + \
[Stack(*item) for item in permutations(blocks, 2)]
initial = State({OnTable(block) for block in blocks} |
{Clear(block) for block in blocks} |
{ArmEmpty()})
tower = blocks[:height]
goal = PartialState({OnTable(blocks[0]), ArmEmpty()} |
{On(obj, under_obj) for under_obj, obj in pairs(tower)})
<|code_end|>
. Use current file imports:
(from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations)
and context including class names, function names, or small code snippets from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | return STRIPSProblem(initial, goal, operators) |
Next line prediction: <|code_start|>
class Clear(Literal): pass
class OnTable(Literal): pass
class ArmEmpty(Literal): pass
class Holding(Literal): pass
class On(Literal): pass
class Pick(Action):
def __init__(self, obj):
<|code_end|>
. Use current file imports:
(from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations)
and context including class names, function names, or small code snippets from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | super(self.__class__, self).__init__(arg_info(currentframe())) |
Given the following code snippet before the placeholder: <|code_start|>
class Clear(Literal): pass
class OnTable(Literal): pass
class ArmEmpty(Literal): pass
class Holding(Literal): pass
class On(Literal): pass
class Pick(Action):
def __init__(self, obj):
<|code_end|>
, predict the next line using imports from the current file:
from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations
and context including class names, function names, and sometimes code from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | super(self.__class__, self).__init__(arg_info(currentframe())) |
Given the following code snippet before the placeholder: <|code_start|> super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Holding(obj), Clear(under_obj)}
self.effects = {Clear(obj), ArmEmpty(), On(obj, under_obj),
~Holding(obj), ~Clear(under_obj)}
class Unstack(Action):
def __init__(self, obj, under_obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
self.conditions = {Clear(obj), ArmEmpty(), On(obj, under_obj)}
self.effects = {Holding(obj), Clear(under_obj),
~Clear(obj), ~ArmEmpty(), ~On(obj, under_obj)}
###########################################################################
def line_stack_blocks(n=10, height=5):
height = max(height, 0)
n = max(height, n)
blocks = ['Block{}'.format(i) for i in range(1, n+1)]
operators = [Pick(item) for item in blocks] + \
[Place(item) for item in blocks] + \
[Unstack(*item) for item in permutations(blocks, 2)] + \
[Stack(*item) for item in permutations(blocks, 2)]
initial = State({OnTable(block) for block in blocks} |
{Clear(block) for block in blocks} |
{ArmEmpty()})
tower = blocks[:height]
goal = PartialState({OnTable(blocks[0]), ArmEmpty()} |
<|code_end|>
, predict the next line using imports from the current file:
from strips.operators import Action
from strips.states import State, PartialState, Literal, STRIPSProblem
from misc.utils import arg_info, currentframe
from misc.functions import pairs
from itertools import permutations
and context including class names, function names, and sometimes code from other files:
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: strips/states.py
# class Literal(object):
# class State(object):
# class PartialState(object):
# def __init__(self, *args):
# def negated(self):
# def copy(self):
# def positive(self):
# def negate(self):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __lt__(self, other):
# def __str__(self):
# def __init__(self, atoms, external=None):
# def identity(self):
# def holds(self, literal):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
# def __init__(self, literals, test=lambda state: True):
# def contains(self, state):
# def __iter__(self):
# def __eq__(self, other):
# def __ne__(self, other):
# def __hash__(self):
# def __str__(self):
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: misc/functions.py
# def pairs(lst):
# return zip(lst[:-1], lst[1:])
. Output only the next line. | {On(obj, under_obj) for under_obj, obj in pairs(tower)}) |
Here is a snippet: <|code_start|> if value in marked[level][var]: continue
if ALL_BACK_POINTERS:
easiest_operator = argmin(lambda o: EASIEST_HEURISTIC(o, operator_costs, variable_costs, goals),
(o for o, n in operator_costs.items() if n.level < level and var in o.effects and o.effects[var] == value))
else:
easiest_operator = argmin(lambda o: EASIEST_HEURISTIC(o, operator_costs, variable_costs, goals),
(o for o in operator_layers[level-1] if var in o.effects and o.effects[var] == value))
plan[level-1].add(easiest_operator)
for var2, value2 in easiest_operator.conditions.items():
if value2 not in marked[level-1][var2]:
goals[variable_costs[var2][value2].level][var2].add(value2)
for var2, value2 in easiest_operator.effects.items():
marked[level][var2].add(value2)
marked[level-1][var2].add(value2) # Assumes that actions are read off in order they are selected (no need to reachieve)
return plan, goals
###########################################################################
def plan_cost(goal, operator_costs, relaxed_plan, relaxed_goals):
return sum(operator.cost for operator in flatten(relaxed_plan))
def plan_length(goal, operator_costs, relaxed_plan, relaxed_goals):
return len(flatten(relaxed_plan))
def multi_cost(goal, operator_costs, relaxed_plan, relaxed_goals):
return plan_cost(goal, operator_costs, relaxed_plan, relaxed_goals), operator_costs[goal].cost, operator_costs[goal].level
###########################################################################
def filter_axioms(operators):
<|code_end|>
. Write the next line using the current file imports:
from .hsp import *
from .operators import Axiom
and context from other files:
# Path: sas/operators.py
# class Axiom(Operator):
# cost = 0
, which may include functions, classes, or code. Output only the next line. | return list(filter(lambda o: not isinstance(o, Axiom), operators)) |
Next line prediction: <|code_start|>
def add_operator_transitions(operator, transitions):
for variable, (start, end) in transitions.items():
if start is not None:
<|code_end|>
. Use current file imports:
(from planner.conditions import SubstateCondition
from planner.effects import ValueEffect
from planner.states import Substate)
and context including class names, function names, or small code snippets from other files:
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: planner/effects.py
# class ValueEffect(Effect):
# def __init__(self, value):
# super(self.__class__, self).__init__()
# self.value = value
# def __call__(self, *args):
# return self.value
# def __repr__(self):
# return 'VE' + str_object((self.value,))
#
# Path: planner/states.py
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
. Output only the next line. | operator.conditions.append(SubstateCondition(Substate({variable: start}))) |
Given snippet: <|code_start|>
def add_operator_transitions(operator, transitions):
for variable, (start, end) in transitions.items():
if start is not None:
operator.conditions.append(SubstateCondition(Substate({variable: start})))
if end is not None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from planner.conditions import SubstateCondition
from planner.effects import ValueEffect
from planner.states import Substate
and context:
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: planner/effects.py
# class ValueEffect(Effect):
# def __init__(self, value):
# super(self.__class__, self).__init__()
# self.value = value
# def __call__(self, *args):
# return self.value
# def __repr__(self):
# return 'VE' + str_object((self.value,))
#
# Path: planner/states.py
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
which might include code, classes, or functions. Output only the next line. | operator.effects[variable] = ValueEffect(end) |
Given the following code snippet before the placeholder: <|code_start|>
def add_operator_transitions(operator, transitions):
for variable, (start, end) in transitions.items():
if start is not None:
<|code_end|>
, predict the next line using imports from the current file:
from planner.conditions import SubstateCondition
from planner.effects import ValueEffect
from planner.states import Substate
and context including class names, function names, and sometimes code from other files:
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: planner/effects.py
# class ValueEffect(Effect):
# def __init__(self, value):
# super(self.__class__, self).__init__()
# self.value = value
# def __call__(self, *args):
# return self.value
# def __repr__(self):
# return 'VE' + str_object((self.value,))
#
# Path: planner/states.py
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
. Output only the next line. | operator.conditions.append(SubstateCondition(Substate({variable: start}))) |
Given the following code snippet before the placeholder: <|code_start|>
class Pick(Action):
def __init__(self, obj):
super(self.__class__, self).__init__(arg_info(currentframe()))
<|code_end|>
, predict the next line using imports from the current file:
from retired.discrete.operators import add_operator_transitions
from planner.operators import Action
from misc.utils import arg_info, currentframe
and context including class names, function names, and sometimes code from other files:
# Path: retired/discrete/operators.py
# def add_operator_transitions(operator, transitions):
# for variable, (start, end) in transitions.items():
# if start is not None:
# operator.conditions.append(SubstateCondition(Substate({variable: start})))
# if end is not None:
# operator.effects[variable] = ValueEffect(end)
#
# Path: planner/operators.py
# class Action(Operator):
# cost = 1
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
. Output only the next line. | add_operator_transitions(self, { |
Predict the next line after this snippet: <|code_start|> cv.pops += 1
if (cv.pops - 1) % recurrence != 0:
queue.append(cv)
continue
space.iterations += 1
if debug is not None:
debug(cv)
for nv in cv.unexplored(): # TODO - should reverse order for DFS
nv.pops = 0
if nv.contained(goal):
return space.solution(nv)
if nv.generate():
queue.append(nv)
if cv.generate():
queue.append(cv)
return space.failure()
##################################################
def rdfs(*args):
return recurrent_search(lambda queue: queue.pop(), *args)
def rbfs(*args):
return recurrent_search(lambda queue: queue.popleft(), *args)
def random_walk(*args):
<|code_end|>
using the current file's imports:
from collections import deque
from .utils import pop_random, pop_rrt
from ..state_space import StateSpace
from misc.functions import elapsed_time
and any relevant context from other files:
# Path: planner/progression/utils.py
# def pop_random(queue):
# queue.rotate(randint(0, len(queue) - 1))
# return queue.popleft()
#
# def pop_rrt(distance, sample, goal_sample=None, goal_probability=DEFAULT_GOAL_PROBABILITY):
# return lambda queue: pop_min(
# queue, lambda sv: distance(sv.state, sample_target(
# sample, goal_sample=goal_sample, goal_probability=goal_probability)))
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
. Output only the next line. | return recurrent_search(pop_random, *args) |
Given the following code snippet before the placeholder: <|code_start|> if debug is not None:
debug(cv)
for nv in cv.unexplored(): # TODO - should reverse order for DFS
nv.pops = 0
if nv.contained(goal):
return space.solution(nv)
if nv.generate():
queue.append(nv)
if cv.generate():
queue.append(cv)
return space.failure()
##################################################
def rdfs(*args):
return recurrent_search(lambda queue: queue.pop(), *args)
def rbfs(*args):
return recurrent_search(lambda queue: queue.popleft(), *args)
def random_walk(*args):
return recurrent_search(pop_random, *args)
def rrt(start, goal, generator, recurrence, max_time, max_iterations, max_generations, max_cost, max_length,
debug, distance, sample, goal_sample, goal_probability):
<|code_end|>
, predict the next line using imports from the current file:
from collections import deque
from .utils import pop_random, pop_rrt
from ..state_space import StateSpace
from misc.functions import elapsed_time
and context including class names, function names, and sometimes code from other files:
# Path: planner/progression/utils.py
# def pop_random(queue):
# queue.rotate(randint(0, len(queue) - 1))
# return queue.popleft()
#
# def pop_rrt(distance, sample, goal_sample=None, goal_probability=DEFAULT_GOAL_PROBABILITY):
# return lambda queue: pop_min(
# queue, lambda sv: distance(sv.state, sample_target(
# sample, goal_sample=goal_sample, goal_probability=goal_probability)))
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
. Output only the next line. | return recurrent_search(pop_rrt(distance, sample, goal_sample, goal_probability), start, goal, generator, |
Predict the next line after this snippet: <|code_start|>
def recurrent_search(pop, start, goal, generator, recurrence, max_time, max_iterations, max_generations, max_cost,
max_length, debug):
space = StateSpace(generator, start, 1, max_generations, max_cost, max_length)
sv = space.root
if sv.contained(goal):
return space.solution(sv)
if not sv.generate():
return space.failure()
queue = deque([sv])
sv.pops = 0
<|code_end|>
using the current file's imports:
from collections import deque
from .utils import pop_random, pop_rrt
from ..state_space import StateSpace
from misc.functions import elapsed_time
and any relevant context from other files:
# Path: planner/progression/utils.py
# def pop_random(queue):
# queue.rotate(randint(0, len(queue) - 1))
# return queue.popleft()
#
# def pop_rrt(distance, sample, goal_sample=None, goal_probability=DEFAULT_GOAL_PROBABILITY):
# return lambda queue: pop_min(
# queue, lambda sv: distance(sv.state, sample_target(
# sample, goal_sample=goal_sample, goal_probability=goal_probability)))
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
. Output only the next line. | while queue and (elapsed_time(space.start_time) < max_time) and (space.iterations < max_iterations): |
Next line prediction: <|code_start|>
"""
def set_inactive(self):
if not self.active: return
self.active = False
for connector in self.connectors:
connector.update_inactive()
#for source_vertex, _ in self.mappings:
# if source_vertex is not None:
# source_vertex.update_inactive()
def update_inactive(self):
if not self.active or self == self.rg.goal: return # TODO - decide if better condition
self.active = False # Temporarily set to inactive
for _, sink_vertex in self.mappings:
sink_vertex.update_inactive()
if sink_vertex.active:
self.active = True
return
# Cannot find active parent node
self.set_inactive()
"""
def __str__(self):
return 'E(' + str(self.value) + ')'
__repr__ = __str__
def node_str(self):
node_str = self.value.__class__.__name__
<|code_end|>
. Use current file imports:
(from .utils import *
from planner.operators import Operator
from misc.utils import str_object)
and context including class names, function names, or small code snippets from other files:
# Path: planner/operators.py
# class Operator(object):
# def __init__(self, args):
# self.args = args
# for k, v in args.items():
# setattr(self, k, v)
# self.conditions = []
# self.effects = {}
# def __contains__(self, state):
# return all(state in precondition for precondition in self.conditions)
# def apply(self, state):
# return State(dict(list(state) + [(var, effect(state)) for var, effect in self.effects.items()]))
# def __call__(self, state):
# if state not in self: return None
# return self.apply(state)
# def __iter__(self):
# yield self
# def __len__(self):
# return 1
# def fixed_conditions(self):
# fc = {}
# for condition in self.conditions:
# if isinstance(condition, SubstateCondition):
# for var, value in condition.substate:
# if var in fc and fc[var] != value:
# raise RuntimeError('Condition has conflicting conditions')
# fc[var] = value
# return fc
# def fixed_effects(self):
# return {var: effect.value for var, effect in self.effects.items()
# if isinstance(effect, ValueEffect)}
# def fixed_image(self):
# return merge_dicts(self.fixed_conditions(), self.fixed_effects())
# #def image(self):
# # pass
# #def fixed_preimage(self):
# # pass
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.args == other.args
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.args.items())))
# def __str__(self):
# return self.__class__.__name__ + str_args(self.args)
# __repr__ = __str__
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
. Output only the next line. | if isinstance(self.value, Operator): |
Predict the next line for this snippet: <|code_start|> def set_inactive(self):
if not self.active: return
self.active = False
for connector in self.connectors:
connector.update_inactive()
#for source_vertex, _ in self.mappings:
# if source_vertex is not None:
# source_vertex.update_inactive()
def update_inactive(self):
if not self.active or self == self.rg.goal: return # TODO - decide if better condition
self.active = False # Temporarily set to inactive
for _, sink_vertex in self.mappings:
sink_vertex.update_inactive()
if sink_vertex.active:
self.active = True
return
# Cannot find active parent node
self.set_inactive()
"""
def __str__(self):
return 'E(' + str(self.value) + ')'
__repr__ = __str__
def node_str(self):
node_str = self.value.__class__.__name__
if isinstance(self.value, Operator):
for name, arg in self.value.args.items():
<|code_end|>
with the help of current file imports:
from .utils import *
from planner.operators import Operator
from misc.utils import str_object
and context from other files:
# Path: planner/operators.py
# class Operator(object):
# def __init__(self, args):
# self.args = args
# for k, v in args.items():
# setattr(self, k, v)
# self.conditions = []
# self.effects = {}
# def __contains__(self, state):
# return all(state in precondition for precondition in self.conditions)
# def apply(self, state):
# return State(dict(list(state) + [(var, effect(state)) for var, effect in self.effects.items()]))
# def __call__(self, state):
# if state not in self: return None
# return self.apply(state)
# def __iter__(self):
# yield self
# def __len__(self):
# return 1
# def fixed_conditions(self):
# fc = {}
# for condition in self.conditions:
# if isinstance(condition, SubstateCondition):
# for var, value in condition.substate:
# if var in fc and fc[var] != value:
# raise RuntimeError('Condition has conflicting conditions')
# fc[var] = value
# return fc
# def fixed_effects(self):
# return {var: effect.value for var, effect in self.effects.items()
# if isinstance(effect, ValueEffect)}
# def fixed_image(self):
# return merge_dicts(self.fixed_conditions(), self.fixed_effects())
# #def image(self):
# # pass
# #def fixed_preimage(self):
# # pass
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.args == other.args
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.args.items())))
# def __str__(self):
# return self.__class__.__name__ + str_args(self.args)
# __repr__ = __str__
#
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
, which may contain function names, class names, or code. Output only the next line. | node_str += '\n' + str_object(name) + '=' + str_object(arg) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
DIRECTORY = './simulations/sas/planning/'
def solve(problem, print_profile):
initial, goal, operators = problem()
dt = datetime.datetime.now()
directory = DIRECTORY + '{}/{}/{}/'.format(
problem.__name__, dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S'))
<|code_end|>
with the help of current file imports:
from misc.profiling import *
from misc.utils import SEPARATOR, randomize
from sas.utils import *
from sas.pop import pop_solve
from sas.relaxed_pop import relaxed_pop
from planner.meta.forward_hierarchy import fixed_search, pp_hierarchy_level
import sas.domains as domains
import sys
import getopt
import time
import datetime
import argparse
and context from other files:
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: sas/pop.py
# def pop_solve(initial, goal, operators, max_length=float('inf')):
# initial_plan = PartialPlan([initial, goal],
# {(initial, goal)},
# [(g, goal) for g in goal.cond()],
# [])
# #operators.sort()
# iterations = 0
# expanded = 1
# if initial_plan.solved():
# return initial_plan.extract_plan(), (iterations, expanded)
#
# BFS = False
# if BFS:
# queue = deque([initial_plan])
# else:
# queue = [(initial_plan.rank(operators), initial_plan)]
# while queue:
# #queue = deque(sorted(queue, key=lambda q: q.rank()))
# if BFS:
# plan = queue.popleft()
# else:
# _, plan = heappop(queue)
# #print(len(queue), sorted(queue, key=lambda q: q.rank()))
# print(iterations, expanded, plan.heuristic(operators), plan.length()) #, len(neighbors)
# #print(plan)
# #raw_input()
# iterations += 1
# for new_plan in plan.neighbors(operators):
# if new_plan.length() > max_length:
# continue
# expanded += 1
# if new_plan.solved():
# return new_plan.extract_plan(), (iterations, expanded)
# if BFS:
# queue.append(new_plan)
# else:
# heappush(queue, (new_plan.rank(operators), new_plan))
# return None, (iterations, expanded)
#
# Path: sas/relaxed_pop.py
# def relaxed_pop(initial, goal, operators, QueueClass=FIFOPriorityQueue):
# initial_plan = get_initial_plan(initial, goal)
# #operators.sort()
# iterations = 0
# expanded = 1
#
# #priority_fn = lambda p: p.length() # NOTE - super slow
# #priority_fn = lambda p: p.length() + p.unsatisfied_goals()
# priority_fn = lambda p: p.unsatisfied_goals()
#
# if initial_plan.solved():
# return initial_plan.extract_plan(), (iterations, expanded)
#
# queue = QueueClass()
# queue.push(priority_fn(initial_plan), initial_plan)
# while queue:
# plan = queue.pop()
# print(iterations, expanded, plan.length(), plan.unsatisfied_goals(), priority_fn(plan))
# iterations += 1
# for new_plan in plan.neighbors(operators):
# expanded += 1
# if new_plan.solved():
# return new_plan.extract_plan(), (iterations, expanded)
# queue.push(priority_fn(new_plan), new_plan)
# return None, (iterations, expanded)
#
# Path: planner/meta/forward_hierarchy.py
# def fixed_search(start, goal, operators, subsearch, hierarchy, level=0):
# # Modify operators wrt hierarchy but not goal?
# # Can always modify operators to produce additional effects from the projected preconditions
#
# modified_operators = []
# #for operator in operators + [goal]: # TODO - include goal
# for operator in operators:
# modified_operator = deepcopy(operator)
# modified_operator.original = operator
# for v, val in operator.cond():
# if v not in operator.effects: # NOTE - adds operator image
# modified_operator.effects[v] = val
# if hierarchy((v, val), operator) > level:
# del modified_operator.conditions[v]
# modified_operators.append(modified_operator)
#
# plan, state_space = subsearch(start, goal, modified_operators)
# #print(plan.length)
# if plan is None:
# return None, None
#
# state = start
# sequence = []
# #for operator in plan.operators + [goal]: # TODO - should I assume that the last operator achieves the goal or not?
# for modified_operator in plan.operators:
# operator = modified_operator.original
# if state not in operator:
# #print(state, operator)
# #print()
# subplan, subdata = fixed_search(state, Goal(operator.conditions), operators, subsearch, hierarchy, level=level+1)
# if subplan is None:
# return None, None
# state = subplan.get_states()[-1]
# sequence += subplan.operators
# if operator != goal:
# state = operator(state)
# sequence.append(operator)
# return Plan(start, sequence), None # TODO - merge state-spaces
#
# def pp_hierarchy_level(cond, operator):
# v, val = cond
# if v == 'robot':
# return 1
# return 0
, which may contain function names, class names, or code. Output only the next line. | print(SEPARATOR + '\nSolving sas problem ' + problem.__name__) |
Given snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
DIRECTORY = './simulations/sas/planning/'
def solve(problem, print_profile):
initial, goal, operators = problem()
dt = datetime.datetime.now()
directory = DIRECTORY + '{}/{}/{}/'.format(
problem.__name__, dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S'))
print(SEPARATOR + '\nSolving sas problem ' + problem.__name__)
def execute():
start_time = time.time()
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from misc.profiling import *
from misc.utils import SEPARATOR, randomize
from sas.utils import *
from sas.pop import pop_solve
from sas.relaxed_pop import relaxed_pop
from planner.meta.forward_hierarchy import fixed_search, pp_hierarchy_level
import sas.domains as domains
import sys
import getopt
import time
import datetime
import argparse
and context:
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: sas/pop.py
# def pop_solve(initial, goal, operators, max_length=float('inf')):
# initial_plan = PartialPlan([initial, goal],
# {(initial, goal)},
# [(g, goal) for g in goal.cond()],
# [])
# #operators.sort()
# iterations = 0
# expanded = 1
# if initial_plan.solved():
# return initial_plan.extract_plan(), (iterations, expanded)
#
# BFS = False
# if BFS:
# queue = deque([initial_plan])
# else:
# queue = [(initial_plan.rank(operators), initial_plan)]
# while queue:
# #queue = deque(sorted(queue, key=lambda q: q.rank()))
# if BFS:
# plan = queue.popleft()
# else:
# _, plan = heappop(queue)
# #print(len(queue), sorted(queue, key=lambda q: q.rank()))
# print(iterations, expanded, plan.heuristic(operators), plan.length()) #, len(neighbors)
# #print(plan)
# #raw_input()
# iterations += 1
# for new_plan in plan.neighbors(operators):
# if new_plan.length() > max_length:
# continue
# expanded += 1
# if new_plan.solved():
# return new_plan.extract_plan(), (iterations, expanded)
# if BFS:
# queue.append(new_plan)
# else:
# heappush(queue, (new_plan.rank(operators), new_plan))
# return None, (iterations, expanded)
#
# Path: sas/relaxed_pop.py
# def relaxed_pop(initial, goal, operators, QueueClass=FIFOPriorityQueue):
# initial_plan = get_initial_plan(initial, goal)
# #operators.sort()
# iterations = 0
# expanded = 1
#
# #priority_fn = lambda p: p.length() # NOTE - super slow
# #priority_fn = lambda p: p.length() + p.unsatisfied_goals()
# priority_fn = lambda p: p.unsatisfied_goals()
#
# if initial_plan.solved():
# return initial_plan.extract_plan(), (iterations, expanded)
#
# queue = QueueClass()
# queue.push(priority_fn(initial_plan), initial_plan)
# while queue:
# plan = queue.pop()
# print(iterations, expanded, plan.length(), plan.unsatisfied_goals(), priority_fn(plan))
# iterations += 1
# for new_plan in plan.neighbors(operators):
# expanded += 1
# if new_plan.solved():
# return new_plan.extract_plan(), (iterations, expanded)
# queue.push(priority_fn(new_plan), new_plan)
# return None, (iterations, expanded)
#
# Path: planner/meta/forward_hierarchy.py
# def fixed_search(start, goal, operators, subsearch, hierarchy, level=0):
# # Modify operators wrt hierarchy but not goal?
# # Can always modify operators to produce additional effects from the projected preconditions
#
# modified_operators = []
# #for operator in operators + [goal]: # TODO - include goal
# for operator in operators:
# modified_operator = deepcopy(operator)
# modified_operator.original = operator
# for v, val in operator.cond():
# if v not in operator.effects: # NOTE - adds operator image
# modified_operator.effects[v] = val
# if hierarchy((v, val), operator) > level:
# del modified_operator.conditions[v]
# modified_operators.append(modified_operator)
#
# plan, state_space = subsearch(start, goal, modified_operators)
# #print(plan.length)
# if plan is None:
# return None, None
#
# state = start
# sequence = []
# #for operator in plan.operators + [goal]: # TODO - should I assume that the last operator achieves the goal or not?
# for modified_operator in plan.operators:
# operator = modified_operator.original
# if state not in operator:
# #print(state, operator)
# #print()
# subplan, subdata = fixed_search(state, Goal(operator.conditions), operators, subsearch, hierarchy, level=level+1)
# if subplan is None:
# return None, None
# state = subplan.get_states()[-1]
# sequence += subplan.operators
# if operator != goal:
# state = operator(state)
# sequence.append(operator)
# return Plan(start, sequence), None # TODO - merge state-spaces
#
# def pp_hierarchy_level(cond, operator):
# v, val = cond
# if v == 'robot':
# return 1
# return 0
which might include code, classes, or functions. Output only the next line. | output = default_plan(initial, goal, randomize(operators)) |
Using the snippet: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [
SubstateCondition(Substate({('on', blocks[height-1]): 'table'}))
])
<|code_end|>
, determine the next line of code. You have imports:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and context (class names, function names, or code) available:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
. Output only the next line. | actions = [Pick(item) for item in blocks] + [Place(item) for item in blocks] + \ |
Given snippet: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [
SubstateCondition(Substate({('on', blocks[height-1]): 'table'}))
])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and context:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
which might include code, classes, or functions. Output only the next line. | actions = [Pick(item) for item in blocks] + [Place(item) for item in blocks] + \ |
Given the code snippet: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [
SubstateCondition(Substate({('on', blocks[height-1]): 'table'}))
])
actions = [Pick(item) for item in blocks] + [Place(item) for item in blocks] + \
<|code_end|>
, generate the next line using the imports in this file:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and context (functions, classes, or occasionally code) from other files:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
. Output only the next line. | [Unstack(*item) for item in permutations(blocks, 2)] + [Stack(*item) for item in permutations(blocks, 2)] |
Given the following code snippet before the placeholder: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [
SubstateCondition(Substate({('on', blocks[height-1]): 'table'}))
])
actions = [Pick(item) for item in blocks] + [Place(item) for item in blocks] + \
<|code_end|>
, predict the next line using imports from the current file:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and context including class names, function names, and sometimes code from other files:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
. Output only the next line. | [Unstack(*item) for item in permutations(blocks, 2)] + [Stack(*item) for item in permutations(blocks, 2)] |
Given the code snippet: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [
SubstateCondition(Substate({('on', blocks[height-1]): 'table'}))
])
actions = [Pick(item) for item in blocks] + [Place(item) for item in blocks] + \
[Unstack(*item) for item in permutations(blocks, 2)] + [Stack(*item) for item in permutations(blocks, 2)]
<|code_end|>
, generate the next line using the imports in this file:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and context (functions, classes, or occasionally code) from other files:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
. Output only the next line. | return start, goal, lambda rg: InitDiscreteScheduler(rg, actions) |
Next line prediction: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
<|code_end|>
. Use current file imports:
(from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations)
and context including class names, function names, or small code snippets from other files:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
. Output only the next line. | SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [ |
Predict the next line for this snippet: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
<|code_end|>
with the help of current file imports:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and context from other files:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
, which may contain function names, class names, or code. Output only the next line. | goal = PartialState([ |
Predict the next line after this snippet: <|code_start|>
def restack(n=10, height=5):
blocks = ['B%d'%i for i in range(1, n+1)]
start = State(merge_dicts(
{('on', blocks[0]): 'table', ('clear', blocks[height-1]): True},
{('on', blocks[i+1]): blocks[i] for i in range(height-1)},
{('on', blocks[i]): 'table' for i in range(height, n)},
{('clear', blocks[i]): True for i in range(height, n)}
))
goal = PartialState([
<|code_end|>
using the current file's imports:
from .operators import Pick, Place, Stack, Unstack
from retired.discrete.schedulers import InitDiscreteScheduler
from planner.states import State, Substate, PartialState
from planner.conditions import SubstateCondition
from misc.functions import merge_dicts
from itertools import permutations
and any relevant context from other files:
# Path: retired/discrete/blocks_world/operators.py
# class Pick(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): ('table', False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# })
#
# class Place(Action):
# def __init__(self, obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, 'table'),
# 'holding': (obj, False),
# })
#
# class Stack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (None, base_obj),
# 'holding': (obj, False),
# ('clear', base_obj): (True, False),
# })
#
# class Unstack(Action):
# def __init__(self, obj, base_obj):
# super(self.__class__, self).__init__(arg_info(currentframe()))
# add_operator_transitions(self, {
# ('on', obj): (base_obj, False),
# ('clear', obj): (True, None),
# 'holding': (False, obj),
# ('clear', base_obj): (None, True),
# })
#
# Path: retired/discrete/schedulers.py
# class InitDiscreteScheduler(Scheduler):
# def __init__(self, rg, operators):
# super(self.__class__, self).__init__(rg)
# self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
# connect_discrete_conditions(self.rg, self.rg.goal)
# for operator in operators:
# if not is_discrete_operator(operator):
# raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
# edge = self.rg.edge(operator)
# edge.intermediates.update(edge.connectors)
# connect_discrete_operator(self.rg, edge)
# def __call__(self, start_vertex, goal_connector):
# return []
#
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# class Substate(DictPrintObject, Mapping):
# def __init__(self, values):
# HashObject.__init__(self)
# self.__dict__[HASH_DICT] = values
# def variables(self):
# return set(self.__dict__[HASH_DICT].keys())
# def includes(self, other):
# return all(var in self and self[var] == other[var] for var in other.variables()) # TODO - test if state
# def __getitem__(self, var):
# return self.get(var)
# def __iter__(self):
# return self.__dict__[HASH_DICT].items()
# def __len__(self):
# return len(self.__dict__[HASH_DICT])
# def __str__(self):
# return 'SS' + str_args(self.__dict__[HASH_DICT])
#
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
#
# Path: misc/functions.py
# def merge_dicts(*args):
# result = {}
# for d in args:
# result.update(d)
# return result
# # return dict(reduce(operator.add, [d.items() for d in args]))
. Output only the next line. | SubstateCondition(Substate({('on', blocks[i]): blocks[i+1]})) for i in range(height-1)] + [ |
Based on the snippet: <|code_start|>
# TODO
# - Replanning
# - Non-aggressive hierarchy (allowing open subproblems)
# - Other factored planning
def search(start, goal, hierarchy, level=0):
level_start = State({v: start.get(v) for v in start.values
if some(lambda item: v in item[0], hierarchy[:level + 1])})
print('-----------------------------------------------------------------\n')
print(level, level_start, goal)
plan, data = hierarchy[level][1](level_start, goal)
time, iterations, states = data.time, data.iterations, data.states
if plan is None: return None, planner.main.SearchData(time, iterations, states)
print([action.name for (action, _) in plan.sequence if action is not None])
print()
sequence = [(None, start)]
cost, length = plan.cost, plan.length
for action, _ in plan.sequence:
if action is not None:
current_state = sequence[-1][1]
if not action.applicable(current_state):
<|code_end|>
, predict the immediate next line with the help of imports:
from state_expanders import *
from strips.states import State, PartialState
from misc.functions import some
and context (classes, functions, sometimes code) from other files:
# Path: strips/states.py
# class State(object):
# def __init__(self, atoms, external=None):
# self.atoms = frozenset(atoms)
# self.external = external
# # TODO: refine function where external is updated
# # TODO: should I assume external is hashable?
# def identity(self):
# return self.__class__, frozenset(self.__dict__.items())
# def holds(self, literal):
# return literal.negated == (literal.positive() not in self.atoms)
# __contains__ = holds
# def __iter__(self):
# return iter(self.atoms)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.identity() == other.identity())
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash(self.identity())
# def __str__(self):
# #return '{}({})'.format(self.__class__.__name__, id(self))
# return self.__class__.__name__ + str_object(self.atoms)
# __repr__ = __str__
#
# class PartialState(object):
# def __init__(self, literals, test=lambda state: True):
# self.conditions = frozenset(literals)
# self.test = test # TODO: cache the test results
# def contains(self, state):
# return all(literal in state for literal in self.conditions) # and self.test(state)
# __contains__ = contains
# def __iter__(self):
# return iter(self.conditions)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash((self.__class__, self.conditions))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
#
# Path: misc/functions.py
# def some(function, iterable):
# return any(function(item) for item in iterable)
. Output only the next line. | subplan, subdata = search(current_state, PartialState(action.pre()), hierarchy, level=level+1) |
Based on the snippet: <|code_start|>
Solution = namedtuple('Solution', ['plan', 'state_space'])
Priority = namedtuple('Priority', ['cost', 'length'])
class Plan(object):
def __init__(self, start, operators):
self.start = start
self.operators = operators
@property
def cost(self):
if not self.operators:
return 0
return sum(operator.cost for operator in self.operators)
@property
def length(self):
return len(self.operators)
@property
def priority(self):
return Priority(self.cost, self.length)
def __iter__(self):
return iter(self.operators)
def get_states(self):
states = [self.start]
for operator in self.operators:
#assert states[-1] in operator
#states.append(operator(states[-1]))
states.append(operator.apply(states[-1]))
return states
def get_derived_states(self, axioms):
states = [self.start]
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple
from .operators import derive_predicates, MacroOperator
from misc.functions import elapsed_time, safe_remove, implies
from misc.numerical import INF
from misc.objects import str_line
import time
and context (classes, functions, sometimes code) from other files:
# Path: planner/operators.py
# def derive_predicates(state, axioms):
# if not axioms:
# return state, []
# is_strips = 'strips' in axioms[0].__class__.__module__ # TODO: clean this up
# if is_strips:
# from strips.operators import derive_state
# return derive_state(state, axioms)
# return derive_predicates_slow(state, axioms)
#
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def safe_remove(sequence, item):
# try:
# sequence.remove(item)
# return True
# except ValueError:
# return False
#
# def implies(a, b):
# return not a or b
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/objects.py
# def str_line(*args):
# return ''.join(str_object(item) for item in args)
. Output only the next line. | derived_state, axiom_plan = derive_predicates(states[-1], axioms) |
Given snippet: <|code_start|> self.root.cost = 0
self.root.length = 0
self.root.extensions += 1
self.best_h = None # None | INF
def has_state(self, state):
return state in self.vertices
__contains__ = has_state
def get_state(self, state):
if state not in self:
self.vertices[state] = Vertex(state, self)
return self.vertices[state]
__getitem__ = get_state
def __iter__(self):
return iter(self.vertices.values())
def __len__(self):
return len(self.vertices)
def new_iteration(self, vertex):
self.iterations += 1
if elapsed_time(self.last_dump) >= self.dump_rate:
self.dump()
# TODO: record dead ends here
#return vertex.is_dead_end() # TODO: might not have called h_cost
def is_active(self):
return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
def extend(self, vertex, operator):
if (vertex.cost + operator.cost <= self.max_cost) \
and (vertex.length + len(operator) <= self.max_length) \
and vertex.contained(operator):
#if vertex.state in operator:
if self.axioms:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from collections import namedtuple
from .operators import derive_predicates, MacroOperator
from misc.functions import elapsed_time, safe_remove, implies
from misc.numerical import INF
from misc.objects import str_line
import time
and context:
# Path: planner/operators.py
# def derive_predicates(state, axioms):
# if not axioms:
# return state, []
# is_strips = 'strips' in axioms[0].__class__.__module__ # TODO: clean this up
# if is_strips:
# from strips.operators import derive_state
# return derive_state(state, axioms)
# return derive_predicates_slow(state, axioms)
#
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def safe_remove(sequence, item):
# try:
# sequence.remove(item)
# return True
# except ValueError:
# return False
#
# def implies(a, b):
# return not a or b
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/objects.py
# def str_line(*args):
# return ''.join(str_object(item) for item in args)
which might include code, classes, or functions. Output only the next line. | assert not isinstance(operator, MacroOperator) |
Predict the next line for this snippet: <|code_start|> self.generator_fn, self.axioms = generator_fn, []
# TODO: could check whether these are violated generically
self.max_extensions = max_extensions
self.max_generations = max_generations
self.max_cost = max_cost
self.max_length = max_length
self.max_time = max_time
self.max_iterations = max_iterations
self.verbose = verbose
self.dump_rate = dump_rate
self.last_dump = time.time()
self.root = self[start]
self.root.cost = 0
self.root.length = 0
self.root.extensions += 1
self.best_h = None # None | INF
def has_state(self, state):
return state in self.vertices
__contains__ = has_state
def get_state(self, state):
if state not in self:
self.vertices[state] = Vertex(state, self)
return self.vertices[state]
__getitem__ = get_state
def __iter__(self):
return iter(self.vertices.values())
def __len__(self):
return len(self.vertices)
def new_iteration(self, vertex):
self.iterations += 1
<|code_end|>
with the help of current file imports:
from collections import namedtuple
from .operators import derive_predicates, MacroOperator
from misc.functions import elapsed_time, safe_remove, implies
from misc.numerical import INF
from misc.objects import str_line
import time
and context from other files:
# Path: planner/operators.py
# def derive_predicates(state, axioms):
# if not axioms:
# return state, []
# is_strips = 'strips' in axioms[0].__class__.__module__ # TODO: clean this up
# if is_strips:
# from strips.operators import derive_state
# return derive_state(state, axioms)
# return derive_predicates_slow(state, axioms)
#
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def safe_remove(sequence, item):
# try:
# sequence.remove(item)
# return True
# except ValueError:
# return False
#
# def implies(a, b):
# return not a or b
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/objects.py
# def str_line(*args):
# return ''.join(str_object(item) for item in args)
, which may contain function names, class names, or code. Output only the next line. | if elapsed_time(self.last_dump) >= self.dump_rate: |
Based on the snippet: <|code_start|>
def test_parent_operator(sink_vertex):
parent_edge = sink_vertex.parent_edge
if parent_edge is None:
return True
return parent_edge.evaluate_test()
class Vertex(object):
def __init__(self, state, state_space):
self.state = state
self.derived_state, self.axiom_plan = derive_predicates(state, state_space.axioms)
self.state_space = state_space
self.generator = state_space.generator_fn(self)
self.operators = []
self.incoming_edges = []
self.outgoing_edges = []
self.extensions = 0 # TODO: deprecate
self.generations = 0
self.explored = 0
self.h_cost = None
self.reset_path()
# @property
# def extensions(self):
# return len(self.outgoing_edges)
@property
def num_unexplored(self):
#return self.extensions - self.explored
return len(self.outgoing_edges) - self.explored
def reset_path(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple
from .operators import derive_predicates, MacroOperator
from misc.functions import elapsed_time, safe_remove, implies
from misc.numerical import INF
from misc.objects import str_line
import time
and context (classes, functions, sometimes code) from other files:
# Path: planner/operators.py
# def derive_predicates(state, axioms):
# if not axioms:
# return state, []
# is_strips = 'strips' in axioms[0].__class__.__module__ # TODO: clean this up
# if is_strips:
# from strips.operators import derive_state
# return derive_state(state, axioms)
# return derive_predicates_slow(state, axioms)
#
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def safe_remove(sequence, item):
# try:
# sequence.remove(item)
# return True
# except ValueError:
# return False
#
# def implies(a, b):
# return not a or b
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/objects.py
# def str_line(*args):
# return ''.join(str_object(item) for item in args)
. Output only the next line. | self.cost = INF # TODO: path_cost |
Here is a snippet: <|code_start|> @property
def length(self):
return len(self.operators)
@property
def priority(self):
return Priority(self.cost, self.length)
def __iter__(self):
return iter(self.operators)
def get_states(self):
states = [self.start]
for operator in self.operators:
#assert states[-1] in operator
#states.append(operator(states[-1]))
states.append(operator.apply(states[-1]))
return states
def get_derived_states(self, axioms):
states = [self.start]
derived_state, axiom_plan = derive_predicates(states[-1], axioms)
derived_states = [derived_state]
axiom_plans = [axiom_plan]
for operator in self.operators:
assert derived_states[-1] in operator
states.append(operator.apply(states[-1]))
derived_state, axiom_plan = derive_predicates(states[-1], axioms)
derived_states.append(derived_state)
axiom_plans.append(axiom_plan)
return derived_states, axiom_plans
def __str__(self):
s = '{name} | Cost: {self.cost} | Length {self.length}'.format(name=self.__class__.__name__, self=self)
for i, operator in enumerate(self.operators):
<|code_end|>
. Write the next line using the current file imports:
from collections import namedtuple
from .operators import derive_predicates, MacroOperator
from misc.functions import elapsed_time, safe_remove, implies
from misc.numerical import INF
from misc.objects import str_line
import time
and context from other files:
# Path: planner/operators.py
# def derive_predicates(state, axioms):
# if not axioms:
# return state, []
# is_strips = 'strips' in axioms[0].__class__.__module__ # TODO: clean this up
# if is_strips:
# from strips.operators import derive_state
# return derive_state(state, axioms)
# return derive_predicates_slow(state, axioms)
#
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def safe_remove(sequence, item):
# try:
# sequence.remove(item)
# return True
# except ValueError:
# return False
#
# def implies(a, b):
# return not a or b
#
# Path: misc/numerical.py
# INF = float('inf')
#
# Path: misc/objects.py
# def str_line(*args):
# return ''.join(str_object(item) for item in args)
, which may include functions, classes, or code. Output only the next line. | s += str_line('\n%d | '%(i+1), operator) |
Given the code snippet: <|code_start|> for operator in operators:
if not is_discrete_operator(operator):
raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
edge = self.rg.edge(operator)
edge.intermediates.update(edge.connectors)
connect_discrete_operator(self.rg, edge)
def __call__(self, start_vertex, goal_connector):
return []
class CallDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.operators = operators
def __call__(self, start_vertex, goal_connector):
assert is_discrete_condition(goal_connector.condition)
vertex = self.rg.vertex(goal_connector.condition.substate)
vertex.connect(goal_connector)
variable, value = list(vertex.substate)[0]
for operator in self.operators:
if variable in operator.effects:
effect = operator.effects[variable]
if is_discrete_effect(effect) and effect.value == value:
self.rg.edge(operator).connect(vertex)
return []
class SubplannerDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
<|code_end|>
, generate the next line using the imports in this file:
from .subplanners import DiscreteSubplanner
from .operators import is_discrete_condition, is_discrete_effect, is_discrete_operator, \
connect_discrete_conditions, connect_discrete_operator
and context (functions, classes, or occasionally code) from other files:
# Path: retired/discrete/subplanners.py
# class DiscreteSubplanner(Subplanner):
# def __init__(self, operators):
# self.operators = operators
# def generator(self, start_vertex, goal_connector, rg):
# #yield # NOTE - include if don't want initial generation
# vertex = rg.vertex(goal_connector.condition.substate)
# vertex.connect(goal_connector)
# variable, value = list(vertex.substate)[0]
#
# for operator in self.operators:
# if variable in operator.effects:
# effect = operator.effects[variable]
# if is_discrete_effect(effect) and effect.value == value:
# rg.edge(operator).connect(vertex)
# yield
#
# Path: retired/discrete/operators.py
# def is_discrete_condition(condition):
# return isinstance(condition, SubstateCondition) and len(condition.substate) == 1
#
# def is_discrete_effect(effect):
# return isinstance(effect, ValueEffect)
#
# def is_discrete_operator(operator):
# for condition in operator.conditions:
# if not is_discrete_condition(condition):
# return False
# for _, effect in operator.effects.items():
# if not is_discrete_effect(effect):
# return False
# return True
#
# def connect_discrete_conditions(rg, edge):
# for connector in edge.connectors:
# if is_discrete_condition(connector.condition):
# vertex = rg.vertex(connector.condition.substate)
# vertex.connect(connector)
# if rg.start.substate in connector.condition:
# rg.start.connect(connector)
#
# def connect_discrete_operator(rg, edge):
# connect_discrete_conditions(rg, edge)
# connect_discrete_effects(rg, edge)
. Output only the next line. | self.subplanner = DiscreteSubplanner(operators) |
Here is a snippet: <|code_start|>
class GeneratingScheduler(Scheduler):
def __init__(self, rg, subplanners):
super(self.__class__, self).__init__(rg)
self.subplanners = subplanners
def __call__ (self, start_vertex, connector):
return [subplanner(start_vertex, connector, self.rg) for subplanner in self.subplanners
if subplanner.applicable(start_vertex, connector, self.rg)]
###########################################################################
class InitDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
connect_discrete_conditions(self.rg, self.rg.goal)
for operator in operators:
if not is_discrete_operator(operator):
raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
edge = self.rg.edge(operator)
edge.intermediates.update(edge.connectors)
connect_discrete_operator(self.rg, edge)
def __call__(self, start_vertex, goal_connector):
return []
class CallDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.operators = operators
def __call__(self, start_vertex, goal_connector):
<|code_end|>
. Write the next line using the current file imports:
from .subplanners import DiscreteSubplanner
from .operators import is_discrete_condition, is_discrete_effect, is_discrete_operator, \
connect_discrete_conditions, connect_discrete_operator
and context from other files:
# Path: retired/discrete/subplanners.py
# class DiscreteSubplanner(Subplanner):
# def __init__(self, operators):
# self.operators = operators
# def generator(self, start_vertex, goal_connector, rg):
# #yield # NOTE - include if don't want initial generation
# vertex = rg.vertex(goal_connector.condition.substate)
# vertex.connect(goal_connector)
# variable, value = list(vertex.substate)[0]
#
# for operator in self.operators:
# if variable in operator.effects:
# effect = operator.effects[variable]
# if is_discrete_effect(effect) and effect.value == value:
# rg.edge(operator).connect(vertex)
# yield
#
# Path: retired/discrete/operators.py
# def is_discrete_condition(condition):
# return isinstance(condition, SubstateCondition) and len(condition.substate) == 1
#
# def is_discrete_effect(effect):
# return isinstance(effect, ValueEffect)
#
# def is_discrete_operator(operator):
# for condition in operator.conditions:
# if not is_discrete_condition(condition):
# return False
# for _, effect in operator.effects.items():
# if not is_discrete_effect(effect):
# return False
# return True
#
# def connect_discrete_conditions(rg, edge):
# for connector in edge.connectors:
# if is_discrete_condition(connector.condition):
# vertex = rg.vertex(connector.condition.substate)
# vertex.connect(connector)
# if rg.start.substate in connector.condition:
# rg.start.connect(connector)
#
# def connect_discrete_operator(rg, edge):
# connect_discrete_conditions(rg, edge)
# connect_discrete_effects(rg, edge)
, which may include functions, classes, or code. Output only the next line. | assert is_discrete_condition(goal_connector.condition) |
Given the following code snippet before the placeholder: <|code_start|>###########################################################################
class InitDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
connect_discrete_conditions(self.rg, self.rg.goal)
for operator in operators:
if not is_discrete_operator(operator):
raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
edge = self.rg.edge(operator)
edge.intermediates.update(edge.connectors)
connect_discrete_operator(self.rg, edge)
def __call__(self, start_vertex, goal_connector):
return []
class CallDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.operators = operators
def __call__(self, start_vertex, goal_connector):
assert is_discrete_condition(goal_connector.condition)
vertex = self.rg.vertex(goal_connector.condition.substate)
vertex.connect(goal_connector)
variable, value = list(vertex.substate)[0]
for operator in self.operators:
if variable in operator.effects:
effect = operator.effects[variable]
<|code_end|>
, predict the next line using imports from the current file:
from .subplanners import DiscreteSubplanner
from .operators import is_discrete_condition, is_discrete_effect, is_discrete_operator, \
connect_discrete_conditions, connect_discrete_operator
and context including class names, function names, and sometimes code from other files:
# Path: retired/discrete/subplanners.py
# class DiscreteSubplanner(Subplanner):
# def __init__(self, operators):
# self.operators = operators
# def generator(self, start_vertex, goal_connector, rg):
# #yield # NOTE - include if don't want initial generation
# vertex = rg.vertex(goal_connector.condition.substate)
# vertex.connect(goal_connector)
# variable, value = list(vertex.substate)[0]
#
# for operator in self.operators:
# if variable in operator.effects:
# effect = operator.effects[variable]
# if is_discrete_effect(effect) and effect.value == value:
# rg.edge(operator).connect(vertex)
# yield
#
# Path: retired/discrete/operators.py
# def is_discrete_condition(condition):
# return isinstance(condition, SubstateCondition) and len(condition.substate) == 1
#
# def is_discrete_effect(effect):
# return isinstance(effect, ValueEffect)
#
# def is_discrete_operator(operator):
# for condition in operator.conditions:
# if not is_discrete_condition(condition):
# return False
# for _, effect in operator.effects.items():
# if not is_discrete_effect(effect):
# return False
# return True
#
# def connect_discrete_conditions(rg, edge):
# for connector in edge.connectors:
# if is_discrete_condition(connector.condition):
# vertex = rg.vertex(connector.condition.substate)
# vertex.connect(connector)
# if rg.start.substate in connector.condition:
# rg.start.connect(connector)
#
# def connect_discrete_operator(rg, edge):
# connect_discrete_conditions(rg, edge)
# connect_discrete_effects(rg, edge)
. Output only the next line. | if is_discrete_effect(effect) and effect.value == value: |
Predict the next line after this snippet: <|code_start|>
class Scheduler(object):
def __init__(self, rg):
self.rg = rg
def __call__(self, start_vertex, connector):
raise NotImplementedError('Scheduler must implement __call__(self, start_vertex, connector)')
class GeneratingScheduler(Scheduler):
def __init__(self, rg, subplanners):
super(self.__class__, self).__init__(rg)
self.subplanners = subplanners
def __call__ (self, start_vertex, connector):
return [subplanner(start_vertex, connector, self.rg) for subplanner in self.subplanners
if subplanner.applicable(start_vertex, connector, self.rg)]
###########################################################################
class InitDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
connect_discrete_conditions(self.rg, self.rg.goal)
for operator in operators:
<|code_end|>
using the current file's imports:
from .subplanners import DiscreteSubplanner
from .operators import is_discrete_condition, is_discrete_effect, is_discrete_operator, \
connect_discrete_conditions, connect_discrete_operator
and any relevant context from other files:
# Path: retired/discrete/subplanners.py
# class DiscreteSubplanner(Subplanner):
# def __init__(self, operators):
# self.operators = operators
# def generator(self, start_vertex, goal_connector, rg):
# #yield # NOTE - include if don't want initial generation
# vertex = rg.vertex(goal_connector.condition.substate)
# vertex.connect(goal_connector)
# variable, value = list(vertex.substate)[0]
#
# for operator in self.operators:
# if variable in operator.effects:
# effect = operator.effects[variable]
# if is_discrete_effect(effect) and effect.value == value:
# rg.edge(operator).connect(vertex)
# yield
#
# Path: retired/discrete/operators.py
# def is_discrete_condition(condition):
# return isinstance(condition, SubstateCondition) and len(condition.substate) == 1
#
# def is_discrete_effect(effect):
# return isinstance(effect, ValueEffect)
#
# def is_discrete_operator(operator):
# for condition in operator.conditions:
# if not is_discrete_condition(condition):
# return False
# for _, effect in operator.effects.items():
# if not is_discrete_effect(effect):
# return False
# return True
#
# def connect_discrete_conditions(rg, edge):
# for connector in edge.connectors:
# if is_discrete_condition(connector.condition):
# vertex = rg.vertex(connector.condition.substate)
# vertex.connect(connector)
# if rg.start.substate in connector.condition:
# rg.start.connect(connector)
#
# def connect_discrete_operator(rg, edge):
# connect_discrete_conditions(rg, edge)
# connect_discrete_effects(rg, edge)
. Output only the next line. | if not is_discrete_operator(operator): |
Next line prediction: <|code_start|>
class Scheduler(object):
def __init__(self, rg):
self.rg = rg
def __call__(self, start_vertex, connector):
raise NotImplementedError('Scheduler must implement __call__(self, start_vertex, connector)')
class GeneratingScheduler(Scheduler):
def __init__(self, rg, subplanners):
super(self.__class__, self).__init__(rg)
self.subplanners = subplanners
def __call__ (self, start_vertex, connector):
return [subplanner(start_vertex, connector, self.rg) for subplanner in self.subplanners
if subplanner.applicable(start_vertex, connector, self.rg)]
###########################################################################
class InitDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
<|code_end|>
. Use current file imports:
(from .subplanners import DiscreteSubplanner
from .operators import is_discrete_condition, is_discrete_effect, is_discrete_operator, \
connect_discrete_conditions, connect_discrete_operator)
and context including class names, function names, or small code snippets from other files:
# Path: retired/discrete/subplanners.py
# class DiscreteSubplanner(Subplanner):
# def __init__(self, operators):
# self.operators = operators
# def generator(self, start_vertex, goal_connector, rg):
# #yield # NOTE - include if don't want initial generation
# vertex = rg.vertex(goal_connector.condition.substate)
# vertex.connect(goal_connector)
# variable, value = list(vertex.substate)[0]
#
# for operator in self.operators:
# if variable in operator.effects:
# effect = operator.effects[variable]
# if is_discrete_effect(effect) and effect.value == value:
# rg.edge(operator).connect(vertex)
# yield
#
# Path: retired/discrete/operators.py
# def is_discrete_condition(condition):
# return isinstance(condition, SubstateCondition) and len(condition.substate) == 1
#
# def is_discrete_effect(effect):
# return isinstance(effect, ValueEffect)
#
# def is_discrete_operator(operator):
# for condition in operator.conditions:
# if not is_discrete_condition(condition):
# return False
# for _, effect in operator.effects.items():
# if not is_discrete_effect(effect):
# return False
# return True
#
# def connect_discrete_conditions(rg, edge):
# for connector in edge.connectors:
# if is_discrete_condition(connector.condition):
# vertex = rg.vertex(connector.condition.substate)
# vertex.connect(connector)
# if rg.start.substate in connector.condition:
# rg.start.connect(connector)
#
# def connect_discrete_operator(rg, edge):
# connect_discrete_conditions(rg, edge)
# connect_discrete_effects(rg, edge)
. Output only the next line. | connect_discrete_conditions(self.rg, self.rg.goal) |
Next line prediction: <|code_start|>
class Scheduler(object):
def __init__(self, rg):
self.rg = rg
def __call__(self, start_vertex, connector):
raise NotImplementedError('Scheduler must implement __call__(self, start_vertex, connector)')
class GeneratingScheduler(Scheduler):
def __init__(self, rg, subplanners):
super(self.__class__, self).__init__(rg)
self.subplanners = subplanners
def __call__ (self, start_vertex, connector):
return [subplanner(start_vertex, connector, self.rg) for subplanner in self.subplanners
if subplanner.applicable(start_vertex, connector, self.rg)]
###########################################################################
class InitDiscreteScheduler(Scheduler):
def __init__(self, rg, operators):
super(self.__class__, self).__init__(rg)
self.rg.goal.intermediates.update(self.rg.goal.connectors) # NOTE - marks as intermediates to prevent growing
connect_discrete_conditions(self.rg, self.rg.goal)
for operator in operators:
if not is_discrete_operator(operator):
raise RuntimeError(self.__class__.__name__ + ' passed non-discrete operator')
edge = self.rg.edge(operator)
edge.intermediates.update(edge.connectors)
<|code_end|>
. Use current file imports:
(from .subplanners import DiscreteSubplanner
from .operators import is_discrete_condition, is_discrete_effect, is_discrete_operator, \
connect_discrete_conditions, connect_discrete_operator)
and context including class names, function names, or small code snippets from other files:
# Path: retired/discrete/subplanners.py
# class DiscreteSubplanner(Subplanner):
# def __init__(self, operators):
# self.operators = operators
# def generator(self, start_vertex, goal_connector, rg):
# #yield # NOTE - include if don't want initial generation
# vertex = rg.vertex(goal_connector.condition.substate)
# vertex.connect(goal_connector)
# variable, value = list(vertex.substate)[0]
#
# for operator in self.operators:
# if variable in operator.effects:
# effect = operator.effects[variable]
# if is_discrete_effect(effect) and effect.value == value:
# rg.edge(operator).connect(vertex)
# yield
#
# Path: retired/discrete/operators.py
# def is_discrete_condition(condition):
# return isinstance(condition, SubstateCondition) and len(condition.substate) == 1
#
# def is_discrete_effect(effect):
# return isinstance(effect, ValueEffect)
#
# def is_discrete_operator(operator):
# for condition in operator.conditions:
# if not is_discrete_condition(condition):
# return False
# for _, effect in operator.effects.items():
# if not is_discrete_effect(effect):
# return False
# return True
#
# def connect_discrete_conditions(rg, edge):
# for connector in edge.connectors:
# if is_discrete_condition(connector.condition):
# vertex = rg.vertex(connector.condition.substate)
# vertex.connect(connector)
# if rg.start.substate in connector.condition:
# rg.start.connect(connector)
#
# def connect_discrete_operator(rg, edge):
# connect_discrete_conditions(rg, edge)
# connect_discrete_effects(rg, edge)
. Output only the next line. | connect_discrete_operator(self.rg, edge) |
Next line prediction: <|code_start|># TODO: move this into a shared class
class DomainError(Exception):
def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
self.salary = salary
self.message = message
super().__init__(self.message)
# def __str__(self):
# return self.message
class Operator(PartialState):
cost = None
def __init__(self, args):
#super(Operator, self).__init__(...)
for k, v in args.items():
setattr(self, k, v)
self.args = args # TODO - use FrozenDict instead
self._frozen_args = frozenset(args.items())
self._hash = None
self.conditions = None
self.effects = None
self.test = lambda state: True
self.forward = lambda state: state
# TODO: override instead?
# def test(self, state):
# return True
# def forward(self, state):
# return state
applicable = PartialState.contains
def apply(self, state):
# TODO: cancellation semantics
<|code_end|>
. Use current file imports:
(from collections import defaultdict, deque
from .states import State, PartialState
from misc.objects import str_object)
and context including class names, function names, or small code snippets from other files:
# Path: strips/states.py
# class State(object):
# def __init__(self, atoms, external=None):
# self.atoms = frozenset(atoms)
# self.external = external
# # TODO: refine function where external is updated
# # TODO: should I assume external is hashable?
# def identity(self):
# return self.__class__, frozenset(self.__dict__.items())
# def holds(self, literal):
# return literal.negated == (literal.positive() not in self.atoms)
# __contains__ = holds
# def __iter__(self):
# return iter(self.atoms)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.identity() == other.identity())
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash(self.identity())
# def __str__(self):
# #return '{}({})'.format(self.__class__.__name__, id(self))
# return self.__class__.__name__ + str_object(self.atoms)
# __repr__ = __str__
#
# class PartialState(object):
# def __init__(self, literals, test=lambda state: True):
# self.conditions = frozenset(literals)
# self.test = test # TODO: cache the test results
# def contains(self, state):
# return all(literal in state for literal in self.conditions) # and self.test(state)
# __contains__ = contains
# def __iter__(self):
# return iter(self.conditions)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash((self.__class__, self.conditions))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
#
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | return State({atom for atom in state.atoms if atom.negate() not in self.effects} | |
Based on the snippet: <|code_start|>
# TODO: move this into a shared class
class DomainError(Exception):
def __init__(self, salary, message="Salary is not in (5000, 15000) range"):
self.salary = salary
self.message = message
super().__init__(self.message)
# def __str__(self):
# return self.message
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import defaultdict, deque
from .states import State, PartialState
from misc.objects import str_object
and context (classes, functions, sometimes code) from other files:
# Path: strips/states.py
# class State(object):
# def __init__(self, atoms, external=None):
# self.atoms = frozenset(atoms)
# self.external = external
# # TODO: refine function where external is updated
# # TODO: should I assume external is hashable?
# def identity(self):
# return self.__class__, frozenset(self.__dict__.items())
# def holds(self, literal):
# return literal.negated == (literal.positive() not in self.atoms)
# __contains__ = holds
# def __iter__(self):
# return iter(self.atoms)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.identity() == other.identity())
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash(self.identity())
# def __str__(self):
# #return '{}({})'.format(self.__class__.__name__, id(self))
# return self.__class__.__name__ + str_object(self.atoms)
# __repr__ = __str__
#
# class PartialState(object):
# def __init__(self, literals, test=lambda state: True):
# self.conditions = frozenset(literals)
# self.test = test # TODO: cache the test results
# def contains(self, state):
# return all(literal in state for literal in self.conditions) # and self.test(state)
# __contains__ = contains
# def __iter__(self):
# return iter(self.conditions)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash((self.__class__, self.conditions))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
#
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | class Operator(PartialState): |
Continue the code snippet: <|code_start|> self.forward = lambda state: state
# TODO: override instead?
# def test(self, state):
# return True
# def forward(self, state):
# return state
applicable = PartialState.contains
def apply(self, state):
# TODO: cancellation semantics
return State({atom for atom in state.atoms if atom.negate() not in self.effects} |
{literal for literal in self.effects if not literal.negated}, external=state.external)
def __call__(self, state):
#return self.apply(state) if self.applicable(state) else None
assert self.applicable(state)
return self.apply(state)
def is_axiom(self):
return isinstance(self, Axiom)
def dump(self):
print('{}\npre: {}\neff: {}\ncost: {}'.format(self, self.conditions, self.effects, self.cost))
def __iter__(self):
yield self
def __len__(self):
return 1
def __eq__(self, other):
return (type(self) == type(other)) and (self._frozen_args == other._frozen_args)
def __hash__(self):
if self._hash is None:
self._hash = hash((self.__class__, self._frozen_args))
return self._hash
def __str__(self):
<|code_end|>
. Use current file imports:
from collections import defaultdict, deque
from .states import State, PartialState
from misc.objects import str_object
and context (classes, functions, or code) from other files:
# Path: strips/states.py
# class State(object):
# def __init__(self, atoms, external=None):
# self.atoms = frozenset(atoms)
# self.external = external
# # TODO: refine function where external is updated
# # TODO: should I assume external is hashable?
# def identity(self):
# return self.__class__, frozenset(self.__dict__.items())
# def holds(self, literal):
# return literal.negated == (literal.positive() not in self.atoms)
# __contains__ = holds
# def __iter__(self):
# return iter(self.atoms)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.identity() == other.identity())
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash(self.identity())
# def __str__(self):
# #return '{}({})'.format(self.__class__.__name__, id(self))
# return self.__class__.__name__ + str_object(self.atoms)
# __repr__ = __str__
#
# class PartialState(object):
# def __init__(self, literals, test=lambda state: True):
# self.conditions = frozenset(literals)
# self.test = test # TODO: cache the test results
# def contains(self, state):
# return all(literal in state for literal in self.conditions) # and self.test(state)
# __contains__ = contains
# def __iter__(self):
# return iter(self.conditions)
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not (self == other)
# def __hash__(self):
# return hash((self.__class__, self.conditions))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
#
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | return self.__class__.__name__ + str_object(self.args) |
Next line prediction: <|code_start|>
def set_inactive(self):
if not self.active: return
self.active = False
for vertex in self.vertices:
vertex.update_inactive()
def update_inactive(self): # TODO - this is really slow. Only search if not greedy and reached?
if not self.active: return
self.active = False # Temporarily set to inactive
for edge in self.edges:
edge.update_inactive()
if edge.active:
self.active = True
return
# Cannot find active parent node
self.set_inactive()
#def copy(self, rg):
# new_connector = type(self)(self.condition, rg)
# pass
def __str__(self):
return 'C(' + str(self.condition) + ')'
__repr__ = __str__
def node_str(self):
node_str = self.condition.__class__.__name__
for value in self.condition.__dict__['__hash_dict'].values():
<|code_end|>
. Use current file imports:
(from .utils import *
from misc.objects import str_object)
and context including class names, function names, or small code snippets from other files:
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | node_str += '\n' + str_object(value) |
Given the following code snippet before the placeholder: <|code_start|>
#from .set_additive import *
def h_0(state, goal, operators):
return 0
def h_naive(state, goal, operators):
return sum(1 for var, value in goal.cond() if state[var] != value)
def h_blind(state, goal, operators):
return min(operator.cost for operator in ha_applicable(state, goal, operators))
###########################################################################
def ha_all(state, goal, operators):
<|code_end|>
, predict the next line using imports from the current file:
import time
from misc.utils import INF, randomize
from sas.downward import Problem
from .ff import filter_axioms, in_add, ff_fn, plan_cost, first_combine
from planner.progression import deferred_best_first_search
from .downward import solve_sas
and context including class names, function names, and sometimes code from other files:
# Path: misc/utils.py
# SEPARATOR = '\n'+85*'-'+'\n'
# def arg_info(frame, ignore=['self']):
# def function_name(stack): # NOTE - stack = inspect.stack()
# def get_path(frame):
# def get_directory(abs_path):
# def global_fn(name):
# def refresh(module_name):
#
# Path: sas/downward.py
# class Problem(object):
# default_val = False
# def __init__(self, initial, goal, actions, axioms):
# self.var_indices = {}
# self.var_order = []
# self.var_val_indices = {}
# self.var_val_order = {}
# self.axioms = axioms
# self.mutexes = []
# self.costs = True
#
# self.initial = initial
# for var, val in initial.values.items():
# self.add_val(var, val)
# self.goal = goal
# for var, val in goal.conditions.items():
# self.add_val(var, val)
#
# self.actions = actions
# for action in self.actions:
# for var, val in action.conditions.items():
# self.add_val(var, val)
# for var, val in action.effects.items():
# self.add_val(var, val)
#
# def print_problem(self):
# print(self.initial.values.keys())
# print(len(self.initial.values))
# print(len(self.var_order))
# print(set(self.var_order) - set(self.initial.values.keys()))
# for var in self.var_order:
# print(var)
# print(self.var_val_order[var])
# print()
#
# def add_var(self, var):
# if var not in self.var_indices:
# self.var_indices[var] = len(self.var_order)
# self.var_order.append(var)
# self.var_val_indices[var] = {}
# self.var_val_order[var] = []
# self.add_val(var, self.default_val) # NOTE - I assume a default False value
#
# def add_val(self, var, val):
# self.add_var(var)
# if val not in self.var_val_indices[var]:
# self.var_val_indices[var][val] = len(self.var_val_order[var])
# self.var_val_order[var].append(val)
#
# def get_var(self, var):
# return self.var_indices[var]
#
# def get_val(self, var, val):
# return self.var_val_indices[var][val]
#
# def get_var_val(self, var, val):
# return self.get_var(var), self.get_val(var, val)
#
# Path: sas/ff.py
# def get_layers(costs):
# def flat_layer(_, layer):
# def random_layer(_, layer):
# def easy_layer(costs, layer):
# def hard_layer(costs, layer):
# def zero_cost(*args): return 0
# def operator_cost(operator, operator_costs, **args): return operator_costs[operator]
# def new_conditions_cost(operator, operator_costs, variable_costs, goals): # TODO - include marked pruning
# def extract_relaxed_plan(goal, variable_costs, operator_costs):
# def plan_cost(goal, operator_costs, relaxed_plan, relaxed_goals):
# def plan_length(goal, operator_costs, relaxed_plan, relaxed_goals):
# def multi_cost(goal, operator_costs, relaxed_plan, relaxed_goals):
# def filter_axioms(operators):
# def none(goal, operator_costs, relaxed_plan, relaxed_goals):
# def applicable(goal, operator_costs, relaxed_plan, relaxed_goals):
# def first_goals(goal, operator_costs, relaxed_plan, relaxed_goals):
# def first_operators(goal, operator_costs, relaxed_plan, relaxed_goals):
# def first_combine(goal, operator_costs, relaxed_plan, relaxed_goals):
# def ff(state, goal, operators, heuristic, helpful_actions, op=sum, unit=False):
# def ff_fn(heuristic, helpful_actions, op=sum, unit=False):
# def h_ff_max(state, goal, operators):
# def h_ff_add(state, goal, operators):
# ALL_BACK_POINTERS = False
# LAYER_ORDER = easy_layer
# EASIEST_HEURISTIC = new_conditions_cost
#
# Path: planner/progression/best_first.py
# def deferred_best_first_search(start, goal, generator, priority, stack=False, debug=None, **kwargs):
# space = StateSpace(generator, start, max_extensions=INF, **kwargs) # TODO: max_extensions=1 can fail when test
# queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, space.root)])
# while not queue.empty() and space.is_active():
# cv = queue.pop()
# cv.evaluate() # cv.generate()
# space.new_iteration(cv)
# if cv.is_dead_end():
# continue
# if not test_parent_operator(cv): # always lazy
# continue
# if debug is not None:
# debug(cv)
# if test_goal(cv, goal):
# return space.solution(cv)
# successors = list(cv.unexplored())
# if not cv.enumerated():
# successors.append(cv) # TODO: use its prior value
# for nv in order_successors(successors, stack):
# # TODO: incorporate the path cost of nv instead of cv
# queue.push(priority(cv), nv)
# return space.failure()
#
# Path: sas/downward.py
# def solve_sas(problem):
# write_sas(problem)
# plan = fast_downward()
# if plan is None:
# return None
# return convert_solution(plan, problem)
. Output only the next line. | return filter_axioms(operators) |
Given the code snippet: <|code_start|> literal_cost = operator_cost + (operator.cost if not unit else 1)
literal_level = operator_level + 1
# literal_level = operator_level + (1 if not operator.is_axiom() else 0)
for effect in operator.effects:
# Only computes costs for relevant operators
if (effect in unprocessed) and (effect not in literal_costs or
(literal_cost < literal_costs[effect].cost)):
literal_costs[effect] = Pair(literal_cost, literal_level)
heappush(queue, (literal_cost, effect))
return False
for operator in unsatisfied:
if unsatisfied[operator] == 0:
process_operator(operator)
while queue:
_, literal = heappop(queue)
if literal not in unprocessed:
continue
for operator in unprocessed[literal]:
unsatisfied[operator] -= 1
if unsatisfied[operator] == 0:
process_operator(operator)
del unprocessed[literal]
return literal_costs, operator_costs
###########################################################################
def h_add(state, goal, operators):
_, operator_costs = compute_costs(state, goal, operators, op=sum)
<|code_end|>
, generate the next line using the imports in this file:
from collections import defaultdict, namedtuple
from heapq import heappush, heappop
from misc.numerical import INF
and context (functions, classes, or occasionally code) from other files:
# Path: misc/numerical.py
# INF = float('inf')
. Output only the next line. | return operator_costs[goal].cost if goal in operator_costs else INF |
Based on the snippet: <|code_start|> self.sign = True
@property
def negated(self):
return not self.sign
def copy(self):
new = self.__class__(*self.args)
new.sign = self.sign
return new
def positive(self):
new = self.copy()
new.sign = True
return new
__abs__ = positive # abs(literal)
def negate(self):
new = self.copy()
new.sign = not self.sign
return new
__neg__ = negate # -literal
__invert__ = negate # ~literal
def __iter__(self):
return iter(self.args)
def __eq__(self, other):
return (type(self) == type(other)) and (self.sign == other.sign) and (self.args == other.args)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash((self.__class__, self.args, self.sign))
def __lt__(self, other):
return id(self) < id(other)
def __str__(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from collections import namedtuple
from misc.objects import str_object
and context (classes, functions, sometimes code) from other files:
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | s = self.__class__.__name__ + str_object(self.args) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
def solve(problem_name, print_profile=False):
dt = datetime.datetime.now()
directory = './simulations/discrete/planning/{}/{}/{}/'.format(
problem_name, dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S'))
start, goal, Scheduler = getattr(problems, problem_name)()
generator = default_scheduler_generator(goal, Scheduler)
print(SEPARATOR + '\nSolving planning problem ' + problem_name)
def execute():
<|code_end|>
, predict the next line using imports from the current file:
from misc.utils import *
from planner.main import default_plan
from retired.planners.main import default_scheduler_generator
import retired.discrete.problems as problems
import sys
import getopt
import datetime
and context including class names, function names, and sometimes code from other files:
# Path: planner/main.py
# def default_plan(start, goal, generator, search=False, meta=None, debug=False):
# search = default_search(search, debug)
# if meta is not None:
# meta = default_meta(meta)
# return meta(start, goal, generator, search)
# return search(start, goal, generator)
#
# Path: retired/planners/main.py
# def default_scheduler_generator(goal, Scheduler):
# connectivity_graph = RelaxedConnectivityGraph(goal, Scheduler)
# heuristic = h_ff_add
# helpful_actions = ha_achieving_macro_sorted # ha_relaxed_plan_action_macro_sorted | ha_achieving_macro_sorted
# max_time = INF
# max_iterations = INF
# max_cycles = INF
# max_generations = INF
# greedy = False
# return lambda vertex: connectivity_generator(vertex, connectivity_graph, heuristic, helpful_actions,
# max_time=max_time, max_iterations=max_iterations, max_cycles=max_cycles, max_generations=max_generations, greedy=greedy)
. Output only the next line. | output = default_plan(start, goal, generator) |
Using the snippet: <|code_start|>#!/usr/bin/env python
from __future__ import print_function
def solve(problem_name, print_profile=False):
dt = datetime.datetime.now()
directory = './simulations/discrete/planning/{}/{}/{}/'.format(
problem_name, dt.strftime('%Y-%m-%d'), dt.strftime('%H-%M-%S'))
start, goal, Scheduler = getattr(problems, problem_name)()
<|code_end|>
, determine the next line of code. You have imports:
from misc.utils import *
from planner.main import default_plan
from retired.planners.main import default_scheduler_generator
import retired.discrete.problems as problems
import sys
import getopt
import datetime
and context (class names, function names, or code) available:
# Path: planner/main.py
# def default_plan(start, goal, generator, search=False, meta=None, debug=False):
# search = default_search(search, debug)
# if meta is not None:
# meta = default_meta(meta)
# return meta(start, goal, generator, search)
# return search(start, goal, generator)
#
# Path: retired/planners/main.py
# def default_scheduler_generator(goal, Scheduler):
# connectivity_graph = RelaxedConnectivityGraph(goal, Scheduler)
# heuristic = h_ff_add
# helpful_actions = ha_achieving_macro_sorted # ha_relaxed_plan_action_macro_sorted | ha_achieving_macro_sorted
# max_time = INF
# max_iterations = INF
# max_cycles = INF
# max_generations = INF
# greedy = False
# return lambda vertex: connectivity_generator(vertex, connectivity_graph, heuristic, helpful_actions,
# max_time=max_time, max_iterations=max_iterations, max_cycles=max_cycles, max_generations=max_generations, greedy=greedy)
. Output only the next line. | generator = default_scheduler_generator(goal, Scheduler) |
Given the following code snippet before the placeholder: <|code_start|>
class Operator(object):
def __init__(self, args):
self.args = args
for k, v in args.items():
setattr(self, k, v)
self.conditions = []
self.effects = {}
def __contains__(self, state):
return all(state in precondition for precondition in self.conditions)
def apply(self, state):
return State(dict(list(state) + [(var, effect(state)) for var, effect in self.effects.items()]))
def __call__(self, state):
if state not in self: return None
return self.apply(state)
def __iter__(self):
yield self
def __len__(self):
return 1
def fixed_conditions(self):
fc = {}
for condition in self.conditions:
if isinstance(condition, SubstateCondition):
for var, value in condition.substate:
if var in fc and fc[var] != value:
raise RuntimeError('Condition has conflicting conditions')
fc[var] = value
return fc
def fixed_effects(self):
return {var: effect.value for var, effect in self.effects.items()
<|code_end|>
, predict the next line using imports from the current file:
from .states import *
from misc.utils import *
from .effects import ValueEffect
from .conditions import SubstateCondition
from strips.operators import derive_state
and context including class names, function names, and sometimes code from other files:
# Path: planner/effects.py
# class ValueEffect(Effect):
# def __init__(self, value):
# super(self.__class__, self).__init__()
# self.value = value
# def __call__(self, *args):
# return self.value
# def __repr__(self):
# return 'VE' + str_object((self.value,))
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
. Output only the next line. | if isinstance(effect, ValueEffect)} |
Predict the next line after this snippet: <|code_start|>
class Operator(object):
def __init__(self, args):
self.args = args
for k, v in args.items():
setattr(self, k, v)
self.conditions = []
self.effects = {}
def __contains__(self, state):
return all(state in precondition for precondition in self.conditions)
def apply(self, state):
return State(dict(list(state) + [(var, effect(state)) for var, effect in self.effects.items()]))
def __call__(self, state):
if state not in self: return None
return self.apply(state)
def __iter__(self):
yield self
def __len__(self):
return 1
def fixed_conditions(self):
fc = {}
for condition in self.conditions:
<|code_end|>
using the current file's imports:
from .states import *
from misc.utils import *
from .effects import ValueEffect
from .conditions import SubstateCondition
from strips.operators import derive_state
and any relevant context from other files:
# Path: planner/effects.py
# class ValueEffect(Effect):
# def __init__(self, value):
# super(self.__class__, self).__init__()
# self.value = value
# def __call__(self, *args):
# return self.value
# def __repr__(self):
# return 'VE' + str_object((self.value,))
#
# Path: planner/conditions.py
# class SubstateCondition(Condition):
# def __init__(self, substate):
# super(self.__class__, self).__init__()
# self.substate = substate
# self.variables = frozenset(substate.variables())
# def __contains__(self, substate):
# return all(var in substate and substate[var] == value for var, value in self.substate)
# def __str__(self):
# return 'SC' + str_args(self.substate.__dict__['__hash_dict'])
# __repr__ = __str__
. Output only the next line. | if isinstance(condition, SubstateCondition): |
Next line prediction: <|code_start|>
def incremental_goal_addition(start, goal, search): # Replace generator_fn with state_space
start_time = time()
operators = []
current = start # Allow starting at start state each time
for i in range(len(goal)):
plan_data, _ = search(current, PartialState(goal.conditions[:i+1]))
if plan_data is None: return None, SearchData(time() - start_time, None, None)
operators += plan_data.operators
<|code_end|>
. Use current file imports:
(from time import time
from planner.operators import MacroOperator
from planner.states import PartialState)
and context including class names, function names, or small code snippets from other files:
# Path: planner/operators.py
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: planner/states.py
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
. Output only the next line. | current = MacroOperator(*plan_data.operators)(current)[-1] |
Here is a snippet: <|code_start|>
def incremental_goal_addition(start, goal, search): # Replace generator_fn with state_space
start_time = time()
operators = []
current = start # Allow starting at start state each time
for i in range(len(goal)):
<|code_end|>
. Write the next line using the current file imports:
from time import time
from planner.operators import MacroOperator
from planner.states import PartialState
and context from other files:
# Path: planner/operators.py
# class MacroOperator(object):
# def __init__(self, *operators):
# self.operators = tuple(operators)
# self.cost = sum(operator.cost for operator in operators)
# def __contains__(self, state):
# return self(state) is not None
# def __call__(self, state):
# states = [state]
# for operator in self.operators:
# new_state = operator(states[-1])
# if new_state is None: return None
# states.append(new_state)
# return states
# def __iter__(self):
# return (operator for operator in self.operators)
# def __len__(self):
# return len(self.operators)
# def __eq__(self, other):
# if type(self) != type(other): return False
# return self.operators == other.operators
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, self.operators))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.operators)
# __repr__ = __str__
#
# Path: planner/states.py
# class PartialState(SinglePrintObject):
# #__slots__ = ('conditions',)
# def __init__(self, conditions):
# HashObject.__init__(self)
# self.conditions = tuple(conditions)
# def __contains__(self, state):
# return all(state in condition for condition in self.conditions)
# def __iter__(self):
# for condition in self.conditions:
# yield condition
# def __len__(self):
# return len(self.conditions)
, which may include functions, classes, or code. Output only the next line. | plan_data, _ = search(current, PartialState(goal.conditions[:i+1])) |
Based on the snippet: <|code_start|># TODO: use FF or FD software for heuristics
def none(operator_costs, relaxed_plan, relaxed_goals):
return []
def applicable(operator_costs, relaxed_plan, relaxed_goals):
return [o for o, (_, level) in operator_costs.items()
if isinstance(o, Action) and (level == 0)]
def backpointers(operator_costs, relaxed_plan, relaxed_goals):
# Retrace actions without using extract_relaxed_plan
# Could also do h_max and h_add versions
raise NotImplementedError()
def first_goals(operator_costs, relaxed_plan, relaxed_goals):
if len(relaxed_goals) <= 1:
return []
return [o for o, (_, level) in operator_costs.items()
if isinstance(o, Action) and (level == 0) and any(effect in relaxed_goals[1] for effect in o.effects)]
def first_operators(operator_costs, relaxed_plan, relaxed_goals):
if not relaxed_plan:
return []
return [o for o in relaxed_plan[0] if isinstance(o, Action)]
# TODO: prioritize helpful actions
###########################################################################
def ff(state, goal, operators, heuristic, helpful_actions, op=max, unit=False):
<|code_end|>
, predict the immediate next line with the help of imports:
from strips.hsp import compute_costs
from strips.operators import Action
from misc.functions import argmin, flatten, INF
and context (classes, functions, sometimes code) from other files:
# Path: strips/hsp.py
# def compute_costs(state, goal, operators, op=max, unit=False):
# unprocessed = defaultdict(list) # TODO: store this in memory
# unsatisfied = {}
# for operator in operators + [goal]:
# unsatisfied[operator] = len(operator.conditions)
# for literal in operator.conditions:
# unprocessed[literal].append(operator)
#
# literal_costs = {literal: Pair(0, 0) for literal in unprocessed if literal in state}
# operator_costs = {}
# queue = [(pair.cost, literal) for literal, pair in literal_costs.items()]
#
# def process_operator(operator):
# operator_cost = operator_level = 0
# if len(operator.conditions) != 0:
# operator_cost = op(literal_costs[literal].cost for literal in operator.conditions)
# operator_level = max(literal_costs[literal].level for literal in operator.conditions)
# operator_costs[operator] = Pair(operator_cost, operator_level)
# if operator == goal:
# # TODO: terminate earlier if the goal is achieved
# return True
# literal_cost = operator_cost + (operator.cost if not unit else 1)
# literal_level = operator_level + 1
# # literal_level = operator_level + (1 if not operator.is_axiom() else 0)
# for effect in operator.effects:
# # Only computes costs for relevant operators
# if (effect in unprocessed) and (effect not in literal_costs or
# (literal_cost < literal_costs[effect].cost)):
# literal_costs[effect] = Pair(literal_cost, literal_level)
# heappush(queue, (literal_cost, effect))
# return False
#
# for operator in unsatisfied:
# if unsatisfied[operator] == 0:
# process_operator(operator)
# while queue:
# _, literal = heappop(queue)
# if literal not in unprocessed:
# continue
# for operator in unprocessed[literal]:
# unsatisfied[operator] -= 1
# if unsatisfied[operator] == 0:
# process_operator(operator)
# del unprocessed[literal]
#
# return literal_costs, operator_costs
#
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# def irange(start, stop=None, step=1): #np.arange
# def erange(start, stop=None, step=1):
# def some(function, iterable):
# def every(function, iterable):
# def first(function, iterable):
# def argmax(function, sequence):
# def argmin(function, sequence):
# def pop_max(function, array):
# def pop_min(function, array):
# def safe_remove(sequence, item):
# def safe_function(function, sequence, default):
# def safe_choice(sequence, default=None):
# def safe_max(sequence, default=-INF):
# def safe_min(sequence, default=INF):
# def safe_maxmin(iterable_of_iterables):
# def safe_minmax(iterable_of_iterables):
# def safe_index(sequence, value, default=-1):
# def pairs(lst):
# def randomize(sequence):
# def random_sequence(sequence):
# def reverse(iterable):
# def flatten(iterable_of_iterables):
# def squash(nested_iterables):
# def round_robin(*iterables):
# def merge_unique(iterables, sort=False):
# def merge_dicts(*args):
# def in_add(x, s):
# def implies(a, b):
. Output only the next line. | literal_costs, operator_costs = compute_costs(state, goal, operators, op=op, unit=unit) |
Given the following code snippet before the placeholder: <|code_start|> for effect in easiest_operator.effects:
marked[level].add(effect)
marked[level-1].add(effect)
return plan, goals
###########################################################################
def plan_cost(relaxed_plan, unit=False):
if relaxed_plan is None:
return INF
return sum(operator.cost if not unit else 1
for operator in flatten(relaxed_plan))
def plan_length(relaxed_plan):
if relaxed_plan is None:
return INF
return len(flatten(relaxed_plan))
def multi_cost(goal, operator_costs, relaxed_plan, relaxed_goals):
return plan_cost(relaxed_plan), operator_costs[goal].cost, operator_costs[goal].level
###########################################################################
# TODO: use FF or FD software for heuristics
def none(operator_costs, relaxed_plan, relaxed_goals):
return []
def applicable(operator_costs, relaxed_plan, relaxed_goals):
return [o for o, (_, level) in operator_costs.items()
<|code_end|>
, predict the next line using imports from the current file:
from strips.hsp import compute_costs
from strips.operators import Action
from misc.functions import argmin, flatten, INF
and context including class names, function names, and sometimes code from other files:
# Path: strips/hsp.py
# def compute_costs(state, goal, operators, op=max, unit=False):
# unprocessed = defaultdict(list) # TODO: store this in memory
# unsatisfied = {}
# for operator in operators + [goal]:
# unsatisfied[operator] = len(operator.conditions)
# for literal in operator.conditions:
# unprocessed[literal].append(operator)
#
# literal_costs = {literal: Pair(0, 0) for literal in unprocessed if literal in state}
# operator_costs = {}
# queue = [(pair.cost, literal) for literal, pair in literal_costs.items()]
#
# def process_operator(operator):
# operator_cost = operator_level = 0
# if len(operator.conditions) != 0:
# operator_cost = op(literal_costs[literal].cost for literal in operator.conditions)
# operator_level = max(literal_costs[literal].level for literal in operator.conditions)
# operator_costs[operator] = Pair(operator_cost, operator_level)
# if operator == goal:
# # TODO: terminate earlier if the goal is achieved
# return True
# literal_cost = operator_cost + (operator.cost if not unit else 1)
# literal_level = operator_level + 1
# # literal_level = operator_level + (1 if not operator.is_axiom() else 0)
# for effect in operator.effects:
# # Only computes costs for relevant operators
# if (effect in unprocessed) and (effect not in literal_costs or
# (literal_cost < literal_costs[effect].cost)):
# literal_costs[effect] = Pair(literal_cost, literal_level)
# heappush(queue, (literal_cost, effect))
# return False
#
# for operator in unsatisfied:
# if unsatisfied[operator] == 0:
# process_operator(operator)
# while queue:
# _, literal = heappop(queue)
# if literal not in unprocessed:
# continue
# for operator in unprocessed[literal]:
# unsatisfied[operator] -= 1
# if unsatisfied[operator] == 0:
# process_operator(operator)
# del unprocessed[literal]
#
# return literal_costs, operator_costs
#
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# def irange(start, stop=None, step=1): #np.arange
# def erange(start, stop=None, step=1):
# def some(function, iterable):
# def every(function, iterable):
# def first(function, iterable):
# def argmax(function, sequence):
# def argmin(function, sequence):
# def pop_max(function, array):
# def pop_min(function, array):
# def safe_remove(sequence, item):
# def safe_function(function, sequence, default):
# def safe_choice(sequence, default=None):
# def safe_max(sequence, default=-INF):
# def safe_min(sequence, default=INF):
# def safe_maxmin(iterable_of_iterables):
# def safe_minmax(iterable_of_iterables):
# def safe_index(sequence, value, default=-1):
# def pairs(lst):
# def randomize(sequence):
# def random_sequence(sequence):
# def reverse(iterable):
# def flatten(iterable_of_iterables):
# def squash(nested_iterables):
# def round_robin(*iterables):
# def merge_unique(iterables, sort=False):
# def merge_dicts(*args):
# def in_add(x, s):
# def implies(a, b):
. Output only the next line. | if isinstance(o, Action) and (level == 0)] |
Predict the next line after this snippet: <|code_start|>def get_layers(costs):
num_layers = max(pair.level for pair in costs.values()) + 1
layers = [[] for _ in range(num_layers)]
for value, (_, level) in costs.items():
layers[level].append(value)
return layers
# def print_rpg(literal_layers, operator_layers):
# for level in range(len(literal_layers)):
# print('Level', level)
# if level != 0:
# print('Operators', str_iterable(operator_layers[level-1]))
# print('Literals', str_iterable(literal_layers[level]), '\n')
def extract_relaxed_plan(goal, literal_costs, operator_costs):
#literal_layers = get_layers(literal_costs)
operator_layers = get_layers(operator_costs)
#print_rpg(literal_layers, operator_layers)
num_goal_layers = operator_costs[goal].level + 1
goals = [set() for _ in range(num_goal_layers)]
plan = [set() for _ in range(num_goal_layers - 1)]
marked = [set() for _ in range(num_goal_layers)]
for literal in goal.conditions:
goals[literal_costs[literal].level].add(literal)
for level in reversed(range(1, num_goal_layers)):
for literal in goals[level]:
if literal in marked[level]:
continue
<|code_end|>
using the current file's imports:
from strips.hsp import compute_costs
from strips.operators import Action
from misc.functions import argmin, flatten, INF
and any relevant context from other files:
# Path: strips/hsp.py
# def compute_costs(state, goal, operators, op=max, unit=False):
# unprocessed = defaultdict(list) # TODO: store this in memory
# unsatisfied = {}
# for operator in operators + [goal]:
# unsatisfied[operator] = len(operator.conditions)
# for literal in operator.conditions:
# unprocessed[literal].append(operator)
#
# literal_costs = {literal: Pair(0, 0) for literal in unprocessed if literal in state}
# operator_costs = {}
# queue = [(pair.cost, literal) for literal, pair in literal_costs.items()]
#
# def process_operator(operator):
# operator_cost = operator_level = 0
# if len(operator.conditions) != 0:
# operator_cost = op(literal_costs[literal].cost for literal in operator.conditions)
# operator_level = max(literal_costs[literal].level for literal in operator.conditions)
# operator_costs[operator] = Pair(operator_cost, operator_level)
# if operator == goal:
# # TODO: terminate earlier if the goal is achieved
# return True
# literal_cost = operator_cost + (operator.cost if not unit else 1)
# literal_level = operator_level + 1
# # literal_level = operator_level + (1 if not operator.is_axiom() else 0)
# for effect in operator.effects:
# # Only computes costs for relevant operators
# if (effect in unprocessed) and (effect not in literal_costs or
# (literal_cost < literal_costs[effect].cost)):
# literal_costs[effect] = Pair(literal_cost, literal_level)
# heappush(queue, (literal_cost, effect))
# return False
#
# for operator in unsatisfied:
# if unsatisfied[operator] == 0:
# process_operator(operator)
# while queue:
# _, literal = heappop(queue)
# if literal not in unprocessed:
# continue
# for operator in unprocessed[literal]:
# unsatisfied[operator] -= 1
# if unsatisfied[operator] == 0:
# process_operator(operator)
# del unprocessed[literal]
#
# return literal_costs, operator_costs
#
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# def irange(start, stop=None, step=1): #np.arange
# def erange(start, stop=None, step=1):
# def some(function, iterable):
# def every(function, iterable):
# def first(function, iterable):
# def argmax(function, sequence):
# def argmin(function, sequence):
# def pop_max(function, array):
# def pop_min(function, array):
# def safe_remove(sequence, item):
# def safe_function(function, sequence, default):
# def safe_choice(sequence, default=None):
# def safe_max(sequence, default=-INF):
# def safe_min(sequence, default=INF):
# def safe_maxmin(iterable_of_iterables):
# def safe_minmax(iterable_of_iterables):
# def safe_index(sequence, value, default=-1):
# def pairs(lst):
# def randomize(sequence):
# def random_sequence(sequence):
# def reverse(iterable):
# def flatten(iterable_of_iterables):
# def squash(nested_iterables):
# def round_robin(*iterables):
# def merge_unique(iterables, sort=False):
# def merge_dicts(*args):
# def in_add(x, s):
# def implies(a, b):
. Output only the next line. | easiest_operator = argmin(lambda o: operator_costs[o].cost, |
Given the code snippet: <|code_start|> num_goal_layers = operator_costs[goal].level + 1
goals = [set() for _ in range(num_goal_layers)]
plan = [set() for _ in range(num_goal_layers - 1)]
marked = [set() for _ in range(num_goal_layers)]
for literal in goal.conditions:
goals[literal_costs[literal].level].add(literal)
for level in reversed(range(1, num_goal_layers)):
for literal in goals[level]:
if literal in marked[level]:
continue
easiest_operator = argmin(lambda o: operator_costs[o].cost,
(o for o in operator_layers[level-1] if literal in o.effects))
#easiest_operator = argmin(lambda o: operator_costs[o].cost,
# (o for o, p in operator_costs.items() if p.level < level and literal in o.effects))
plan[level-1].add(easiest_operator)
for condition in easiest_operator.conditions:
goals[literal_costs[condition].level].add(condition)
for effect in easiest_operator.effects:
marked[level].add(effect)
marked[level-1].add(effect)
return plan, goals
###########################################################################
def plan_cost(relaxed_plan, unit=False):
if relaxed_plan is None:
return INF
return sum(operator.cost if not unit else 1
<|code_end|>
, generate the next line using the imports in this file:
from strips.hsp import compute_costs
from strips.operators import Action
from misc.functions import argmin, flatten, INF
and context (functions, classes, or occasionally code) from other files:
# Path: strips/hsp.py
# def compute_costs(state, goal, operators, op=max, unit=False):
# unprocessed = defaultdict(list) # TODO: store this in memory
# unsatisfied = {}
# for operator in operators + [goal]:
# unsatisfied[operator] = len(operator.conditions)
# for literal in operator.conditions:
# unprocessed[literal].append(operator)
#
# literal_costs = {literal: Pair(0, 0) for literal in unprocessed if literal in state}
# operator_costs = {}
# queue = [(pair.cost, literal) for literal, pair in literal_costs.items()]
#
# def process_operator(operator):
# operator_cost = operator_level = 0
# if len(operator.conditions) != 0:
# operator_cost = op(literal_costs[literal].cost for literal in operator.conditions)
# operator_level = max(literal_costs[literal].level for literal in operator.conditions)
# operator_costs[operator] = Pair(operator_cost, operator_level)
# if operator == goal:
# # TODO: terminate earlier if the goal is achieved
# return True
# literal_cost = operator_cost + (operator.cost if not unit else 1)
# literal_level = operator_level + 1
# # literal_level = operator_level + (1 if not operator.is_axiom() else 0)
# for effect in operator.effects:
# # Only computes costs for relevant operators
# if (effect in unprocessed) and (effect not in literal_costs or
# (literal_cost < literal_costs[effect].cost)):
# literal_costs[effect] = Pair(literal_cost, literal_level)
# heappush(queue, (literal_cost, effect))
# return False
#
# for operator in unsatisfied:
# if unsatisfied[operator] == 0:
# process_operator(operator)
# while queue:
# _, literal = heappop(queue)
# if literal not in unprocessed:
# continue
# for operator in unprocessed[literal]:
# unsatisfied[operator] -= 1
# if unsatisfied[operator] == 0:
# process_operator(operator)
# del unprocessed[literal]
#
# return literal_costs, operator_costs
#
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# def irange(start, stop=None, step=1): #np.arange
# def erange(start, stop=None, step=1):
# def some(function, iterable):
# def every(function, iterable):
# def first(function, iterable):
# def argmax(function, sequence):
# def argmin(function, sequence):
# def pop_max(function, array):
# def pop_min(function, array):
# def safe_remove(sequence, item):
# def safe_function(function, sequence, default):
# def safe_choice(sequence, default=None):
# def safe_max(sequence, default=-INF):
# def safe_min(sequence, default=INF):
# def safe_maxmin(iterable_of_iterables):
# def safe_minmax(iterable_of_iterables):
# def safe_index(sequence, value, default=-1):
# def pairs(lst):
# def randomize(sequence):
# def random_sequence(sequence):
# def reverse(iterable):
# def flatten(iterable_of_iterables):
# def squash(nested_iterables):
# def round_robin(*iterables):
# def merge_unique(iterables, sort=False):
# def merge_dicts(*args):
# def in_add(x, s):
# def implies(a, b):
. Output only the next line. | for operator in flatten(relaxed_plan)) |
Predict the next line for this snippet: <|code_start|> operator_layers = get_layers(operator_costs)
#print_rpg(literal_layers, operator_layers)
num_goal_layers = operator_costs[goal].level + 1
goals = [set() for _ in range(num_goal_layers)]
plan = [set() for _ in range(num_goal_layers - 1)]
marked = [set() for _ in range(num_goal_layers)]
for literal in goal.conditions:
goals[literal_costs[literal].level].add(literal)
for level in reversed(range(1, num_goal_layers)):
for literal in goals[level]:
if literal in marked[level]:
continue
easiest_operator = argmin(lambda o: operator_costs[o].cost,
(o for o in operator_layers[level-1] if literal in o.effects))
#easiest_operator = argmin(lambda o: operator_costs[o].cost,
# (o for o, p in operator_costs.items() if p.level < level and literal in o.effects))
plan[level-1].add(easiest_operator)
for condition in easiest_operator.conditions:
goals[literal_costs[condition].level].add(condition)
for effect in easiest_operator.effects:
marked[level].add(effect)
marked[level-1].add(effect)
return plan, goals
###########################################################################
def plan_cost(relaxed_plan, unit=False):
if relaxed_plan is None:
<|code_end|>
with the help of current file imports:
from strips.hsp import compute_costs
from strips.operators import Action
from misc.functions import argmin, flatten, INF
and context from other files:
# Path: strips/hsp.py
# def compute_costs(state, goal, operators, op=max, unit=False):
# unprocessed = defaultdict(list) # TODO: store this in memory
# unsatisfied = {}
# for operator in operators + [goal]:
# unsatisfied[operator] = len(operator.conditions)
# for literal in operator.conditions:
# unprocessed[literal].append(operator)
#
# literal_costs = {literal: Pair(0, 0) for literal in unprocessed if literal in state}
# operator_costs = {}
# queue = [(pair.cost, literal) for literal, pair in literal_costs.items()]
#
# def process_operator(operator):
# operator_cost = operator_level = 0
# if len(operator.conditions) != 0:
# operator_cost = op(literal_costs[literal].cost for literal in operator.conditions)
# operator_level = max(literal_costs[literal].level for literal in operator.conditions)
# operator_costs[operator] = Pair(operator_cost, operator_level)
# if operator == goal:
# # TODO: terminate earlier if the goal is achieved
# return True
# literal_cost = operator_cost + (operator.cost if not unit else 1)
# literal_level = operator_level + 1
# # literal_level = operator_level + (1 if not operator.is_axiom() else 0)
# for effect in operator.effects:
# # Only computes costs for relevant operators
# if (effect in unprocessed) and (effect not in literal_costs or
# (literal_cost < literal_costs[effect].cost)):
# literal_costs[effect] = Pair(literal_cost, literal_level)
# heappush(queue, (literal_cost, effect))
# return False
#
# for operator in unsatisfied:
# if unsatisfied[operator] == 0:
# process_operator(operator)
# while queue:
# _, literal = heappop(queue)
# if literal not in unprocessed:
# continue
# for operator in unprocessed[literal]:
# unsatisfied[operator] -= 1
# if unsatisfied[operator] == 0:
# process_operator(operator)
# del unprocessed[literal]
#
# return literal_costs, operator_costs
#
# Path: strips/operators.py
# class Action(Operator):
# cost = 1 # TODO: cost function
#
# Path: misc/functions.py
# def elapsed_time(start_time):
# def irange(start, stop=None, step=1): #np.arange
# def erange(start, stop=None, step=1):
# def some(function, iterable):
# def every(function, iterable):
# def first(function, iterable):
# def argmax(function, sequence):
# def argmin(function, sequence):
# def pop_max(function, array):
# def pop_min(function, array):
# def safe_remove(sequence, item):
# def safe_function(function, sequence, default):
# def safe_choice(sequence, default=None):
# def safe_max(sequence, default=-INF):
# def safe_min(sequence, default=INF):
# def safe_maxmin(iterable_of_iterables):
# def safe_minmax(iterable_of_iterables):
# def safe_index(sequence, value, default=-1):
# def pairs(lst):
# def randomize(sequence):
# def random_sequence(sequence):
# def reverse(iterable):
# def flatten(iterable_of_iterables):
# def squash(nested_iterables):
# def round_robin(*iterables):
# def merge_unique(iterables, sort=False):
# def merge_dicts(*args):
# def in_add(x, s):
# def implies(a, b):
, which may contain function names, class names, or code. Output only the next line. | return INF |
Next line prediction: <|code_start|>def write_actions(actions):
s = '%s\n'%len(actions)
for action in actions:
s += '\n' + write_action(action)
return s
###########################################################################
def write_axiom(axiom):
s = 'begin_rule\n'
s += '%s\n'%len(axiom.pre)
for var, val in axiom.pre:
s += '%s %s\n'%(var, val)
var_con = -1 # Indicates no value
s += ' %s %s %s\n'%(axiom.var, var_con, axiom.val)
s += 'end_rule'
return s
def write_axioms(axioms):
s = '%s\n'%len(axioms)
for axiom in axioms:
s += '\n' + write_axiom(axiom)
return s
###########################################################################
PATH = 'output.sas'
def write_file(problem):
<|code_end|>
. Use current file imports:
(from misc.io import write)
and context including class names, function names, or small code snippets from other files:
# Path: misc/io.py
# def write(filename, string):
# with open(filename, 'w') as f:
# f.write(string)
. Output only the next line. | write(PATH, problem) |
Here is a snippet: <|code_start|>
def semideferred_best_first_search(start, goal, generator, priority, stack, max_time, max_iterations,
max_generations, max_cost, max_length, debug):
# TODO: variants that don't add states to the search queue until parent revisited
state_space = StateSpace(generator, start, 1, max_generations, max_cost, max_length)
sv = state_space.root
if sv.contained(goal):
return state_space.plan(sv), state_space
queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, sv)])
<|code_end|>
. Write the next line using the current file imports:
from misc.functions import elapsed_time, first
from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue
from planner.state_space import StateSpace
and context from other files:
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def first(function, iterable):
# for item in iterable:
# if function(item):
# return item
# return None
#
# Path: misc/priority_queue.py
# class FILOPriorityQueue(PriorityQueue):
# sign = -1
#
# class FIFOPriorityQueue(PriorityQueue):
# sign = 1
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
, which may include functions, classes, or code. Output only the next line. | while not queue.empty() and (elapsed_time(state_space.start_time) < max_time) \ |
Here is a snippet: <|code_start|>
def semideferred_best_first_search(start, goal, generator, priority, stack, max_time, max_iterations,
max_generations, max_cost, max_length, debug):
# TODO: variants that don't add states to the search queue until parent revisited
state_space = StateSpace(generator, start, 1, max_generations, max_cost, max_length)
sv = state_space.root
if sv.contained(goal):
return state_space.plan(sv), state_space
queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, sv)])
while not queue.empty() and (elapsed_time(state_space.start_time) < max_time) \
and (state_space.iterations < max_iterations):
cv = queue.pop()
if not cv.has_unexplored() and not cv.generate():
continue
state_space.iterations += 1
if debug is not None:
debug(cv)
successors = list(cv.unexplored()) + [cv]
<|code_end|>
. Write the next line using the current file imports:
from misc.functions import elapsed_time, first
from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue
from planner.state_space import StateSpace
and context from other files:
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def first(function, iterable):
# for item in iterable:
# if function(item):
# return item
# return None
#
# Path: misc/priority_queue.py
# class FILOPriorityQueue(PriorityQueue):
# sign = -1
#
# class FIFOPriorityQueue(PriorityQueue):
# sign = 1
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
, which may include functions, classes, or code. Output only the next line. | gv = first(lambda v: v.contained(goal), successors[:-1]) |
Here is a snippet: <|code_start|>
def semideferred_best_first_search(start, goal, generator, priority, stack, max_time, max_iterations,
max_generations, max_cost, max_length, debug):
# TODO: variants that don't add states to the search queue until parent revisited
state_space = StateSpace(generator, start, 1, max_generations, max_cost, max_length)
sv = state_space.root
if sv.contained(goal):
return state_space.plan(sv), state_space
<|code_end|>
. Write the next line using the current file imports:
from misc.functions import elapsed_time, first
from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue
from planner.state_space import StateSpace
and context from other files:
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def first(function, iterable):
# for item in iterable:
# if function(item):
# return item
# return None
#
# Path: misc/priority_queue.py
# class FILOPriorityQueue(PriorityQueue):
# sign = -1
#
# class FIFOPriorityQueue(PriorityQueue):
# sign = 1
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
, which may include functions, classes, or code. Output only the next line. | queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, sv)]) |
Based on the snippet: <|code_start|>
def semideferred_best_first_search(start, goal, generator, priority, stack, max_time, max_iterations,
max_generations, max_cost, max_length, debug):
# TODO: variants that don't add states to the search queue until parent revisited
state_space = StateSpace(generator, start, 1, max_generations, max_cost, max_length)
sv = state_space.root
if sv.contained(goal):
return state_space.plan(sv), state_space
<|code_end|>
, predict the immediate next line with the help of imports:
from misc.functions import elapsed_time, first
from misc.priority_queue import FILOPriorityQueue, FIFOPriorityQueue
from planner.state_space import StateSpace
and context (classes, functions, sometimes code) from other files:
# Path: misc/functions.py
# def elapsed_time(start_time):
# return time.time() - start_time
#
# def first(function, iterable):
# for item in iterable:
# if function(item):
# return item
# return None
#
# Path: misc/priority_queue.py
# class FILOPriorityQueue(PriorityQueue):
# sign = -1
#
# class FIFOPriorityQueue(PriorityQueue):
# sign = 1
#
# Path: planner/state_space.py
# class StateSpace(object):
# def __init__(self, generator_fn, start, max_extensions=INF, max_generations=INF, max_cost=INF, max_length=INF,
# max_time=INF, max_iterations=INF, verbose=True, dump_rate=1.): # 0 | 1 | INF
# # TODO: move queue here?
# self.start_time = time.time()
# self.iterations = 0
# self.num_expanded = 0
# self.num_generations = 0
# self.vertices = {}
# self.edges = [] # NOTE - allowing parallel-edges
# #self.solutions = []
# if isinstance(generator_fn, tuple): # TODO - fix this by making the operators a direct argument
# self.generator_fn, self.axioms = generator_fn
# else:
# self.generator_fn, self.axioms = generator_fn, []
# # TODO: could check whether these are violated generically
# self.max_extensions = max_extensions
# self.max_generations = max_generations
# self.max_cost = max_cost
# self.max_length = max_length
# self.max_time = max_time
# self.max_iterations = max_iterations
# self.verbose = verbose
# self.dump_rate = dump_rate
# self.last_dump = time.time()
# self.root = self[start]
# self.root.cost = 0
# self.root.length = 0
# self.root.extensions += 1
# self.best_h = None # None | INF
# def has_state(self, state):
# return state in self.vertices
# __contains__ = has_state
# def get_state(self, state):
# if state not in self:
# self.vertices[state] = Vertex(state, self)
# return self.vertices[state]
# __getitem__ = get_state
# def __iter__(self):
# return iter(self.vertices.values())
# def __len__(self):
# return len(self.vertices)
# def new_iteration(self, vertex):
# self.iterations += 1
# if elapsed_time(self.last_dump) >= self.dump_rate:
# self.dump()
# # TODO: record dead ends here
# #return vertex.is_dead_end() # TODO: might not have called h_cost
# def is_active(self):
# return (elapsed_time(self.start_time) < self.max_time) or (self.iterations < self.max_iterations)
# def extend(self, vertex, operator):
# if (vertex.cost + operator.cost <= self.max_cost) \
# and (vertex.length + len(operator) <= self.max_length) \
# and vertex.contained(operator):
# #if vertex.state in operator:
# if self.axioms:
# assert not isinstance(operator, MacroOperator)
# sink_state = operator.apply(vertex.state) # TODO - this won't work for MacroOperators yet?
# else:
# sink_state = operator(vertex.state)[-1] if isinstance(operator, MacroOperator) else operator(vertex.state)
# if (sink_state is not None) and (self[sink_state].extensions < self.max_extensions):
# sink_vertex = self[sink_state]
# self.edges.append(Edge(vertex, sink_vertex, operator, self))
# sink_vertex.extensions += 1
# return sink_vertex
# return None
# def retrace(self, vertex):
# if vertex is not None:
# if vertex == self.root:
# return []
# sequence = self.retrace(vertex.parent_edge.source)
# if sequence is not None:
# return sequence + list(vertex.parent_edge.operator)
# return None
# def plan(self, vertex):
# sequence = self.retrace(vertex)
# if sequence is None:
# return None
# return Plan(self.root.state, sequence)
# def solution(self, vertex):
# #self.dump()
# return Solution(self.plan(vertex), self)
# def failure(self):
# self.dump()
# return Solution(None, self)
# def time_elapsed(self):
# return elapsed_time(self.start_time)
# def __repr__(self):
# # TODO: deadends, backtracking, expanded/generated until last jump, etc.
# return 'Iterations: {iterations} | State Space: {state_space} | Expanded: {expanded} | ' \
# 'Generations: {generations} | Heuristic: {heuristic} | Time: {time:.3f}'.format(
# iterations=self.iterations, state_space=len(self), expanded=self.num_expanded,
# generations=self.num_generations, heuristic=self.best_h, time=self.time_elapsed())
# def dump(self):
# if not self.verbose:
# return
# self.last_dump = time.time()
# print(self)
# # TODO: record iterations since last heuristic
. Output only the next line. | queue = (FILOPriorityQueue if stack else FIFOPriorityQueue)([(None, sv)]) |
Based on the snippet: <|code_start|> def set_inactive(self):
if not self.active: return
self.active = False
for source_vertex, edge in self.sources:
edge.update_inactive()
if source_vertex is not None:
source_vertex.update_inactive()
def update_inactive(self): # TODO - this is really slow. Only search if not greedy and reached?
if not self.active: return
self.active = False # Temporarily set to inactive
for connector in self.connectors:
connector.update_inactive()
if connector.active:
self.active = True
return
for sink_vertex, _ in self.sinks:
sink_vertex.update_inactive()
if sink_vertex.active:
self.active = True
return
# Cannot find active parent node
self.set_inactive()
def __str__(self):
return 'V(' + str(self.substate) + ')'
__repr__ = __str__
def node_str(self):
<|code_end|>
, predict the immediate next line with the help of imports:
from .utils import *
from planner.states import State
from misc.objects import str_object
and context (classes, functions, sometimes code) from other files:
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | if isinstance(self.substate, State): |
Given the code snippet: <|code_start|>
self.active = False
for source_vertex, edge in self.sources:
edge.update_inactive()
if source_vertex is not None:
source_vertex.update_inactive()
def update_inactive(self): # TODO - this is really slow. Only search if not greedy and reached?
if not self.active: return
self.active = False # Temporarily set to inactive
for connector in self.connectors:
connector.update_inactive()
if connector.active:
self.active = True
return
for sink_vertex, _ in self.sinks:
sink_vertex.update_inactive()
if sink_vertex.active:
self.active = True
return
# Cannot find active parent node
self.set_inactive()
def __str__(self):
return 'V(' + str(self.substate) + ')'
__repr__ = __str__
def node_str(self):
if isinstance(self.substate, State):
return self.substate.__class__.__name__
<|code_end|>
, generate the next line using the imports in this file:
from .utils import *
from planner.states import State
from misc.objects import str_object
and context (functions, classes, or occasionally code) from other files:
# Path: planner/states.py
# class State(Substate):
# def __init__(self, values):
# super(self.__class__, self).__init__({var: value for var, value in values.items() if value is not False})
# def __getitem__(self, var):
# if var not in self.__dict__[HASH_DICT]: return False
# return self.__dict__[HASH_DICT][var]
# def substate(self, variables):
# return Substate({var: self[var] for var in variables})
# def __call__(self, variables):
# return self.substate(variables)
#
# Path: misc/objects.py
# def str_object(obj):
# if type(obj) in (list, np.ndarray):
# return '[%s]' % ', '.join(str_object(item) for item in obj)
# if type(obj) == tuple:
# return '(%s)' % ', '.join(str_object(item) for item in obj)
# if type(obj) == dict:
# return '{%s}' % ', '.join(str_object(item) + ': ' + str_object(obj[item])
# for item in sorted(obj.keys(), key=lambda k: str_object(k)))
# if type(obj) in (set, frozenset):
# return '{%s}' % ', '.join(sorted(str_object(item) for item in obj))
# if type(obj) in (float, np.float64):
# obj = round(obj, 3)
# if obj == 0:
# obj = 0 # NOTE - catches -0.0 bug
# return '%.3f'%obj
# if isinstance(obj, types.FunctionType):
# return obj.__name__
# return str(obj)
. Output only the next line. | return '\n'.join([str_object(variable) + '=' + str_object(value) for variable, value in self.substate]) |
Using the snippet: <|code_start|>
class GoalConditions(PartialState):
def __init__(self, conditions): # Difference is that this is a list
self.conditions = conditions
def cond(self):
return self.conditions
#def __contains__(self, state):
# return all(state[var] == value for var, value in self.cond())
class UniqueOperator(object):
next_index = 0
def __init__(self, action):
self.action = action
self.index = UniqueOperator.next_index
UniqueOperator.next_index += 1
def __repr__(self):
return str(self.action) + '#' + str(self.index)
#def effects(action):
# if isinstance(action, Operator):
# return action.effects
# if isinstance(action, State):
# return action.values # TODO - should include default false values
# if isinstance(action, Goal):
# return {}
# raise ValueError(action)
def achieves(operator, item):
(var, val) = item
<|code_end|>
, determine the next line of code. You have imports:
import random
from .operators import Operator
from .states import State, Goal, PartialState
from heapq import heappop, heappush
from collections import deque
from .hsp import h_add, h_max
and context (class names, function names, or code) available:
# Path: sas/operators.py
# class Operator(PartialState):
# def __init__(self, args):
# for k, v in args.items():
# setattr(self, k, v)
# self.args = args # TODO - use FrozenDict instead
# self._frozen_args = frozenset(args.items())
# self._hash = None
# self.conditions = None
# self.effects = None
# self.test = lambda state: True
# def eff(self):
# return self.effects.items()
# def apply(self, state):
# return State(merge_dicts(state.values, self.effects))
# def __call__(self, state):
# if state not in self:
# return None
# return self.apply(state)
# def __iter__(self):
# yield self
# def __len__(self):
# return 1
# def __eq__(self, other):
# return (type(self) == type(other)) and (self._frozen_args == other._frozen_args)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# if self._hash is None:
# self._hash = hash((self.__class__, self._frozen_args))
# return self._hash
# def __str__(self):
# return self.__class__.__name__ + str_object(self.args)
# __repr__ = __str__
#
# Path: sas/states.py
# class State(object):
# def __init__(self, values):
# self.values = {var: value for var, value in values.items() if value is not False}
# def __getitem__(self, var):
# if var not in self.values: return False
# return self.values[var]
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.values == other.values)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.values.items())))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.values)
# __repr__ = __str__
#
# class Goal(PartialState): # TODO: unify PartialState and Goal
# def __init__(self, values, test=lambda state: True):
# self.conditions = values
# self.test = test
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.cond())))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
#
# class PartialState(object):
# def cond(self):
# return self.conditions.items()
# def __contains__(self, state):
# return all(state[var] == value for var, value in self.cond()) #and self.test(state)
#
# Path: sas/hsp.py
# def h_add(state, goal, operators):
# _, operator_costs = compute_costs(state, goal, operators, op=sum)
# return operator_costs[goal].cost if goal in operator_costs else None
#
# def h_max(state, goal, operators):
# _, operator_costs = compute_costs(state, goal, operators, op=max)
# return operator_costs[goal].cost if goal in operator_costs else None
. Output only the next line. | if isinstance(operator, Operator): |
Here is a snippet: <|code_start|> self.conditions = conditions
def cond(self):
return self.conditions
#def __contains__(self, state):
# return all(state[var] == value for var, value in self.cond())
class UniqueOperator(object):
next_index = 0
def __init__(self, action):
self.action = action
self.index = UniqueOperator.next_index
UniqueOperator.next_index += 1
def __repr__(self):
return str(self.action) + '#' + str(self.index)
#def effects(action):
# if isinstance(action, Operator):
# return action.effects
# if isinstance(action, State):
# return action.values # TODO - should include default false values
# if isinstance(action, Goal):
# return {}
# raise ValueError(action)
def achieves(operator, item):
(var, val) = item
if isinstance(operator, Operator):
return var in operator.effects and operator.effects[var] == val
if isinstance(operator, UniqueOperator):
return var in operator.action.effects and operator.action.effects[var] == val
<|code_end|>
. Write the next line using the current file imports:
import random
from .operators import Operator
from .states import State, Goal, PartialState
from heapq import heappop, heappush
from collections import deque
from .hsp import h_add, h_max
and context from other files:
# Path: sas/operators.py
# class Operator(PartialState):
# def __init__(self, args):
# for k, v in args.items():
# setattr(self, k, v)
# self.args = args # TODO - use FrozenDict instead
# self._frozen_args = frozenset(args.items())
# self._hash = None
# self.conditions = None
# self.effects = None
# self.test = lambda state: True
# def eff(self):
# return self.effects.items()
# def apply(self, state):
# return State(merge_dicts(state.values, self.effects))
# def __call__(self, state):
# if state not in self:
# return None
# return self.apply(state)
# def __iter__(self):
# yield self
# def __len__(self):
# return 1
# def __eq__(self, other):
# return (type(self) == type(other)) and (self._frozen_args == other._frozen_args)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# if self._hash is None:
# self._hash = hash((self.__class__, self._frozen_args))
# return self._hash
# def __str__(self):
# return self.__class__.__name__ + str_object(self.args)
# __repr__ = __str__
#
# Path: sas/states.py
# class State(object):
# def __init__(self, values):
# self.values = {var: value for var, value in values.items() if value is not False}
# def __getitem__(self, var):
# if var not in self.values: return False
# return self.values[var]
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.values == other.values)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.values.items())))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.values)
# __repr__ = __str__
#
# class Goal(PartialState): # TODO: unify PartialState and Goal
# def __init__(self, values, test=lambda state: True):
# self.conditions = values
# self.test = test
# def __eq__(self, other):
# return (type(self) == type(other)) and (self.conditions == other.conditions)
# def __ne__(self, other):
# return not self == other
# def __hash__(self):
# return hash((self.__class__, frozenset(self.cond())))
# def __str__(self):
# return self.__class__.__name__ + str_object(self.conditions)
# __repr__ = __str__
#
# class PartialState(object):
# def cond(self):
# return self.conditions.items()
# def __contains__(self, state):
# return all(state[var] == value for var, value in self.cond()) #and self.test(state)
#
# Path: sas/hsp.py
# def h_add(state, goal, operators):
# _, operator_costs = compute_costs(state, goal, operators, op=sum)
# return operator_costs[goal].cost if goal in operator_costs else None
#
# def h_max(state, goal, operators):
# _, operator_costs = compute_costs(state, goal, operators, op=max)
# return operator_costs[goal].cost if goal in operator_costs else None
, which may include functions, classes, or code. Output only the next line. | if isinstance(operator, State): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.