Dataset Viewer
index
int64 0
10k
| blob_id
stringlengths 40
40
| step-1
stringlengths 0
305k
| step-2
stringlengths 6
1.1M
⌀ | step-3
stringlengths 15
1.23M
⌀ | step-4
stringlengths 23
1.34M
⌀ | step-5
stringlengths 55
1.2M
⌀ | step-ids
sequencelengths 1
5
|
---|---|---|---|---|---|---|---|
0 | aff1a9263e183610f403a4d6a7f27b45eacb7ff2 | <mask token>
| <mask token>
print(name * 1000)
| name = 'valentina '
print(name * 1000)
| name='valentina '
print(name*1000)
| null | [
0,
1,
2,
3
] |
1 | eabf06481509962652812af67ad59da5cfe30fae | <mask token>
| <mask token>
__all__ = ('__title__', '__summary__', '__version__', '__author__',
'__license__', '__copyright__')
__title__ = 'mupub'
__summary__ = 'Musical score publishing utility for the Mutopia Project'
<mask token>
__version__ = '1.0.8'
__author__ = 'Glen Larsen, Chris Sawer'
__author_email__ = '[email protected]'
__uri__ = 'http://mutopiaproject.org/'
__license__ = 'MIT'
__copyright__ = 'Copyright 2018 The Mutopia Project'
<mask token>
| <mask token>
__all__ = ('__title__', '__summary__', '__version__', '__author__',
'__license__', '__copyright__')
__title__ = 'mupub'
__summary__ = 'Musical score publishing utility for the Mutopia Project'
<mask token>
__version__ = '1.0.8'
__author__ = 'Glen Larsen, Chris Sawer'
__author_email__ = '[email protected]'
__uri__ = 'http://mutopiaproject.org/'
__license__ = 'MIT'
__copyright__ = 'Copyright 2018 The Mutopia Project'
from .assets import collect_assets
from .commands.build import build
from .commands.check import check
from .commands.init import init
from .commands.tag import tag
from .commands.clean import clean
from .config import CONFIG_DICT, CONFIG_DIR, getDBPath
from .config import test_config, saveConfig
from .core import MUTOPIA_BASE, FTP_BASE, URL_BASE
from .core import id_from_footer
from .exceptions import BadConfiguration, IncompleteBuild, TagProcessException
from .header import Loader, LYLoader, VersionLoader
from .header import RawLoader, Header, REQUIRED_FIELDS
from .header import find_header
from .lily import LyLocator, LyVersion
from .validate import Validator, DBValidator, in_repository
from .tagedit import tag_header, tag_file
from .rdfu import NS, MuRDF
from .utils import resolve_input, resolve_lysfile
| """ mupub module.
"""
__all__ = (
'__title__', '__summary__', '__version__',
'__author__', '__license__', '__copyright__',
)
__title__ = 'mupub'
__summary__ = 'Musical score publishing utility for the Mutopia Project'
"""Versioning:
This utility follows a MAJOR . MINOR . EDIT format. Upon a major
release, the MAJOR number is incremented and the MINOR is zeroed.
During development of an upcoming release, the MINOR number may be
incremented.
"""
__version__ = '1.0.8'
__author__ = 'Glen Larsen, Chris Sawer'
__author_email__= '[email protected]'
__uri__ = 'http://mutopiaproject.org/'
__license__ = 'MIT'
__copyright__ = 'Copyright 2018 The Mutopia Project'
from .assets import collect_assets
from .commands.build import build
from .commands.check import check
from .commands.init import init
from .commands.tag import tag
from .commands.clean import clean
from .config import CONFIG_DICT, CONFIG_DIR, getDBPath
from .config import test_config, saveConfig
from .core import MUTOPIA_BASE, FTP_BASE, URL_BASE
from .core import id_from_footer
from .exceptions import BadConfiguration, IncompleteBuild, TagProcessException
from .header import Loader, LYLoader, VersionLoader
from .header import RawLoader, Header, REQUIRED_FIELDS
from .header import find_header
from .lily import LyLocator, LyVersion
from .validate import Validator, DBValidator, in_repository
from .tagedit import tag_header, tag_file
from .rdfu import NS, MuRDF
from .utils import resolve_input,resolve_lysfile
| null | [
0,
1,
2,
3
] |
2 | 54f0ed5f705d5ada28721301f297b2b0058773ad | <mask token>
class _GenericBot:
<mask token>
def __init__(self, pos, inventory=None):
"""Initialize with an empty inventory.
inventory is a dictionary. If None, an empty one will be used."""
if inventory is None:
self._inventory = {}
else:
self._inventory = deepcopy(inventory)
self._pos = deepcopy(pos)
<mask token>
<mask token>
<mask token>
def get_legal_actions(self, block_=None):
"""Return a list of legal actions.
If block_ is None, return all legal actions. Otherwise, return all
legal actions that don't involve placing the block."""
return self._get_move_actions(block_) + self._get_mine_actions(
) + self._get_placement_actions(block_)
<mask token>
<mask token>
def _place(self, loc, exclude=None, block_=None):
"""Place a block from the inventory only.
If exclude is not None, place a block that is not 'exclude'.
If block is not None, place that block only.
"""
if not self._inventory:
raise Exception('Inventory empty')
if block_ is None:
for key in self._inventory:
if key != exclude:
block_ = key
break
else:
raise Exception(
'You requested not to place %s, but it is the only block in the inventory.'
% exclude)
if block_ not in self._inventory:
raise Exception('Block %s is not in the inventory' % block_)
if self._inventory[block_] == 1:
del self._inventory[block_]
else:
self._inventory[block_] -= 1
self._set_block(loc, block_)
<mask token>
<mask token>
<mask token>
<mask token>
def _get_move_actions(self, exclude=None):
"""Return a list of legal movement actions.
exclude is the block to exclude.
"""
rtn = []
can_move_up = self._get_block(self._pos + _Vec3(0, 2, 0)) in {_AIR,
_WATER}
if can_move_up:
if self._surrounded():
rtn.append({'func': '_move', 'args': (self._pos + _Vec3(0,
1, 0),)})
else:
rtn.append({'func': '_move_up', 'args': (exclude,)})
hidden_block = self._get_block(self._pos + _Vec3(0, -2, 0))
if hidden_block == _WATER or hidden_block not in {_AIR, _LAVA}:
rtn.append({'func': '_move_down'})
for dir_ in _adj_dirs():
rtn.extend(self._side_moves(dir_, can_move_up))
return rtn
def _side_moves(self, dir_, can_move_up):
"""Return the list of side moves.
dir_ is an adjacent direction.
can_move_up is a boolean for whether or not the bot can move up.
"""
rtn = []
base_pos = self._pos + dir_
base_block = self._get_block(base_pos)
empty_blocks = {_AIR, _WATER}
if can_move_up and base_block not in {_AIR, _LAVA, _WATER}:
for vert_dir in [_Vec3(0, 1, 0), _Vec3(0, 2, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
rtn.append({'func': '_move', 'args': (base_pos + _Vec3(0, 1,
0),)})
for vert_dir in [_Vec3(), _Vec3(0, 1, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
pos = base_pos + _Vec3(0, -1, 0)
for _ in xrange(_DROP_PLUS_1):
block_ = self._get_block(pos)
if block_ != _AIR:
if block_ != _LAVA:
rtn.append({'func': '_move', 'args': (pos + _Vec3(0,
1, 0),)})
break
pos.y -= 1
<mask token>
def _get_mine_actions(self):
"""Return a list of legal mining actions (that only involve mining
and not moving)."""
rtn = []
dont_mine = {_AIR, _WATER, _LAVA}
pos_above = self._pos + _Vec3(0, 2, 0)
if self._get_block(pos_above) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos_above,)})
for dir_ in _adj_dirs():
pos = self._pos + dir_
for _ in xrange(2):
if self._get_block(pos) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos,)})
pos = pos + _Vec3(0, 1, 0)
return rtn
def _get_placement_actions(self, exclude=None):
"""Return a list of legal actions that only involve placing a block
from the inventory.
exclude is a block id. It is the block that should not be placed. If None,
any block can be placed."""
if not self._has_blocks_to_place(exclude=exclude):
return []
dirs = [_Vec3(0, 2, 0)]
for dir_ in _adj_dirs():
dirs.extend([dir_, dir_ + _Vec3(0, 1, 0)])
if self._get_block(self._pos + dir_) in [_AIR, _WATER]:
dirs.append(dir_ + _Vec3(0, -1, 0))
rtn = []
for dir_ in dirs:
pos = self._pos + dir_
if self._can_place(pos):
rtn.append({'func': '_place', 'args': (pos,), 'kwargs': {
'exclude': exclude}})
return rtn
<mask token>
def _has_blocks_to_place(self, exclude=None):
"""Return whether or not the bot can place a block from the
inventory. If exclude is None, any block can be placed."""
for block_ in self._inventory:
if block_ != exclude:
return True
return False
<mask token>
<mask token>
class _ImaginaryBot(_GenericBot):
"""A bot used for finding paths that doesn't actually change blocks
in the world."""
def __init__(self, pos, inventory=None):
"""Create a new bot."""
_GenericBot.__init__(self, pos, inventory)
self._changes = {}
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
self._changes[deepcopy(pos)] = block
def _get_block(self, pos):
"""Get the block at the position."""
if pos in self._changes:
return self._changes[pos]
else:
return _get_mc().getBlock(pos)
def get_block(self, pos):
"""The public version."""
return self._get_block(pos)
def __hash__(self):
"""Return the hash."""
return hash(frozenset([self._pos] + _key_vals(self._inventory) +
_key_vals(self._changes)))
class Bot(_GenericBot):
"""The real bot.
All vector arguments are Vec3s."""
_BOT_BLOCK = block.IRON_BLOCK.id
def __init__(self):
"""Create a bot next to the player."""
pos = _get_mc().player.getTilePos() + Vec3(2, 0, 0)
pos = _Vec3(pos.x, pos.y, pos.z)
_GenericBot.__init__(self, pos)
self._pos = pos
self._move(self._pos)
@staticmethod
def destroy_all():
"""Destroy all bots within a small distance (in case I forget to
destroy one)."""
player_loc = _player_loc()
minec = _get_mc()
rad = 10
for x in xrange(player_loc.x - rad, player_loc.x + rad):
for y in xrange(player_loc.y - rad, player_loc.y + rad):
for z in xrange(player_loc.z - rad, player_loc.z + rad):
if minec.getBlock(x, y, z) == Bot._BOT_BLOCK:
minec.setBlock(x, y, z, _AIR)
def destroy(self):
"""Set itself to air."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
def fetch(self, block_name):
"""Mine and return a block to the player."""
imag_bot = _ImaginaryBot(self._pos, self._inventory)
block_id = getattr(block, block_name).id
block_loc = self._get_block_loc(block_id)
mine_prob = _MineProblem(imag_bot, block_loc, block_id)
mine_actions = astar(mine_prob, _mine_heuristic)
self.take_actions(mine_actions, _DELAY)
imag_bot = _ImaginaryBot(self._pos, self._inventory)
player_loc = _player_loc()
return_prob = _ReturnProblem(imag_bot, block_id, player_loc)
return_actions = astar(return_prob, _return_heuristic)
imag_bot.take_actions(return_actions)
return_actions.append({'func': '_place', 'args': (imag_bot.get_pos(
) + player_loc) / 2, 'kwargs': {'block': block_id}})
self.take_actions(return_actions, _DELAY)
def _get_block_loc(self, block_id):
"""Return the location of the block."""
find_prob = FindProblem(self._pos, block_id)
dirs = bfs(find_prob)
return self._pos + sum(dirs)
def _set_block(self, pos, block_):
"""Place an actual block in the world.
block is a block id."""
_get_mc().setBlock(pos, block_)
def _get_block(self, pos):
"""Get the block at the position."""
return _get_mc().getBlock(pos)
def _move(self, pos):
"""Move there, and set the appropriate blocks."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
self._set_block(pos, self._BOT_BLOCK)
self._set_block(pos + _Vec3(0, 1, 0), self._BOT_BLOCK)
self._pos = pos
class FindProblem(SearchProblem):
"""Problem for finding the location of a block in the world.
A state in this problem is a location.
"""
def __init__(self, start_loc, block_id):
"""Initialize."""
self._start_loc = deepcopy(start_loc)
self._block_id = block_id
def getStartState(self):
"""Return the starting location."""
return self._start_loc
def isGoalState(self, state):
return _get_mc().getBlock(state) == self._block_id
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for dir_ in _all_dirs():
successor = state + dir_
if successor.y <= _get_mc().getHeight(successor.x, successor.z
) and _get_mc().getBlock(successor) != _BEDROCK:
rtn.append((successor, dir_, 1))
return rtn
class _MineProblem(SearchProblem):
"""The problem of finding the block and mining it (not returning
it)."""
def __init__(self, imag_bot, block_loc, block_id):
"""Initialize the problem with an _ImaginaryBot.
block_loc is a Vec3.
"""
self._bot = imag_bot
self._block_loc = deepcopy(block_loc)
self._block_id = block_id
def get_block_loc(self):
"""Return the block location."""
return deepcopy(self._block_loc)
def get_block_id(self):
"""Return the block it's trying to mine."""
return self._block_id
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot has the block."""
return state.contains(self._block_id)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions():
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
class _ReturnProblem(SearchProblem):
"""The problem of returning to the player. This does not place the block
next to the player."""
def __init__(self, imag_bot, block_, player_loc):
"""Initialized the problem with an _ImaginaryBot.
block is a block id."""
self._bot = imag_bot
self._block = block_
self._player_loc = player_loc
def get_player_loc(self):
"""Return the player location."""
return deepcopy(self._player_loc)
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot is next to the player."""
diff = state.get_pos() - self._player_loc
return diff.y == 0 and (diff.x == 0 or diff.z == 0) and abs(diff.x
) + abs(diff.z) == 2 and state.get_block(self._player_loc +
diff / 2 + _Vec3(0, -1, 0)) not in (_AIR, _LAVA, _WATER)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions(self._block):
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
<mask token>
| <mask token>
class _GenericBot:
<mask token>
def __init__(self, pos, inventory=None):
"""Initialize with an empty inventory.
inventory is a dictionary. If None, an empty one will be used."""
if inventory is None:
self._inventory = {}
else:
self._inventory = deepcopy(inventory)
self._pos = deepcopy(pos)
def take_action(self, action):
"""Take the action (acquired from _get_legal_actions)."""
getattr(self, action['func'])(*action.get('args', ()), **action.get
('kwargs', {}))
def take_actions(self, actions, seconds=None):
"""Take these actions. If seconds is not None, sleep 'seconds'
seconds.
"""
if not actions:
return
self.take_action(actions[0])
for action in actions[1:]:
if seconds is not None:
sleep(seconds)
self.take_action(action)
def get_pos(self):
"""Return the position."""
return deepcopy(self._pos)
def get_legal_actions(self, block_=None):
"""Return a list of legal actions.
If block_ is None, return all legal actions. Otherwise, return all
legal actions that don't involve placing the block."""
return self._get_move_actions(block_) + self._get_mine_actions(
) + self._get_placement_actions(block_)
<mask token>
def _get_block(self, pos):
"""Get the block at the position."""
raise NotImplementedError
def _place(self, loc, exclude=None, block_=None):
"""Place a block from the inventory only.
If exclude is not None, place a block that is not 'exclude'.
If block is not None, place that block only.
"""
if not self._inventory:
raise Exception('Inventory empty')
if block_ is None:
for key in self._inventory:
if key != exclude:
block_ = key
break
else:
raise Exception(
'You requested not to place %s, but it is the only block in the inventory.'
% exclude)
if block_ not in self._inventory:
raise Exception('Block %s is not in the inventory' % block_)
if self._inventory[block_] == 1:
del self._inventory[block_]
else:
self._inventory[block_] -= 1
self._set_block(loc, block_)
def _move_down(self):
"""Move and mine the block below."""
new_pos = self._pos + _Vec3(0, -1, 0)
block_ = self._get_block(new_pos)
if block_ != _WATER:
self._add_to_inv(block_)
self._move(new_pos)
<mask token>
<mask token>
def _mine(self, loc):
"""Mine the block."""
block_ = self._get_block(loc)
self._add_to_inv(block_)
self._set_block(loc, _AIR)
def _get_move_actions(self, exclude=None):
"""Return a list of legal movement actions.
exclude is the block to exclude.
"""
rtn = []
can_move_up = self._get_block(self._pos + _Vec3(0, 2, 0)) in {_AIR,
_WATER}
if can_move_up:
if self._surrounded():
rtn.append({'func': '_move', 'args': (self._pos + _Vec3(0,
1, 0),)})
else:
rtn.append({'func': '_move_up', 'args': (exclude,)})
hidden_block = self._get_block(self._pos + _Vec3(0, -2, 0))
if hidden_block == _WATER or hidden_block not in {_AIR, _LAVA}:
rtn.append({'func': '_move_down'})
for dir_ in _adj_dirs():
rtn.extend(self._side_moves(dir_, can_move_up))
return rtn
def _side_moves(self, dir_, can_move_up):
"""Return the list of side moves.
dir_ is an adjacent direction.
can_move_up is a boolean for whether or not the bot can move up.
"""
rtn = []
base_pos = self._pos + dir_
base_block = self._get_block(base_pos)
empty_blocks = {_AIR, _WATER}
if can_move_up and base_block not in {_AIR, _LAVA, _WATER}:
for vert_dir in [_Vec3(0, 1, 0), _Vec3(0, 2, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
rtn.append({'func': '_move', 'args': (base_pos + _Vec3(0, 1,
0),)})
for vert_dir in [_Vec3(), _Vec3(0, 1, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
pos = base_pos + _Vec3(0, -1, 0)
for _ in xrange(_DROP_PLUS_1):
block_ = self._get_block(pos)
if block_ != _AIR:
if block_ != _LAVA:
rtn.append({'func': '_move', 'args': (pos + _Vec3(0,
1, 0),)})
break
pos.y -= 1
<mask token>
def _get_mine_actions(self):
"""Return a list of legal mining actions (that only involve mining
and not moving)."""
rtn = []
dont_mine = {_AIR, _WATER, _LAVA}
pos_above = self._pos + _Vec3(0, 2, 0)
if self._get_block(pos_above) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos_above,)})
for dir_ in _adj_dirs():
pos = self._pos + dir_
for _ in xrange(2):
if self._get_block(pos) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos,)})
pos = pos + _Vec3(0, 1, 0)
return rtn
def _get_placement_actions(self, exclude=None):
"""Return a list of legal actions that only involve placing a block
from the inventory.
exclude is a block id. It is the block that should not be placed. If None,
any block can be placed."""
if not self._has_blocks_to_place(exclude=exclude):
return []
dirs = [_Vec3(0, 2, 0)]
for dir_ in _adj_dirs():
dirs.extend([dir_, dir_ + _Vec3(0, 1, 0)])
if self._get_block(self._pos + dir_) in [_AIR, _WATER]:
dirs.append(dir_ + _Vec3(0, -1, 0))
rtn = []
for dir_ in dirs:
pos = self._pos + dir_
if self._can_place(pos):
rtn.append({'func': '_place', 'args': (pos,), 'kwargs': {
'exclude': exclude}})
return rtn
<mask token>
def _has_blocks_to_place(self, exclude=None):
"""Return whether or not the bot can place a block from the
inventory. If exclude is None, any block can be placed."""
for block_ in self._inventory:
if block_ != exclude:
return True
return False
<mask token>
<mask token>
class _ImaginaryBot(_GenericBot):
"""A bot used for finding paths that doesn't actually change blocks
in the world."""
def __init__(self, pos, inventory=None):
"""Create a new bot."""
_GenericBot.__init__(self, pos, inventory)
self._changes = {}
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
self._changes[deepcopy(pos)] = block
def _get_block(self, pos):
"""Get the block at the position."""
if pos in self._changes:
return self._changes[pos]
else:
return _get_mc().getBlock(pos)
def get_block(self, pos):
"""The public version."""
return self._get_block(pos)
def __hash__(self):
"""Return the hash."""
return hash(frozenset([self._pos] + _key_vals(self._inventory) +
_key_vals(self._changes)))
class Bot(_GenericBot):
"""The real bot.
All vector arguments are Vec3s."""
_BOT_BLOCK = block.IRON_BLOCK.id
def __init__(self):
"""Create a bot next to the player."""
pos = _get_mc().player.getTilePos() + Vec3(2, 0, 0)
pos = _Vec3(pos.x, pos.y, pos.z)
_GenericBot.__init__(self, pos)
self._pos = pos
self._move(self._pos)
@staticmethod
def destroy_all():
"""Destroy all bots within a small distance (in case I forget to
destroy one)."""
player_loc = _player_loc()
minec = _get_mc()
rad = 10
for x in xrange(player_loc.x - rad, player_loc.x + rad):
for y in xrange(player_loc.y - rad, player_loc.y + rad):
for z in xrange(player_loc.z - rad, player_loc.z + rad):
if minec.getBlock(x, y, z) == Bot._BOT_BLOCK:
minec.setBlock(x, y, z, _AIR)
def destroy(self):
"""Set itself to air."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
def fetch(self, block_name):
"""Mine and return a block to the player."""
imag_bot = _ImaginaryBot(self._pos, self._inventory)
block_id = getattr(block, block_name).id
block_loc = self._get_block_loc(block_id)
mine_prob = _MineProblem(imag_bot, block_loc, block_id)
mine_actions = astar(mine_prob, _mine_heuristic)
self.take_actions(mine_actions, _DELAY)
imag_bot = _ImaginaryBot(self._pos, self._inventory)
player_loc = _player_loc()
return_prob = _ReturnProblem(imag_bot, block_id, player_loc)
return_actions = astar(return_prob, _return_heuristic)
imag_bot.take_actions(return_actions)
return_actions.append({'func': '_place', 'args': (imag_bot.get_pos(
) + player_loc) / 2, 'kwargs': {'block': block_id}})
self.take_actions(return_actions, _DELAY)
def _get_block_loc(self, block_id):
"""Return the location of the block."""
find_prob = FindProblem(self._pos, block_id)
dirs = bfs(find_prob)
return self._pos + sum(dirs)
def _set_block(self, pos, block_):
"""Place an actual block in the world.
block is a block id."""
_get_mc().setBlock(pos, block_)
def _get_block(self, pos):
"""Get the block at the position."""
return _get_mc().getBlock(pos)
def _move(self, pos):
"""Move there, and set the appropriate blocks."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
self._set_block(pos, self._BOT_BLOCK)
self._set_block(pos + _Vec3(0, 1, 0), self._BOT_BLOCK)
self._pos = pos
class FindProblem(SearchProblem):
"""Problem for finding the location of a block in the world.
A state in this problem is a location.
"""
def __init__(self, start_loc, block_id):
"""Initialize."""
self._start_loc = deepcopy(start_loc)
self._block_id = block_id
def getStartState(self):
"""Return the starting location."""
return self._start_loc
def isGoalState(self, state):
return _get_mc().getBlock(state) == self._block_id
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for dir_ in _all_dirs():
successor = state + dir_
if successor.y <= _get_mc().getHeight(successor.x, successor.z
) and _get_mc().getBlock(successor) != _BEDROCK:
rtn.append((successor, dir_, 1))
return rtn
class _MineProblem(SearchProblem):
"""The problem of finding the block and mining it (not returning
it)."""
def __init__(self, imag_bot, block_loc, block_id):
"""Initialize the problem with an _ImaginaryBot.
block_loc is a Vec3.
"""
self._bot = imag_bot
self._block_loc = deepcopy(block_loc)
self._block_id = block_id
def get_block_loc(self):
"""Return the block location."""
return deepcopy(self._block_loc)
def get_block_id(self):
"""Return the block it's trying to mine."""
return self._block_id
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot has the block."""
return state.contains(self._block_id)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions():
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
class _ReturnProblem(SearchProblem):
"""The problem of returning to the player. This does not place the block
next to the player."""
def __init__(self, imag_bot, block_, player_loc):
"""Initialized the problem with an _ImaginaryBot.
block is a block id."""
self._bot = imag_bot
self._block = block_
self._player_loc = player_loc
def get_player_loc(self):
"""Return the player location."""
return deepcopy(self._player_loc)
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot is next to the player."""
diff = state.get_pos() - self._player_loc
return diff.y == 0 and (diff.x == 0 or diff.z == 0) and abs(diff.x
) + abs(diff.z) == 2 and state.get_block(self._player_loc +
diff / 2 + _Vec3(0, -1, 0)) not in (_AIR, _LAVA, _WATER)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions(self._block):
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
<mask token>
| <mask token>
class _Vec3(Vec3):
"""A Vec3 that is hashable. Everything in this program should use this
class."""
def __hash__(self):
"""Return the hash."""
return hash((self.x, self.y, self.z))
def clone(self):
"""Return a clone."""
return _Vec3(self.x, self.y, self.z)
class _GenericBot:
"""A generic bot."""
def __init__(self, pos, inventory=None):
"""Initialize with an empty inventory.
inventory is a dictionary. If None, an empty one will be used."""
if inventory is None:
self._inventory = {}
else:
self._inventory = deepcopy(inventory)
self._pos = deepcopy(pos)
def take_action(self, action):
"""Take the action (acquired from _get_legal_actions)."""
getattr(self, action['func'])(*action.get('args', ()), **action.get
('kwargs', {}))
def take_actions(self, actions, seconds=None):
"""Take these actions. If seconds is not None, sleep 'seconds'
seconds.
"""
if not actions:
return
self.take_action(actions[0])
for action in actions[1:]:
if seconds is not None:
sleep(seconds)
self.take_action(action)
def get_pos(self):
"""Return the position."""
return deepcopy(self._pos)
def get_legal_actions(self, block_=None):
"""Return a list of legal actions.
If block_ is None, return all legal actions. Otherwise, return all
legal actions that don't involve placing the block."""
return self._get_move_actions(block_) + self._get_mine_actions(
) + self._get_placement_actions(block_)
def contains(self, block_):
"""Return whether or not the bot contains the block id."""
return block_ in self._inventory
def _get_block(self, pos):
"""Get the block at the position."""
raise NotImplementedError
def _place(self, loc, exclude=None, block_=None):
"""Place a block from the inventory only.
If exclude is not None, place a block that is not 'exclude'.
If block is not None, place that block only.
"""
if not self._inventory:
raise Exception('Inventory empty')
if block_ is None:
for key in self._inventory:
if key != exclude:
block_ = key
break
else:
raise Exception(
'You requested not to place %s, but it is the only block in the inventory.'
% exclude)
if block_ not in self._inventory:
raise Exception('Block %s is not in the inventory' % block_)
if self._inventory[block_] == 1:
del self._inventory[block_]
else:
self._inventory[block_] -= 1
self._set_block(loc, block_)
def _move_down(self):
"""Move and mine the block below."""
new_pos = self._pos + _Vec3(0, -1, 0)
block_ = self._get_block(new_pos)
if block_ != _WATER:
self._add_to_inv(block_)
self._move(new_pos)
def _add_to_inv(self, block_):
"""Add the block to the inventory."""
if block_ in self._inventory:
self._inventory[block_] += 1
else:
self._inventory[block_] = 1
def _move_up(self, exclude=None):
"""Move and place a block below.
If exclude is not None, place a block that is not 'exclude'.
"""
self._move(self._pos + _Vec3(0, 1, 0))
self._place(self._pos + _Vec3(0, -1, 0), exclude)
def _mine(self, loc):
"""Mine the block."""
block_ = self._get_block(loc)
self._add_to_inv(block_)
self._set_block(loc, _AIR)
def _get_move_actions(self, exclude=None):
"""Return a list of legal movement actions.
exclude is the block to exclude.
"""
rtn = []
can_move_up = self._get_block(self._pos + _Vec3(0, 2, 0)) in {_AIR,
_WATER}
if can_move_up:
if self._surrounded():
rtn.append({'func': '_move', 'args': (self._pos + _Vec3(0,
1, 0),)})
else:
rtn.append({'func': '_move_up', 'args': (exclude,)})
hidden_block = self._get_block(self._pos + _Vec3(0, -2, 0))
if hidden_block == _WATER or hidden_block not in {_AIR, _LAVA}:
rtn.append({'func': '_move_down'})
for dir_ in _adj_dirs():
rtn.extend(self._side_moves(dir_, can_move_up))
return rtn
def _side_moves(self, dir_, can_move_up):
"""Return the list of side moves.
dir_ is an adjacent direction.
can_move_up is a boolean for whether or not the bot can move up.
"""
rtn = []
base_pos = self._pos + dir_
base_block = self._get_block(base_pos)
empty_blocks = {_AIR, _WATER}
if can_move_up and base_block not in {_AIR, _LAVA, _WATER}:
for vert_dir in [_Vec3(0, 1, 0), _Vec3(0, 2, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
rtn.append({'func': '_move', 'args': (base_pos + _Vec3(0, 1,
0),)})
for vert_dir in [_Vec3(), _Vec3(0, 1, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
pos = base_pos + _Vec3(0, -1, 0)
for _ in xrange(_DROP_PLUS_1):
block_ = self._get_block(pos)
if block_ != _AIR:
if block_ != _LAVA:
rtn.append({'func': '_move', 'args': (pos + _Vec3(0,
1, 0),)})
break
pos.y -= 1
def _surrounded(self):
"""Return whether or not the bot is surrounded by water."""
for dir_ in _adj_dirs():
if self._get_block(self._pos + dir_) != _WATER:
return False
return True
def _get_mine_actions(self):
"""Return a list of legal mining actions (that only involve mining
and not moving)."""
rtn = []
dont_mine = {_AIR, _WATER, _LAVA}
pos_above = self._pos + _Vec3(0, 2, 0)
if self._get_block(pos_above) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos_above,)})
for dir_ in _adj_dirs():
pos = self._pos + dir_
for _ in xrange(2):
if self._get_block(pos) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos,)})
pos = pos + _Vec3(0, 1, 0)
return rtn
def _get_placement_actions(self, exclude=None):
"""Return a list of legal actions that only involve placing a block
from the inventory.
exclude is a block id. It is the block that should not be placed. If None,
any block can be placed."""
if not self._has_blocks_to_place(exclude=exclude):
return []
dirs = [_Vec3(0, 2, 0)]
for dir_ in _adj_dirs():
dirs.extend([dir_, dir_ + _Vec3(0, 1, 0)])
if self._get_block(self._pos + dir_) in [_AIR, _WATER]:
dirs.append(dir_ + _Vec3(0, -1, 0))
rtn = []
for dir_ in dirs:
pos = self._pos + dir_
if self._can_place(pos):
rtn.append({'func': '_place', 'args': (pos,), 'kwargs': {
'exclude': exclude}})
return rtn
def _can_place(self, loc):
"""Return whether or not the bot can place a block at that location
independent of what it has in its inventory."""
non_blocks = [_AIR, _WATER, _LAVA]
player = [self._pos, self._pos + _Vec3(0, 1, 0)]
for dir_ in (_adj_dirs + [_Vec3(0, 1, 0), _Vec3(0, -1, 0)]):
new_loc = loc + dir_
if new_loc not in player and self._get_block(new_loc
) not in non_blocks:
return True
return False
def _has_blocks_to_place(self, exclude=None):
"""Return whether or not the bot can place a block from the
inventory. If exclude is None, any block can be placed."""
for block_ in self._inventory:
if block_ != exclude:
return True
return False
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
raise NotImplementedError
def _move(self, pos):
"""Move there only."""
self._pos = deepcopy(pos)
class _ImaginaryBot(_GenericBot):
"""A bot used for finding paths that doesn't actually change blocks
in the world."""
def __init__(self, pos, inventory=None):
"""Create a new bot."""
_GenericBot.__init__(self, pos, inventory)
self._changes = {}
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
self._changes[deepcopy(pos)] = block
def _get_block(self, pos):
"""Get the block at the position."""
if pos in self._changes:
return self._changes[pos]
else:
return _get_mc().getBlock(pos)
def get_block(self, pos):
"""The public version."""
return self._get_block(pos)
def __hash__(self):
"""Return the hash."""
return hash(frozenset([self._pos] + _key_vals(self._inventory) +
_key_vals(self._changes)))
class Bot(_GenericBot):
"""The real bot.
All vector arguments are Vec3s."""
_BOT_BLOCK = block.IRON_BLOCK.id
def __init__(self):
"""Create a bot next to the player."""
pos = _get_mc().player.getTilePos() + Vec3(2, 0, 0)
pos = _Vec3(pos.x, pos.y, pos.z)
_GenericBot.__init__(self, pos)
self._pos = pos
self._move(self._pos)
@staticmethod
def destroy_all():
"""Destroy all bots within a small distance (in case I forget to
destroy one)."""
player_loc = _player_loc()
minec = _get_mc()
rad = 10
for x in xrange(player_loc.x - rad, player_loc.x + rad):
for y in xrange(player_loc.y - rad, player_loc.y + rad):
for z in xrange(player_loc.z - rad, player_loc.z + rad):
if minec.getBlock(x, y, z) == Bot._BOT_BLOCK:
minec.setBlock(x, y, z, _AIR)
def destroy(self):
"""Set itself to air."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
def fetch(self, block_name):
"""Mine and return a block to the player."""
imag_bot = _ImaginaryBot(self._pos, self._inventory)
block_id = getattr(block, block_name).id
block_loc = self._get_block_loc(block_id)
mine_prob = _MineProblem(imag_bot, block_loc, block_id)
mine_actions = astar(mine_prob, _mine_heuristic)
self.take_actions(mine_actions, _DELAY)
imag_bot = _ImaginaryBot(self._pos, self._inventory)
player_loc = _player_loc()
return_prob = _ReturnProblem(imag_bot, block_id, player_loc)
return_actions = astar(return_prob, _return_heuristic)
imag_bot.take_actions(return_actions)
return_actions.append({'func': '_place', 'args': (imag_bot.get_pos(
) + player_loc) / 2, 'kwargs': {'block': block_id}})
self.take_actions(return_actions, _DELAY)
def _get_block_loc(self, block_id):
"""Return the location of the block."""
find_prob = FindProblem(self._pos, block_id)
dirs = bfs(find_prob)
return self._pos + sum(dirs)
def _set_block(self, pos, block_):
"""Place an actual block in the world.
block is a block id."""
_get_mc().setBlock(pos, block_)
def _get_block(self, pos):
"""Get the block at the position."""
return _get_mc().getBlock(pos)
def _move(self, pos):
"""Move there, and set the appropriate blocks."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
self._set_block(pos, self._BOT_BLOCK)
self._set_block(pos + _Vec3(0, 1, 0), self._BOT_BLOCK)
self._pos = pos
class FindProblem(SearchProblem):
"""Problem for finding the location of a block in the world.
A state in this problem is a location.
"""
def __init__(self, start_loc, block_id):
"""Initialize."""
self._start_loc = deepcopy(start_loc)
self._block_id = block_id
def getStartState(self):
"""Return the starting location."""
return self._start_loc
def isGoalState(self, state):
return _get_mc().getBlock(state) == self._block_id
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for dir_ in _all_dirs():
successor = state + dir_
if successor.y <= _get_mc().getHeight(successor.x, successor.z
) and _get_mc().getBlock(successor) != _BEDROCK:
rtn.append((successor, dir_, 1))
return rtn
class _MineProblem(SearchProblem):
"""The problem of finding the block and mining it (not returning
it)."""
def __init__(self, imag_bot, block_loc, block_id):
"""Initialize the problem with an _ImaginaryBot.
block_loc is a Vec3.
"""
self._bot = imag_bot
self._block_loc = deepcopy(block_loc)
self._block_id = block_id
def get_block_loc(self):
"""Return the block location."""
return deepcopy(self._block_loc)
def get_block_id(self):
"""Return the block it's trying to mine."""
return self._block_id
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot has the block."""
return state.contains(self._block_id)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions():
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
class _ReturnProblem(SearchProblem):
"""The problem of returning to the player. This does not place the block
next to the player."""
def __init__(self, imag_bot, block_, player_loc):
"""Initialized the problem with an _ImaginaryBot.
block is a block id."""
self._bot = imag_bot
self._block = block_
self._player_loc = player_loc
def get_player_loc(self):
"""Return the player location."""
return deepcopy(self._player_loc)
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot is next to the player."""
diff = state.get_pos() - self._player_loc
return diff.y == 0 and (diff.x == 0 or diff.z == 0) and abs(diff.x
) + abs(diff.z) == 2 and state.get_block(self._player_loc +
diff / 2 + _Vec3(0, -1, 0)) not in (_AIR, _LAVA, _WATER)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions(self._block):
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
<mask token>
def _player_loc():
"""Return the player's location."""
return _to_my_vec3(_get_mc().player.getTilePos())
<mask token>
def _all_dirs():
"""Return all adjacent directions."""
return _adj_dirs() + [_Vec3(0, 1, 0), _Vec3(0, -1, 0)]
<mask token>
def _key_vals(dict_):
"""Return a list of key-val tuples."""
return [(key, val) for key, val in dict_.iteritems()]
| <mask token>
class _Vec3(Vec3):
"""A Vec3 that is hashable. Everything in this program should use this
class."""
def __hash__(self):
"""Return the hash."""
return hash((self.x, self.y, self.z))
def clone(self):
"""Return a clone."""
return _Vec3(self.x, self.y, self.z)
class _GenericBot:
"""A generic bot."""
def __init__(self, pos, inventory=None):
"""Initialize with an empty inventory.
inventory is a dictionary. If None, an empty one will be used."""
if inventory is None:
self._inventory = {}
else:
self._inventory = deepcopy(inventory)
self._pos = deepcopy(pos)
def take_action(self, action):
"""Take the action (acquired from _get_legal_actions)."""
getattr(self, action['func'])(*action.get('args', ()), **action.get
('kwargs', {}))
def take_actions(self, actions, seconds=None):
"""Take these actions. If seconds is not None, sleep 'seconds'
seconds.
"""
if not actions:
return
self.take_action(actions[0])
for action in actions[1:]:
if seconds is not None:
sleep(seconds)
self.take_action(action)
def get_pos(self):
"""Return the position."""
return deepcopy(self._pos)
def get_legal_actions(self, block_=None):
"""Return a list of legal actions.
If block_ is None, return all legal actions. Otherwise, return all
legal actions that don't involve placing the block."""
return self._get_move_actions(block_) + self._get_mine_actions(
) + self._get_placement_actions(block_)
def contains(self, block_):
"""Return whether or not the bot contains the block id."""
return block_ in self._inventory
def _get_block(self, pos):
"""Get the block at the position."""
raise NotImplementedError
def _place(self, loc, exclude=None, block_=None):
"""Place a block from the inventory only.
If exclude is not None, place a block that is not 'exclude'.
If block is not None, place that block only.
"""
if not self._inventory:
raise Exception('Inventory empty')
if block_ is None:
for key in self._inventory:
if key != exclude:
block_ = key
break
else:
raise Exception(
'You requested not to place %s, but it is the only block in the inventory.'
% exclude)
if block_ not in self._inventory:
raise Exception('Block %s is not in the inventory' % block_)
if self._inventory[block_] == 1:
del self._inventory[block_]
else:
self._inventory[block_] -= 1
self._set_block(loc, block_)
def _move_down(self):
"""Move and mine the block below."""
new_pos = self._pos + _Vec3(0, -1, 0)
block_ = self._get_block(new_pos)
if block_ != _WATER:
self._add_to_inv(block_)
self._move(new_pos)
def _add_to_inv(self, block_):
"""Add the block to the inventory."""
if block_ in self._inventory:
self._inventory[block_] += 1
else:
self._inventory[block_] = 1
def _move_up(self, exclude=None):
"""Move and place a block below.
If exclude is not None, place a block that is not 'exclude'.
"""
self._move(self._pos + _Vec3(0, 1, 0))
self._place(self._pos + _Vec3(0, -1, 0), exclude)
def _mine(self, loc):
"""Mine the block."""
block_ = self._get_block(loc)
self._add_to_inv(block_)
self._set_block(loc, _AIR)
def _get_move_actions(self, exclude=None):
"""Return a list of legal movement actions.
exclude is the block to exclude.
"""
rtn = []
can_move_up = self._get_block(self._pos + _Vec3(0, 2, 0)) in {_AIR,
_WATER}
if can_move_up:
if self._surrounded():
rtn.append({'func': '_move', 'args': (self._pos + _Vec3(0,
1, 0),)})
else:
rtn.append({'func': '_move_up', 'args': (exclude,)})
hidden_block = self._get_block(self._pos + _Vec3(0, -2, 0))
if hidden_block == _WATER or hidden_block not in {_AIR, _LAVA}:
rtn.append({'func': '_move_down'})
for dir_ in _adj_dirs():
rtn.extend(self._side_moves(dir_, can_move_up))
return rtn
def _side_moves(self, dir_, can_move_up):
"""Return the list of side moves.
dir_ is an adjacent direction.
can_move_up is a boolean for whether or not the bot can move up.
"""
rtn = []
base_pos = self._pos + dir_
base_block = self._get_block(base_pos)
empty_blocks = {_AIR, _WATER}
if can_move_up and base_block not in {_AIR, _LAVA, _WATER}:
for vert_dir in [_Vec3(0, 1, 0), _Vec3(0, 2, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
rtn.append({'func': '_move', 'args': (base_pos + _Vec3(0, 1,
0),)})
for vert_dir in [_Vec3(), _Vec3(0, 1, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
pos = base_pos + _Vec3(0, -1, 0)
for _ in xrange(_DROP_PLUS_1):
block_ = self._get_block(pos)
if block_ != _AIR:
if block_ != _LAVA:
rtn.append({'func': '_move', 'args': (pos + _Vec3(0,
1, 0),)})
break
pos.y -= 1
def _surrounded(self):
"""Return whether or not the bot is surrounded by water."""
for dir_ in _adj_dirs():
if self._get_block(self._pos + dir_) != _WATER:
return False
return True
def _get_mine_actions(self):
"""Return a list of legal mining actions (that only involve mining
and not moving)."""
rtn = []
dont_mine = {_AIR, _WATER, _LAVA}
pos_above = self._pos + _Vec3(0, 2, 0)
if self._get_block(pos_above) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos_above,)})
for dir_ in _adj_dirs():
pos = self._pos + dir_
for _ in xrange(2):
if self._get_block(pos) not in dont_mine:
rtn.append({'func': '_mine', 'args': (pos,)})
pos = pos + _Vec3(0, 1, 0)
return rtn
def _get_placement_actions(self, exclude=None):
"""Return a list of legal actions that only involve placing a block
from the inventory.
exclude is a block id. It is the block that should not be placed. If None,
any block can be placed."""
if not self._has_blocks_to_place(exclude=exclude):
return []
dirs = [_Vec3(0, 2, 0)]
for dir_ in _adj_dirs():
dirs.extend([dir_, dir_ + _Vec3(0, 1, 0)])
if self._get_block(self._pos + dir_) in [_AIR, _WATER]:
dirs.append(dir_ + _Vec3(0, -1, 0))
rtn = []
for dir_ in dirs:
pos = self._pos + dir_
if self._can_place(pos):
rtn.append({'func': '_place', 'args': (pos,), 'kwargs': {
'exclude': exclude}})
return rtn
def _can_place(self, loc):
"""Return whether or not the bot can place a block at that location
independent of what it has in its inventory."""
non_blocks = [_AIR, _WATER, _LAVA]
player = [self._pos, self._pos + _Vec3(0, 1, 0)]
for dir_ in (_adj_dirs + [_Vec3(0, 1, 0), _Vec3(0, -1, 0)]):
new_loc = loc + dir_
if new_loc not in player and self._get_block(new_loc
) not in non_blocks:
return True
return False
def _has_blocks_to_place(self, exclude=None):
"""Return whether or not the bot can place a block from the
inventory. If exclude is None, any block can be placed."""
for block_ in self._inventory:
if block_ != exclude:
return True
return False
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
raise NotImplementedError
def _move(self, pos):
"""Move there only."""
self._pos = deepcopy(pos)
class _ImaginaryBot(_GenericBot):
"""A bot used for finding paths that doesn't actually change blocks
in the world."""
def __init__(self, pos, inventory=None):
"""Create a new bot."""
_GenericBot.__init__(self, pos, inventory)
self._changes = {}
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
self._changes[deepcopy(pos)] = block
def _get_block(self, pos):
"""Get the block at the position."""
if pos in self._changes:
return self._changes[pos]
else:
return _get_mc().getBlock(pos)
def get_block(self, pos):
"""The public version."""
return self._get_block(pos)
def __hash__(self):
"""Return the hash."""
return hash(frozenset([self._pos] + _key_vals(self._inventory) +
_key_vals(self._changes)))
class Bot(_GenericBot):
"""The real bot.
All vector arguments are Vec3s."""
_BOT_BLOCK = block.IRON_BLOCK.id
def __init__(self):
"""Create a bot next to the player."""
pos = _get_mc().player.getTilePos() + Vec3(2, 0, 0)
pos = _Vec3(pos.x, pos.y, pos.z)
_GenericBot.__init__(self, pos)
self._pos = pos
self._move(self._pos)
@staticmethod
def destroy_all():
"""Destroy all bots within a small distance (in case I forget to
destroy one)."""
player_loc = _player_loc()
minec = _get_mc()
rad = 10
for x in xrange(player_loc.x - rad, player_loc.x + rad):
for y in xrange(player_loc.y - rad, player_loc.y + rad):
for z in xrange(player_loc.z - rad, player_loc.z + rad):
if minec.getBlock(x, y, z) == Bot._BOT_BLOCK:
minec.setBlock(x, y, z, _AIR)
def destroy(self):
"""Set itself to air."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
def fetch(self, block_name):
"""Mine and return a block to the player."""
imag_bot = _ImaginaryBot(self._pos, self._inventory)
block_id = getattr(block, block_name).id
block_loc = self._get_block_loc(block_id)
mine_prob = _MineProblem(imag_bot, block_loc, block_id)
mine_actions = astar(mine_prob, _mine_heuristic)
self.take_actions(mine_actions, _DELAY)
imag_bot = _ImaginaryBot(self._pos, self._inventory)
player_loc = _player_loc()
return_prob = _ReturnProblem(imag_bot, block_id, player_loc)
return_actions = astar(return_prob, _return_heuristic)
imag_bot.take_actions(return_actions)
return_actions.append({'func': '_place', 'args': (imag_bot.get_pos(
) + player_loc) / 2, 'kwargs': {'block': block_id}})
self.take_actions(return_actions, _DELAY)
def _get_block_loc(self, block_id):
"""Return the location of the block."""
find_prob = FindProblem(self._pos, block_id)
dirs = bfs(find_prob)
return self._pos + sum(dirs)
def _set_block(self, pos, block_):
"""Place an actual block in the world.
block is a block id."""
_get_mc().setBlock(pos, block_)
def _get_block(self, pos):
"""Get the block at the position."""
return _get_mc().getBlock(pos)
def _move(self, pos):
"""Move there, and set the appropriate blocks."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
self._set_block(pos, self._BOT_BLOCK)
self._set_block(pos + _Vec3(0, 1, 0), self._BOT_BLOCK)
self._pos = pos
class FindProblem(SearchProblem):
"""Problem for finding the location of a block in the world.
A state in this problem is a location.
"""
def __init__(self, start_loc, block_id):
"""Initialize."""
self._start_loc = deepcopy(start_loc)
self._block_id = block_id
def getStartState(self):
"""Return the starting location."""
return self._start_loc
def isGoalState(self, state):
return _get_mc().getBlock(state) == self._block_id
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for dir_ in _all_dirs():
successor = state + dir_
if successor.y <= _get_mc().getHeight(successor.x, successor.z
) and _get_mc().getBlock(successor) != _BEDROCK:
rtn.append((successor, dir_, 1))
return rtn
class _MineProblem(SearchProblem):
"""The problem of finding the block and mining it (not returning
it)."""
def __init__(self, imag_bot, block_loc, block_id):
"""Initialize the problem with an _ImaginaryBot.
block_loc is a Vec3.
"""
self._bot = imag_bot
self._block_loc = deepcopy(block_loc)
self._block_id = block_id
def get_block_loc(self):
"""Return the block location."""
return deepcopy(self._block_loc)
def get_block_id(self):
"""Return the block it's trying to mine."""
return self._block_id
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot has the block."""
return state.contains(self._block_id)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions():
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
class _ReturnProblem(SearchProblem):
"""The problem of returning to the player. This does not place the block
next to the player."""
def __init__(self, imag_bot, block_, player_loc):
"""Initialized the problem with an _ImaginaryBot.
block is a block id."""
self._bot = imag_bot
self._block = block_
self._player_loc = player_loc
def get_player_loc(self):
"""Return the player location."""
return deepcopy(self._player_loc)
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot is next to the player."""
diff = state.get_pos() - self._player_loc
return diff.y == 0 and (diff.x == 0 or diff.z == 0) and abs(diff.x
) + abs(diff.z) == 2 and state.get_block(self._player_loc +
diff / 2 + _Vec3(0, -1, 0)) not in (_AIR, _LAVA, _WATER)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions(self._block):
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
def _mine_heuristic(bot, problem):
"""Return the mining heuristic.
bot is an _ImaginaryBot.
"""
if bot.contains(problem.get_block_id()):
return 0
bot_pos = bot.get_pos()
dest_pos = problem.get_block_loc()
man_dist = _manhattan((bot_pos.x, bot_pos.z), (dest_pos.x, dest_pos.z))
y_diff = bot_pos.y - dest_pos.y
if y_diff < 0:
y_diff += 1
if y_diff == 0:
return man_dist
drop = _DROP if y_diff > 0 else 1
y_diff = abs(y_diff)
drops = _drops(y_diff, drop)
if man_dist > drops:
return man_dist
if man_dist == drops:
return man_dist + 1
if drop == 1:
return drops
if y_diff % drop == 1:
return drops
return drops + 1
<mask token>
def _return_heuristic(bot, problem):
"""Return the return heuristic.
bot is an _ImaginaryBot.
"""
bot_pos = bot.get_pos()
player_pos = problem.get_player_loc()
bot_plane_pos = bot.x, bot.z
y_diff = bot_pos.y - player_pos.y
drop = _DROP if y_diff > 0 else 1
y_diff = abs(y_diff)
drops = _drops(y_diff, drop)
min_man = float('inf')
for dir_ in _adj_dirs():
loc = player_pos + 2 * dir_
man_dist = _manhattan(bot_plane_pos, (loc.x, loc.z))
if man_dist < min_man:
min_man = man_dist
if man_dist < drops:
return drops
return min_man
def _to_my_vec3(vec):
"""Return the _Vec3 alternative of the Vec3."""
return _Vec3(vec.x, vec.y, vec.z)
def _player_loc():
"""Return the player's location."""
return _to_my_vec3(_get_mc().player.getTilePos())
def _adj_dirs():
"""Return the adjacent directions."""
return [_Vec3(1, 0, 0), _Vec3(-1, 0, 0), _Vec3(0, 0, 1), _Vec3(0, 0, -1)]
def _all_dirs():
"""Return all adjacent directions."""
return _adj_dirs() + [_Vec3(0, 1, 0), _Vec3(0, -1, 0)]
<mask token>
def _key_vals(dict_):
"""Return a list of key-val tuples."""
return [(key, val) for key, val in dict_.iteritems()]
| """Module for the bot"""
from copy import deepcopy
from time import sleep
import mcpi.minecraft as minecraft
from mcpi.vec3 import Vec3
import mcpi.block as block
from search import SearchProblem, astar, bfs
from singleton import singleton
_AIR = block.AIR.id
_WATER = block.WATER.id
_LAVA = block.LAVA.id
_BEDROCK = block.BEDROCK.id
_DROP = 2 # It can drop at most this many
_DROP_PLUS_1 = _DROP + 1
_DELAY = 1
class _Vec3(Vec3):
"""A Vec3 that is hashable. Everything in this program should use this
class."""
def __hash__(self):
"""Return the hash."""
return hash((self.x, self.y, self.z))
def clone(self):
"""Return a clone."""
return _Vec3(self.x, self.y, self.z)
class _GenericBot:
"""A generic bot."""
def __init__(self, pos, inventory=None):
"""Initialize with an empty inventory.
inventory is a dictionary. If None, an empty one will be used."""
if inventory is None:
self._inventory = {}
else:
self._inventory = deepcopy(inventory)
self._pos = deepcopy(pos)
def take_action(self, action):
"""Take the action (acquired from _get_legal_actions)."""
getattr(self, action['func'])(
*action.get('args', ()),
**action.get('kwargs', {})
)
def take_actions(self, actions, seconds=None):
"""Take these actions. If seconds is not None, sleep 'seconds'
seconds.
"""
if not actions:
return
self.take_action(actions[0])
for action in actions[1:]:
if seconds is not None:
sleep(seconds)
self.take_action(action)
def get_pos(self):
"""Return the position."""
return deepcopy(self._pos)
def get_legal_actions(self, block_=None):
"""Return a list of legal actions.
If block_ is None, return all legal actions. Otherwise, return all
legal actions that don't involve placing the block."""
return self._get_move_actions(block_) + self._get_mine_actions() + \
self._get_placement_actions(block_)
def contains(self, block_):
"""Return whether or not the bot contains the block id."""
return block_ in self._inventory
def _get_block(self, pos):
"""Get the block at the position."""
raise NotImplementedError
def _place(self, loc, exclude=None, block_=None):
"""Place a block from the inventory only.
If exclude is not None, place a block that is not 'exclude'.
If block is not None, place that block only.
"""
if not self._inventory:
raise Exception('Inventory empty')
if block_ is None:
for key in self._inventory:
if key != exclude:
block_ = key
break
else:
raise Exception((
'You requested not to place %s, but it is the only '
'block in the inventory.' % exclude
))
if block_ not in self._inventory:
raise Exception('Block %s is not in the inventory' % block_)
if self._inventory[block_] == 1:
del self._inventory[block_]
else:
self._inventory[block_] -= 1
self._set_block(loc, block_)
def _move_down(self):
"""Move and mine the block below."""
new_pos = self._pos + _Vec3(0, -1, 0)
block_ = self._get_block(new_pos)
if block_ != _WATER:
self._add_to_inv(block_)
self._move(new_pos)
def _add_to_inv(self, block_):
"""Add the block to the inventory."""
if block_ in self._inventory:
self._inventory[block_] += 1
else:
self._inventory[block_] = 1
def _move_up(self, exclude=None):
"""Move and place a block below.
If exclude is not None, place a block that is not 'exclude'.
"""
self._move(self._pos + _Vec3(0, 1, 0))
self._place(self._pos + _Vec3(0, -1, 0), exclude)
def _mine(self, loc):
"""Mine the block."""
block_ = self._get_block(loc)
self._add_to_inv(block_)
self._set_block(loc, _AIR)
def _get_move_actions(self, exclude=None):
"""Return a list of legal movement actions.
exclude is the block to exclude.
"""
rtn = []
# Check for moving up
can_move_up = self._get_block(self._pos + _Vec3(0, 2, 0)) in {_AIR, _WATER}
if can_move_up:
if self._surrounded():
rtn.append({
'func': '_move',
'args': (self._pos + _Vec3(0, 1, 0),)
})
else:
rtn.append({
'func': '_move_up',
'args': (exclude,)
})
# Check for moving down
hidden_block = self._get_block(self._pos + _Vec3(0, -2, 0))
if hidden_block == _WATER or hidden_block not in {_AIR, _LAVA}:
rtn.append({'func': '_move_down'})
# Check for side moves
for dir_ in _adj_dirs():
rtn.extend(self._side_moves(dir_, can_move_up))
return rtn
def _side_moves(self, dir_, can_move_up):
"""Return the list of side moves.
dir_ is an adjacent direction.
can_move_up is a boolean for whether or not the bot can move up.
"""
rtn = []
base_pos = self._pos + dir_
base_block = self._get_block(base_pos)
empty_blocks = {_AIR, _WATER}
# Check if it can move up
if can_move_up and base_block not in {_AIR, _LAVA, _WATER}:
for vert_dir in [_Vec3(0, 1, 0), _Vec3(0, 2, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
else:
rtn.append({
'func': '_move',
'args': (base_pos + _Vec3(0, 1, 0),)
})
# Check if it can move in that direction
for vert_dir in [_Vec3(), _Vec3(0, 1, 0)]:
if self._get_block(base_pos + vert_dir) not in empty_blocks:
break
# Fall
else:
pos = base_pos + _Vec3(0, -1, 0)
for _ in xrange(_DROP_PLUS_1):
block_ = self._get_block(pos)
if block_ != _AIR:
if block_ != _LAVA:
rtn.append({
'func': '_move',
'args': (pos + _Vec3(0, 1, 0),)
})
break
pos.y -= 1
def _surrounded(self):
"""Return whether or not the bot is surrounded by water."""
for dir_ in _adj_dirs():
if self._get_block(self._pos + dir_) != _WATER:
return False
return True
def _get_mine_actions(self):
"""Return a list of legal mining actions (that only involve mining
and not moving)."""
rtn = []
dont_mine = {_AIR, _WATER, _LAVA}
# Mine above.
pos_above = self._pos + _Vec3(0, 2, 0)
if self._get_block(pos_above) not in dont_mine:
rtn.append({
'func': '_mine',
'args': (pos_above,)
})
for dir_ in _adj_dirs():
pos = self._pos + dir_
for _ in xrange(2):
if self._get_block(pos) not in dont_mine:
rtn.append({
'func': '_mine',
'args': (pos,)
})
pos = pos + _Vec3(0, 1, 0)
return rtn
def _get_placement_actions(self, exclude=None):
"""Return a list of legal actions that only involve placing a block
from the inventory.
exclude is a block id. It is the block that should not be placed. If None,
any block can be placed."""
if not self._has_blocks_to_place(exclude=exclude):
return []
dirs = [_Vec3(0, 2, 0)]
for dir_ in _adj_dirs():
dirs.extend([dir_, dir_ + _Vec3(0, 1, 0)])
if self._get_block(self._pos + dir_) in [_AIR, _WATER]:
dirs.append(dir_ + _Vec3(0, -1, 0))
rtn = []
for dir_ in dirs:
pos = self._pos + dir_
if self._can_place(pos):
rtn.append({
'func': '_place',
'args': (pos,),
'kwargs': {'exclude': exclude}
})
return rtn
def _can_place(self, loc):
"""Return whether or not the bot can place a block at that location
independent of what it has in its inventory."""
non_blocks = [_AIR, _WATER, _LAVA]
player = [self._pos, self._pos + _Vec3(0, 1, 0)]
for dir_ in _adj_dirs + [_Vec3(0, 1, 0), _Vec3(0, -1, 0)]:
new_loc = loc + dir_
if new_loc not in player and self._get_block(new_loc) \
not in non_blocks:
return True
return False
def _has_blocks_to_place(self, exclude=None):
"""Return whether or not the bot can place a block from the
inventory. If exclude is None, any block can be placed."""
for block_ in self._inventory:
if block_ != exclude:
return True
return False
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
raise NotImplementedError
def _move(self, pos):
"""Move there only."""
self._pos = deepcopy(pos)
class _ImaginaryBot(_GenericBot):
"""A bot used for finding paths that doesn't actually change blocks
in the world."""
def __init__(self, pos, inventory=None):
"""Create a new bot."""
_GenericBot.__init__(self, pos, inventory)
self._changes = {} # Changes to the world
def _set_block(self, pos, block_):
"""Set a block. block_ is the block id."""
self._changes[deepcopy(pos)] = block
def _get_block(self, pos):
"""Get the block at the position."""
if pos in self._changes:
return self._changes[pos]
else:
return _get_mc().getBlock(pos)
def get_block(self, pos):
"""The public version."""
return self._get_block(pos)
def __hash__(self):
"""Return the hash."""
return hash(frozenset([self._pos] + \
_key_vals(self._inventory) + \
_key_vals(self._changes)
))
class Bot(_GenericBot):
"""The real bot.
All vector arguments are Vec3s."""
_BOT_BLOCK = block.IRON_BLOCK.id
def __init__(self):
"""Create a bot next to the player."""
pos = _get_mc().player.getTilePos() + Vec3(2, 0, 0)
pos = _Vec3(pos.x, pos.y, pos.z)
_GenericBot.__init__(self, pos)
self._pos = pos
self._move(self._pos)
@staticmethod
def destroy_all():
"""Destroy all bots within a small distance (in case I forget to
destroy one)."""
player_loc = _player_loc()
minec = _get_mc()
rad = 10
for x in xrange(player_loc.x - rad, player_loc.x + rad):
for y in xrange(player_loc.y - rad, player_loc.y + rad):
for z in xrange(player_loc.z - rad, player_loc.z + rad):
if minec.getBlock(x, y, z) == Bot._BOT_BLOCK:
minec.setBlock(x, y, z, _AIR)
def destroy(self):
"""Set itself to air."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
def fetch(self, block_name):
"""Mine and return a block to the player."""
imag_bot = _ImaginaryBot(self._pos, self._inventory)
block_id = getattr(block, block_name).id
block_loc = self._get_block_loc(block_id)
mine_prob = _MineProblem(imag_bot, block_loc, block_id)
mine_actions = astar(mine_prob, _mine_heuristic)
self.take_actions(mine_actions, _DELAY)
imag_bot = _ImaginaryBot(self._pos, self._inventory)
player_loc = _player_loc()
return_prob = _ReturnProblem(imag_bot, block_id, player_loc)
return_actions = astar(return_prob, _return_heuristic)
imag_bot.take_actions(return_actions)
return_actions.append({
'func': '_place',
'args': (imag_bot.get_pos() + player_loc) / 2,
'kwargs': {'block': block_id}
})
self.take_actions(return_actions, _DELAY)
def _get_block_loc(self, block_id):
"""Return the location of the block."""
find_prob = FindProblem(self._pos, block_id)
dirs = bfs(find_prob)
return self._pos + sum(dirs)
def _set_block(self, pos, block_):
"""Place an actual block in the world.
block is a block id."""
_get_mc().setBlock(pos, block_)
def _get_block(self, pos):
"""Get the block at the position."""
return _get_mc().getBlock(pos)
def _move(self, pos):
"""Move there, and set the appropriate blocks."""
self._set_block(self._pos, _AIR)
self._set_block(self._pos + _Vec3(0, 1, 0), _AIR)
self._set_block(pos, self._BOT_BLOCK)
self._set_block(pos + _Vec3(0, 1, 0), self._BOT_BLOCK)
self._pos = pos
class FindProblem(SearchProblem):
"""Problem for finding the location of a block in the world.
A state in this problem is a location.
"""
def __init__(self, start_loc, block_id):
"""Initialize."""
self._start_loc = deepcopy(start_loc)
self._block_id = block_id
def getStartState(self):
"""Return the starting location."""
return self._start_loc
def isGoalState(self, state):
return _get_mc().getBlock(state) == self._block_id
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for dir_ in _all_dirs():
successor = state + dir_
if successor.y <= _get_mc().getHeight(successor.x, successor.z) \
and _get_mc().getBlock(successor) != _BEDROCK:
rtn.append((successor, dir_, 1))
return rtn
class _MineProblem(SearchProblem):
"""The problem of finding the block and mining it (not returning
it)."""
def __init__(self, imag_bot, block_loc, block_id):
"""Initialize the problem with an _ImaginaryBot.
block_loc is a Vec3.
"""
self._bot = imag_bot
self._block_loc = deepcopy(block_loc)
self._block_id = block_id
def get_block_loc(self):
"""Return the block location."""
return deepcopy(self._block_loc)
def get_block_id(self):
"""Return the block it's trying to mine."""
return self._block_id
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot has the block."""
return state.contains(self._block_id)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions():
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
class _ReturnProblem(SearchProblem):
"""The problem of returning to the player. This does not place the block
next to the player."""
def __init__(self, imag_bot, block_, player_loc):
"""Initialized the problem with an _ImaginaryBot.
block is a block id."""
self._bot = imag_bot
self._block = block_
self._player_loc = player_loc
def get_player_loc(self):
"""Return the player location."""
return deepcopy(self._player_loc)
def getStartState(self):
"""Return the bot passed in."""
return self._bot
def isGoalState(self, state):
"""Return whether or not the bot is next to the player."""
diff = state.get_pos() - self._player_loc
return diff.y == 0 and (diff.x == 0 or diff.z == 0) and \
abs(diff.x) + abs(diff.z) == 2 and \
state.get_block(self._player_loc + diff/2 + _Vec3(0, -1, 0)) not in \
(_AIR, _LAVA, _WATER)
def getSuccessors(self, state):
"""Return the successors."""
rtn = []
for action in state.get_legal_actions(self._block):
successor = deepcopy(state)
successor.take_action(action)
rtn.append((successor, action, 1))
return rtn
def _mine_heuristic(bot, problem):
"""Return the mining heuristic.
bot is an _ImaginaryBot.
"""
if bot.contains(problem.get_block_id()):
return 0
bot_pos = bot.get_pos()
dest_pos = problem.get_block_loc()
# If man == dy: return man + 1
# If man > dy: return man
# If man < dy: return dy?
man_dist = _manhattan((bot_pos.x, bot_pos.z), (dest_pos.x, dest_pos.z))
y_diff = bot_pos.y - dest_pos.y
if y_diff < 0:
y_diff += 1
if y_diff == 0:
return man_dist
# Transform so that it's only dropping
drop = _DROP if y_diff > 0 else 1
y_diff = abs(y_diff)
drops = _drops(y_diff, drop)
if man_dist > drops:
return man_dist
if man_dist == drops:
return man_dist + 1
if drop == 1:
return drops
if y_diff % drop == 1:
return drops
return drops + 1
def _drops(dist, drop):
"""Return the number of times it takes to drop a distance dist. drop is the
length of one drop. Both are assumed positive."""
rtn = dist / drop
if dist % drop != 0:
rtn += 1
return rtn
def _return_heuristic(bot, problem):
"""Return the return heuristic.
bot is an _ImaginaryBot.
"""
bot_pos = bot.get_pos()
player_pos = problem.get_player_loc()
bot_plane_pos = (bot.x, bot.z)
y_diff = bot_pos.y - player_pos.y
drop = _DROP if y_diff > 0 else 1
y_diff = abs(y_diff)
drops = _drops(y_diff, drop)
min_man = float('inf')
for dir_ in _adj_dirs():
loc = player_pos + 2 * dir_
man_dist = _manhattan(bot_plane_pos, (loc.x, loc.z))
if man_dist < min_man:
min_man = man_dist
if man_dist < drops:
return drops
return min_man
def _to_my_vec3(vec):
"""Return the _Vec3 alternative of the Vec3."""
return _Vec3(vec.x, vec.y, vec.z)
def _player_loc():
"""Return the player's location."""
return _to_my_vec3(_get_mc().player.getTilePos())
def _adj_dirs():
"""Return the adjacent directions."""
return [_Vec3(1, 0, 0), _Vec3(-1, 0, 0), _Vec3(0, 0, 1), _Vec3(0, 0, -1)]
def _all_dirs():
"""Return all adjacent directions."""
return _adj_dirs() + [_Vec3(0, 1, 0), _Vec3(0, -1, 0)]
def _manhattan(pos1, pos2):
"""Return the manhattan distance. pos1 and pos2 should be iterable."""
return sum(abs(val1 - val2) for val1, val2 in zip(pos1, pos2))
@singleton
def _get_mc():
"""Return the Minecraft instance."""
return minecraft.Minecraft.create()
def _key_vals(dict_):
"""Return a list of key-val tuples."""
return [(key, val) for key, val in dict_.iteritems()]
| [
48,
54,
69,
73,
79
] |
3 | 45969b346d6d5cbdef2f5d2f74270cf12024072d | <mask token>
| <mask token>
class Migration(migrations.Migration):
<mask token>
<mask token>
| <mask token>
class Migration(migrations.Migration):
dependencies = [('search', '0003_auto_20230209_1441')]
operations = [migrations.CreateModel(name='SearchSettings', fields=[(
'id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID'))], options={'permissions': ((
'change_boost', 'Edit boost settings for search components'), (
'view_explore', 'View the global search explore page')), 'managed':
False, 'default_permissions': ()})]
| from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('search', '0003_auto_20230209_1441')]
operations = [migrations.CreateModel(name='SearchSettings', fields=[(
'id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID'))], options={'permissions': ((
'change_boost', 'Edit boost settings for search components'), (
'view_explore', 'View the global search explore page')), 'managed':
False, 'default_permissions': ()})]
| # Generated by Django 4.1.9 on 2023-06-29 16:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("search", "0003_auto_20230209_1441"),
]
operations = [
migrations.CreateModel(
name="SearchSettings",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
],
options={
"permissions": (
("change_boost", "Edit boost settings for search components"),
("view_explore", "View the global search explore page"),
),
"managed": False,
"default_permissions": (),
},
),
]
| [
0,
1,
2,
3,
4
] |
4 | 3fbf1768a2fe78df591c49490dfce5fb374e7fc2 | from functools import wraps
import os
def restoring_chdir(fn):
#XXX:dc: This would be better off in a neutral module
@wraps(fn)
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
The Base for all Builders. Defines the API for subclasses.
All workflow steps need to return true, otherwise it is assumed something
went wrong and the Builder will stop
"""
workflow = ['clean', 'build', 'move']
def __init__(self, version):
self.version = version
def run(self):
for step in self.workflow:
fn = getattr(self, step)
result = fn()
assert result
@restoring_chdir
def force(self):
"""
An optional step to force a build even when nothing has changed.
"""
print "Forcing a build by touching files"
os.chdir(self.version.project.conf_dir(self.version.slug))
os.system('touch * && touch */*')
def clean(self):
"""
Clean up the version so it's ready for usage.
This is used to add RTD specific stuff to Sphinx, and to
implement whitelists on projects as well.
It is guaranteed to be called before your project is built.
"""
raise NotImplementedError
def build(self):
"""
Do the actual building of the documentation.
"""
raise NotImplementedError
def move(self):
"""
Move the documentation from it's generated place to its final home.
This needs to understand both a single server dev environment,
as well as a multi-server environment.
"""
raise NotImplementedError
@property
def changed(self):
"""
Says whether the documentation has changed, and requires further action.
This is mainly used to short-circuit more expensive builds of other
output formats if the project docs didn't change on an update.
Subclasses are recommended to override for more efficient builds.
Defaults to `True`
"""
return True
| null | null | null | null | [
0
] |
5 | 67b967b688aeac1270eee836e0f6e6b3555b933e | <mask token>
| <mask token>
if u_avg < u_bat_min:
print('proper shut down of the machine due to low battery')
else:
print('tout va bien dormez braves gens')
| <mask token>
pidcmes = Pidcmes()
u_bat_min = 3.7
n_moy = 20
stop_run = False
u_avg = pidcmes.get_tension(n_moy)
if u_avg < u_bat_min:
print('proper shut down of the machine due to low battery')
else:
print('tout va bien dormez braves gens')
| <mask token>
import time
import datetime as dt
from subprocess import call
from pidcmes_lib import Pidcmes
pidcmes = Pidcmes()
u_bat_min = 3.7
n_moy = 20
stop_run = False
u_avg = pidcmes.get_tension(n_moy)
if u_avg < u_bat_min:
print('proper shut down of the machine due to low battery')
else:
print('tout va bien dormez braves gens')
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This program is run at regular intervals to check the battery charge status of the uninterruptible power supply.
In our case, it is a LiPo battery with a nominal voltage of 3.7 volts. By setting the voltage for the
Raspberry PI shutdown procedure at 3.7 V,we ensure that the processor has enough time to make a clean shutdown.
This program must be launched at regular intervals (5 inute in our case) by the Raspberry PI OS cron task scheduler.
The crontab -e command in the home directory opens the cron file and the command line would for example be for a trigger every 5 minutes:
5 * * * * sudo /usr/bin/python3 /home/pi/dev_python/amod/pidcmes_bbu.py
"""
import time
import datetime as dt
from subprocess import call
from pidcmes_lib import Pidcmes # class for 'pidcmes' procedures
pidcmes = Pidcmes() # initialize pidcmese class
u_bat_min = 3.7 # minumum battery voltage
n_moy = 20 # averaging to reduce glitches
stop_run = False # to control the execution (run/stop)
u_avg = pidcmes.get_tension(n_moy) # read the value in volts
if u_avg < u_bat_min:# or i > 10:
print("proper shut down of the machine due to low battery")
# time.sleep(5)
# call("sudo shutdown -h now", shell=True) # shutdown the RASPI
else:
print("tout va bien dormez braves gens")
| [
0,
1,
2,
3,
4
] |
6 | c59707ba07c1659d94684c54cdd7bb2658cba935 | <mask token>
class H2OBaseCrossValidator(six.with_metaclass(ABCMeta)):
<mask token>
<mask token>
def split(self, frame, y=None):
"""Generate indices to split data into training and test.
Parameters
----------
frame : ``H2OFrame``
The h2o frame to split
y : str, optional (default=None)
The name of the column to stratify, if applicable.
Returns
-------
train : ndarray
The training set indices for the split
test : ndarray
The testing set indices for that split
"""
frame = check_frame(frame, copy=False)
indices = np.arange(frame.shape[0])
for test_index in self._iter_test_masks(frame, y):
train_index = indices[np.logical_not(test_index)]
test_index = indices[test_index]
yield list(train_index), list(test_index)
<mask token>
def _iter_test_indices(self, frame, y=None):
raise NotImplementedError(
'this method must be implemented by a subclass')
<mask token>
def __repr__(self):
return _build_repr(self)
<mask token>
class H2OBaseShuffleSplit(six.with_metaclass(ABCMeta)):
"""Base class for H2OShuffleSplit and H2OStratifiedShuffleSplit. This
is used for ``h2o_train_test_split`` in strategic train/test splits of
H2OFrames. Implementing subclasses should override ``_iter_indices``.
Parameters
----------
n_splits : int, optional (default=2)
The number of folds or splits in the split
test_size : float or int, optional (default=0.1)
The ratio of observations for the test fold
train_size : float or int, optional (default=None)
The ratio of observations for the train fold
random_state : int or RandomState, optional (default=None)
The random state for duplicative purposes.
"""
def __init__(self, n_splits=2, test_size=0.1, train_size=None,
random_state=None):
_validate_shuffle_split_init(test_size, train_size)
self.n_splits = n_splits
self.test_size = test_size
self.train_size = train_size
self.random_state = random_state
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
for train, test in self._iter_indices(frame, y):
yield train, test
@abstractmethod
def _iter_indices(self, frame, y):
"""Abstract method for iterating the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
pass
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the shuffle split.
"""
return self.n_splits
def __repr__(self):
return _build_repr(self)
class H2OShuffleSplit(H2OBaseShuffleSplit):
"""Default shuffle splitter used for ``h2o_train_test_split``.
This shuffle split class will not perform any stratification, and
will simply shuffle indices and split into the number of specified
sub-frames.
"""
def _iter_indices(self, frame, y=None):
"""Iterate the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify. Since this class does
not perform stratification, ``y`` is unused.
Returns
-------
ind_train : np.ndarray, shape=(n_samples,)
The train indices
ind_test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
rng = check_random_state(self.random_state)
for i in range(self.n_splits):
permutation = rng.permutation(n_samples)
ind_test = permutation[:n_test]
ind_train = permutation[n_test:n_test + n_train]
yield ind_train, ind_test
class H2OStratifiedShuffleSplit(H2OBaseShuffleSplit):
"""Shuffle splitter used for ``h2o_train_test_split`` when stratified
option is specified. This shuffle split class will perform stratification.
"""
def _iter_indices(self, frame, y):
"""Iterate the indices with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
Returns
-------
train : np.ndarray, shape=(n_samples,)
The train indices
test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
y = _val_y(y)
target = np.asarray(frame[y].as_data_frame(use_pandas=True)[y].tolist()
)
classes, y_indices = np.unique(target, return_inverse=True)
n_classes = classes.shape[0]
class_counts = bincount(y_indices)
if np.min(class_counts) < 2:
raise ValueError(
'The least populated class in y has only 1 member, which is too few. The minimum number of labels for any class cannot be less than 2.'
)
if n_train < n_classes:
raise ValueError(
'The train_size=%d should be greater than or equal to the number of classes=%d'
% (n_train, n_classes))
if n_test < n_classes:
raise ValueError(
'The test_size=%d should be greater than or equal to the number of classes=%d'
% (n_test, n_classes))
rng = check_random_state(self.random_state)
p_i = class_counts / float(n_samples)
n_i = np.round(n_train * p_i).astype(int)
t_i = np.minimum(class_counts - n_i, np.round(n_test * p_i).astype(int)
)
for _ in range(self.n_splits):
train = []
test = []
for i, class_i in enumerate(classes):
permutation = rng.permutation(class_counts[i])
perm_indices_class_i = np.where(target == class_i)[0][
permutation]
train.extend(perm_indices_class_i[:n_i[i]])
test.extend(perm_indices_class_i[n_i[i]:n_i[i] + t_i[i]])
if len(train) + len(test) < n_train + n_test:
missing_indices = np.where(bincount(train + test, minlength
=len(target)) == 0)[0]
missing_indices = rng.permutation(missing_indices)
n_missing_train = n_train - len(train)
n_missing_test = n_test - len(test)
if n_missing_train > 0:
train.extend(missing_indices[:n_missing_train])
if n_missing_test > 0:
test.extend(missing_indices[-n_missing_test:])
train = rng.permutation(train)
test = rng.permutation(test)
yield train, test
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedShuffleSplit, self).split(frame, y)
class _H2OBaseKFold(six.with_metaclass(ABCMeta, H2OBaseCrossValidator)):
"""Base class for KFold and Stratified KFold.
Parameters
----------
n_folds : int
The number of splits
shuffle : bool
Whether to shuffle indices
random_state : int or RandomState
The random state for the split
"""
@abstractmethod
def __init__(self, n_folds, shuffle, random_state):
if not isinstance(n_folds, numbers.Integral):
raise ValueError(
'n_folds must be of Integral type. %s of type %s was passed' %
(n_folds, type(n_folds)))
n_folds = int(n_folds)
if n_folds <= 1:
raise ValueError(
'k-fold cross-validation requires at least one train/test split by setting n_folds=2 or more'
)
if shuffle not in [True, False]:
raise TypeError(
'shuffle must be True or False. Got %s (type=%s)' % (str(
shuffle), type(shuffle)))
self.n_folds = n_folds
self.shuffle = shuffle
self.random_state = random_state
@overrides(H2OBaseCrossValidator)
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
frame = check_frame(frame, copy=False)
n_obs = frame.shape[0]
if self.n_folds > n_obs:
raise ValueError('Cannot have n_folds greater than n_obs')
for train, test in super(_H2OBaseKFold, self).split(frame, y):
yield train, test
@overrides(H2OBaseCrossValidator)
def get_n_splits(self):
"""Get the number of splits or folds.
Returns
-------
n_folds : int
The number of folds
"""
return self.n_folds
class H2OKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OKFold, self).__init__(n_folds, shuffle, random_state)
@overrides(_H2OBaseKFold)
def _iter_test_indices(self, frame, y=None):
n_obs = frame.shape[0]
indices = np.arange(n_obs)
if self.shuffle:
check_random_state(self.random_state).shuffle(indices)
n_folds = self.n_folds
fold_sizes = n_obs // n_folds * np.ones(n_folds, dtype=np.int)
fold_sizes[:n_obs % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
yield indices[start:stop]
current = stop
class H2OStratifiedKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame with
stratified splits.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OStratifiedKFold, self).__init__(n_folds, shuffle, random_state
)
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedKFold, self).split(frame, y)
def _iter_test_masks(self, frame, y):
test_folds = self._make_test_folds(frame, y)
for i in range(self.n_folds):
yield test_folds == i
def _make_test_folds(self, frame, y):
if self.shuffle:
rng = check_random_state(self.random_state)
else:
rng = self.random_state
y = _val_y(y)
if y is None:
raise ValueError(
'H2OStratifiedKFold requires a target name (got None)')
target = frame[y].as_data_frame(use_pandas=True)[y].values
n_samples = target.shape[0]
unique_y, y_inversed = np.unique(target, return_inverse=True)
y_counts = bincount(y_inversed)
min_labels = np.min(y_counts)
if np.all(self.n_folds > y_counts):
raise ValueError(
'All the n_labels for individual classes are less than %d folds.'
% self.n_folds, Warning)
if self.n_folds > min_labels:
warnings.warn(
'The least populated class in y has only %d members, which is too few. The minimum number of labels for any class cannot be less than n_folds=%d.'
% (min_labels, self.n_folds), Warning)
if SK18:
per_cls_cvs = [KFold(self.n_folds, shuffle=self.shuffle,
random_state=rng).split(np.zeros(max(count, self.n_folds))) for
count in y_counts]
else:
per_cls_cvs = [KFold(max(count, self.n_folds), self.n_folds,
shuffle=self.shuffle, random_state=rng) for count in y_counts]
test_folds = np.zeros(n_samples, dtype=np.int)
for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):
for cls, (_, test_split) in zip(unique_y, per_cls_splits):
cls_test_folds = test_folds[target == cls]
test_split = test_split[test_split < len(cls_test_folds)]
cls_test_folds[test_split] = test_fold_indices
test_folds[target == cls] = cls_test_folds
return test_folds
| <mask token>
class H2OBaseCrossValidator(six.with_metaclass(ABCMeta)):
<mask token>
<mask token>
def split(self, frame, y=None):
"""Generate indices to split data into training and test.
Parameters
----------
frame : ``H2OFrame``
The h2o frame to split
y : str, optional (default=None)
The name of the column to stratify, if applicable.
Returns
-------
train : ndarray
The training set indices for the split
test : ndarray
The testing set indices for that split
"""
frame = check_frame(frame, copy=False)
indices = np.arange(frame.shape[0])
for test_index in self._iter_test_masks(frame, y):
train_index = indices[np.logical_not(test_index)]
test_index = indices[test_index]
yield list(train_index), list(test_index)
def _iter_test_masks(self, frame, y=None):
"""Generates boolean masks corresponding to the tests set.
Parameters
----------
frame : H2OFrame
The h2o frame to split
y : string, optional (default=None)
The column to stratify.
Returns
-------
test_mask : np.ndarray, shape=(n_samples,)
The indices for the test split
"""
for test_index in self._iter_test_indices(frame, y):
test_mask = np.zeros(frame.shape[0], dtype=np.bool)
test_mask[test_index] = True
yield test_mask
def _iter_test_indices(self, frame, y=None):
raise NotImplementedError(
'this method must be implemented by a subclass')
@abstractmethod
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the cross validator.
"""
pass
def __repr__(self):
return _build_repr(self)
<mask token>
class H2OBaseShuffleSplit(six.with_metaclass(ABCMeta)):
"""Base class for H2OShuffleSplit and H2OStratifiedShuffleSplit. This
is used for ``h2o_train_test_split`` in strategic train/test splits of
H2OFrames. Implementing subclasses should override ``_iter_indices``.
Parameters
----------
n_splits : int, optional (default=2)
The number of folds or splits in the split
test_size : float or int, optional (default=0.1)
The ratio of observations for the test fold
train_size : float or int, optional (default=None)
The ratio of observations for the train fold
random_state : int or RandomState, optional (default=None)
The random state for duplicative purposes.
"""
def __init__(self, n_splits=2, test_size=0.1, train_size=None,
random_state=None):
_validate_shuffle_split_init(test_size, train_size)
self.n_splits = n_splits
self.test_size = test_size
self.train_size = train_size
self.random_state = random_state
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
for train, test in self._iter_indices(frame, y):
yield train, test
@abstractmethod
def _iter_indices(self, frame, y):
"""Abstract method for iterating the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
pass
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the shuffle split.
"""
return self.n_splits
def __repr__(self):
return _build_repr(self)
class H2OShuffleSplit(H2OBaseShuffleSplit):
"""Default shuffle splitter used for ``h2o_train_test_split``.
This shuffle split class will not perform any stratification, and
will simply shuffle indices and split into the number of specified
sub-frames.
"""
def _iter_indices(self, frame, y=None):
"""Iterate the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify. Since this class does
not perform stratification, ``y`` is unused.
Returns
-------
ind_train : np.ndarray, shape=(n_samples,)
The train indices
ind_test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
rng = check_random_state(self.random_state)
for i in range(self.n_splits):
permutation = rng.permutation(n_samples)
ind_test = permutation[:n_test]
ind_train = permutation[n_test:n_test + n_train]
yield ind_train, ind_test
class H2OStratifiedShuffleSplit(H2OBaseShuffleSplit):
"""Shuffle splitter used for ``h2o_train_test_split`` when stratified
option is specified. This shuffle split class will perform stratification.
"""
def _iter_indices(self, frame, y):
"""Iterate the indices with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
Returns
-------
train : np.ndarray, shape=(n_samples,)
The train indices
test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
y = _val_y(y)
target = np.asarray(frame[y].as_data_frame(use_pandas=True)[y].tolist()
)
classes, y_indices = np.unique(target, return_inverse=True)
n_classes = classes.shape[0]
class_counts = bincount(y_indices)
if np.min(class_counts) < 2:
raise ValueError(
'The least populated class in y has only 1 member, which is too few. The minimum number of labels for any class cannot be less than 2.'
)
if n_train < n_classes:
raise ValueError(
'The train_size=%d should be greater than or equal to the number of classes=%d'
% (n_train, n_classes))
if n_test < n_classes:
raise ValueError(
'The test_size=%d should be greater than or equal to the number of classes=%d'
% (n_test, n_classes))
rng = check_random_state(self.random_state)
p_i = class_counts / float(n_samples)
n_i = np.round(n_train * p_i).astype(int)
t_i = np.minimum(class_counts - n_i, np.round(n_test * p_i).astype(int)
)
for _ in range(self.n_splits):
train = []
test = []
for i, class_i in enumerate(classes):
permutation = rng.permutation(class_counts[i])
perm_indices_class_i = np.where(target == class_i)[0][
permutation]
train.extend(perm_indices_class_i[:n_i[i]])
test.extend(perm_indices_class_i[n_i[i]:n_i[i] + t_i[i]])
if len(train) + len(test) < n_train + n_test:
missing_indices = np.where(bincount(train + test, minlength
=len(target)) == 0)[0]
missing_indices = rng.permutation(missing_indices)
n_missing_train = n_train - len(train)
n_missing_test = n_test - len(test)
if n_missing_train > 0:
train.extend(missing_indices[:n_missing_train])
if n_missing_test > 0:
test.extend(missing_indices[-n_missing_test:])
train = rng.permutation(train)
test = rng.permutation(test)
yield train, test
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedShuffleSplit, self).split(frame, y)
class _H2OBaseKFold(six.with_metaclass(ABCMeta, H2OBaseCrossValidator)):
"""Base class for KFold and Stratified KFold.
Parameters
----------
n_folds : int
The number of splits
shuffle : bool
Whether to shuffle indices
random_state : int or RandomState
The random state for the split
"""
@abstractmethod
def __init__(self, n_folds, shuffle, random_state):
if not isinstance(n_folds, numbers.Integral):
raise ValueError(
'n_folds must be of Integral type. %s of type %s was passed' %
(n_folds, type(n_folds)))
n_folds = int(n_folds)
if n_folds <= 1:
raise ValueError(
'k-fold cross-validation requires at least one train/test split by setting n_folds=2 or more'
)
if shuffle not in [True, False]:
raise TypeError(
'shuffle must be True or False. Got %s (type=%s)' % (str(
shuffle), type(shuffle)))
self.n_folds = n_folds
self.shuffle = shuffle
self.random_state = random_state
@overrides(H2OBaseCrossValidator)
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
frame = check_frame(frame, copy=False)
n_obs = frame.shape[0]
if self.n_folds > n_obs:
raise ValueError('Cannot have n_folds greater than n_obs')
for train, test in super(_H2OBaseKFold, self).split(frame, y):
yield train, test
@overrides(H2OBaseCrossValidator)
def get_n_splits(self):
"""Get the number of splits or folds.
Returns
-------
n_folds : int
The number of folds
"""
return self.n_folds
class H2OKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OKFold, self).__init__(n_folds, shuffle, random_state)
@overrides(_H2OBaseKFold)
def _iter_test_indices(self, frame, y=None):
n_obs = frame.shape[0]
indices = np.arange(n_obs)
if self.shuffle:
check_random_state(self.random_state).shuffle(indices)
n_folds = self.n_folds
fold_sizes = n_obs // n_folds * np.ones(n_folds, dtype=np.int)
fold_sizes[:n_obs % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
yield indices[start:stop]
current = stop
class H2OStratifiedKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame with
stratified splits.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OStratifiedKFold, self).__init__(n_folds, shuffle, random_state
)
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedKFold, self).split(frame, y)
def _iter_test_masks(self, frame, y):
test_folds = self._make_test_folds(frame, y)
for i in range(self.n_folds):
yield test_folds == i
def _make_test_folds(self, frame, y):
if self.shuffle:
rng = check_random_state(self.random_state)
else:
rng = self.random_state
y = _val_y(y)
if y is None:
raise ValueError(
'H2OStratifiedKFold requires a target name (got None)')
target = frame[y].as_data_frame(use_pandas=True)[y].values
n_samples = target.shape[0]
unique_y, y_inversed = np.unique(target, return_inverse=True)
y_counts = bincount(y_inversed)
min_labels = np.min(y_counts)
if np.all(self.n_folds > y_counts):
raise ValueError(
'All the n_labels for individual classes are less than %d folds.'
% self.n_folds, Warning)
if self.n_folds > min_labels:
warnings.warn(
'The least populated class in y has only %d members, which is too few. The minimum number of labels for any class cannot be less than n_folds=%d.'
% (min_labels, self.n_folds), Warning)
if SK18:
per_cls_cvs = [KFold(self.n_folds, shuffle=self.shuffle,
random_state=rng).split(np.zeros(max(count, self.n_folds))) for
count in y_counts]
else:
per_cls_cvs = [KFold(max(count, self.n_folds), self.n_folds,
shuffle=self.shuffle, random_state=rng) for count in y_counts]
test_folds = np.zeros(n_samples, dtype=np.int)
for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):
for cls, (_, test_split) in zip(unique_y, per_cls_splits):
cls_test_folds = test_folds[target == cls]
test_split = test_split[test_split < len(cls_test_folds)]
cls_test_folds[test_split] = test_fold_indices
test_folds[target == cls] = cls_test_folds
return test_folds
| <mask token>
class H2OBaseCrossValidator(six.with_metaclass(ABCMeta)):
<mask token>
def __init__(self):
pass
def split(self, frame, y=None):
"""Generate indices to split data into training and test.
Parameters
----------
frame : ``H2OFrame``
The h2o frame to split
y : str, optional (default=None)
The name of the column to stratify, if applicable.
Returns
-------
train : ndarray
The training set indices for the split
test : ndarray
The testing set indices for that split
"""
frame = check_frame(frame, copy=False)
indices = np.arange(frame.shape[0])
for test_index in self._iter_test_masks(frame, y):
train_index = indices[np.logical_not(test_index)]
test_index = indices[test_index]
yield list(train_index), list(test_index)
def _iter_test_masks(self, frame, y=None):
"""Generates boolean masks corresponding to the tests set.
Parameters
----------
frame : H2OFrame
The h2o frame to split
y : string, optional (default=None)
The column to stratify.
Returns
-------
test_mask : np.ndarray, shape=(n_samples,)
The indices for the test split
"""
for test_index in self._iter_test_indices(frame, y):
test_mask = np.zeros(frame.shape[0], dtype=np.bool)
test_mask[test_index] = True
yield test_mask
def _iter_test_indices(self, frame, y=None):
raise NotImplementedError(
'this method must be implemented by a subclass')
@abstractmethod
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the cross validator.
"""
pass
def __repr__(self):
return _build_repr(self)
<mask token>
class H2OBaseShuffleSplit(six.with_metaclass(ABCMeta)):
"""Base class for H2OShuffleSplit and H2OStratifiedShuffleSplit. This
is used for ``h2o_train_test_split`` in strategic train/test splits of
H2OFrames. Implementing subclasses should override ``_iter_indices``.
Parameters
----------
n_splits : int, optional (default=2)
The number of folds or splits in the split
test_size : float or int, optional (default=0.1)
The ratio of observations for the test fold
train_size : float or int, optional (default=None)
The ratio of observations for the train fold
random_state : int or RandomState, optional (default=None)
The random state for duplicative purposes.
"""
def __init__(self, n_splits=2, test_size=0.1, train_size=None,
random_state=None):
_validate_shuffle_split_init(test_size, train_size)
self.n_splits = n_splits
self.test_size = test_size
self.train_size = train_size
self.random_state = random_state
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
for train, test in self._iter_indices(frame, y):
yield train, test
@abstractmethod
def _iter_indices(self, frame, y):
"""Abstract method for iterating the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
pass
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the shuffle split.
"""
return self.n_splits
def __repr__(self):
return _build_repr(self)
class H2OShuffleSplit(H2OBaseShuffleSplit):
"""Default shuffle splitter used for ``h2o_train_test_split``.
This shuffle split class will not perform any stratification, and
will simply shuffle indices and split into the number of specified
sub-frames.
"""
def _iter_indices(self, frame, y=None):
"""Iterate the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify. Since this class does
not perform stratification, ``y`` is unused.
Returns
-------
ind_train : np.ndarray, shape=(n_samples,)
The train indices
ind_test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
rng = check_random_state(self.random_state)
for i in range(self.n_splits):
permutation = rng.permutation(n_samples)
ind_test = permutation[:n_test]
ind_train = permutation[n_test:n_test + n_train]
yield ind_train, ind_test
class H2OStratifiedShuffleSplit(H2OBaseShuffleSplit):
"""Shuffle splitter used for ``h2o_train_test_split`` when stratified
option is specified. This shuffle split class will perform stratification.
"""
def _iter_indices(self, frame, y):
"""Iterate the indices with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
Returns
-------
train : np.ndarray, shape=(n_samples,)
The train indices
test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
y = _val_y(y)
target = np.asarray(frame[y].as_data_frame(use_pandas=True)[y].tolist()
)
classes, y_indices = np.unique(target, return_inverse=True)
n_classes = classes.shape[0]
class_counts = bincount(y_indices)
if np.min(class_counts) < 2:
raise ValueError(
'The least populated class in y has only 1 member, which is too few. The minimum number of labels for any class cannot be less than 2.'
)
if n_train < n_classes:
raise ValueError(
'The train_size=%d should be greater than or equal to the number of classes=%d'
% (n_train, n_classes))
if n_test < n_classes:
raise ValueError(
'The test_size=%d should be greater than or equal to the number of classes=%d'
% (n_test, n_classes))
rng = check_random_state(self.random_state)
p_i = class_counts / float(n_samples)
n_i = np.round(n_train * p_i).astype(int)
t_i = np.minimum(class_counts - n_i, np.round(n_test * p_i).astype(int)
)
for _ in range(self.n_splits):
train = []
test = []
for i, class_i in enumerate(classes):
permutation = rng.permutation(class_counts[i])
perm_indices_class_i = np.where(target == class_i)[0][
permutation]
train.extend(perm_indices_class_i[:n_i[i]])
test.extend(perm_indices_class_i[n_i[i]:n_i[i] + t_i[i]])
if len(train) + len(test) < n_train + n_test:
missing_indices = np.where(bincount(train + test, minlength
=len(target)) == 0)[0]
missing_indices = rng.permutation(missing_indices)
n_missing_train = n_train - len(train)
n_missing_test = n_test - len(test)
if n_missing_train > 0:
train.extend(missing_indices[:n_missing_train])
if n_missing_test > 0:
test.extend(missing_indices[-n_missing_test:])
train = rng.permutation(train)
test = rng.permutation(test)
yield train, test
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedShuffleSplit, self).split(frame, y)
class _H2OBaseKFold(six.with_metaclass(ABCMeta, H2OBaseCrossValidator)):
"""Base class for KFold and Stratified KFold.
Parameters
----------
n_folds : int
The number of splits
shuffle : bool
Whether to shuffle indices
random_state : int or RandomState
The random state for the split
"""
@abstractmethod
def __init__(self, n_folds, shuffle, random_state):
if not isinstance(n_folds, numbers.Integral):
raise ValueError(
'n_folds must be of Integral type. %s of type %s was passed' %
(n_folds, type(n_folds)))
n_folds = int(n_folds)
if n_folds <= 1:
raise ValueError(
'k-fold cross-validation requires at least one train/test split by setting n_folds=2 or more'
)
if shuffle not in [True, False]:
raise TypeError(
'shuffle must be True or False. Got %s (type=%s)' % (str(
shuffle), type(shuffle)))
self.n_folds = n_folds
self.shuffle = shuffle
self.random_state = random_state
@overrides(H2OBaseCrossValidator)
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
frame = check_frame(frame, copy=False)
n_obs = frame.shape[0]
if self.n_folds > n_obs:
raise ValueError('Cannot have n_folds greater than n_obs')
for train, test in super(_H2OBaseKFold, self).split(frame, y):
yield train, test
@overrides(H2OBaseCrossValidator)
def get_n_splits(self):
"""Get the number of splits or folds.
Returns
-------
n_folds : int
The number of folds
"""
return self.n_folds
class H2OKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OKFold, self).__init__(n_folds, shuffle, random_state)
@overrides(_H2OBaseKFold)
def _iter_test_indices(self, frame, y=None):
n_obs = frame.shape[0]
indices = np.arange(n_obs)
if self.shuffle:
check_random_state(self.random_state).shuffle(indices)
n_folds = self.n_folds
fold_sizes = n_obs // n_folds * np.ones(n_folds, dtype=np.int)
fold_sizes[:n_obs % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
yield indices[start:stop]
current = stop
class H2OStratifiedKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame with
stratified splits.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OStratifiedKFold, self).__init__(n_folds, shuffle, random_state
)
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedKFold, self).split(frame, y)
def _iter_test_masks(self, frame, y):
test_folds = self._make_test_folds(frame, y)
for i in range(self.n_folds):
yield test_folds == i
def _make_test_folds(self, frame, y):
if self.shuffle:
rng = check_random_state(self.random_state)
else:
rng = self.random_state
y = _val_y(y)
if y is None:
raise ValueError(
'H2OStratifiedKFold requires a target name (got None)')
target = frame[y].as_data_frame(use_pandas=True)[y].values
n_samples = target.shape[0]
unique_y, y_inversed = np.unique(target, return_inverse=True)
y_counts = bincount(y_inversed)
min_labels = np.min(y_counts)
if np.all(self.n_folds > y_counts):
raise ValueError(
'All the n_labels for individual classes are less than %d folds.'
% self.n_folds, Warning)
if self.n_folds > min_labels:
warnings.warn(
'The least populated class in y has only %d members, which is too few. The minimum number of labels for any class cannot be less than n_folds=%d.'
% (min_labels, self.n_folds), Warning)
if SK18:
per_cls_cvs = [KFold(self.n_folds, shuffle=self.shuffle,
random_state=rng).split(np.zeros(max(count, self.n_folds))) for
count in y_counts]
else:
per_cls_cvs = [KFold(max(count, self.n_folds), self.n_folds,
shuffle=self.shuffle, random_state=rng) for count in y_counts]
test_folds = np.zeros(n_samples, dtype=np.int)
for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):
for cls, (_, test_split) in zip(unique_y, per_cls_splits):
cls_test_folds = test_folds[target == cls]
test_split = test_split[test_split < len(cls_test_folds)]
cls_test_folds[test_split] = test_fold_indices
test_folds[target == cls] = cls_test_folds
return test_folds
| <mask token>
def _build_repr(self):
cls = self.__class__
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
init_signature = signature(init)
if init is object.__init__:
args = []
else:
args = sorted([p.name for p in init_signature.parameters.values() if
p.name != 'self' and p.kind != p.VAR_KEYWORD])
class_name = self.__class__.__name__
params = dict()
for key in args:
warnings.simplefilter('always', DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category == DeprecationWarning:
continue
finally:
warnings.filters.pop(0)
params[key] = value
return '%s(%s)' % (class_name, _pprint(params, offset=len(class_name)))
def check_cv(cv=3):
"""Checks the ``cv`` parameter to determine
whether it's a valid int or H2OBaseCrossValidator.
Parameters
----------
cv : int or H2OBaseCrossValidator, optional (default=3)
The number of folds or the H2OBaseCrossValidator
instance.
Returns
-------
cv : H2OBaseCrossValidator
The instance of H2OBaseCrossValidator
"""
if cv is None:
cv = 3
if isinstance(cv, numbers.Integral):
return H2OKFold(cv)
if not isinstance(cv, H2OBaseCrossValidator):
raise ValueError(
'expected int or instance of H2OBaseCrossValidator but got %s' %
type(cv))
return cv
def h2o_train_test_split(frame, test_size=None, train_size=None,
random_state=None, stratify=None):
"""Splits an H2OFrame into random train and test subsets
Parameters
----------
frame : H2OFrame
The h2o frame to split
test_size : float, int, or None (default=None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the test split. If
int, represents the absolute number of test samples. If None,
the value is automatically set to the complement of the train size.
If train size is also None, test size is set to 0.25
train_size : float, int, or None (default=None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the train split. If
int, represents the absolute number of train samples. If None,
the value is automatically set to the complement of the test size.
random_state : int or RandomState
Pseudo-random number generator state used for random sampling.
stratify : str or None (default=None)
The name of the target on which to stratify the sampling
Returns
-------
out : tuple, shape=(2,)
training_frame : H2OFrame
The training fold split
testing_frame : H2OFrame
The testing fold split
"""
frame = check_frame(frame, copy=False)
if test_size is None and train_size is None:
test_size = 0.25
if stratify is not None:
CVClass = H2OStratifiedShuffleSplit
else:
CVClass = H2OShuffleSplit
cv = CVClass(n_splits=2, test_size=test_size, train_size=train_size,
random_state=random_state)
tr_te_tuples = [(tr, te) for tr, te in cv.split(frame, stratify)][0]
train, test = sorted(list(tr_te_tuples[0])), sorted(list(tr_te_tuples[1]))
out = frame[train, :], frame[test, :]
return out
<mask token>
def _val_y(y):
if isinstance(y, six.string_types):
return str(y)
elif y is None:
return y
raise TypeError('y must be a string. Got %s' % y)
class H2OBaseCrossValidator(six.with_metaclass(ABCMeta)):
"""Base class for H2O cross validation operations.
All implementing subclasses should override ``get_n_splits``
and ``_iter_test_indices``.
"""
def __init__(self):
pass
def split(self, frame, y=None):
"""Generate indices to split data into training and test.
Parameters
----------
frame : ``H2OFrame``
The h2o frame to split
y : str, optional (default=None)
The name of the column to stratify, if applicable.
Returns
-------
train : ndarray
The training set indices for the split
test : ndarray
The testing set indices for that split
"""
frame = check_frame(frame, copy=False)
indices = np.arange(frame.shape[0])
for test_index in self._iter_test_masks(frame, y):
train_index = indices[np.logical_not(test_index)]
test_index = indices[test_index]
yield list(train_index), list(test_index)
def _iter_test_masks(self, frame, y=None):
"""Generates boolean masks corresponding to the tests set.
Parameters
----------
frame : H2OFrame
The h2o frame to split
y : string, optional (default=None)
The column to stratify.
Returns
-------
test_mask : np.ndarray, shape=(n_samples,)
The indices for the test split
"""
for test_index in self._iter_test_indices(frame, y):
test_mask = np.zeros(frame.shape[0], dtype=np.bool)
test_mask[test_index] = True
yield test_mask
def _iter_test_indices(self, frame, y=None):
raise NotImplementedError(
'this method must be implemented by a subclass')
@abstractmethod
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the cross validator.
"""
pass
def __repr__(self):
return _build_repr(self)
def _validate_shuffle_split_init(test_size, train_size):
"""Validation helper to check the test_size and train_size at init"""
if test_size is None and train_size is None:
raise ValueError('test_size and train_size can not both be None')
if test_size is not None:
if np.asarray(test_size).dtype.kind == 'f':
if test_size >= 1.0:
raise ValueError(
'test_size=%f should be smaller than 1.0 or be an integer'
% test_size)
elif np.asarray(test_size).dtype.kind != 'i':
raise ValueError('Invalid value for test_size: %r' % test_size)
if train_size is not None:
if np.asarray(train_size).dtype.kind == 'f':
if train_size >= 1.0:
raise ValueError(
'train_size=%f should be smaller than 1.0 or be an integer'
% test_size)
elif np.asarray(test_size
).dtype.kind == 'f' and train_size + test_size > 1.0:
raise ValueError(
'The sum of test_size and train_size = %fshould be smaller than 1.0. Reduce test_size and/or train_size.'
% (train_size + test_size))
elif np.asarray(train_size).dtype.kind != 'i':
raise ValueError('Invalid value for train_size: %r' % train_size)
def _validate_shuffle_split(n_samples, test_size, train_size):
if test_size is not None and np.asarray(test_size
).dtype.kind == 'i' and test_size >= n_samples:
raise ValueError(
'test_size=%d should be smaller than the number of samples %d' %
(test_size, n_samples))
if train_size is not None and np.asarray(train_size
).dtype.kind == 'i' and train_size >= n_samples:
raise ValueError(
'train_size=%d should be smaller than the number of samples %d' %
(train_size, n_samples))
if np.asarray(test_size).dtype.kind == 'f':
n_test = ceil(test_size * n_samples)
elif np.asarray(test_size).dtype.kind == 'i':
n_test = float(test_size)
if train_size is None:
n_train = n_samples - n_test
elif np.asarray(train_size).dtype.kind == 'f':
n_train = floor(train_size * n_samples)
else:
n_train = float(train_size)
if test_size is None:
n_test = n_samples - n_train
if n_train + n_test > n_samples:
raise ValueError(
'The sum of train_size and test_size=%d, should be smaller than the number of samples %d. Reduce test_size and/or train_size.'
% (n_train + n_test, n_samples))
return int(n_train), int(n_test)
class H2OBaseShuffleSplit(six.with_metaclass(ABCMeta)):
"""Base class for H2OShuffleSplit and H2OStratifiedShuffleSplit. This
is used for ``h2o_train_test_split`` in strategic train/test splits of
H2OFrames. Implementing subclasses should override ``_iter_indices``.
Parameters
----------
n_splits : int, optional (default=2)
The number of folds or splits in the split
test_size : float or int, optional (default=0.1)
The ratio of observations for the test fold
train_size : float or int, optional (default=None)
The ratio of observations for the train fold
random_state : int or RandomState, optional (default=None)
The random state for duplicative purposes.
"""
def __init__(self, n_splits=2, test_size=0.1, train_size=None,
random_state=None):
_validate_shuffle_split_init(test_size, train_size)
self.n_splits = n_splits
self.test_size = test_size
self.train_size = train_size
self.random_state = random_state
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
for train, test in self._iter_indices(frame, y):
yield train, test
@abstractmethod
def _iter_indices(self, frame, y):
"""Abstract method for iterating the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
pass
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the shuffle split.
"""
return self.n_splits
def __repr__(self):
return _build_repr(self)
class H2OShuffleSplit(H2OBaseShuffleSplit):
"""Default shuffle splitter used for ``h2o_train_test_split``.
This shuffle split class will not perform any stratification, and
will simply shuffle indices and split into the number of specified
sub-frames.
"""
def _iter_indices(self, frame, y=None):
"""Iterate the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify. Since this class does
not perform stratification, ``y`` is unused.
Returns
-------
ind_train : np.ndarray, shape=(n_samples,)
The train indices
ind_test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
rng = check_random_state(self.random_state)
for i in range(self.n_splits):
permutation = rng.permutation(n_samples)
ind_test = permutation[:n_test]
ind_train = permutation[n_test:n_test + n_train]
yield ind_train, ind_test
class H2OStratifiedShuffleSplit(H2OBaseShuffleSplit):
"""Shuffle splitter used for ``h2o_train_test_split`` when stratified
option is specified. This shuffle split class will perform stratification.
"""
def _iter_indices(self, frame, y):
"""Iterate the indices with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
Returns
-------
train : np.ndarray, shape=(n_samples,)
The train indices
test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
y = _val_y(y)
target = np.asarray(frame[y].as_data_frame(use_pandas=True)[y].tolist()
)
classes, y_indices = np.unique(target, return_inverse=True)
n_classes = classes.shape[0]
class_counts = bincount(y_indices)
if np.min(class_counts) < 2:
raise ValueError(
'The least populated class in y has only 1 member, which is too few. The minimum number of labels for any class cannot be less than 2.'
)
if n_train < n_classes:
raise ValueError(
'The train_size=%d should be greater than or equal to the number of classes=%d'
% (n_train, n_classes))
if n_test < n_classes:
raise ValueError(
'The test_size=%d should be greater than or equal to the number of classes=%d'
% (n_test, n_classes))
rng = check_random_state(self.random_state)
p_i = class_counts / float(n_samples)
n_i = np.round(n_train * p_i).astype(int)
t_i = np.minimum(class_counts - n_i, np.round(n_test * p_i).astype(int)
)
for _ in range(self.n_splits):
train = []
test = []
for i, class_i in enumerate(classes):
permutation = rng.permutation(class_counts[i])
perm_indices_class_i = np.where(target == class_i)[0][
permutation]
train.extend(perm_indices_class_i[:n_i[i]])
test.extend(perm_indices_class_i[n_i[i]:n_i[i] + t_i[i]])
if len(train) + len(test) < n_train + n_test:
missing_indices = np.where(bincount(train + test, minlength
=len(target)) == 0)[0]
missing_indices = rng.permutation(missing_indices)
n_missing_train = n_train - len(train)
n_missing_test = n_test - len(test)
if n_missing_train > 0:
train.extend(missing_indices[:n_missing_train])
if n_missing_test > 0:
test.extend(missing_indices[-n_missing_test:])
train = rng.permutation(train)
test = rng.permutation(test)
yield train, test
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedShuffleSplit, self).split(frame, y)
class _H2OBaseKFold(six.with_metaclass(ABCMeta, H2OBaseCrossValidator)):
"""Base class for KFold and Stratified KFold.
Parameters
----------
n_folds : int
The number of splits
shuffle : bool
Whether to shuffle indices
random_state : int or RandomState
The random state for the split
"""
@abstractmethod
def __init__(self, n_folds, shuffle, random_state):
if not isinstance(n_folds, numbers.Integral):
raise ValueError(
'n_folds must be of Integral type. %s of type %s was passed' %
(n_folds, type(n_folds)))
n_folds = int(n_folds)
if n_folds <= 1:
raise ValueError(
'k-fold cross-validation requires at least one train/test split by setting n_folds=2 or more'
)
if shuffle not in [True, False]:
raise TypeError(
'shuffle must be True or False. Got %s (type=%s)' % (str(
shuffle), type(shuffle)))
self.n_folds = n_folds
self.shuffle = shuffle
self.random_state = random_state
@overrides(H2OBaseCrossValidator)
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
frame = check_frame(frame, copy=False)
n_obs = frame.shape[0]
if self.n_folds > n_obs:
raise ValueError('Cannot have n_folds greater than n_obs')
for train, test in super(_H2OBaseKFold, self).split(frame, y):
yield train, test
@overrides(H2OBaseCrossValidator)
def get_n_splits(self):
"""Get the number of splits or folds.
Returns
-------
n_folds : int
The number of folds
"""
return self.n_folds
class H2OKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OKFold, self).__init__(n_folds, shuffle, random_state)
@overrides(_H2OBaseKFold)
def _iter_test_indices(self, frame, y=None):
n_obs = frame.shape[0]
indices = np.arange(n_obs)
if self.shuffle:
check_random_state(self.random_state).shuffle(indices)
n_folds = self.n_folds
fold_sizes = n_obs // n_folds * np.ones(n_folds, dtype=np.int)
fold_sizes[:n_obs % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
yield indices[start:stop]
current = stop
class H2OStratifiedKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame with
stratified splits.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OStratifiedKFold, self).__init__(n_folds, shuffle, random_state
)
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedKFold, self).split(frame, y)
def _iter_test_masks(self, frame, y):
test_folds = self._make_test_folds(frame, y)
for i in range(self.n_folds):
yield test_folds == i
def _make_test_folds(self, frame, y):
if self.shuffle:
rng = check_random_state(self.random_state)
else:
rng = self.random_state
y = _val_y(y)
if y is None:
raise ValueError(
'H2OStratifiedKFold requires a target name (got None)')
target = frame[y].as_data_frame(use_pandas=True)[y].values
n_samples = target.shape[0]
unique_y, y_inversed = np.unique(target, return_inverse=True)
y_counts = bincount(y_inversed)
min_labels = np.min(y_counts)
if np.all(self.n_folds > y_counts):
raise ValueError(
'All the n_labels for individual classes are less than %d folds.'
% self.n_folds, Warning)
if self.n_folds > min_labels:
warnings.warn(
'The least populated class in y has only %d members, which is too few. The minimum number of labels for any class cannot be less than n_folds=%d.'
% (min_labels, self.n_folds), Warning)
if SK18:
per_cls_cvs = [KFold(self.n_folds, shuffle=self.shuffle,
random_state=rng).split(np.zeros(max(count, self.n_folds))) for
count in y_counts]
else:
per_cls_cvs = [KFold(max(count, self.n_folds), self.n_folds,
shuffle=self.shuffle, random_state=rng) for count in y_counts]
test_folds = np.zeros(n_samples, dtype=np.int)
for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):
for cls, (_, test_split) in zip(unique_y, per_cls_splits):
cls_test_folds = test_folds[target == cls]
test_split = test_split[test_split < len(cls_test_folds)]
cls_test_folds[test_split] = test_fold_indices
test_folds[target == cls] = cls_test_folds
return test_folds
| from __future__ import division, print_function, absolute_import
import numbers
import warnings
from abc import ABCMeta, abstractmethod
import numpy as np
from .base import check_frame
from skutil.base import overrides
from sklearn.externals import six
from sklearn.base import _pprint
from sklearn.utils.fixes import signature, bincount
from sklearn.utils import check_random_state
from math import ceil, floor
try:
from h2o import H2OEstimator
except ImportError:
from h2o.estimators.estimator_base import H2OEstimator
try:
from sklearn.model_selection import KFold
SK18 = True
except ImportError:
from sklearn.cross_validation import KFold
SK18 = False
__all__ = [
'check_cv',
'h2o_train_test_split',
'H2OKFold',
'H2OShuffleSplit',
'H2OStratifiedKFold',
'H2OStratifiedShuffleSplit'
]
def _build_repr(self):
# XXX This is copied from sklearn.BaseEstimator's get_params
cls = self.__class__
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
init_signature = signature(init)
if init is object.__init__:
args = []
else:
args = sorted([p.name for p in init_signature.parameters.values()
if p.name != 'self' and p.kind != p.VAR_KEYWORD])
class_name = self.__class__.__name__
params = dict()
for key in args:
warnings.simplefilter("always", DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category == DeprecationWarning:
continue
finally:
warnings.filters.pop(0)
params[key] = value
return '%s(%s)' % (class_name, _pprint(params, offset=len(class_name)))
def check_cv(cv=3):
"""Checks the ``cv`` parameter to determine
whether it's a valid int or H2OBaseCrossValidator.
Parameters
----------
cv : int or H2OBaseCrossValidator, optional (default=3)
The number of folds or the H2OBaseCrossValidator
instance.
Returns
-------
cv : H2OBaseCrossValidator
The instance of H2OBaseCrossValidator
"""
if cv is None:
cv = 3
if isinstance(cv, numbers.Integral):
return H2OKFold(cv)
if not isinstance(cv, H2OBaseCrossValidator):
raise ValueError('expected int or instance of '
'H2OBaseCrossValidator but got %s'
% type(cv))
return cv
def h2o_train_test_split(frame, test_size=None, train_size=None, random_state=None, stratify=None):
"""Splits an H2OFrame into random train and test subsets
Parameters
----------
frame : H2OFrame
The h2o frame to split
test_size : float, int, or None (default=None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the test split. If
int, represents the absolute number of test samples. If None,
the value is automatically set to the complement of the train size.
If train size is also None, test size is set to 0.25
train_size : float, int, or None (default=None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the train split. If
int, represents the absolute number of train samples. If None,
the value is automatically set to the complement of the test size.
random_state : int or RandomState
Pseudo-random number generator state used for random sampling.
stratify : str or None (default=None)
The name of the target on which to stratify the sampling
Returns
-------
out : tuple, shape=(2,)
training_frame : H2OFrame
The training fold split
testing_frame : H2OFrame
The testing fold split
"""
frame = check_frame(frame, copy=False)
if test_size is None and train_size is None:
test_size = 0.25
if stratify is not None:
CVClass = H2OStratifiedShuffleSplit
else:
CVClass = H2OShuffleSplit
cv = CVClass(n_splits=2,
test_size=test_size,
train_size=train_size,
random_state=random_state)
# for the h2o one, we only need iter 0
tr_te_tuples = [(tr, te) for tr, te in cv.split(frame, stratify)][0]
# h2o "doesn't reorder rows" so we need to keep these sorted...
train, test = sorted(list(tr_te_tuples[0])), sorted(list(tr_te_tuples[1]))
out = (
frame[train, :],
frame[test, :]
)
return out
# Avoid a pb with nosetests...
h2o_train_test_split.__test__ = False
def _val_y(y):
if isinstance(y, six.string_types):
return str(y)
elif y is None:
return y
raise TypeError('y must be a string. Got %s' % y)
class H2OBaseCrossValidator(six.with_metaclass(ABCMeta)):
"""Base class for H2O cross validation operations.
All implementing subclasses should override ``get_n_splits``
and ``_iter_test_indices``.
"""
def __init__(self):
pass
def split(self, frame, y=None):
"""Generate indices to split data into training and test.
Parameters
----------
frame : ``H2OFrame``
The h2o frame to split
y : str, optional (default=None)
The name of the column to stratify, if applicable.
Returns
-------
train : ndarray
The training set indices for the split
test : ndarray
The testing set indices for that split
"""
frame = check_frame(frame, copy=False)
indices = np.arange(frame.shape[0])
for test_index in self._iter_test_masks(frame, y):
train_index = indices[np.logical_not(test_index)]
test_index = indices[test_index]
# h2o can't handle anything but lists...
yield list(train_index), list(test_index)
def _iter_test_masks(self, frame, y=None):
"""Generates boolean masks corresponding to the tests set.
Parameters
----------
frame : H2OFrame
The h2o frame to split
y : string, optional (default=None)
The column to stratify.
Returns
-------
test_mask : np.ndarray, shape=(n_samples,)
The indices for the test split
"""
for test_index in self._iter_test_indices(frame, y):
test_mask = np.zeros(frame.shape[0], dtype=np.bool)
test_mask[test_index] = True
yield test_mask
def _iter_test_indices(self, frame, y=None):
raise NotImplementedError('this method must be implemented by a subclass')
@abstractmethod
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the cross validator.
"""
pass
def __repr__(self):
return _build_repr(self)
def _validate_shuffle_split_init(test_size, train_size):
"""Validation helper to check the test_size and train_size at init"""
if test_size is None and train_size is None:
raise ValueError('test_size and train_size can not both be None')
if test_size is not None:
if np.asarray(test_size).dtype.kind == 'f':
if test_size >= 1.:
raise ValueError(
'test_size=%f should be smaller '
'than 1.0 or be an integer' % test_size)
elif np.asarray(test_size).dtype.kind != 'i':
raise ValueError('Invalid value for test_size: %r' % test_size)
if train_size is not None:
if np.asarray(train_size).dtype.kind == 'f':
if train_size >= 1.:
raise ValueError(
'train_size=%f should be smaller '
'than 1.0 or be an integer' % test_size)
elif (np.asarray(test_size).dtype.kind == 'f' and
(train_size + test_size) > 1.):
raise ValueError('The sum of test_size and train_size = %f'
'should be smaller than 1.0. Reduce test_size '
'and/or train_size.' % (train_size + test_size))
elif np.asarray(train_size).dtype.kind != 'i':
raise ValueError('Invalid value for train_size: %r' % train_size)
def _validate_shuffle_split(n_samples, test_size, train_size):
if test_size is not None and np.asarray(test_size).dtype.kind == 'i' and test_size >= n_samples:
raise ValueError('test_size=%d should be smaller '
'than the number of samples %d' % (test_size, n_samples))
if train_size is not None and np.asarray(train_size).dtype.kind == 'i' and train_size >= n_samples:
raise ValueError('train_size=%d should be smaller '
'than the number of samples %d' % (train_size, n_samples))
if np.asarray(test_size).dtype.kind == 'f':
n_test = ceil(test_size * n_samples)
elif np.asarray(test_size).dtype.kind == 'i':
n_test = float(test_size)
if train_size is None:
n_train = n_samples - n_test
elif np.asarray(train_size).dtype.kind == 'f':
n_train = floor(train_size * n_samples)
else:
n_train = float(train_size)
if test_size is None:
n_test = n_samples - n_train
if n_train + n_test > n_samples:
raise ValueError('The sum of train_size and test_size=%d, '
'should be smaller than the number of '
'samples %d. Reduce test_size and/or '
'train_size.' % (n_train + n_test, n_samples))
return int(n_train), int(n_test)
class H2OBaseShuffleSplit(six.with_metaclass(ABCMeta)):
"""Base class for H2OShuffleSplit and H2OStratifiedShuffleSplit. This
is used for ``h2o_train_test_split`` in strategic train/test splits of
H2OFrames. Implementing subclasses should override ``_iter_indices``.
Parameters
----------
n_splits : int, optional (default=2)
The number of folds or splits in the split
test_size : float or int, optional (default=0.1)
The ratio of observations for the test fold
train_size : float or int, optional (default=None)
The ratio of observations for the train fold
random_state : int or RandomState, optional (default=None)
The random state for duplicative purposes.
"""
def __init__(self, n_splits=2, test_size=0.1, train_size=None, random_state=None):
_validate_shuffle_split_init(test_size, train_size)
self.n_splits = n_splits
self.test_size = test_size
self.train_size = train_size
self.random_state = random_state
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
for train, test in self._iter_indices(frame, y):
yield train, test
@abstractmethod
def _iter_indices(self, frame, y):
"""Abstract method for iterating the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
pass
def get_n_splits(self):
"""Get the number of splits or folds for
this instance of the shuffle split.
"""
return self.n_splits
def __repr__(self):
return _build_repr(self)
class H2OShuffleSplit(H2OBaseShuffleSplit):
"""Default shuffle splitter used for ``h2o_train_test_split``.
This shuffle split class will not perform any stratification, and
will simply shuffle indices and split into the number of specified
sub-frames.
"""
def _iter_indices(self, frame, y=None):
"""Iterate the indices.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify. Since this class does
not perform stratification, ``y`` is unused.
Returns
-------
ind_train : np.ndarray, shape=(n_samples,)
The train indices
ind_test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size, self.train_size)
rng = check_random_state(self.random_state)
for i in range(self.n_splits):
permutation = rng.permutation(n_samples)
ind_test = permutation[:n_test]
ind_train = permutation[n_test:(n_test + n_train)]
yield ind_train, ind_test
class H2OStratifiedShuffleSplit(H2OBaseShuffleSplit):
"""Shuffle splitter used for ``h2o_train_test_split`` when stratified
option is specified. This shuffle split class will perform stratification.
"""
def _iter_indices(self, frame, y):
"""Iterate the indices with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
Returns
-------
train : np.ndarray, shape=(n_samples,)
The train indices
test : np.ndarray, shape=(n_samples,)
The test indices
"""
n_samples = frame.shape[0]
n_train, n_test = _validate_shuffle_split(n_samples,
self.test_size, self.train_size)
# need to validate y...
y = _val_y(y)
target = np.asarray(frame[y].as_data_frame(use_pandas=True)[y].tolist())
classes, y_indices = np.unique(target, return_inverse=True)
n_classes = classes.shape[0]
class_counts = bincount(y_indices)
if np.min(class_counts) < 2:
raise ValueError('The least populated class in y has only 1 '
'member, which is too few. The minimum number of labels '
'for any class cannot be less than 2.')
if n_train < n_classes:
raise ValueError('The train_size=%d should be greater than or '
'equal to the number of classes=%d' % (n_train, n_classes))
if n_test < n_classes:
raise ValueError('The test_size=%d should be greater than or '
'equal to the number of classes=%d' % (n_test, n_classes))
rng = check_random_state(self.random_state)
p_i = class_counts / float(n_samples)
n_i = np.round(n_train * p_i).astype(int)
t_i = np.minimum(class_counts - n_i, np.round(n_test * p_i).astype(int))
for _ in range(self.n_splits):
train = []
test = []
for i, class_i in enumerate(classes):
permutation = rng.permutation(class_counts[i])
perm_indices_class_i = np.where((target == class_i))[0][permutation]
train.extend(perm_indices_class_i[:n_i[i]])
test.extend(perm_indices_class_i[n_i[i]:n_i[i] + t_i[i]])
# Might end up here with less samples in train and test than we asked
# for, due to rounding errors.
if len(train) + len(test) < n_train + n_test:
missing_indices = np.where(bincount(train + test, minlength=len(target)) == 0)[0]
missing_indices = rng.permutation(missing_indices)
n_missing_train = n_train - len(train)
n_missing_test = n_test - len(test)
if n_missing_train > 0:
train.extend(missing_indices[:n_missing_train])
if n_missing_test > 0:
test.extend(missing_indices[-n_missing_test:])
train = rng.permutation(train)
test = rng.permutation(test)
yield train, test
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedShuffleSplit, self).split(frame, y)
class _H2OBaseKFold(six.with_metaclass(ABCMeta, H2OBaseCrossValidator)):
"""Base class for KFold and Stratified KFold.
Parameters
----------
n_folds : int
The number of splits
shuffle : bool
Whether to shuffle indices
random_state : int or RandomState
The random state for the split
"""
@abstractmethod
def __init__(self, n_folds, shuffle, random_state):
if not isinstance(n_folds, numbers.Integral):
raise ValueError('n_folds must be of Integral type. '
'%s of type %s was passed' % (n_folds, type(n_folds)))
n_folds = int(n_folds)
if n_folds <= 1:
raise ValueError('k-fold cross-validation requires at least one '
'train/test split by setting n_folds=2 or more')
if shuffle not in [True, False]:
raise TypeError('shuffle must be True or False. Got %s (type=%s)'
% (str(shuffle), type(shuffle)))
self.n_folds = n_folds
self.shuffle = shuffle
self.random_state = random_state
@overrides(H2OBaseCrossValidator)
def split(self, frame, y=None):
"""Split the frame.
Parameters
----------
frame : H2OFrame
The frame to split
y : string, optional (default=None)
The column to stratify.
"""
frame = check_frame(frame, copy=False)
n_obs = frame.shape[0]
if self.n_folds > n_obs:
raise ValueError('Cannot have n_folds greater than n_obs')
for train, test in super(_H2OBaseKFold, self).split(frame, y):
yield train, test
@overrides(H2OBaseCrossValidator)
def get_n_splits(self):
"""Get the number of splits or folds.
Returns
-------
n_folds : int
The number of folds
"""
return self.n_folds
class H2OKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OKFold, self).__init__(n_folds, shuffle, random_state)
@overrides(_H2OBaseKFold)
def _iter_test_indices(self, frame, y=None):
n_obs = frame.shape[0]
indices = np.arange(n_obs)
if self.shuffle:
check_random_state(self.random_state).shuffle(indices)
n_folds = self.n_folds
fold_sizes = (n_obs // n_folds) * np.ones(n_folds, dtype=np.int)
fold_sizes[:n_obs % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
yield indices[start:stop]
current = stop
class H2OStratifiedKFold(_H2OBaseKFold):
"""K-folds cross-validator for an H2OFrame with
stratified splits.
Parameters
----------
n_folds : int, optional (default=3)
The number of splits
shuffle : bool, optional (default=False)
Whether to shuffle indices
random_state : int or RandomState, optional (default=None)
The random state for the split
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(H2OStratifiedKFold, self).__init__(n_folds, shuffle, random_state)
def split(self, frame, y):
"""Split the frame with stratification.
Parameters
----------
frame : H2OFrame
The frame to split
y : string
The column to stratify.
"""
return super(H2OStratifiedKFold, self).split(frame, y)
def _iter_test_masks(self, frame, y):
test_folds = self._make_test_folds(frame, y)
for i in range(self.n_folds):
yield test_folds == i
def _make_test_folds(self, frame, y):
if self.shuffle:
rng = check_random_state(self.random_state)
else:
rng = self.random_state
# validate that it's a string
y = _val_y(y) # gets a string back or None
if y is None:
raise ValueError('H2OStratifiedKFold requires a target name (got None)')
target = frame[y].as_data_frame(use_pandas=True)[y].values
n_samples = target.shape[0]
unique_y, y_inversed = np.unique(target, return_inverse=True)
y_counts = bincount(y_inversed)
min_labels = np.min(y_counts)
if np.all(self.n_folds > y_counts):
raise ValueError(('All the n_labels for individual classes'
' are less than %d folds.'
% self.n_folds), Warning)
if self.n_folds > min_labels:
warnings.warn(('The least populated class in y has only %d'
' members, which is too few. The minimum'
' number of labels for any class cannot'
' be less than n_folds=%d.'
% (min_labels, self.n_folds)), Warning)
# NOTE FROM SKLEARN:
# pre-assign each sample to a test fold index using individual KFold
# splitting strategies for each class so as to respect the balance of
# classes
# NOTE: Passing the data corresponding to ith class say X[y==class_i]
# will break when the data is not 100% stratifiable for all classes.
# So we pass np.zeroes(max(c, n_folds)) as data to the KFold.
# Remember, however that we might be using the old-fold KFold which doesn't
# have a split method...
if SK18:
per_cls_cvs = [
KFold(self.n_folds, # using sklearn's KFold here
shuffle=self.shuffle,
random_state=rng).split(np.zeros(max(count, self.n_folds)))
for count in y_counts
]
else:
per_cls_cvs = [
KFold(max(count, self.n_folds), # using sklearn's KFold here
self.n_folds,
shuffle=self.shuffle,
random_state=rng)
for count in y_counts
]
test_folds = np.zeros(n_samples, dtype=np.int)
for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):
for cls, (_, test_split) in zip(unique_y, per_cls_splits):
cls_test_folds = test_folds[target == cls]
# the test split can be too big because we used
# KFold(...).split(X[:max(c, n_folds)]) when data is not 100%
# stratifiable for all the classes
# (we use a warning instead of raising an exception)
# If this is the case, let's trim it:
test_split = test_split[test_split < len(cls_test_folds)]
cls_test_folds[test_split] = test_fold_indices
test_folds[target == cls] = cls_test_folds
return test_folds
| [
33,
35,
36,
43,
47
] |
7 | 41cfd558824b6561114a48a694b1e6e6a7cb8c05 | <mask token>
| <mask token>
def app(page):
if not login_status():
title_container = st.empty()
remail_input_container = st.empty()
rpw_input_container = st.empty()
rregister_button_container = st.empty()
email = remail_input_container.text_input('Email ')
password = rpw_input_container.text_input('Password ', type='password')
rregister_button = rregister_button_container.button('Register')
if rregister_button:
title_container.empty()
remail_input_container.empty()
rpw_input_container.empty()
rregister_button_container.empty()
login()
page.app()
st.experimental_rerun()
| import streamlit as st
from streamlit.components.v1 import components
from streamlit.report_thread import get_report_ctx
from util.session import *
from multipage import MultiPage
from pages import register
def app(page):
if not login_status():
title_container = st.empty()
remail_input_container = st.empty()
rpw_input_container = st.empty()
rregister_button_container = st.empty()
email = remail_input_container.text_input('Email ')
password = rpw_input_container.text_input('Password ', type='password')
rregister_button = rregister_button_container.button('Register')
if rregister_button:
title_container.empty()
remail_input_container.empty()
rpw_input_container.empty()
rregister_button_container.empty()
login()
page.app()
st.experimental_rerun()
| import streamlit as st
from streamlit.components.v1 import components
from streamlit.report_thread import get_report_ctx
from util.session import *
from multipage import MultiPage
from pages import register
def app(page):
if not login_status():
title_container = st.empty()
remail_input_container = st.empty()
rpw_input_container = st.empty()
rregister_button_container = st.empty()
# title_container.write("Register")
email = remail_input_container.text_input("Email ")
password = rpw_input_container.text_input("Password ", type="password")
rregister_button = rregister_button_container.button('Register')
if rregister_button:
title_container.empty()
remail_input_container.empty()
rpw_input_container.empty()
rregister_button_container.empty()
login()
page.app()
st.experimental_rerun() | null | [
0,
1,
2,
3
] |
8 | f2bb44600f011a205c71985ad94c18f7e058634f | <mask token>
def from_url(url: str) ->Image.Image:
api_response = requests.get(url).content
response_bytes = BytesIO(api_response)
return Image.open(response_bytes)
def from_file(path: str) ->Union[Image.Image, None]:
if os.path.exists(path):
return Image.open(path)
else:
return None
<mask token>
| <mask token>
def get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str],
Image.Image]:
def _apply(filepath: str, url: str) ->Image.Image:
img = from_file(filepath)
if img is None:
img = from_url(url)
img.save(filepath, img_format)
return img.convert('RGB')
return _apply
def from_url(url: str) ->Image.Image:
api_response = requests.get(url).content
response_bytes = BytesIO(api_response)
return Image.open(response_bytes)
def from_file(path: str) ->Union[Image.Image, None]:
if os.path.exists(path):
return Image.open(path)
else:
return None
<mask token>
| <mask token>
def get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str],
Image.Image]:
def _apply(filepath: str, url: str) ->Image.Image:
img = from_file(filepath)
if img is None:
img = from_url(url)
img.save(filepath, img_format)
return img.convert('RGB')
return _apply
def from_url(url: str) ->Image.Image:
api_response = requests.get(url).content
response_bytes = BytesIO(api_response)
return Image.open(response_bytes)
def from_file(path: str) ->Union[Image.Image, None]:
if os.path.exists(path):
return Image.open(path)
else:
return None
def load_metadata(path: str, cols: Iterable[int], class_cols: Collection[
int]=tuple(), valid_only: bool=True, **reader_args) ->Tuple[List, int,
List, List[Dict[str, int]], List[Dict[int, str]], int]:
metadata = []
class_to_index: List[Dict[str, int]] = [{}] * len(class_cols)
index_to_class: List[Dict[int, str]] = [{}] * len(class_cols)
next_indices = [0] * len(class_cols)
with open(path, 'r', newline='', encoding='utf8') as metadata_file:
reader = csv.reader(metadata_file, **reader_args)
headers = next(reader)
for row in reader:
if len(row) != 0:
metadatum = [row[c] for c in cols]
for c, class_col in enumerate(class_cols):
if not row[class_col] in class_to_index[c]:
class_to_index[c][row[class_col]] = next_indices[c]
index_to_class[c][next_indices[c]] = row[class_col]
next_indices[c] += 1
if valid_only and '' in metadatum:
continue
metadata.append(metadatum)
len_metadata = len(metadata)
num_classes = 0 if len(next_indices) == 0 else next_indices[-1]
return (metadata, len_metadata, headers, class_to_index, index_to_class,
num_classes)
| import os
import requests
from PIL import Image
from io import BytesIO
import csv
from typing import Iterable, List, Tuple, Dict, Callable, Union, Collection
def get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str],
Image.Image]:
def _apply(filepath: str, url: str) ->Image.Image:
img = from_file(filepath)
if img is None:
img = from_url(url)
img.save(filepath, img_format)
return img.convert('RGB')
return _apply
def from_url(url: str) ->Image.Image:
api_response = requests.get(url).content
response_bytes = BytesIO(api_response)
return Image.open(response_bytes)
def from_file(path: str) ->Union[Image.Image, None]:
if os.path.exists(path):
return Image.open(path)
else:
return None
def load_metadata(path: str, cols: Iterable[int], class_cols: Collection[
int]=tuple(), valid_only: bool=True, **reader_args) ->Tuple[List, int,
List, List[Dict[str, int]], List[Dict[int, str]], int]:
metadata = []
class_to_index: List[Dict[str, int]] = [{}] * len(class_cols)
index_to_class: List[Dict[int, str]] = [{}] * len(class_cols)
next_indices = [0] * len(class_cols)
with open(path, 'r', newline='', encoding='utf8') as metadata_file:
reader = csv.reader(metadata_file, **reader_args)
headers = next(reader)
for row in reader:
if len(row) != 0:
metadatum = [row[c] for c in cols]
for c, class_col in enumerate(class_cols):
if not row[class_col] in class_to_index[c]:
class_to_index[c][row[class_col]] = next_indices[c]
index_to_class[c][next_indices[c]] = row[class_col]
next_indices[c] += 1
if valid_only and '' in metadatum:
continue
metadata.append(metadatum)
len_metadata = len(metadata)
num_classes = 0 if len(next_indices) == 0 else next_indices[-1]
return (metadata, len_metadata, headers, class_to_index, index_to_class,
num_classes)
| import os
import requests
from PIL import Image
from io import BytesIO
import csv
from typing import Iterable, List, Tuple, Dict, Callable, Union, Collection
# pull the image from the api endpoint and save it if we don't have it, else load it from disk
def get_img_from_file_or_url(img_format: str = 'JPEG') -> Callable[[str, str], Image.Image]:
def _apply(filepath: str, url: str) -> Image.Image:
img = from_file(filepath)
if img is None:
img = from_url(url)
img.save(filepath, img_format)
return img.convert('RGB') # convert to rgb if not already (eg if grayscale)
return _apply
def from_url(url: str) -> Image.Image:
api_response = requests.get(url).content
response_bytes = BytesIO(api_response)
return Image.open(response_bytes)
def from_file(path: str) -> Union[Image.Image, None]:
if os.path.exists(path):
return Image.open(path)
else:
return None
def load_metadata(path: str, cols: Iterable[int], class_cols: Collection[int] = tuple(), valid_only: bool = True, **reader_args)\
-> Tuple[List, int, List, List[Dict[str, int]], List[Dict[int, str]], int]:
metadata = []
# one dict for each class col
class_to_index: List[Dict[str, int]] = [{}] * len(class_cols)
index_to_class: List[Dict[int, str]] = [{}] * len(class_cols)
next_indices = [0] * len(class_cols) # next index for a new class value
with open(path, 'r', newline='', encoding="utf8") as metadata_file:
reader = csv.reader(metadata_file, **reader_args)
headers = next(reader)
for row in reader:
if len(row) != 0:
metadatum = [row[c] for c in cols]
# for all class cols, add their vals to the class_to_index and index_to_class dicts if not there already
for c, class_col in enumerate(class_cols):
if not row[class_col] in class_to_index[c]:
class_to_index[c][row[class_col]] = next_indices[c]
index_to_class[c][next_indices[c]] = row[class_col]
next_indices[c] += 1
if valid_only and '' in metadatum:
continue
metadata.append(metadatum)
len_metadata = len(metadata)
num_classes = 0 if len(next_indices) == 0 else next_indices[-1]
# split off the headers
return metadata, len_metadata, headers, class_to_index, index_to_class, num_classes
| [
2,
3,
4,
5,
6
] |
9 | 302605d8bb45b1529742bf9441d476f0276085b9 | "<mask token>\n\n\nclass MyMainWindow(QMainWindow):\n <mask token>\n\n def initUI(self):\n (...TRUNCATED) | "<mask token>\n\n\nclass MyMainWindow(QMainWindow):\n\n def __init__(self):\n super().__in(...TRUNCATED) | "<mask token>\n\n\nclass MyMainWindow(QMainWindow):\n\n def __init__(self):\n super().__in(...TRUNCATED) | "import sys\nfrom PyQt5.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QFrame, QSp(...TRUNCATED) | "import sys\nfrom PyQt5.QtWidgets import (QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QFrame,\n (...TRUNCATED) | [
12,
14,
15,
17,
18
] |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 96