python_code
stringlengths 0
4.04M
| repo_name
stringlengths 8
58
| file_path
stringlengths 5
147
|
---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
| CTrLBenchmark-master | ctrl/concepts/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import hashlib
import numpy as np
import torch
from torch.distributions import Multinomial
class Concept(abc.ABC):
def __init__(self, id):
self._samples = None
self.descriptor = id
def get_samples(self):
return self._samples
def get_attributes(self, attribute_ids):
raise NotImplementedError('Attrs not supported anymore')
@abc.abstractmethod
def init_samples(self, n_per_split):
raise NotImplementedError
def __repr__(self):
return self.descriptor
def __hash__(self):
h = hashlib.md5(self.descriptor.encode('utf-8')).hexdigest()
return int(h, 16)
class ComposedConcept(Concept):
def __init__(self, concepts, cluster_mean=None, weights=None, *args,
**kwargs):
super(ComposedConcept, self).__init__(*args, **kwargs)
self._concepts = concepts
self.mean = cluster_mean
if weights is None:
weights = torch.ones(len(self.get_atomic_concepts()))
self.weights = weights / weights.sum()
def init_samples(self, N):
assert self._samples is None
all_samples = [c.get_samples() for c in self._concepts]
if torch.is_tensor(all_samples[0][0]):
cat_func = torch.cat
else:
cat_func = np.concatenate
self._samples = [cat_func(split) for split in zip(*all_samples)]
def _get_samples(self, n, attributes=None, split_id=None, rng=None):
if not attributes:
attributes = []
if not rng:
rng = np.random.default_rng()
samples = []
sample_attributes = []
samples_per_concept = rng.multinomial(n, self.weights)
for concept, n_samples in zip(self.get_atomic_concepts(),
samples_per_concept):
if n_samples == 0:
continue
c_samples, c_attrs = concept._get_samples(n_samples,
attributes=attributes,
split_id=split_id,
rng=rng)
samples.append(c_samples)
sample_attributes.append(c_attrs)
if attributes:
sample_attributes = torch.cat(sample_attributes)
else:
sample_attributes = torch.Tensor()
if torch.is_tensor(samples[0]):
cat_func = torch.cat
else:
cat_func = np.concatenate
return cat_func(samples), sample_attributes
def get_atomic_concepts(self):
return sum([c.get_atomic_concepts() for c in self._concepts], [])
| CTrLBenchmark-master | ctrl/concepts/concept.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Trees of concepts
"""
import abc
import logging
from collections import defaultdict
import bs4
import networkx as nx
import numpy as np
import torch
from ctrl.commons.tree import Tree
from ctrl.commons.utils import default_colors
from ctrl.concepts.concept import ComposedConcept
from pydot import quote_if_necessary
logger = logging.getLogger(__name__)
class ConceptTree(Tree):
def __init__(self, n_levels, n_children, n_samples_per_concept, n_attrs,
*args, **kwargs):
"""
High level structure from which we can retrieve concepts while
respecting some constraints. Could be an subtype of an abstract
ConceptPool class if we want to represent the concepts using another
data structure at some point. Currently we are only using Trees so
an additional level of abstraction isn't required.
:param n_levels:
:param n_children:
:param n_samples_per_concept: list of integers representing the number
of samples per split for each leaf concept
:param split_names: Should have the same length as
`n_samples_per_concept`
"""
if isinstance(n_children, list) and len(n_children) == 1:
n_children = n_children * n_levels
if isinstance(n_children, list):
n_levels = len(n_children)
self.n_levels = n_levels
self.depth = n_levels
self.n_children = n_children
# self.concepts = []
if n_attrs != 0:
raise ValueError('Attributes have been removed for v1.')
self.attributes = []
self.attribute_similarities = None
super().__init__(*args, **kwargs)
self.init_data(n_samples_per_concept=n_samples_per_concept)
@abc.abstractmethod
def build_tree(self):
raise NotImplementedError
def init_data(self, n_samples_per_concept):
"""
Init all nodes but the root, starting from the leafs and
climbing up the tree.
:param n_samples_per_concept: Iterable containing the number of samples
per split.
For example [500, 200] will init the data for two splits, containing
500 samples for the first one and 200 samples for the second.
"""
for node in self.tree.successors(self.root_node):
self._init_node(node, n_samples_per_concept)
def _init_node(self, node, n_samples_per_leaf):
successors = self.tree.successors(node)
for succ in successors:
self._init_node(succ, n_samples_per_leaf)
node.init_samples(n_samples_per_leaf)
def get_compatible_concepts(self, N=None, exclude_concepts=None,
leaf_only=False, preferred_lca_dist=-1,
max_lca_dist=-1, branch=None, nodes=None):
"""
Searches for N compatible concepts in the pool
:param N: Int, Number of concepts to select
:param exclude_concepts: Iterable, Concepts already selected, their
parents and children will also be excluded from the search.
:param leaf_only: Bool, the selection will be made only on leaf concepts
if True.
:return: A List of N compatible concepts.
:raises ValueError: If the selection is not possible.
"""
force_nodes = None
if branch is not None:
for node in self.tree.successors(self.root_node):
if node.descriptor == branch:
force_nodes = nx.descendants(self.tree, node)
if leaf_only:
force_nodes = self.leaf_nodes.intersection(force_nodes)
assert force_nodes, 'Can\'t find branch {}'.format(branch)
elif nodes:
force_nodes = set()
for c in self.all_concepts:
for n in nodes:
if c.descriptor.endswith(n):
force_nodes.add(c)
if len(nodes) != len(force_nodes):
raise ValueError('Got concepts {} when nodes {} where asked.'
.format(nodes, force_nodes))
return self.get_compatible_nodes(N, exclude_concepts, leaf_only,
preferred_lca_dist, max_lca_dist,
force_nodes)
def get_closest_categories(self, categories):
res = None
max_sim = None
for i, c1 in enumerate(categories):
for c2 in categories[i + 1:]:
sim = self.get_pair_similarity(c1, c2)
if max_sim is None or sim > max_sim:
res = [(c1, c2)]
max_sim = sim
elif sim == max_sim:
res.append((c1, c2))
return res
def get_pair_similarity(self, cat1, cat2):
"""
Compute the similarity between cat1 and cat2 as the minimum similarity
between concepts composing cat1 and atomic concepts composing cat2.
:param cat1: Iterable of concepts
:param cat2: Iterable of concepts
:return: The minimum wu_palmer similarity between concepts in cat1 and
cat2.
"""
cur_min = None
for c1 in cat1:
for c2 in cat2:
sim = self.wu_palmer(c1, c2)
if cur_min is None or sim < cur_min:
cur_min = sim
return cur_min
def merge_closest_categories(self, categories):
pairs = self.get_closest_categories(categories)
selected_pair = self.rnd.choice(pairs)
categories.remove(selected_pair[0])
categories.remove(selected_pair[1])
categories.append(selected_pair[0] + selected_pair[1])
return categories
def get_widest_categories(self, categories):
"""
Get the categories that covers the widest part of the tree. Computed
using the lowest common ancestor of all the concepts contained in each
category.
:param categories: Iterable of iterables of concepts to select from
:return: A list containing the categories covering the widest part of
the tree.
"""
lca = (self.lowest_common_ancestor(tuple(cat)) for cat in categories)
depths = (self.shortest_path_lengths[self.root_node][node] for node in
lca)
min_depth_categories = None
min_depth = None
for (cat, depth) in zip(categories, depths):
if min_depth is None or depth < min_depth:
min_depth_categories = [cat]
min_depth = depth
elif depth == min_depth:
min_depth_categories.append(cat)
return min_depth_categories
def split_category(self, category, lca=None):
"""
:param category:
:param lca: The Lowest Common Ancestor of the concepts contained in this
category. Will be computed if this parameter is left to None.
:return:
"""
if lca is None:
lca = self.lowest_common_ancestor(tuple(category))
if len(category) == 1:
assert isinstance(category[0], ComposedConcept)
assert category[0] == lca
new_categories = [[n] for n in self.tree.successors(lca)]
else:
new_cat_dict = defaultdict(list)
for concept in category:
new_cat_lca = self.shortest_paths[lca][concept][1]
new_cat_dict[new_cat_lca].append(concept)
new_categories = list(new_cat_dict.values())
return new_categories
def categories_sim(self, cats1, cats2):
"""
Only implemented for two pairs of categories, each category being
composed by only 1 concept.
:param cats1:
:param cats2:
:return:
"""
assert len(cats1) == len(cats2)
if not all(len(cat) == 1 for cat in cats1) \
and all(len(cat) == 1 for cat in cats2):
logger.warning('Can\'t compute sim between {} and {}'
.format(cats1, cats2))
return float('nan')
# Lets save some time if the categories are the same:
if set(cats1) == set(cats2):
return 1
# First compute all pairwise similarities between categories
sim_mat = torch.empty(len(cats1), len(cats2))
for i, c1 in enumerate(cats1):
for j, c2 in enumerate(cats2):
sim_mat[i, j] = self.wu_palmer(c1[0], c2[0])
# Then Greedily create the pairs
n_categories = len(cats1)
pairs = []
for k in range(len(cats1)):
a = torch.argmax(sim_mat).item()
i = a // n_categories
j = a % n_categories
# the new pair is (cats1[i], cats2[j])
pairs.append(sim_mat[i, j].item())
sim_mat[i] = -1
sim_mat[:, j] = -1
return np.mean(pairs)
def y_attributes_sim(self, y1, y2):
use_cluster_id_1, attrs_1 = y1
use_cluster_id_2, attrs_2 = y2
if not use_cluster_id_1 == use_cluster_id_2:
logger.warning('Only one tasks using cluster_id !')
return float('nan')
attrs_sims = []
if use_cluster_id_1:
attrs_sims.append(1)
for attr_1, attr_2 in zip(attrs_1, attrs_2):
attrs_sims.append(self.attribute_similarities[attr_1][attr_2])
return np.mean(attrs_sims)
def _concepts_to_nodes(self, concepts):
logger.warning('_concepts_to_nodes is deprecated')
return concepts
def _nodes_to_concepts(self, nodes):
logger.warning('_nodes_to_concepts is deprecated')
return nodes
@property
def leaf_concepts(self):
return self.leaf_nodes
@property
def all_concepts(self):
return self.all_nodes
@abc.abstractmethod
def plot_concepts(self, viz):
raise NotImplementedError
def draw_tree(self, highlighted_concepts=None, tree=None, viz=None,
colors=None, title=None):
"""
:param highlighted_concepts:
:param tree:
:return: A Pydot object
"""
if tree is None:
tree = self.tree
if colors is None:
colors = default_colors
p = nx.drawing.nx_pydot.to_pydot(tree)
if highlighted_concepts:
if not isinstance(highlighted_concepts[0], (list, tuple)):
highlighted_concepts = [highlighted_concepts]
# Give a color to each group of nodes
color_dict = {}
for i, concept_list in enumerate(highlighted_concepts):
highlighted_nodes = [c.descriptor for c in concept_list]
for node in highlighted_nodes:
# quote_if_necessary is required to handle names in the same
# way as pydot
color_dict[quote_if_necessary(node)] = colors[
i % len(colors)]
for node in p.get_nodes():
if node.obj_dict['name'] in color_dict:
node.set_style('filled')
node.set_fillcolor(color_dict[node.obj_dict['name']])
width = 18
p.set_size('{}x1'.format(width))
if viz:
svg_bytes = p.create_svg()
soup = bs4.BeautifulSoup(svg_bytes, 'xml')
width = float(soup.svg.attrs['width'][:-2]) * 1.35
height = float(soup.svg.attrs['height'][:-2]) * 1.4
viz.svg(svgstr=str(svg_bytes),
opts=dict(title=title,
width=width,
height=height
))
return p
def draw_attrs(self, viz):
all_concepts = self.leaf_concepts
for i, attr in enumerate(self.attributes):
attr_positive_concepts = []
for concept in all_concepts:
if concept.attrs[i] == 1:
attr_positive_concepts.append(concept)
self.draw_tree(highlighted_concepts=attr_positive_concepts, viz=viz,
title='attr {}'.format(i))
def __str__(self):
return type(self).__name__
| CTrLBenchmark-master | ctrl/concepts/concept_tree.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import torchvision
from ctrl.concepts.concept import ComposedConcept, Concept
from ctrl.concepts.concept_tree import ConceptTree
from ctrl.instances.DTD import DTD
from ctrl.instances.taxonomies import TAXONOMY
from torchvision.datasets import CIFAR10, CIFAR100, MNIST, SVHN, \
FashionMNIST
logger = logging.getLogger(__name__)
IMAGE_DS = {
'cifar10': CIFAR10,
'cifar100': CIFAR100,
'mnist': MNIST,
'fashion-mnist': FashionMNIST,
'svhn': SVHN,
'dtd': DTD,
}
class ImageConcept(Concept):
def __init__(self, samples, split_rnd, val_size=None, val_ratio=None,
*args, **kwargs):
super(ImageConcept, self).__init__(*args, **kwargs)
if val_size is not None:
assert val_ratio is None
else:
assert val_ratio is not None
self.is_static = True
self._samples = samples
self.val_size = val_size
self.val_ratio = val_ratio
self.split_rnd = split_rnd
self.attrs = None
def init_samples(self, n_per_split):
n_splits = len(n_per_split)
self.attrs = [torch.Tensor().long() for _ in range(n_splits)]
if n_splits == len(self._samples):
pass
elif n_splits == 3 and len(self._samples) == 2:
# We need to split the train_set
train_samples = self._samples[0]
train_size = train_samples.shape[0]
# assert train_size in [500, 5000]
idx = self.split_rnd.permutation(train_size)
if self.val_size is None:
val_size = int(np.floor(self.val_ratio * train_size))
else:
val_size = self.val_size
self._samples = (train_samples[idx[:-val_size]],
train_samples[idx[-val_size:]],
self._samples[1])
else:
raise NotImplementedError
def _get_samples(self, n, attributes, split_id, rng):
assert not attributes, 'Can\'t use attributes with Images for now'
n_samples = self._samples[split_id].size(0)
if n_samples > n:
idx = rng.choice(n_samples, n, replace=False)
samples = self._samples[split_id][idx]
else:
samples = self._samples[split_id]
if attributes:
selected_attributes = self.attrs[split_id][idx][:, attributes]
else:
selected_attributes = None
return samples, selected_attributes
def get_atomic_concepts(self):
return [self]
def get_attr(self, x, y):
assert self._samples[0].size(1) == 1, 'Don\'t know what an attribute' \
' is for 3D images'
tresh = self._samples[0].max().float() / 2
new_attr = []
for i, samples_split in enumerate(self._samples):
split_attr = samples_split[:, 0, y, x].float() > tresh
new_attr.append(split_attr.long().unsqueeze(1))
return new_attr
class ImageDatasetTree(ConceptTree):
def __init__(self, data_path, split_seed, img_size, val_size=None,
val_ratio=None, expand_channels=False, *args, **kwargs):
if not data_path:
data_path = Path.home()/'.ctrl_data'
self.data_path = data_path
self.img_size = img_size
# We already have rnd available from the Tree parent class, but we
# need a new random state that won't vary across runs to create the
# val split
self.split_rnd = np.random.RandomState(split_seed)
self.val_size = val_size
self.val_ratio = val_ratio
self.expand_channels = expand_channels
super().__init__(*args, **kwargs)
def build_tree(self):
if self.name not in IMAGE_DS:
raise ValueError('Unknown image dataset: {}'.format(self.name))
ds_class = IMAGE_DS[self.name]
common_params = dict(root=self.data_path, download=True)
if self.name in ['svhn', 'dtd', 'aircraft']:
self.trainset = ds_class(split='train', **common_params)
self.testset = ds_class(split='test', **common_params)
else:
self.trainset = ds_class(train=True, **common_params)
self.testset = ds_class(train=False, **common_params)
self.train_samples, self.train_targets = self._format_ds(self.trainset)
self.test_samples, self.test_targets = self._format_ds(self.testset)
self.height, self.width = self.train_samples.size()[-2:]
taxonomy = TAXONOMY[self.name]
concepts = self._build_tree(taxonomy)
root_concept = ComposedConcept(concepts, id=self.name)
self.tree.add_node(root_concept)
for sub_concept in concepts:
self.tree.add_edge(root_concept, sub_concept)
del self.trainset, self.testset, \
self.train_samples, self.test_samples, \
self.train_targets, self.test_targets
return root_concept
def _build_tree(self, current_level_concepts):
new_concepts = []
if isinstance(current_level_concepts, dict):
# Not yet at the lowest level
for name, lower_concepts in current_level_concepts.items():
concepts = self._build_tree(lower_concepts)
concept_name = '{} {}'.format(self.name, name)
new_concept = ComposedConcept(concepts=concepts,
id=concept_name)
self.tree.add_node(new_concept)
self.all_nodes.add(new_concept)
for c in concepts:
self.tree.add_edge(new_concept, c)
new_concepts.append(new_concept)
elif isinstance(current_level_concepts, list):
# Adding lowest level concepts
for c in current_level_concepts:
samples = self._get_samples(c)
concept_name = '{} {}'.format(self.name, c)
concept = ImageConcept(id=concept_name, samples=samples,
split_rnd=self.split_rnd,
val_size=self.val_size,
val_ratio=self.val_ratio)
self.tree.add_node(concept)
self.all_nodes.add(concept)
self.leaf_nodes.add(concept)
new_concepts.append(concept)
else:
raise NotImplementedError()
return new_concepts
def _format_ds(self, dataset):
"""
Unify the format of the datasets so that they all have the same type,
shape and size.
"""
if hasattr(dataset, 'targets'):
# Cifar, Mnist
targets = dataset.targets
else:
# SVHN
targets = dataset.labels
if not torch.is_tensor(targets):
targets = torch.tensor(targets)
samples = dataset.data
if isinstance(samples, np.ndarray):
if samples.shape[-1] in [1, 3]:
# CIFAR Channels are at the end
samples = samples.transpose((0, 3, 1, 2))
assert samples.shape[1] in [1, 3]
samples = torch.from_numpy(samples)
if samples.ndimension() == 3:
# Add the channel dim
samples = samples.unsqueeze(1)
if self.expand_channels and samples.size(1) == 1:
samples = samples.expand(-1, 3, -1, -1)
# samples = samples.float()
cur_size = list(samples.shape[-2:])
if cur_size != self.img_size:
logger.warning('Resizing {} ({}->{})'.format(self.name,
cur_size,
self.img_size))
samples = F.interpolate(samples.float(), self.img_size,
mode='bilinear',
align_corners=False).byte()
return samples, targets
def _get_samples(self, concept):
concept_idx = self._get_class_to_idx()[concept]
train_concept_mask = self.train_targets == concept_idx
test_concept_mask = self.test_targets == concept_idx
train_samples = self.train_samples[train_concept_mask]
test_samples = self.test_samples[test_concept_mask]
assert train_samples.size(1) in [1, 3] and \
test_samples.size(1) in [1, 3]
return train_samples, test_samples
def _get_class_to_idx(self):
if hasattr(self.trainset, 'class_to_idx'):
assert self.trainset.class_to_idx == self.testset.class_to_idx
return self.trainset.class_to_idx
else:
taxo = TAXONOMY[self.name]
assert isinstance(taxo, list)
return {_class: i for i, _class in enumerate(taxo)}
def plot_concepts(self, viz):
for c in self.leaf_concepts:
images = [self.rnd.choice(s) for s in c._samples]
grid = torchvision.utils.make_grid(images)
viz.image(grid, opts={'title': c.descriptor,
'width': grid.size(2) * 3,
'height': grid.size(1) * 3.2})
def draw_attrs(self, viz):
pass
| CTrLBenchmark-master | ctrl/instances/image_dataset_tree.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import networkx as nx
import numpy as np
import torch
import torchvision
from ctrl.concepts.concept import ComposedConcept
from ctrl.concepts.concept_tree import ConceptTree
from ctrl.instances.taxonomies import TAXONOMY
class MultiDomainDatasetTree(ConceptTree):
def __init__(self, **kwargs):
self.children = []
extracted = []
for k, v in kwargs.items():
if 'child' in k:
extracted.append(k)
self.children.append(v)
for k in extracted:
del kwargs[k]
n_levels = max(child.n_levels for child in self.children)
super().__init__(n_levels=n_levels, n_children=None,
n_samples_per_concept=None, **kwargs)
def build_tree(self):
child_concepts = [child.root_node for child in self.children]
root_concept = ComposedConcept(child_concepts, id=self.name)
self.tree.add_node(root_concept)
for child in self.children:
self.tree = nx.compose(self.tree, child.tree)
self.tree.add_edge(root_concept, child.root_node)
self.leaf_nodes = self.leaf_nodes.union(child.leaf_nodes)
self.all_nodes = self.all_nodes.union(child.all_nodes)
return root_concept
def init_data(self, n_samples_per_concept):
pass
def _format_ds(self, dataset):
if hasattr(dataset, 'targets'):
# Cifar, Mnist
targets = dataset.targets
else:
# SVHN
targets = dataset.labels
if not torch.is_tensor(targets):
targets = torch.tensor(targets)
samples = dataset.data
if isinstance(samples, np.ndarray):
if samples.shape[-1] in [1, 3]:
# CIFAR Channels are at the end
samples = samples.transpose((0, 3, 1, 2))
assert samples.shape[1] in [1, 3]
samples = torch.from_numpy(samples)
if samples.ndimension() == 3:
# Add the channel dim
samples = samples.unsqueeze(1)
return samples, targets
def _get_samples(self, concept):
concept_idx = self._get_class_to_idx()[concept]
train_concept_mask = self.train_targets == concept_idx
test_concept_mask = self.test_targets == concept_idx
train_samples = self.train_samples[train_concept_mask]
test_samples = self.test_samples[test_concept_mask]
assert train_samples.size(1) in [1, 3] and \
test_samples.size(1) in [1, 3]
return train_samples, test_samples
def _get_class_to_idx(self):
if hasattr(self.trainset, 'class_to_idx'):
assert self.trainset.class_to_idx == self.testset.class_to_idx
return self.trainset.class_to_idx
else:
taxo = TAXONOMY[self.name]
assert isinstance(taxo, list)
return {_class: i for i, _class in enumerate(taxo)}
def plot_concepts(self, viz):
for c in self.leaf_concepts:
images = [self.rnd.choice(s) for s in c._samples]
grid = torchvision.utils.make_grid(images)
viz.image(grid, opts={'title': c.descriptor,
'width': grid.size(2) * 3,
'height': grid.size(1) * 3.2})
| CTrLBenchmark-master | ctrl/instances/md_tree.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
| CTrLBenchmark-master | ctrl/instances/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
cifar100_taxonomy = {
'aquatic mammals': ['beaver', 'dolphin', 'otter', 'seal', 'whale'],
'fish': ['aquarium_fish', 'flatfish', 'ray', 'shark', 'trout'],
'flowers': ['orchid', 'poppy', 'rose', 'sunflower', 'tulip'],
'food containers': ['bottle', 'bowl', 'can', 'cup', 'plate'],
'fruit and vegetables': ['apple', 'mushroom', 'orange', 'pear',
'sweet_pepper'],
'household electrical devices': ['clock', 'keyboard', 'lamp', 'telephone',
'television'],
'household furniture': ['bed', 'chair', 'couch', 'table', 'wardrobe'],
'insects': ['bee', 'beetle', 'butterfly', 'caterpillar', 'cockroach'],
'large carnivores': ['bear', 'leopard', 'lion', 'tiger', 'wolf'],
'large man-made outdoor things': ['bridge', 'castle', 'house', 'road',
'skyscraper'],
'large natural outdoor scenes': ['cloud', 'forest', 'mountain', 'plain',
'sea'],
'large omnivores and herbivores': ['camel', 'cattle', 'chimpanzee',
'elephant', 'kangaroo'],
'medium-sized mammals': ['fox', 'porcupine', 'possum', 'raccoon', 'skunk'],
'non-insect invertebrates': ['crab', 'lobster', 'snail', 'spider', 'worm'],
'people': ['baby', 'boy', 'girl', 'man', 'woman'],
'reptiles': ['crocodile', 'dinosaur', 'lizard', 'snake', 'turtle'],
'small mammals': ['hamster', 'mouse', 'rabbit', 'shrew', 'squirrel'],
'trees': ['maple_tree', 'oak_tree', 'palm_tree', 'pine_tree',
'willow_tree'],
'vehicles 1': ['bicycle', 'bus', 'motorcycle', 'pickup_truck', 'train'],
'vehicles 2': ['lawn_mower', 'rocket', 'streetcar', 'tank', 'tractor'],
}
cifar10_taxonomy = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog',
'frog', 'horse', 'ship', 'truck']
mnist_taxonomy = ['0 - zero', '1 - one', '2 - two', '3 - three', '4 - four',
'5 - five', '6 - six', '7 - seven', '8 - eight', '9 - nine']
famnist_taxonomy = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal',
'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
dtd_taxonomy = ['banded', 'blotchy', 'braided', 'bubbly', 'bumpy', 'chequered',
'cobwebbed', 'cracked', 'crosshatched', 'crystalline',
'dotted', 'fibrous', 'flecked', 'freckled', 'frilly', 'gauzy',
'grid', 'grooved', 'honeycombed', 'interlaced', 'knitted',
'lacelike', 'lined', 'marbled', 'matted', 'meshed', 'paisley',
'perforated', 'pitted', 'pleated', 'polka-dotted', 'porous',
'potholed', 'scaly', 'smeared', 'spiralled', 'sprinkled',
'stained', 'stratified', 'striped', 'studded', 'swirly',
'veined', 'waffled', 'woven', 'wrinkled', 'zigzagged']
TAXONOMY = {'cifar100': cifar100_taxonomy,
'cifar10': cifar10_taxonomy,
'mnist': mnist_taxonomy,
'svhn': mnist_taxonomy,
'fashion-mnist': famnist_taxonomy,
'dtd': dtd_taxonomy,
}
| CTrLBenchmark-master | ctrl/instances/taxonomies.py |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import glob
import itertools
import os
from collections import defaultdict
import numpy as np
import torch
from torchvision.datasets import VisionDataset
from torchvision.datasets.folder import pil_loader
from torchvision.datasets.utils import gen_bar_updater
from tqdm import tqdm
import tarfile
import urllib
def center_crop(img, size):
width, height = img.size
left = (width - size[0]) / 2
top = (height - size[1]) / 2
right = (width + size[0]) / 2
bottom = (height + size[1]) / 2
return img.crop((left, top, right, bottom))
def untar(path):
directory_path = os.path.dirname(path)
with tarfile.open(path) as tar_file:
tar_file.extractall(directory_path)
def download(url, path):
if not os.path.exists(path):
os.makedirs(path)
file_name = os.path.join(path, url.split("/")[-1])
if os.path.exists(file_name):
print(f"Dataset already downloaded at {file_name}.")
else:
urllib.request.urlretrieve(url, file_name, reporthook=gen_bar_updater())
return file_name
class DTD(VisionDataset):
folder_name = 'dtd'
processed_folder = 'dtd/processed'
url = 'https://www.robots.ox.ac.uk/~vgg/data/dtd/download/dtd-r1.0.1.tar.gz'
def __init__(self, root, split, download=False, img_size=(32, 32),
transform=None, target_transform=None):
super(DTD, self).__init__(root, transform=transform,
target_transform=target_transform)
pr_file = self._get_processed_name(root, split, img_size)
if download and not os.path.exists(pr_file):
self._download_and_prepare(root, split, img_size)
assert os.path.exists(pr_file)
self.data, self.labels, self.classes = torch.load(pr_file)
def _download_and_prepare(self, root, split, img_size):
archive_path = os.path.join(root, "dtd-r1.0.1.tar.gz")
if not os.path.exists(archive_path):
print("Downloading DTD dataset...")
download(self.url, root)
if not os.path.exists(os.path.join(root, "dtd")):
print("Uncompressing images...")
untar(archive_path)
self._prepare(root, split, img_size)
def _prepare(self, root, split, img_size):
extracted_path = os.path.join(root, self.folder_name)
assert os.path.exists(extracted_path)
os.makedirs(os.path.join(root, self.processed_folder), exist_ok=True)
images = defaultdict(list)
classes = []
data = []
labels = []
labels_path = os.path.join(extracted_path, 'labels')
p = os.path.join(labels_path, '{}1.txt'.format(split))
files = glob.glob(p)
if split == 'train':
p = os.path.join(labels_path, 'val1.txt')
files = itertools.chain(files, glob.glob(p))
files = list(files)
for file in tqdm(files):
with open(file, 'r') as f:
for line in f:
line = line.rstrip('\n')
img = pil_loader(os.path.join(extracted_path, 'images', line))
width, height = img.size
ratio = max(img_size[0] / width, img_size[1] / height)
new_size = (int(width * ratio), int(height * ratio))
img = img.resize(new_size)
img = center_crop(img, img_size)
assert img.size == img_size
cat, img_name = line.split('/')
images[cat].append(np.array(img))
for i, (cl, imgs) in enumerate(sorted(images.items())):
classes.append(cl)
data.append(np.stack(imgs))
labels.append(np.ones(len(imgs)) * i)
data = np.concatenate(data)
labels = np.concatenate(labels)
file_name = self._get_processed_name(root, split, img_size)
print('Saving data to {}'.format(file_name))
torch.save((data, labels, classes), file_name)
def _get_processed_name(self, root, split, img_size):
pr_file = 'dtd-{}-{}x{}.th'.format(split, *img_size)
return os.path.join(root, self.processed_folder, pr_file)
@property
def class_to_idx(self):
return {_class: i for i, _class in enumerate(self.classes)}
| CTrLBenchmark-master | ctrl/instances/DTD.py |
import pytest
import torch
import ctrl
def test_s_plus():
task_gen = ctrl.get_stream('s_plus')
tasks = list(task_gen)
assert len(tasks) == 6
assert tasks[0].src_concepts == tasks[-1].src_concepts
assert len(tasks[0].datasets[0]) < len(tasks[-1].datasets[0])
def test_s_minus():
task_gen = ctrl.get_stream('s_minus')
tasks = list(task_gen)
assert len(tasks) == 6
assert tasks[0].src_concepts == tasks[-1].src_concepts
assert len(tasks[0].datasets[0]) > len(tasks[-1].datasets[0])
stream_lengths = [
('s_plus', 6),
('s_minus', 6),
('s_in', 6),
('s_out', 6),
('s_pl', 5),
# ('s_long', 100)
]
@pytest.mark.parametrize("stream_name, expected_len", stream_lengths)
def test_get_stream_len(stream_name, expected_len):
task_gen = ctrl.get_stream(stream_name)
tasks = list(task_gen)
assert len(tasks) == expected_len
def test_determinism():
task_gen = ctrl.get_stream('s_minus', 10)
tasks_1 = list(task_gen)
task_gen = ctrl.get_stream('s_minus', 10)
tasks_2 = list(task_gen)
for t1, t2 in zip(tasks_1, tasks_2):
assert t1 == t2
| CTrLBenchmark-master | tests/test_ctrl.py |
CTrLBenchmark-master | tests/__init__.py |
|
#Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
# sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../..'))
# -- Project information -----------------------------------------------------
project = 'CTrL Benchmark'
copyright = "2020, Facebook, Inc. and its affiliates"
author = "Tom Veniat, Ludovic Denoyer & Marc'Aurelio Ranzato"
# The full version, including alpha/beta/rc tags
release = '0.0.2'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
# extensions = [
# 'sphinx.ext.autodoc', # Core library for html generation from docstrings
# 'sphinx.ext.autosummary', # Create neat summary tables
# ]
# autosummary_generate = True # Turn on sphinx.ext.autosummary
extensions = [
# 'sphinx.ext.autodoc',
# 'sphinx.ext.autodoc.typehints',
'autoapi.extension',
'sphinx.ext.napoleon',
'sphinx.ext.autodoc',
'sphinx_autodoc_typehints'
]
autoapi_type = 'python'
autoapi_dirs = ['../../ctrl']
# autoapi_template_dir = '_autoapi_templates'
autoapi_python_class_content = 'both'
autodoc_typehints = 'description'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
# html_theme = 'default'
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
| CTrLBenchmark-master | docs/source/conf.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from setuptools import find_packages, setup
setup(
name='dcem',
version='0.0.1',
description="The Differentiable Cross-Entropy Method",
author='Brandon Amos',
author_email='[email protected]',
platforms=['any'],
license="CC BY-NC 4.0",
url='https://github.com/facebookresearch/dcem',
py_modules=['dcem'],
install_requires=[
'numpy>=1<2',
'higher',
'setproctitle',
'lml@git+git://github.com/locuslab/lml.git',
],
dependency_links=[
'git+ssh://[email protected]/locuslab/lml.git#egg=lml-0.0.1'
'git+git://github.com/denisyarats/dmc2gym.git'
]
)
| dcem-main | setup.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import typing
import copy
import numpy as np
import numpy.random as npr
import torch
from torch import nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import ReduceLROnPlateau
import higher
import csv
import os
import pickle as pkl
from dcem import dcem
import hydra
from setproctitle import setproctitle
setproctitle('regression')
@hydra.main(config_path="regression-conf.yaml", strict=True)
def main(cfg):
import sys
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose',
color_scheme='Linux', call_pdb=1)
print('Current dir: ', os.getcwd())
from regression import RegressionExp, UnrollEnergyGD, UnrollEnergyCEM
exp = RegressionExp(cfg)
exp.run()
class RegressionExp():
def __init__(self, cfg):
self.cfg = cfg
self.exp_dir = os.getcwd()
self.model_dir = os.path.join(self.exp_dir, 'models')
os.makedirs(self.model_dir, exist_ok=True)
torch.manual_seed(cfg.seed)
npr.seed(cfg.seed)
self.device = torch.device("cuda") \
if torch.cuda.is_available() else torch.device("cpu")
self.Enet = EnergyNet(n_in=1, n_out=1, n_hidden=cfg.n_hidden).to(self.device)
self.model = hydra.utils.instantiate(cfg.model, self.Enet)
self.load_data()
def dump(self, tag='latest'):
fname = os.path.join(self.exp_dir, f'{tag}.pkl')
pkl.dump(self, open(fname, 'wb'))
def __getstate__(self):
d = copy.copy(self.__dict__)
del d['x_train']
del d['y_train']
return d
def __setstate__(self, d):
self.__dict__ = d
self.load_data()
def load_data(self):
self.x_train = torch.linspace(0., 2.*np.pi, steps=self.cfg.n_samples).to(self.device)
self.y_train = self.x_train*torch.sin(self.x_train)
def run(self):
# opt = optim.SGD(self.Enet.parameters(), lr=1e-1)
opt = optim.Adam(self.Enet.parameters(), lr=1e-3)
lr_sched = ReduceLROnPlateau(opt, 'min', patience=20, factor=0.5, verbose=True)
fieldnames = ['iter', 'loss']
f = open(os.path.join(self.exp_dir, 'loss.csv'), 'w')
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
step = 0
while step < self.cfg.n_update:
if (step in list(range(100)) or step % 10000 == 0):
self.dump(f'{step:07d}')
j = npr.randint(self.cfg.n_samples)
for i in range(self.cfg.n_inner_update):
y_preds = self.model(self.x_train[j].view(1)).squeeze()
loss = F.mse_loss(input=y_preds, target=self.y_train[j])
opt.zero_grad()
loss.backward(retain_graph=True)
if self.cfg.clip_norm:
nn.utils.clip_grad_norm_(self.Enet.parameters(), 1.0)
opt.step()
step += 1
if step % 100 == 0:
y_preds = self.model(self.x_train.view(-1, 1)).squeeze()
loss = F.mse_loss(input=y_preds, target=self.y_train)
lr_sched.step(loss)
print(f'Iteration {step}: Loss {loss:.2f}')
writer.writerow({
'iter': step,
'loss': loss.item(),
})
f.flush()
exp_dir = os.getcwd()
fieldnames = ['iter', 'loss', 'lr']
self.dump('latest')
class EnergyNet(nn.Module):
def __init__(self, n_in: int, n_out: int, n_hidden: int = 256):
super().__init__()
self.n_in = n_in
self.n_out = n_out
self.E_net = nn.Sequential(
nn.Linear(n_in+n_out, n_hidden),
nn.Softplus(),
nn.Linear(n_hidden, n_hidden),
nn.Softplus(),
nn.Linear(n_hidden, n_hidden),
nn.Softplus(),
nn.Linear(n_hidden, 1),
)
def forward(self, x, y):
z = torch.cat((x, y), dim=-1)
E = self.E_net(z)
return E
class UnrollEnergyGD(nn.Module):
def __init__(self, Enet: EnergyNet, n_inner_iter, inner_lr):
super().__init__()
self.Enet = Enet
self.n_inner_iter = n_inner_iter
self.inner_lr = inner_lr
def forward(self, x):
b = x.ndimension() > 1
if not b:
x = x.unsqueeze(0)
assert x.ndimension() == 2
nbatch = x.size(0)
y = torch.zeros(nbatch, self.Enet.n_out, device=x.device, requires_grad=True)
inner_opt = higher.get_diff_optim(
torch.optim.SGD([y], lr=self.inner_lr),
[y], device=x.device
)
for _ in range(self.n_inner_iter):
E = self.Enet(x, y)
y, = inner_opt.step(E.sum(), params=[y])
return y
class UnrollEnergyCEM(nn.Module):
def __init__(self, Enet: EnergyNet, n_sample, n_elite,
n_iter, init_sigma, temp, normalize):
super().__init__()
self.Enet = Enet
self.n_sample = n_sample
self.n_elite = n_elite
self.n_iter = n_iter
self.init_sigma = init_sigma
self.temp = temp
self.normalize = normalize
def forward(self, x):
b = x.ndimension() > 1
if not b:
x = x.unsqueeze(0)
assert x.ndimension() == 2
nbatch = x.size(0)
def f(y):
_x = x.unsqueeze(1).repeat(1, y.size(1), 1)
Es = self.Enet(_x.view(-1, 1), y.view(-1, 1)).view(y.size(0), y.size(1))
return Es
yhat = dcem(
f,
n_batch=nbatch,
nx=1,
n_sample=self.n_sample,
n_elite=self.n_elite,
n_iter=self.n_iter,
init_sigma=self.init_sigma,
temp=self.temp,
device=x.device,
normalize=self.temp,
)
return yhat
if __name__ == '__main__':
import sys
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose',
color_scheme='Linux', call_pdb=1)
main()
| dcem-main | exps/regression.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import numpy.random as npr
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.autograd import grad, Function
from torch.optim.lr_scheduler import ReduceLROnPlateau
import argparse
import os
import math
import gym
import sys
import random
import pickle as pkl
import time
import copy
import itertools
import operator
import pandas as pd
import numdifftools as nd
from multiprocessing import Pool
import matplotlib.pyplot as plt
from matplotlib import cm
plt.style.use('bmh')
import logging
log = logging.getLogger(__name__)
import higher
import hydra
from mpc.env_dx.cartpole import CartpoleDx
from dcem import dcem, dcem_ctrl
# import sys
# from IPython.core import ultratb
# sys.excepthook = ultratb.FormattedTB(mode='Verbose',
# color_scheme='Linux', call_pdb=1)
get_params = lambda *models: itertools.chain.from_iterable(
map(operator.methodcaller('parameters'), models))
@hydra.main(config_path='cartpole_emb.yaml')
def main(cfg):
from cartpole_emb import CartpoleEmbExp, Decode, DCEM, GD
exp = CartpoleEmbExp(cfg)
# exp.estimate_full_cost()
exp.run()
class CartpoleEmbExp():
def __init__(self, cfg):
self.cfg = cfg
self.exp_dir = os.getcwd()
log.info(f'Saving to {self.exp_dir}')
self.device = cfg.device
self.dx = CartpoleDx()
self.n_ctrl = self.dx.n_ctrl
torch.manual_seed(cfg.seed)
kwargs = dict(cfg.method.params)
clz = hydra.utils.get_class(cfg.method['class'])
self.method = clz(
n_ctrl=self.n_ctrl,
dx=self.dx, plan_horizon=cfg.plan_horizon,
device=self.device,
solve_full=self.solve_full, # Somewhat messy to do this.
**kwargs
)
self.lr_sched = ReduceLROnPlateau(
self.method.opt, 'min', patience=20, factor=0.5, verbose=True)
torch.manual_seed(0)
self.xinit_val = sample_init(n_batch=100).to(self.device)
def dump(self, tag='latest'):
fname = os.path.join(self.exp_dir, f'{tag}.pkl')
pkl.dump(self, open(fname, 'wb'))
# def __getstate__(self):
# d = copy.copy(self.__dict__)
# del d['x_train']
# del d['y_train']
# return d
# def __setstate__(self, d):
# self.__dict__ = d
# self.load_data()
def load_data(self):
self.x_train = torch.linspace(0., 2.*np.pi, steps=self.cfg.n_samples).to(self.device)
self.y_train = self.x_train*torch.sin(self.x_train)
def solve_full(self, xinits):
def unroll_dx(x0, us):
rews, xs = rew_nominal(self.dx, x0, us)
return xs, rews
kwargs = copy.deepcopy(self.cfg.full_ctrl_opts)
kwargs['init_sigma'] = kwargs['init_sigma_scale']*(self.dx.upper-self.dx.lower)
del kwargs['init_sigma_scale']
assert False, "TODO: Update to new dcem_ctrl interface"
out = ctrl(
xinits, plan_horizon=self.cfg.plan_horizon, init_mu=0.,
lb=self.dx.lower, ub=self.dx.upper,
rew_step=rew_step,
n_ctrl=self.n_ctrl, unroll_dx=unroll_dx,
dcem_verbose=False,
**kwargs
)
return out
def estimate_full_cost(self):
costs = []
for i in range(100):
xinits = sample_init(n_batch=self.cfg.n_batch).to(self.device)
out = self.solve_full(xinits)
costs.append(out['cost'].item())
print(f'{np.mean(costs):.2f} +/- {np.std(costs):.2f}')
def run(self):
hist = []
self.best_val_loss = None
for i in range(self.cfg.n_train_iter):
xinits = sample_init(n_batch=self.cfg.n_batch).to(self.device)
loss = self.method.train_step(xinits)
hist.append({
'iter': i,
'loss': loss,
'mode': 'train',
})
log.info(f'iter {i} loss {loss:.2f}')
if i % self.cfg.save_interval == 0:
u_emb, emb_cost = self.method.solve(self.xinit_val)
val_loss = emb_cost.mean().item()
self.lr_sched.step(val_loss)
hist.append({
'iter': i,
'loss': val_loss,
'mode': 'val',
})
log.info(f'iter {i} val loss {loss:.2f}')
if self.best_val_loss is None or val_loss < self.best_val_loss:
self.best_val_loss = val_loss
self.dump(tag='best')
self.dump()
# TODO: Pretty inefficient
pd.DataFrame.from_records(hist, index='iter').to_csv(
f'{self.exp_dir}/losses.csv')
def rew_step(xt, ut):
assert xt.ndimension() == 2
assert ut.ndimension() == 2
n_batch, n_ctrl = ut.shape
_, nx = xt.shape
assert xt.size(0) == n_batch
up_rew = xt[:,2]
dist_pen = -0.1*xt[:,0].pow(2)
ctrl_pen = -1e-5*ut.pow(2).sum(dim=1)
return up_rew + dist_pen + ctrl_pen
# @profile
def rew_nominal(dx, xinit, u):
assert u.ndimension() == 3
assert xinit.ndimension() == 2
T, n_batch, n_ctrl = u.shape
_, nx = xinit.shape
assert xinit.size(0) == n_batch
rews = 0.
xt = xinit.clone()
xs = [xt]
for t in range(T):
ut = u[t]
rew = rew_step(xt, ut)
rews += rew
xt = dx(xt, ut)
xs.append(xt)
return rews, torch.stack(xs)
class DCEM():
def __init__(
self, latent_size, ctrl_opts, n_hidden, lr, n_ctrl, dx, plan_horizon, device,
solve_full
):
self.latent_size = latent_size
self.ctrl_opts = ctrl_opts
self.n_hidden = n_hidden
self.lr = lr
self.n_ctrl = n_ctrl
self.dx = dx
self.plan_horizon = plan_horizon
self.device = device
self.decode = Decode(
latent_size, n_hidden,
plan_horizon, n_ctrl, dx.lower, dx.upper
).to(self.device)
self.opt = optim.Adam(self.decode.parameters(), lr=lr)
def get_cost_f(self, xinit):
assert xinit.ndimension() == 2
nbatch = xinit.size(0)
def f_emb(u_emb):
u = self.decode(u_emb.view(-1, self.latent_size))
nsample = u.size(1)//nbatch
xinit_sample = xinit.unsqueeze(1).repeat(1, nsample, 1)
xinit_sample = xinit_sample.view(nbatch*nsample, -1)
cost = -rew_nominal(self.dx, xinit_sample, u)[0]
return cost
return f_emb
def solve(self, xinit, iter_cb=None):
if xinit.ndimension() == 1:
xinit = xinit.unsqueeze(0)
assert xinit.ndimension() == 2
nbatch = xinit.size(0)
if iter_cb is None:
def iter_cb(i, X, fX, I, X_I, mu, sigma):
assert fX.ndimension() == 2
I = I.view(fX.shape)
print(f' + {i}: {(fX*I).sum()/I.sum():.2f}')
print(f' + {I.min().item():.2f}/{I.max().item():.2f}')
# torch.manual_seed(0)
f_emb = self.get_cost_f(xinit)
u_emb = dcem(
f_emb, self.latent_size, init_mu=None,
n_batch=nbatch, device=self.device, iter_cb=iter_cb,
**self.ctrl_opts
)
emb_cost = f_emb(u_emb)
return u_emb, emb_cost
def train_step(self, xinit):
assert xinit.ndimension() == 2 and xinit.size(0) == 1
xinit = xinit.squeeze()
u_emb, emb_cost = self.solve(xinit)
loss = emb_cost.sum()
self.opt.zero_grad()
loss.backward()
# print('---')
# util.print_grad(self.decode)
nn.utils.clip_grad_norm_(self.decode.parameters(), 1.0)
# util.print_grad(self.decode)
self.opt.step()
return loss.item()
class GD():
def __init__(
self, latent_size, n_hidden, lr,
inner_optim_opts,
n_ctrl, dx, plan_horizon, device,
solve_full,
):
self.latent_size = latent_size
self.n_hidden = n_hidden
self.lr = lr
self.inner_optim_opts = inner_optim_opts
self.n_ctrl = n_ctrl
self.dx = dx
self.plan_horizon = plan_horizon
self.device = device
self.decode = Decode(
latent_size, n_hidden,
plan_horizon, n_ctrl, dx.lower, dx.upper
).to(self.device)
self.opt = optim.Adam(self.decode.parameters(), lr=lr)
def get_cost_f(self, xinit):
def f_emb(u_emb):
u = self.decode(u_emb.view(-1, self.latent_size))
# xinit_batch = xinit.repeat(u.size(1), 1) # TODO: Inefficient
cost = -rew_nominal(self.dx, xinit, u)[0]
return cost
return f_emb
def solve(self, xinit):
assert xinit.ndimension() == 2
nbatch = xinit.size(0)
z = torch.zeros(nbatch, self.latent_size,
device=xinit.device, requires_grad=True)
inner_opt = higher.get_diff_optim(
torch.optim.SGD([z], lr=self.inner_optim_opts.lr),
[z], device=xinit.device
)
f_emb = self.get_cost_f(xinit)
for _ in range(self.inner_optim_opts.n_iter):
cost = f_emb(z)
z, = inner_opt.step(cost.sum(), params=[z])
us = self.decode(z)
rews, xs = rew_nominal(self.dx, xinit, us)
cost = -rews
return z, cost
def train_step(self, xinit):
assert xinit.ndimension() == 2
_, cost = self.solve(xinit)
loss = cost.mean()
self.opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(self.decode.parameters(), 1.0)
self.opt.step()
return loss.item()
class Decode(nn.Module):
def __init__(self, n_in, n_hidden, plan_horizon, n_ctrl, lb, ub):
super().__init__()
self.plan_horizon = plan_horizon
self.n_ctrl = n_ctrl
self.lb = lb
self.ub = ub
act = nn.ELU
bias = True
self.net = nn.Sequential(
nn.Linear(n_in, n_hidden, bias=bias),
act(),
nn.Linear(n_hidden, n_hidden, bias=bias),
act(),
nn.Linear(n_hidden, n_hidden, bias=bias),
act(),
nn.Linear(n_hidden, plan_horizon*n_ctrl, bias=bias),
)
def init(m):
if isinstance(m, nn.Linear):
fan_out, fan_in = m.weight.size()
m.weight.data.normal_(0.0, 2./np.sqrt(fan_in+fan_out))
if bias:
m.bias.data.zero_()
self.net.apply(init)
def forward(self, x):
assert x.ndimension() == 2
nbatch = x.size(0)
u = self.net(x)
r = self.ub-self.lb
u = r*torch.sigmoid(u)+self.lb
u = u.t().view(self.plan_horizon, self.n_ctrl, nbatch).transpose(1,2)
return u
def uniform(shape, low, high):
r = high-low
return torch.rand(shape)*r+low
def sample_init(n_batch=1):
pos = uniform(n_batch, -0.5, 0.5)
dpos = uniform(n_batch, -0.5, 0.5)
th = uniform(n_batch, -np.pi, np.pi)
dth = uniform(n_batch, -1., 1.)
xinit = torch.stack((pos, dpos, torch.cos(th), torch.sin(th), dth), dim=1)
return xinit
def plot(fname, title=None):
x = np.linspace(-1.0, 1.0, 20)
y = np.linspace(-1.0, 1.0, 20)
X, Y = np.meshgrid(x, y)
Xflat = X.reshape(-1)
Yflat = Y.reshape(-1)
XYflat = np.stack((Xflat, Yflat), axis=1)
Zflat = f_emb_np(XYflat)
Z = Zflat.reshape(X.shape)
fig, ax = plt.subplots()
CS = ax.contourf(X, Y, Z, cmap=cm.Blues)
fig.colorbar(CS)
ax.set_xlim(-1., 1.)
ax.set_ylim(-1., 1.)
if title is not None:
ax.set_title(title)
fig.tight_layout()
fig.savefig(fname)
if __name__ == '__main__':
main()
| dcem-main | exps/cartpole_emb.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from .dcem import dcem
from .dcem_ctrl import dcem_ctrl
| dcem-main | dcem/__init__.py |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import torch
from dcem import dcem
import sys
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose',
color_scheme='Linux', call_pdb=1)
def bmv(X, y):
return X.bmm(y.unsqueeze(2)).squeeze(2)
def test_dcem():
n_batch = 2
n_sample = 100
N = 2
torch.manual_seed(0)
Q = torch.eye(N).unsqueeze(0).repeat(n_batch, 1, 1)
p = 0.1*torch.randn(n_batch, N)
Q_sample = Q.unsqueeze(1).repeat(1, n_sample, 1, 1).view(n_batch*n_sample, N, N)
p_sample = p.unsqueeze(1).repeat(1, n_sample, 1).view(n_batch*n_sample, N)
def f(X):
assert X.size() == (n_batch, n_sample, N)
X = X.view(n_batch*n_sample, N)
obj = 0.5*(bmv(Q_sample, X)*X).sum(dim=1) + (p_sample*X).sum(dim=1)
obj = obj.view(n_batch, n_sample)
return obj
def iter_cb(i, X, fX, I, X_I, mu, sigma):
print(fX.mean(dim=1))
xhat = dcem(
f, nx = N, n_batch = n_batch, n_sample = n_sample,
n_elite = 50, n_iter = 40,
temp = 1.,
normalize = True,
# temp = np.infty,
init_sigma=1.,
iter_cb = iter_cb,
# lb = -5., ub = 5.,
)
Q_LU = torch.lu(Q)
xstar = -torch.lu_solve(p, *Q_LU)
assert (xhat-xstar).abs().max() < 1e-4
if __name__ == '__main__':
test_dcem()
| dcem-main | dcem/test.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import torch
from dcem import dcem
def dcem_ctrl(
obs,
plan_horizon,
init_mu,
init_sigma,
n_sample,
n_elite,
n_iter,
n_ctrl,
temp,
rollout_cost,
lb=None,
ub=None,
iter_cb=None,
dcem_iter_eps=1e-3,
dcem_normalize=True,
):
squeeze = obs.ndimension() == 1
if squeeze:
obs = obs.unsqueeze(0)
assert obs.ndimension() == 2
n_batch, nx = obs.size()
cem_u_dim = plan_horizon*n_ctrl
obs_sample = obs.unsqueeze(1).repeat(1, n_sample, 1)
obs_sample = obs_sample.view(n_batch*n_sample, -1)
def f(u):
assert u.ndimension() == 3
assert u.size(0) == n_batch
assert u.size(2) == cem_u_dim
N = u.size(1)
assert u.ndimension() == 3
assert u.size() == (n_batch, N, plan_horizon*n_ctrl)
u = u.view(n_batch*N, plan_horizon, n_ctrl)
u = u.transpose(0, 1)
assert u.size() == (plan_horizon, n_batch*N, n_ctrl)
if N == 1:
xt = obs.clone()
elif N == n_sample:
xt = obs_sample.clone()
else:
assert False
cost = rollout_cost(xt, u)
assert cost.ndim == 1 and cost.size(0) == n_batch*N
cost.view(n_batch, -1)
return cost
if init_mu is not None and not isinstance(init_mu, float):
assert init_mu.ndimension() == 2
assert init_mu.size() == (n_batch, cem_u_dim)
u = dcem(
f, cem_u_dim,
n_batch=n_batch,
n_sample=n_sample,
n_elite=n_elite, n_iter=n_iter,
temp=temp,
lb=lb, ub=ub,
normalize=dcem_normalize,
init_mu=init_mu, init_sigma=init_sigma,
iter_eps=dcem_iter_eps,
device=obs.device,
iter_cb=iter_cb,
)
cost = f(u.unsqueeze(1))
out = {}
assert u.size() == (n_batch, plan_horizon*n_ctrl)
u = u.view(n_batch, plan_horizon, n_ctrl)
u = u.transpose(0, 1)
assert u.size() == (plan_horizon, n_batch, n_ctrl)
if squeeze:
u = u.squeeze(1)
out['u'] = u
out['init_u'] = u[0]
out['cost'] = cost
out['f'] = f
return out
| dcem-main | dcem/dcem_ctrl.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal
from lml import LML
def dcem(
f,
nx,
n_batch=1,
n_sample=20,
n_elite=10,
n_iter=10,
temp=1.,
lb=None,
ub=None,
init_mu=None,
init_sigma=None,
device=None,
iter_cb=None,
proj_iterate_cb=None,
lml_verbose=0,
lml_eps=1e-3,
normalize=True,
iter_eps=1e-4,
):
if init_mu is None:
init_mu = 0.
size = (n_batch, nx)
if isinstance(init_mu, torch.Tensor):
mu = init_mu.clone()
elif isinstance(init_mu, float):
mu = init_mu * torch.ones(size, requires_grad=True, device=device)
else:
assert False
# TODO: Check if init_mu is in the domain
if init_sigma is None:
init_sigma = 1.
if isinstance(init_sigma, torch.Tensor):
sigma = init_sigma.clone()
elif isinstance(init_sigma, float):
sigma = init_sigma * torch.ones(
size, requires_grad=True, device=device)
else:
assert False
assert mu.size() == size
assert sigma.size() == size
if lb is not None:
assert isinstance(lb, float)
if ub is not None:
assert isinstance(ub, float)
assert ub > lb
for i in range(n_iter):
X = Normal(mu, sigma).rsample((n_sample,)).transpose(0, 1).to(device)
X = X.contiguous()
if lb is not None or ub is not None:
X = torch.clamp(X, lb, ub)
if proj_iterate_cb is not None:
X = proj_iterate_cb(X)
fX = f(X)
X, fX = X.view(n_batch, n_sample, -1), fX.view(n_batch, n_sample)
if temp is not None and temp < np.infty:
if normalize:
fX_mu = fX.mean(dim=1).unsqueeze(1)
fX_sigma = fX.std(dim=1).unsqueeze(1)
_fX = (fX - fX_mu) / (fX_sigma + 1e-6)
else:
_fX = fX
if n_elite == 1:
# I = LML(N=n_elite, verbose=lml_verbose, eps=lml_eps)(-_fX*temp)
I = torch.softmax(-_fX * temp, dim=1)
else:
I = LML(N=n_elite, verbose=lml_verbose,
eps=lml_eps)(-_fX * temp)
I = I.unsqueeze(2)
else:
I_vals = fX.argsort(dim=1)[:, :n_elite]
# TODO: A scatter would be more efficient here.
I = torch.zeros(n_batch, n_sample, device=device)
for j in range(n_batch):
for v in I_vals[j]:
I[j, v] = 1.
I = I.unsqueeze(2)
assert I.shape[:2] == X.shape[:2]
X_I = I * X
old_mu = mu.clone()
mu = torch.sum(X_I, dim=1) / n_elite
if (mu - old_mu).norm() < iter_eps:
break
sigma = ((I * (X - mu.unsqueeze(1))**2).sum(dim=1) / n_elite).sqrt()
if iter_cb is not None:
iter_cb(i, X, fX, I, X_I, mu, sigma)
if lb is not None or ub is not None:
mu = torch.clamp(mu, lb, ub)
return mu
| dcem-main | dcem/dcem.py |
import sys
from os import curdir, sep
import qrcode
from PIL import Image
from http.server import BaseHTTPRequestHandler, HTTPServer
PORT = 8000
class HTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
if (self.path.endswith(".png")):
self.send_response(200)
self.send_header('Content-type','image/png')
self.end_headers()
with open(curdir+sep+self.path, 'rb') as file:
self.wfile.write(file.read())
else:
self.send_response(200)
self.send_header('Content-type',"text/html")
self.end_headers()
content = '''
<html><head><title>Minecraft QR Code Connect</title></head>
<body>
<h1>Minecraft Bot - QR Code Connect!</h1>
<img src = "qrcode.png" alt="qr code">
</body>
</html>
'''
self.wfile.write(bytes(content,'utf8'))
return
def makeQRCode(info):
img = qrcode.make(info)
img.save(curdir+sep+"qrcode.png","PNG")
def run():
server_address = ('',8000)
httpd = HTTPServer(server_address, HTTPHandler)
httpd.serve_forever()
if __name__ == "__main__":
info = sys.argv[1]
makeQRCode(info)
run()
| craftassist-master | cuberite_plugins/minecraft_asr_app/start_qr_web.py |
"""
generate QR code image and start the webserver to display the image
usage: run python qr_web.py -info <info to put in the qr code image>
to start the webserver and generate the QR Code image.
add the flag -update (webserver is already running, just need to regenerate the QR Code image)
"""
import sys
from os import curdir, sep
import qrcode
from PIL import Image
from http.server import BaseHTTPRequestHandler, HTTPServer
import argparse
PORT = 8000
class HTTPHandler(BaseHTTPRequestHandler):
def do_GET(self):
"""respond to GET requests, either html or png request"""
if (self.path.endswith(".png")):
#handle a png image request
self.send_response(200)
self.send_header('Content-type','image/png')
self.end_headers()
with open(curdir + sep + self.path, 'rb') as file:
self.wfile.write(file.read())
else:
#handle a html (any other) request with sending html back
self.send_response(200)
self.send_header('Content-type',"text/html")
self.end_headers()
content = '''
<html><head><title>Minecraft QR Code Connect</title></head>
<body>
<h1>Minecraft Bot - QR Code Connect!</h1>
<img src = "qrcode.png" alt="qr code">
</body>
</html>
'''
self.wfile.write(bytes(content,'utf8'))
return
def makeQRCode(info):
""" generate QR code that stores info """
img = qrcode.make(info)
img.save(curdir+sep+"qrcode.png","PNG")
def run():
""" start the webserver at PORT on localhost """
print("Connect using QR Code: http://localhost:8000")
server_address = ('',PORT)
httpd = HTTPServer(server_address, HTTPHandler)
#starts the webserver with the configs (specified port and HTTP handler)
httpd.serve_forever()
if __name__ == "__main__":
""" parse the arguments given- either need to start the webserver or just update the QR code """
parser = argparse.ArgumentParser()
parser.add_argument("-update",action="store_true")
parser.add_argument("-info",action="store",default="")
parser.add_argument("-port",type=int,action="store",default=8000)
options = parser.parse_args()
PORT = options.port
makeQRCode(options.info)
if not options.update:
run()
| craftassist-master | cuberite_plugins/minecraft_asr_app/qr_web.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This file generates a craft_recipes.h file that is used by the C++ client.
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("items_ini")
parser.add_argument("crafting_txt")
parser.add_argument(
"-o", "--out-file", required=True, help="path to craft_recipes.h file to write"
)
args = parser.parse_args()
# read items.ini
name2idm = {}
with open(args.items_ini, "r") as f:
lines = f.readlines()
for line in reversed(lines): # reverse so lower ids are used for duplicate names
try:
name, val = line.split("=")
except ValueError:
continue
idm = tuple(map(int, val.split(":"))) if ":" in val else (int(val), 0)
name2idm[name] = idm
# read crafting.txt
def fill_recipe(recipe, idm, xs, ys):
for x in xs:
for y in ys:
idx = (y - 1) * 3 + (x - 1)
if recipe[idx] is None:
recipe[idx] = (idm, 1)
return
old_idm, count = recipe[idx]
if old_idm == idm:
recipe[idx] = (idm, count + 1)
return
raise Exception("Failed", recipe, idm, xs, ys)
idm2recipe = {} # idm -> (recipe, count)
with open(args.crafting_txt, "r") as f:
lines = f.readlines()
for line in lines:
# strip comments, empty lines
line = line.split("#")[0]
if line.strip() == "":
continue
assert "=" in line
result, ingredients = line.split("=")
# parse result, count
if "," in result:
# has count
result_name, count = tuple(map(str.strip, result.split(",")))
count = int(count)
else:
# has no count (default=1)
result_name = result.strip()
count = 1
try:
result_idm = name2idm[result_name.lower()]
except KeyError:
print("Ignoring:", line.strip())
continue
# parse ingredients, fill recipe array
recipe = [None] * 9 # array of (idm, count)
ingredients = tuple(map(str.strip, ingredients.split("|")))
for ingredient in ingredients:
# get ingredient idm
name, *locs = ingredient.replace(" ", "").split(",")
name = name.split("^-1")[0]
idm = name2idm[name.lower()]
# get crafting table locations
try:
for loc in locs:
if loc == "*":
fill_recipe(recipe, idm, (1, 2, 3), (1, 2, 3))
continue
x, y = loc.split(":")
if x == "*":
fill_recipe(recipe, idm, (1, 2, 3), (int(y),))
elif y == "*":
fill_recipe(recipe, idm, (int(x),), (1, 2, 3))
else:
fill_recipe(recipe, idm, (int(x),), (int(y),))
except:
print("Failed ing", ingredient.strip())
idm2recipe[result_idm] = (recipe, count)
# print header file
def format_recipe(idm, recipe, count):
key = (idm[0] << 8) | idm[1]
recipe = [((0, 0), 0) if r is None else r for r in recipe]
ingredients = ",".join(["{{{},{},{}}}".format(d, m, c) for ((d, m), c) in recipe])
val = "{{{{{{{}}}}},{}}}".format(ingredients, count)
return "{{{},{}}}".format(key, val)
HEADER = """
// Generated by python/craft_recipes.py
#pragma once
#include <array>
#include <unordered_map>
struct Ingredient {
uint16_t id;
uint8_t meta;
uint8_t count;
};
struct Recipe {
std::array<Ingredient, 9> ingredients;
uint8_t count;
};
// Map key = (id << 8) | meta
const std::unordered_map<uint32_t, Recipe> RECIPES{
"""
HEADER += ",".join([format_recipe(idm, *recipe) for (idm, recipe) in idm2recipe.items()])
HEADER += "};\n"
with open(args.out_file, "w") as f:
f.write(HEADER)
| craftassist-master | python/generate_recipes.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import argparse
import glob
import logging
import numpy as np
import os
import random
import subprocess
import sys
python_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, python_dir)
from cuberite_process import CuberiteProcess
from repo import repo_home
logging.basicConfig(format="%(asctime)s [%(levelname)s]: %(message)s")
logging.getLogger().setLevel(logging.DEBUG)
def to_unit_vec(yaw, pitch):
pitch *= 3.14159 / 180
yaw *= 3.14159 / 180
return np.array(
[-1 * np.cos(pitch) * np.sin(yaw), -1 * np.sin(pitch), np.cos(pitch) * np.cos(yaw)]
)
def ground_height(blocks):
dirt_pct = np.mean(np.mean(blocks[:, :, :, 0] == 2, axis=1), axis=1)
if (dirt_pct > 0.25).any():
return np.argmax(dirt_pct)
return None
def ray_intersect_triangle(p0, p1, triangle):
## Code taken from:
# https://www.erikrotteveel.com/python/three-dimensional-ray-tracing-in-python/
#
# Tests if a ray starting at point p0, in the direction
# p1 - p0, will intersect with the triangle.
#
# arguments:
# p0, p1: numpy.ndarray, both with shape (3,) for x, y, z.
# triangle: numpy.ndarray, shaped (3,3), with each row
# representing a vertex and three columns for x, y, z.
#
# returns:
# 0 if ray does not intersect triangle,
# 1 if it will intersect the triangle,
# 2 if starting point lies in the triangle.
v0, v1, v2 = triangle
u = v1 - v0
v = v2 - v0
normal = np.cross(u, v)
b = np.inner(normal, p1 - p0)
a = np.inner(normal, v0 - p0)
# Here is the main difference with the code in the link.
# Instead of returning if the ray is in the plane of the
# triangle, we set rI, the parameter at which the ray
# intersects the plane of the triangle, to zero so that
# we can later check if the starting point of the ray
# lies on the triangle. This is important for checking
# if a point is inside a polygon or not.
if b == 0.0:
# ray is parallel to the plane
if a != 0.0:
# ray is outside but parallel to the plane
return 0
else:
# ray is parallel and lies in the plane
rI = 0.0
else:
rI = a / b
if rI < 0.0:
return 0
w = p0 + rI * (p1 - p0) - v0
denom = np.inner(u, v) * np.inner(u, v) - np.inner(u, u) * np.inner(v, v)
si = (np.inner(u, v) * np.inner(w, v) - np.inner(v, v) * np.inner(w, u)) / denom
if (si < 0.0) | (si > 1.0):
return 0
ti = (np.inner(u, v) * np.inner(w, u) - np.inner(u, u) * np.inner(w, v)) / denom
if (ti < 0.0) | (si + ti > 1.0):
return 0
if rI == 0.0:
# point 0 lies ON the triangle. If checking for
# point inside polygon, return 2 so that the loop
# over triangles can stop, because it is on the
# polygon, thus inside.
return 2
return 1
def intersect_cube(xyz, camera, focus):
"""
Test if ray 'focus - camera' intersects with the cube
'(x, y, z) - (x + 1, y + 1, z + 1)'
To do this, we check if at least one triangle intersects with
the ray
"""
x, y, z = xyz
triangles = [
[[x, y, z], [x + 1, y, z], [x + 1, y + 1, z]],
[[x, y, z], [x, y + 1, z], [x + 1, y + 1, z]],
[[x, y, z + 1], [x + 1, y, z + 1], [x + 1, y + 1, z + 1]],
[[x, y, z + 1], [x, y + 1, z + 1], [x + 1, y + 1, z + 1]],
[[x, y, z], [x + 1, y, z], [x + 1, y, z + 1]],
[[x, y, z], [x, y, z + 1], [x + 1, y, z + 1]],
[[x, y + 1, z], [x + 1, y + 1, z], [x + 1, y + 1, z + 1]],
[[x, y + 1, z], [x, y + 1, z + 1], [x + 1, y + 1, z + 1]],
[[x, y, z], [x, y + 1, z], [x, y + 1, z + 1]],
[[x, y, z], [x, y, z + 1], [x, y + 1, z + 1]],
[[x + 1, y, z], [x + 1, y + 1, z], [x + 1, y + 1, z + 1]],
[[x + 1, y, z], [x + 1, y, z + 1], [x + 1, y + 1, z + 1]],
]
for t in triangles:
if (
ray_intersect_triangle(
np.array(camera).astype("float32"),
np.array(focus).astype("float32"),
np.array(t).astype("float32"),
)
== 1
):
return True
return False
def change_one_block(schematic, yaw):
## remove 'air' blocks whose ids are 0s
ymax, zmax, xmax, _ = schematic.shape
ys, zs, xs, _ = np.nonzero(schematic[:, :, :, :1] > 0)
xyzs = list(zip(*[xs, ys, zs]))
distance_range = (5, int((xmax ** 2 + zmax ** 2) ** 0.5 / 2))
min_camera_height = 1 # the camera shouldn't be underground
pitch_range = (-60, 10)
while True:
focus = random.choice(xyzs) # randomly select a block as the focus
pitch = random.randint(*pitch_range)
distance = random.randint(*distance_range)
look_xyz = to_unit_vec(*[yaw, pitch])
camera = focus - (look_xyz * distance)
if camera[1] <= min_camera_height:
continue
intersected = [
(np.linalg.norm(np.array(xyz) - camera), xyz)
for xyz in xyzs
if intersect_cube(xyz, camera, focus)
]
## sort the blocks according to their distances to the camera
## pick the nearest block that intersects with the ray starting at 'camera'
## and looking at 'focus'
intersected = sorted(intersected, key=lambda p: p[0])
if len(intersected) > 0 and intersected[0][0] > distance_range[0]:
## the nearest block should have a distance > 10
break
x, y, z = intersected[0][1]
## change a non-zero block to red wool (id: 35, meta: 14)
schematic[y][z][x] = [35, 14]
return pitch, camera
def render(
npy_file, out_dir, no_chunky, no_vision, port, yaw, pitch, camera, spp, img_size, block_change
):
schematic = np.load(npy_file)
# remove blocks below ground-level
g = ground_height(schematic)
schematic = schematic[(g or 0) :, :, :, :]
if yaw is None:
yaw = random.randint(0, 360 - 1)
if block_change:
pitch, camera = change_one_block(schematic, yaw)
# TODO: +63 only works for flat_world seed=0
camera[1] += 63 # why??
logging.info("Launching cuberite at port {}".format(port))
p = CuberiteProcess(
"flat_world", seed=0, game_mode="creative", place_blocks_yzx=schematic, port=port
)
logging.info("Destroying cuberite at port {}".format(port))
p.destroy()
world_dir = os.path.join(p.workdir, "world")
region_dir = os.path.join(world_dir, "region")
mca_files = glob.glob(os.path.join(region_dir, "*.mca"))
assert len(mca_files) > 0, "No region files at {}".format(region_dir)
render_view_bin = os.path.join(repo_home, "bin/render_view")
assert os.path.isfile(
render_view_bin
), "{} not found.\n\nTry running: make render_view".format(render_view_bin)
procs = []
if not no_vision:
call = [
str(a)
for a in [
render_view_bin,
"--out-dir",
out_dir,
"--mca-files",
*mca_files,
"--camera",
*camera,
"--look",
yaw,
pitch,
]
]
logging.info("CALL: " + " ".join(call))
procs.append(subprocess.Popen(call))
if not no_chunky:
call = [
str(a)
for a in [
"python3.7",
"{}/python/minecraft_render/render.py".format(repo_home),
"--world",
world_dir,
"--out",
"{}/chunky.{}.{}.{}.{}.png".format(
out_dir, list(map(int, camera)), pitch, yaw, int(block_change)
),
"--camera",
*camera,
"--look",
yaw,
pitch,
"--size",
*img_size,
"--spp",
spp,
]
]
logging.info("CALL: " + " ".join(call))
procs.append(subprocess.Popen(call))
for p in procs:
p.wait()
return yaw, pitch, camera
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("npy_schematic")
parser.add_argument(
"--out-dir", "-o", required=True, help="Directory in which to write vision files"
)
parser.add_argument(
"--no-chunky", action="store_true", help="Skip generation of chunky (human-view) images"
)
parser.add_argument("--no-vision", action="store_true", help="Skip generation of agent vision")
parser.add_argument("--spp", type=int, default=100, help="samples per pixel")
parser.add_argument("--port", type=int, default=25565)
parser.add_argument("--size", type=int, nargs=2, default=[800, 600])
args = parser.parse_args()
yaw, pitch, camera = render(
args.npy_schematic,
args.out_dir,
args.no_chunky,
args.no_vision,
args.port,
None,
None,
None,
args.spp,
args.size,
True,
)
| craftassist-master | python/render_one_block_change.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
""" Visualize Segmentation """
import numpy as np
import pickle
import os
import sys
import json
import random
import glob
from tqdm import tqdm
possible_types = [(35, i) for i in range(1, 16)]
possible_types.extend(
[
(1, 0),
(2, 0),
(3, 0),
(5, 0),
(7, 0),
(11, 0),
(12, 0),
(12, 1),
(13, 0),
(17, 0),
(17, 2),
(18, 0),
(19, 0),
(20, 0),
(21, 0),
(22, 0),
(23, 0),
(24, 0),
(25, 0),
]
)
""" Given components, return a generated numpy file. """
def gen_segmentation_npy(raw_data, name, save_folder="../../house_segment/"):
seg_data = []
inf = 100000
xmin, ymin, zmin = inf, inf, inf
xmax, ymax, zmax = -inf, -inf, -inf
for i in range(len(raw_data)):
bid, meta = possible_types[i % len(possible_types)]
for xyz in raw_data[i][1]:
x, y, z = xyz
seg_data.append((x, y, z, bid, meta))
xmin = min(xmin, x)
ymin = min(ymin, y)
zmin = min(zmin, z)
xmax = max(xmax, x)
ymax = max(ymax, y)
zmax = max(zmax, z)
dims = [xmax - xmin + 1, ymax - ymin + 1, zmax - zmin + 1, 2]
mat = np.zeros(dims, dtype="uint8")
for block in seg_data:
x, y, z, bid, meta = block
mat[x - xmin, y - ymin, z - zmin, :] = bid, meta
npy_schematic = np.transpose(mat, (1, 2, 0, 3))
save_file = save_folder + name
np.save(save_file, npy_schematic)
return save_file + ".npy"
def visualize_segmentation(segment_pkl, save_folder="../../house_segment/"):
name = segment_pkl.split("/")[-1][:-4]
if not os.path.exists(save_folder + name):
os.makedirs(save_folder + name)
raw_data = np.load(segment_pkl)
if len(raw_data) > len(possible_types):
print(
"Warning: # of segments exceed total number of different blocks %d > %d"
% (len(raw_data), len(possible_types))
)
npy_file = gen_segmentation_npy(raw_data, name, save_folder + name + "/")
cmd = "python render_schematic.py %s --out-dir=%s" % (npy_file, save_folder + name)
os.system(cmd)
def visualize_segmentation_by_step(segment_pkl, save_folder="../../house_segment/"):
name = segment_pkl.split("/")[-1][:-4]
if not os.path.exists(save_folder + name):
os.makedirs(save_folder + name)
folder_name = save_folder + name + "/real"
if not os.path.exists(folder_name):
os.makedirs(folder_name)
cmd = "python render_schematic.py %s --out-dir=%s" % (
"../../minecraft_houses/%s/schematic.npy" % name,
folder_name,
)
os.system(cmd)
raw_data = np.load(segment_pkl)
if len(raw_data) > len(possible_types):
print(
"Warning: # of segments exceed total number of different blocks %d > %d"
% (len(raw_data), len(possible_types))
)
fname = "../../minecraft_houses/%s/placed.json" % name
build_data = json.load(open(fname, "r"))
time_data = {}
inf = 100000
minx, miny, minz = inf, inf, inf
maxx, maxy, maxz = -inf, -inf, -inf
for i, item in enumerate(build_data):
x, y, z = item[2]
if item[-1] == "B":
continue
assert item[-1] == "P"
minx = min(minx, x)
miny = min(miny, y)
minz = min(minz, z)
maxx = max(maxx, x)
maxy = max(maxy, y)
maxz = max(maxz, z)
for i, item in enumerate(build_data):
x, y, z = item[2]
y -= miny
z -= minz
x -= minx
time_data[(x, y, z)] = i
segments_time = []
for i in range(len(raw_data)):
avg_time = []
for xyz in raw_data[i][1]:
try:
avg_time.append(time_data[xyz])
except:
from IPython import embed
embed()
avg_time = np.mean(avg_time)
segments_time.append((avg_time, i))
segments_time = sorted(segments_time)
order_data = []
for avg_time, cid in segments_time:
order_data.append(raw_data[cid])
order_file = open("%s" % save_folder + "order_data/%s.pkl" % name, "wb")
pickle.dump(order_data, order_file)
order_file.close()
for i in range(len(order_data)):
npy_file = gen_segmentation_npy(
order_data[: i + 1], name + "_step%d" % (i), save_folder + name + "/"
)
folder_name = save_folder + name + "/step%d" % i
if not os.path.exists(folder_name):
os.makedirs(folder_name)
cmd = "python render_schematic.py %s --out-dir=%s" % (npy_file, folder_name)
os.system(cmd)
def save_order_data(segment_pkl, save_folder="../../house_segment/"):
name = segment_pkl.split("/")[-1][:-4]
raw_data = np.load(segment_pkl)
fname = "../../minecraft_houses/%s/placed.json" % name
try:
build_data = json.load(open(fname, "r"))
except:
print("can't load %s ... skip" % fname)
return
time_data = {}
inf = 100000
minx, miny, minz = inf, inf, inf
maxx, maxy, maxz = -inf, -inf, -inf
for i, item in enumerate(build_data):
x, y, z = item[2]
if item[-1] == "B":
continue
assert item[-1] == "P"
minx = min(minx, x)
miny = min(miny, y)
minz = min(minz, z)
maxx = max(maxx, x)
maxy = max(maxy, y)
maxz = max(maxz, z)
for i, item in enumerate(build_data):
x, y, z = item[2]
y -= miny
z -= minz
x -= minx
time_data[(x, y, z)] = i
segments_time = []
for i in range(len(raw_data)):
avg_time = []
for xyz in raw_data[i][1]:
try:
avg_time.append(time_data[xyz])
except:
from IPython import embed
embed()
avg_time = np.mean(avg_time)
segments_time.append((avg_time, i))
segments_time = sorted(segments_time)
order_data = []
for avg_time, cid in segments_time:
order_data.append(raw_data[cid])
order_file = open("%s" % save_folder + "order_data/%s.pkl" % name, "wb")
pickle.dump(order_data, order_file)
order_file.close()
if __name__ == "__main__":
mode = sys.argv[1]
print("mode: %s" % mode)
random.seed(10)
if mode == "auto":
segment_files = glob.glob("../../house_components/*.pkl")
random.shuffle(segment_files)
for i in range(10):
visualize_segmentation_by_step(segment_files[i])
elif mode == "all":
segment_pkl = sys.argv[2]
visualize_segmentation(segment_pkl)
elif mode == "stepbystep":
segment_pkl = sys.argv[2]
visualize_segmentation_by_step(segment_pkl)
elif mode == "saveorder":
segment_files = glob.glob("../../house_components/*.pkl")
for i in tqdm(range(len(segment_files)), desc="save order data"):
save_order_data(segment_files[i])
else:
print("mode not found!")
| craftassist-master | python/visual_segmentation.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import atexit
import logging
import numpy as np
import os
import shutil
import subprocess
import tempfile
import time
import edit_cuberite_config
import place_blocks
import repo
from wait_for_cuberite import wait_for_cuberite
from craftassist.shape_helpers import build_shape_scene
logging.basicConfig(format="%(asctime)s [%(levelname)s]: %(message)s")
logging.getLogger().setLevel(logging.DEBUG)
repo_home = repo.repo_home
DEFAULT_PORT = 25565
def add_plugins(workdir, plugins):
"""Add plugins to cuberite's config"""
for p in plugins:
edit_cuberite_config.add_plugin(workdir + "/settings.ini", p)
def create_workdir(
config_name, seed, game_mode, port, plugins, place_blocks_yzx, workdir_root=None
):
if workdir_root is None:
workdir_root = tempfile.mkdtemp()
os.makedirs(workdir_root, exist_ok=True)
workdir = os.path.join(workdir_root, "cuberite")
config_dir = os.path.join(repo_home, "cuberite_config", config_name)
plugins_dir = os.path.join(repo_home, "cuberite_plugins")
shutil.copytree(config_dir, workdir)
shutil.copytree(plugins_dir, workdir + "/Plugins")
edit_cuberite_config.set_port(workdir + "/settings.ini", port)
edit_cuberite_config.set_seed(workdir + "/world/world.ini", seed)
if game_mode == "survival":
edit_cuberite_config.set_mode_survival(workdir + "/world/world.ini")
elif game_mode == "creative":
edit_cuberite_config.set_mode_creative(workdir + "/world/world.ini")
else:
raise ValueError("create_workdir got bad game_mode={}".format(game_mode))
if place_blocks_yzx is not None:
generate_place_blocks_plugin(workdir, place_blocks_yzx)
add_plugins(workdir, plugins)
return workdir
def generate_place_blocks_plugin(workdir, place_blocks_yzx):
# Generate place_blocks.lua plugin
plugin_dir = workdir + "/Plugins/place_blocks"
plugin_template = plugin_dir + "/place_blocks.lua.template"
# Read plugin template
with open(plugin_template, "r") as f:
template = f.read()
# Generate lua code
if type(place_blocks_yzx) == list:
dicts = place_blocks_yzx
else:
dicts = place_blocks.yzx_to_dicts(place_blocks_yzx)
blocks_to_place = place_blocks.dicts_to_lua(dicts)
out = template.replace("__BLOCKS_TO_PLACE__", blocks_to_place)
# Write lua code
with open(plugin_dir + "/place_blocks.lua", "w") as f:
f.write(out)
# Add place_blocks lua plugin to config
edit_cuberite_config.add_plugin(workdir + "/settings.ini", "place_blocks")
class CuberiteProcess:
def __init__(
self,
config_name,
seed,
game_mode="survival",
port=DEFAULT_PORT,
plugins=[],
log_comm_in=False,
place_blocks_yzx=None,
workdir_root=None,
):
self.workdir = create_workdir(
config_name, seed, game_mode, port, plugins, place_blocks_yzx, workdir_root
)
logging.info("Cuberite workdir: {}".format(self.workdir))
popen = [repo_home + "/cuberite/Server/Cuberite"]
if log_comm_in:
popen.append("--log-comm-in")
self.p = subprocess.Popen(popen, cwd=self.workdir, stdin=subprocess.PIPE)
self.cleaned_up = False
atexit.register(self.atexit)
wait_for_cuberite("localhost", port)
logging.info("Cuberite listening at port {}".format(port))
def destroy(self):
# Cuberite often segfaults if we kill it while an player is disconnecting.
# Rather than fix a bug in Cuberite, let's just give Cuberite a moment to
# gather its bearings.
time.sleep(0.25)
self.p.terminate()
self.p.wait()
self.cleaned_up = True
def wait(self):
self.p.wait()
def atexit(self):
if not self.cleaned_up:
logging.info("Killing pid {}".format(self.p.pid))
self.p.kill()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--config", default="diverse_world")
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--port", type=int, default=25565)
parser.add_argument("--logging", action="store_true")
parser.add_argument("--log-comm-in", action="store_true")
parser.add_argument("--mode", choices=["creative", "survival"], default="creative")
parser.add_argument("--workdir")
parser.add_argument("--npy_schematic")
parser.add_argument("--random_shapes", action="store_true")
parser.add_argument("--add-plugin", action="append", default=[])
args = parser.parse_args()
plugins = ["debug", "chatlog", "point_blocks"] + args.add_plugin
if args.logging:
plugins += ["logging"]
schematic = None
# if args.npy_schematic, load the schematic when starting
if args.npy_schematic:
schematic = np.load(args.npy_schematic)
if args.random_shapes:
# TODO allow both?
print("warning: ignoring the schematic and using random shapes")
if args.random_shapes:
schematic = build_shape_scene()
p = CuberiteProcess(
args.config,
seed=args.seed,
game_mode=args.mode,
port=args.port,
plugins=plugins,
log_comm_in=args.log_comm_in,
place_blocks_yzx=schematic,
workdir_root=args.workdir,
)
p.wait()
| craftassist-master | python/cuberite_process.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import random
import atexit
from agent import Agent
from cuberite_process import CuberiteProcess
random.seed(0)
p = CuberiteProcess("flat_world", seed=0, game_mode="creative")
atexit.register(lambda: p.destroy()) # close Cuberite server when this script exits
agent = Agent("localhost", 25565, "example_bot")
# Random walk forever
while True:
random.choice([agent.step_pos_x, agent.step_pos_z, agent.step_neg_x, agent.step_neg_z])()
| craftassist-master | python/example_agent_random.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This .ini file config parser accepts multiple keys with the same name, unlike
Python's configparser.
"""
import contextlib
@contextlib.contextmanager
def inplace_edit(path):
with open(path, "r") as f:
config = read_config(f.readlines())
yield config
with open(path, "w") as f:
write_config(f, config)
def read_config(lines):
"""Read the config into a dictionary"""
d = {}
current_section = None
for i, line in enumerate(lines):
line = line.strip()
if len(line) == 0 or line.startswith(";"):
continue
if line.startswith("[") and line.endswith("]"):
current_section = line[1:-1]
d[current_section] = {}
else:
if "=" not in line:
raise ValueError("No = in line: {}".format(line))
key, val = line.split("=", maxsplit=1)
if key in d[current_section]:
old_val = d[current_section][key]
if type(old_val) == list:
old_val.append(val)
else:
d[current_section][key] = [old_val, val]
else:
d[current_section][key] = val
return d
def write_config(f, config):
"""Write out config into file f"""
for section, data in config.items():
f.write("[{}]\n".format(section))
for key, val in data.items():
if type(val) == list:
for v in val:
f.write("{}={}\n".format(key, v))
else:
f.write("{}={}\n".format(key, val))
f.write("\n")
| craftassist-master | python/config_parser.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import socket
# Raw bytes of handshake and ping packets, see http://wiki.vg/Protocol#Ping
HANDSHAKE_PING = b"\x10\x00\xd4\x02\tlocalhost\x63\xdd\x01\t\x01\x00\x00\x00\x00\x00\x00\x00*"
# Raw bytes of clientbound pong packet, see http://wiki.vg/Protocol#Pong
PONG = b"\x09\x01\x00\x00\x00\x00\x00\x00\x00\x2a"
def ping(host, port, timeout=10):
"""Ping cuberite using a socket connection"""
s = socket.socket()
s.connect((host, port))
s.settimeout(timeout)
s.send(HANDSHAKE_PING)
response = s.recv(len(PONG))
assert response == PONG, "Bad pong: {}".format(response)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="localhost")
parser.add_argument("--port", type=int, default=25565)
args = parser.parse_args()
print("Sending ping to {}:{}".format(args.host, args.port))
ping(args.host, args.port)
print("Received pong!")
| craftassist-master | python/ping_cuberite.py |
craftassist-master | python/__init__.py |
|
"""
Copyright (c) Facebook, Inc. and its affiliates.
Tool to convert betweeen .schematic and .npy formats
The output is a .npy formatted 4d-array of uint8 with shape (y, z, x, 2), where
the last dimension is id/meta.
"""
import argparse
import os
import subprocess
import tempfile
import gzip
from repo import repo_home
BIN = os.path.join(repo_home, "bin", "schematic_convert")
parser = argparse.ArgumentParser()
parser.add_argument("schematic", help=".schematic file to read")
parser.add_argument("out_file", help="File to write the .npy format to")
args = parser.parse_args()
if not os.path.isfile(BIN):
subprocess.check_call("make schematic_convert", shell=True, cwd=repo_home)
# read the schematic file
with open(args.schematic, "rb") as f:
bs = gzip.GzipFile(fileobj=f).read()
unzipped = tempfile.mktemp()
with open(unzipped, "wb") as f:
f.write(bs)
subprocess.check_call([BIN, unzipped, args.out_file])
| craftassist-master | python/schematic_convert.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import time
import agent
DEFAULT_PORT = 25565
def agent_init(port=DEFAULT_PORT):
""" initialize the agent on localhost at specified port"""
return agent.Agent("localhost", port, default_agent_name())
def default_agent_name():
"""Use a unique name based on timestamp"""
return "bot.{}".format(str(time.time())[3:13])
| craftassist-master | python/agent_connection.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import os
python_dir = os.path.dirname(os.path.realpath(__file__))
repo_home = os.path.join(python_dir, "..")
def path(p):
return os.path.join(repo_home, p)
| craftassist-master | python/repo.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""This file has functions that an help edit the config
got cuberite."""
import config_parser
def set_seed(path, seed):
with config_parser.inplace_edit(path) as config:
config["Seed"]["Seed"] = seed
def add_plugin(path, plugin):
with config_parser.inplace_edit(path) as config:
config["Plugins"]["Plugin"].append(plugin)
def remove_plugin(path, plugin):
with config_parser.inplace_edit(path) as config:
config["Plugins"]["Plugin"].remove(plugin)
def set_mode_survival(path):
with config_parser.inplace_edit(path) as config:
config["General"]["GameMode"] = 0
def set_mode_creative(path):
with config_parser.inplace_edit(path) as config:
config["General"]["GameMode"] = 1
def set_port(path, port):
with config_parser.inplace_edit(path) as config:
config["Server"]["Ports"] = port
| craftassist-master | python/edit_cuberite_config.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import argparse
import glob
import logging
import numpy as np
import os
import pathlib
import subprocess
import sys
python_dir = pathlib.Path(__file__).parents[0].absolute()
sys.path.insert(0, python_dir)
from cuberite_process import CuberiteProcess
from repo import repo_home
logging.basicConfig(stream=sys.stdout, format="%(asctime)s [%(levelname)s]: %(message)s")
logging.getLogger().setLevel(logging.DEBUG)
def to_unit_vec(yaw, pitch):
pitch *= 3.14159 / 180
yaw *= 3.14159 / 180
return np.array(
[-1 * np.cos(pitch) * np.sin(yaw), -1 * np.sin(pitch), np.cos(pitch) * np.cos(yaw)]
)
def ground_height(blocks):
"""Return ground height"""
dirt_pct = np.mean(np.mean(blocks[:, :, :, 0] == 2, axis=1), axis=1)
if (dirt_pct > 0.25).any():
return np.argmax(dirt_pct)
return None
def render(
npy_file, out_dir, world, seed, no_chunky, no_vision, port, distance, yaws, spp, img_size
):
"""This function renders the npy_file in the world using cuberite"""
# step 1: create the world with Cuberite, with npy blocks placed
logging.info("Launching cuberite at port {}".format(port))
if npy_file != "":
schematic = np.load(npy_file)
p = CuberiteProcess(
world, seed=0, game_mode="creative", place_blocks_yzx=schematic, port=port
)
else:
schematic = None
p = CuberiteProcess(
world, seed=0, game_mode="creative", port=port, plugins=["debug", "spawn_position"]
)
logging.info("Destroying cuberite at port {}".format(port))
p.destroy()
world_dir = os.path.join(p.workdir, "world")
print("==========================")
print("WORLD directory:", world_dir)
print("==========================")
region_dir = os.path.join(world_dir, "region")
mca_files = glob.glob(os.path.join(region_dir, "*.mca"))
assert len(mca_files) > 0, "No region files at {}".format(region_dir)
# step 2: render view binary
render_view_bin = os.path.join(repo_home, "bin/render_view")
assert os.path.isfile(
render_view_bin
), "{} not found.\n\nTry running: make render_view".format(render_view_bin)
if schematic is not None:
# render a numpy object, set focus and distance
# remove blocks below ground-level
g = ground_height(schematic)
schematic = schematic[(g or 0) :, :, :, :]
ymax, zmax, xmax, _ = schematic.shape
ymid, zmid, xmid = ymax // 2, zmax // 2, xmax // 2
focus = np.array([xmid, ymid + 63, zmid]) # TODO: +63 only works for flat_world seed=0
if distance is None:
distance = int((xmax ** 2 + zmax ** 2) ** 0.5)
else:
f = open(p.workdir + "/spawn.txt", "r")
playerx, playery, playerz = [float(i) for i in f.read().split("\n")]
f.close()
print("Spawn position:", playerx, playery, playerz)
procs = []
if yaws is None:
yaws = range(0, 360, 90)
for yaw in yaws:
look = [yaw, 0]
look_xyz = to_unit_vec(*look)
if schematic is not None:
camera = focus - (look_xyz * distance)
else:
camera = np.array([playerx, playery + 1.6, playerz])
if not no_vision:
call = [
render_view_bin,
"--out-prefix",
out_dir + "/vision.%d" % yaw,
"--mca-files",
*mca_files,
"--camera",
*camera,
"--sizes",
*img_size,
"--look",
yaw,
0,
"--block",
1,
"--depth",
1,
"--blockpos",
1,
]
call = list(map(str, call))
logging.info("CALL: " + " ".join(call))
procs.append(subprocess.Popen(call))
if not no_chunky:
call = [
"python",
"{}/python/minecraft_render/render.py".format(repo_home),
"--world",
world_dir,
"--out",
"{}/chunky.{}.png".format(out_dir, yaw),
"--camera",
*camera,
"--look",
*look,
"--size",
*img_size,
"--spp",
spp,
"--chunk-min",
-10,
"--chunk-max",
10,
]
call = list(map(str, call))
logging.info("CALL: " + " ".join(call))
procs.append(subprocess.Popen(call))
for p in procs:
p.wait()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--npy_schematic",
default="",
help="a 3D numpy array (e.g., a house) to render in the world, if missing only the world ",
)
parser.add_argument(
"--out-dir", "-o", required=True, help="Directory in which to write vision files"
)
parser.add_argument(
"--world", default="flat_world", help="world style, [flat_world, diverse_world]"
)
parser.add_argument("--seed", default=0, type=int, help="Value of seed")
parser.add_argument(
"--no-chunky", action="store_true", help="Skip generation of chunky (human-view) images"
)
parser.add_argument("--no-vision", action="store_true", help="Skip generation of agent vision")
parser.add_argument("--distance", type=int, help="Distance from camera to schematic center")
parser.add_argument("--yaws", type=int, nargs="+", help="Angles from which to take photos")
parser.add_argument("--spp", type=int, default=100, help="samples per pixel")
parser.add_argument("--port", type=int, default=25565)
parser.add_argument("--size", type=int, nargs=2, default=[256, 256])
args = parser.parse_args()
render(
args.npy_schematic,
args.out_dir,
args.world,
args.seed,
args.no_chunky,
args.no_vision,
args.port,
args.distance,
args.yaws,
args.spp,
args.size,
)
| craftassist-master | python/render_schematic.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
def yzx_to_dicts(yzx, y_offset=63):
"""Converts yzx format array into a dictionary
with keys: x, y, z, id and meta"""
yzx = yzx["schematic"]
ysize, zsize, xsize, _ = yzx.shape
if ysize + y_offset > 255:
raise ValueError("Shape is too big {}".format(yzx.shape))
blocks = []
for y in range(ysize):
for z in range(zsize):
for x in range(xsize):
bid, bmeta = yzx[y, z, x, :]
blocks.append(
{"x": x, "y": y + y_offset, "z": z, "id": int(bid), "meta": int(bmeta)}
)
return blocks
def dicts_to_lua(dicts):
"""Convert the dictionary to lua format"""
block_strs = []
for d in dicts:
s = "{" + ",".join("{}".format(d[k]) for k in ["x", "y", "z", "id", "meta"]) + "}"
block_strs.append(s)
return "{" + ",".join(block_strs) + "}"
| craftassist-master | python/place_blocks.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import socket
import time
import ping_cuberite
def wait_for_server(host, port, wait_ms=200, max_tries=200):
"""This function tries max_tries times to connect to the
host at the port using a socket connection"""
for i in range(max_tries):
try:
s = socket.socket()
s.connect((host, port))
s.close()
return
except ConnectionError as e:
time.sleep(wait_ms / 1000.0)
# Never came up, throw connection error
waited_s = wait_ms * max_tries / 1000
raise ConnectionError("Cuberite not up at port {} after {}s".format(port, waited_s))
def wait_for_cuberite(host, port):
wait_for_server(host, port)
ping_cuberite.ping(host, port, timeout=10)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="localhost")
parser.add_argument("--port", type=int, default=25565)
args = parser.parse_args()
wait_for_cuberite(args.host, args.port)
| craftassist-master | python/wait_for_cuberite.py |
import argparse
import os
class ArgumentParser:
def __init__(self, agent_type, base_path):
self.agent_parsers = {"Minecraft": self.add_mc_parser, "Locobot": self.add_loco_parser}
self.base_path = base_path
self.parser = argparse.ArgumentParser()
# NSP args
self.add_nsp_parser()
# Agent specific args
self.agent_parsers[agent_type]()
# Common / Debug stuff
self.parser.add_argument(
"--verify_hash_script_path",
default="../../data_scripts/compare_directory_hash.sh",
help="path to script that checks hash against latest models",
)
self.parser.add_argument("--verbose", "-v", action="store_true", help="Debug logging")
def add_nsp_parser(self):
nsp_parser = self.parser.add_argument_group("Neural Semantic Parser Args")
nsp_parser.add_argument(
"--model_base_path",
default="#relative",
help="if empty model paths are relative to this file",
)
nsp_parser.add_argument(
"--QA_nsp_model_path",
default="models/semantic_parser/ttad/ttad.pth",
help="path to previous TTAD model for QA",
)
nsp_parser.add_argument(
"--nsp_model_dir",
default="models/semantic_parser/ttad_bert_updated/",
help="path to current listener model dir",
)
nsp_parser.add_argument(
"--nsp_embeddings_path",
default="models/semantic_parser/ttad/ttad_ft_embeds.pth",
help="path to current model embeddings",
)
nsp_parser.add_argument(
"--nsp_grammar_path",
default="models/semantic_parser/ttad/dialogue_grammar.json",
help="path to grammar",
)
nsp_parser.add_argument(
"--nsp_data_dir", default="datasets/annotated_data/", help="path to annotated data"
)
nsp_parser.add_argument(
"--ground_truth_data_dir",
default="datasets/ground_truth/",
help="path to folder of common short and templated commands",
)
nsp_parser.add_argument(
"--no_ground_truth",
action="store_true",
default=False,
help="do not load from ground truth",
)
nsp_parser.add_argument("--web_app", action="store_true", help="use web app")
def add_mc_parser(self):
mc_parser = self.parser.add_argument_group("Minecraft Agent Args")
mc_parser.add_argument(
"--semseg_model_path", default="", help="path to semantic segmentation model"
)
mc_parser.add_argument(
"--geoscorer_model_path", default="", help="path to geoscorer model"
)
mc_parser.add_argument("--port", type=int, default=25565)
mc_parser.add_argument(
"--no_default_behavior",
action="store_true",
help="do not perform default behaviors when idle",
)
def add_loco_parser(self):
loco_parser = self.parser.add_argument_group("Locobot Agent Args")
IP = "192.168.1.244"
if os.getenv("LOCOBOT_IP"):
IP = os.getenv("LOCOBOT_IP")
print("setting default locobot ip from env variable LOCOBOT_IP={}".format(IP))
loco_parser.add_argument("--ip", default=IP, help="IP of the locobot")
loco_parser.add_argument(
"--incoming_chat_path", default="incoming_chat.txt", help="path to incoming chat file"
)
loco_parser.add_argument("--silent", default=False)
loco_parser.add_argument("--backend", default="habitat")
loco_parser.add_argument(
"--perception_model_dir",
default="models/perception/",
help="path to perception model data dir",
)
def fix_path(self, opts):
if opts.model_base_path == "#relative":
base_path = self.base_path
else:
base_path = opts.model_base_path
od = opts.__dict__
for optname, optval in od.items():
if "path" in optname or "dir" in optname:
if optval:
od[optname] = os.path.join(base_path, optval)
return opts
def parse(self):
opts = self.parser.parse_args()
return self.fix_path(opts)
| craftassist-master | python/argument_parser.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import os
import sys
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.stop_condition import StopCondition
class AgentAdjacentStopCondition(StopCondition):
def __init__(self, agent, bid):
super().__init__(agent)
self.bid = bid
self.name = "adjacent_block"
def check(self):
B = self.agent.get_local_blocks(1)
return (B[:, :, :, 0] == self.bid).any()
| craftassist-master | python/craftassist/mc_stop_condition.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from test.fake_agent import FakeAgent
# from craftassist.test.fake_agent import FakeAgent
from typing import Dict
from mc_util import Player, Pos, Look, Item, XYZ, IDM
from world import World, Opt, flat_ground_generator
class BaseSQLMockEnvironment:
def __init__(self):
# Replica of test environment
spec = {
"players": [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))],
"mobs": [],
"ground_generator": flat_ground_generator,
"agent": {"pos": (0, 63, 0)},
"coord_shift": (-16, 54, -16),
}
world_opts = Opt()
world_opts.sl = 32
self.world = World(world_opts, spec)
self.agent = FakeAgent(self.world, opts=None)
self.speaker = "cat"
def handle_logical_form(self, logical_form: Dict, chatstr: str = "") -> Dict[XYZ, IDM]:
"""Handle an action dict and call self.flush()
"""
obj = self.agent.dialogue_manager.handle_logical_form(self.speaker, logical_form, chatstr)
if obj is not None:
self.agent.dialogue_manager.dialogue_stack.append(obj)
self.flush()
return obj
def flush(self) -> Dict[XYZ, IDM]:
"""Update memory and step the dialogue stacks
"""
self.agent.dialogue_manager.dialogue_stack.step()
return
| craftassist-master | python/craftassist/base_sql_mock_environment.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import numpy as np
import os
import pickle
PATH = os.path.join(os.path.dirname(__file__), "../../minecraft_specs")
assert os.path.isdir(PATH), (
"Not found: "
+ PATH
+ "\n\nDid you follow the instructions at "
+ "https://github.com/fairinternal/minecraft#getting-started"
)
_BLOCK_DATA = None
def get_block_data():
global _BLOCK_DATA
if _BLOCK_DATA is None:
_BLOCK_DATA = _pickle_load("block_images/block_data")
return _BLOCK_DATA
_COLOUR_DATA = None
def get_colour_data():
global _COLOUR_DATA
if _COLOUR_DATA is None:
_COLOUR_DATA = _pickle_load("block_images/color_data")
return _COLOUR_DATA
_BLOCK_PROPERTY_DATA = None
def get_block_property_data():
global _BLOCK_PROPERTY_DATA
if _BLOCK_PROPERTY_DATA is None:
_BLOCK_PROPERTY_DATA = _pickle_load("block_images/block_property_data")
return _BLOCK_PROPERTY_DATA
_MOB_PROPERTY_DATA = None
def get_mob_property_data():
global _MOB_PROPERTY_DATA
if _MOB_PROPERTY_DATA is None:
_MOB_PROPERTY_DATA = _pickle_load("block_images/mob_property_data")
return _MOB_PROPERTY_DATA
def get_bid_to_colours():
bid_to_name = get_block_data()["bid_to_name"]
name_to_colors = get_colour_data()["name_to_colors"]
bid_to_colors = {}
for item in bid_to_name.keys():
name = bid_to_name[item]
if name in name_to_colors:
color = name_to_colors[name]
bid_to_colors[item] = color
return bid_to_colors
def get_schematics(limit=-1):
"""Return a list of {'schematic': npy array, 'tags': tags, 'name': names} dicts"""
schem_dir = os.path.join(PATH, "schematics")
s = []
for fname in os.listdir(schem_dir):
fullname = os.path.join(schem_dir, fname)
if not os.path.isdir(fullname):
with open(fullname, "rb") as f:
schematic_premem = pickle.load(f)
assert type(schematic_premem["schematic"]) is np.ndarray
s.append(schematic_premem)
if limit > 0:
s = np.random.permute(s)[:limit]
return s
def _pickle_load(relpath):
with open(os.path.join(PATH, relpath), "rb") as f:
return pickle.load(f)
| craftassist-master | python/craftassist/minecraft_specs.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""This file has implementation for a variety of shapes and
their arrangements"""
import math
import numpy as np
from typing import Optional, Tuple
IDM = Tuple[int, int]
DEFAULT_IDM = (5, 0)
# TODO cylinder
# TODO: add negative versions of each of the shapes
# TODO shape/schematic object with properties
# (resizable, symmetries, color patterns allowed, etc.)
# TODO sheet
# TODO rotate
# TODO (in perception) recognize size
def hollow_triangle(
size=3, depth=1, bid=DEFAULT_IDM, orient="xy", thickness=1, labelme=False, **kwargs
):
"""
Construct an empty isosceles triangle with a given half base length (b/2).
The construction is restricted to having stepped blocks for the
sides other than base. Hence the height is (total base length)//2 + 1.
"""
assert size > 0
side = size * 2 + 1 # total base length
S = []
L = {}
insts = {}
for height in range(side // 2 + 1):
if height < thickness:
r = range(height, side - height)
else:
r = list(range(height, height + thickness))
r = r + list(range(side - height - thickness, side - height))
for i in r:
if i >= 0:
for t in range(0, depth):
if orient == "xy":
S.append(((i, height, t), bid))
elif orient == "yz":
S.append(((t, i, height), bid))
elif orient == "xz":
S.append(((i, t, height), bid))
if not labelme:
return S
else:
return S, L, insts
def hollow_rectangle(
size: Tuple[int, int] = (5, 3),
height: Optional[int] = None,
length: Optional[int] = None,
bid: IDM = DEFAULT_IDM,
thickness=1,
orient="xy",
labelme=False,
**kwargs,
):
R = rectangle(size=size, height=height, length=length, bid=bid, orient=orient)
l = [r[0] for r in R]
m = np.min(l, axis=0)
M = np.max(l, axis=0)
def close_to_border(r):
for i in range(3):
if abs(r[0][i] - m[i]) < thickness or abs(r[0][i] - M[i]) < thickness:
if M[i] > m[i]:
return True
return False
S = [r for r in R if close_to_border(r)]
if not labelme:
return S
else:
return S, {}, {}
def rectangle(
size=(5, 3),
height: Optional[int] = None,
length: Optional[int] = None,
bid: IDM = DEFAULT_IDM,
orient="xy",
labelme=False,
**kwargs,
):
if type(size) is int:
size = [size, size]
if height is not None:
size = (height, size[1])
if length is not None:
size = (size[0], length)
assert size[0] > 0
assert size[1] > 0
size_n = [size[1], size[0], 1]
if orient == "yz":
size_n = [1, size[0], size[1]]
if orient == "xz":
size_n = [size[0], 1, size[1]]
return rectanguloid(size=size_n, bid=bid, labelme=labelme)
def square(size=3, bid=DEFAULT_IDM, orient="xy", labelme=False, **kwargs):
"""Construct square as a rectangle of height and width size"""
size = [size, size]
return rectangle(size=size, bid=bid, orient=orient, labelme=labelme, **kwargs)
def triangle(size=3, bid=DEFAULT_IDM, orient="xy", thickness=1, labelme=False, **kwargs):
"""
Construct an isosceles traingle with a given half base length (b/2).
The construction is restricted to having stepped blocks for the
sides other than base. Hence the height is (total base length)//2 + 1.
"""
assert size > 0
side = size * 2 + 1 # total base length
S = []
L = {}
insts = {}
for height in range(side // 2 + 1):
for i in range(height, side - height):
for t in range(0, thickness):
if orient == "xy":
S.append(((i, height, t), bid))
elif orient == "yz":
S.append(((t, i, height), bid))
elif orient == "xz":
S.append(((i, t, height), bid))
if not labelme:
return S
else:
return S, L, insts
def circle(
radius=4, size=None, bid=DEFAULT_IDM, orient="xy", thickness=1, labelme=False, **kwargs
):
if size is not None:
radius = size // 2
N = 2 * radius
c = N / 2 - 1 / 2
S = []
L = {}
insts = {}
tlist = range(0, thickness)
for r in range(N):
for s in range(N):
in_radius = False
out_core = False
if ((r - c) ** 2 + (s - c) ** 2) ** 0.5 < N / 2:
in_radius = True
if ((r - c) ** 2 + (s - c) ** 2) ** 0.5 > N / 2 - thickness:
out_core = True
if in_radius and out_core:
for t in tlist:
if orient == "xy":
S.append(((r, s, t), bid)) # Render in the xy plane
elif orient == "yz":
S.append(((t, r, s), bid)) # Render in the yz plane
elif orient == "xz":
S.append(((r, t, s), bid)) # Render in the xz plane
if not labelme:
return S
else:
return S, L, insts
def disk(radius=5, size=None, bid=DEFAULT_IDM, orient="xy", thickness=1, labelme=False, **kwargs):
if size is not None:
radius = max(size // 2, 1)
assert radius > 0
N = 2 * radius
c = N / 2 - 1 / 2
S = []
L = {}
insts = {}
tlist = range(0, thickness)
for r in range(N):
for s in range(N):
if ((r - c) ** 2 + (s - c) ** 2) ** 0.5 < N / 2:
for t in tlist:
if orient == "xy":
S.append(((r, s, t), bid)) # Render in the xy plane
elif orient == "yz":
S.append(((t, r, s), bid)) # Render in the yz plane
elif orient == "xz":
S.append(((r, t, s), bid)) # Render in the xz plane
if not labelme:
return S
else:
return S, L, insts
def rectanguloid(
size=None, depth=None, height=None, width=None, bid=DEFAULT_IDM, labelme=False, **kwargs
):
"""Construct a solid rectanguloid"""
if type(size) is int:
size = [size, size, size]
if size is None:
if width is None and height is None and depth is None:
size = [3, 3, 3]
else:
size = [1, 1, 1]
if width is not None:
size[0] = width
if height is not None:
size[1] = height
if depth is not None:
size[2] = depth
assert size[0] > 0
assert size[1] > 0
assert size[2] > 0
S = []
L = {}
for r in range(size[0]):
for s in range(size[1]):
for t in range(size[2]):
S.append(((r, s, t), bid))
if not labelme:
return S
else:
insts = get_rect_instance_seg((0, size[0] - 1), (0, size[1] - 1), (0, size[2] - 1))
L = labels_from_instance_seg(insts, L=L)
return S, L, insts
def near_extremes(x, a, b, r):
"""checks if x is within r of a or b, and between them"""
assert a <= b
if x >= a and x <= b:
if x - a < r or b - x < r:
return True
return False
def rectanguloid_frame(
size=3, thickness=1, bid=DEFAULT_IDM, only_corners=False, labelme=False, **kwargs
):
"""Construct just the lines of a rectanguloid"""
R = hollow_rectanguloid(size=size, thickness=thickness, bid=bid, labelme=False, **kwargs)
M = np.max([l for (l, idm) in R], axis=0)
S = []
for l, idm in R:
bne = [near_extremes(l[i], 0, M[i], thickness) for i in range(3)]
if (only_corners and sum(bne) == 3) or (not only_corners and sum(bne) > 1):
S.append((l, idm))
if not labelme:
return S
else:
return S, {}, {}
def hollow_rectanguloid(size=3, thickness=1, bid=DEFAULT_IDM, labelme=False, **kwargs):
"""Construct a rectanguloid that's hollow inside"""
if type(size) is int:
size = [size, size, size]
inner_size = (
(thickness, size[0] - thickness),
(thickness, size[1] - thickness),
(thickness, size[2] - thickness),
)
assert size[0] > 0
assert size[1] > 0
assert size[2] > 0
assert inner_size[0][0] > 0 and inner_size[0][1] < size[0]
assert inner_size[1][0] > 0 and inner_size[1][1] < size[1]
assert inner_size[2][0] > 0 and inner_size[2][1] < size[2]
os = size
rs = inner_size
S = []
L = {}
interior = []
for r in range(size[0]):
for s in range(size[1]):
for t in range(size[2]):
proceed = False
proceed = proceed or r < rs[0][0] or r >= rs[0][1]
proceed = proceed or s < rs[1][0] or s >= rs[1][1]
proceed = proceed or t < rs[2][0] or t >= rs[2][1]
if proceed:
S.append(((r, s, t), bid))
else:
interior.append((r, s, t))
if not labelme:
return S
else:
insts = get_rect_instance_seg((0, os[0] - 1), (0, os[1] - 1), (0, os[2] - 1))
inner_insts = get_rect_instance_seg(
(rs[0][0] - 1, rs[0][1]), (rs[1][0] - 1, rs[1][1]), (rs[2][0] - 1, rs[2][1])
)
L = labels_from_instance_seg(insts, L=L)
inner_insts = {"inner_" + l: inner_insts[l] for l in inner_insts}
L = labels_from_instance_seg(inner_insts, L=L)
insts.update(inner_insts)
for p in interior:
L[p] = "inside"
insts["inside"] = tuple(interior)
return S, L, insts
def cube(size=3, bid=DEFAULT_IDM, labelme=False, **kwargs):
if type(size) not in (tuple, list):
size = (size, size, size)
return rectanguloid(size=size, bid=bid, labelme=labelme)
def hollow_cube(size=3, thickness=1, bid=DEFAULT_IDM, labelme=False, **kwargs):
return hollow_rectanguloid(
size=(size, size, size), thickness=thickness, bid=bid, labelme=labelme
)
def sphere(radius=5, size=None, bid=DEFAULT_IDM, labelme=False, **kwargs):
"""Construct a solid sphere"""
if size is not None:
radius = size // 2
N = 2 * radius
c = N / 2 - 1 / 2
S = []
L = {}
insts = {"spherical_surface": [[]]}
for r in range(N):
for s in range(N):
for t in range(N):
w = ((r - c) ** 2 + (s - c) ** 2 + (t - c) ** 2) ** 0.5
if w < N / 2:
S.append(((r, s, t), bid))
if w > N / 2 - 1:
if labelme:
L[(r, s, t)] = ["spherical_surface"]
insts["spherical_surface"][0].append((r, s, t))
if not labelme:
return S
else:
return S, L, insts
def spherical_shell(radius=5, size=None, thickness=2, bid=DEFAULT_IDM, labelme=False, **kwargs):
"""Construct a sphere that's hollow inside"""
if size is not None:
radius = size // 2
N = 2 * radius
c = N / 2 - 1 / 2
S = []
L = {}
insts = {"spherical_surface": [[]], "inner_spherical_surface": [[]]}
for r in range(N):
for s in range(N):
for t in range(N):
in_radius = False
out_core = False
w = ((r - c) ** 2 + (s - c) ** 2 + (t - c) ** 2) ** 0.5
if w < N / 2:
in_radius = True
if w > N / 2 - thickness:
out_core = True
if in_radius and out_core:
S.append(((r, s, t), bid))
if labelme and w < N / 2 - thickness + 1:
L[(r, s, t)] = ["inner_spherical_surface"]
insts["inner_spherical_surface"][0].append((r, s, t))
if labelme and in_radius and not out_core:
L[(r, s, t)] = ["inside"]
if in_radius and labelme and w > N / 2 - 1:
L[(r, s, t)] = ["spherical_surface"]
insts["spherical_surface"][0].append((r, s, t))
if not labelme:
return S
else:
return S, L, insts
def square_pyramid(
slope=1, radius=10, size=None, height=None, bid=DEFAULT_IDM, labelme=False, **kwargs
):
if size is not None:
radius = size + 2 # this is a heuristic
assert slope > 0
S = []
L = {}
insts = {
"pyramid_peak": [[]],
"pyramid_bottom_corner": [[], [], [], []],
"pyramid_bottom_edge": [[], [], [], []],
"pyramid_diag_edge": [[], [], [], []],
"pyramid_face": [[], [], [], []],
"pyramid_bottom": [[]],
}
if height is None:
height = math.ceil(slope * radius)
for h in range(height):
start = math.floor(h / slope)
end = 2 * radius - start
for s in range(start, end + 1):
for t in range(start, end + 1):
S.append(((s, h, t), bid))
if labelme:
sstart = s == start
send = s == end
tstart = t == start
tend = t == end
sb = sstart or send
tb = tstart or tend
if h == height - 1:
L[(s, h, t)] = ["pyramid_peak"]
insts["pyramid_peak"][0].append((s, h, t))
if h == 0:
if sstart:
insts["pyramid_bottom_edge"][0].append((s, h, t))
if send:
insts["pyramid_bottom_edge"][1].append((s, h, t))
if tstart:
insts["pyramid_bottom_edge"][2].append((s, h, t))
if tend:
insts["pyramid_bottom_edge"][3].append((s, h, t))
if sb and tb:
L[(s, h, t)] = ["pyramid_bottom_corner"]
i = sstart * 1 + tstart * 2
insts["pyramid_bottom_corner"][i].append((s, h, t))
else:
if sstart:
insts["pyramid_face"][0].append((s, h, t))
if send:
insts["pyramid_face"][1].append((s, h, t))
if tstart:
insts["pyramid_face"][2].append((s, h, t))
if tend:
insts["pyramid_face"][3].append((s, h, t))
if sb and tb:
L[(s, h, t)] = ["pyramid_diag_edge"]
i = sstart * 1 + tstart * 2
insts["pyramid_diag_edge"][i].append((s, h, t))
if not labelme:
return S
else:
return S, L, insts
def tower(height=10, size=None, base=-1, bid=DEFAULT_IDM, labelme=False, **kwargs):
if size is not None:
height = size
D = height // 3
if D < 3:
D = 1
height = 3
if base == 1:
base = 0
if base <= 0:
base = -base + 1
if base > D:
base = D
size = (base, height, base)
return rectanguloid(size=size, bid=bid, labelme=labelme)
else:
if base > D:
base = D
c = D / 2 - 1 / 2
S = []
for s in range(height):
for m in range(base):
for n in range(base):
if ((m - c) ** 2 + (n - c) ** 2) ** 0.5 <= D / 2:
S.append(((m, s, n), bid))
if not labelme:
return S
else:
return S, {}, {}
def ellipsoid(size=(7, 8, 9), bid=DEFAULT_IDM, labelme=False, **kwargs):
if type(size) is int:
size = [size, size, size]
assert size[0] > 0
assert size[1] > 0
assert size[2] > 0
a = size[0]
b = size[1]
c = size[2]
cx = a - 1 / 2
cy = b - 1 / 2
cz = c - 1 / 2
S = []
L = {}
insts = {}
for r in range(2 * a):
for s in range(2 * b):
for t in range(2 * c):
if (((r - cx) / a) ** 2 + ((s - cy) / b) ** 2 + ((t - cz) / c) ** 2) ** 0.5 < 1.0:
S.append(((r, s, t), bid))
if not labelme:
return S
else:
return S, L, insts
def dome(radius=3, size=None, bid=DEFAULT_IDM, thickness=2, labelme=False, **kwargs):
"""Construct a hemisphere, in the direction of positive y axis"""
if size is not None:
radius = max(size // 2, 1)
assert radius > 0
N = 2 * radius
cx = cz = N / 2 - 1 / 2
cy = 0
S = []
L = {}
insts = {}
for r in range(N):
for s in range(N):
for t in range(N):
in_radius = False
out_core = False
if ((r - cx) ** 2 + (s - cy) ** 2 + (t - cz) ** 2) ** 0.5 < N / 2:
in_radius = True
if ((r - cx) ** 2 + (s - cy) ** 2 + (t - cz) ** 2) ** 0.5 > N / 2 - thickness:
out_core = True
if in_radius and out_core:
S.append(((r, s, t), bid))
if not labelme:
return S
else:
return S, L, insts
def arch(size=3, distance=11, bid=DEFAULT_IDM, orient="xy", labelme=False, **kwargs):
""" Arch is a combination of 2 parallel columns, where the columns
are connected by a stepped roof.
Total height of the arch structure:length + distance//2 + 1"""
length = size # Length is the height of 2 parallel columns
# "distance" is the distance between the columns
L = {}
insts = {}
S = []
assert distance % 2 == 1 # distance between the 2 columns should be odd
offset = 0
for i in range(length):
S.append(((offset, i, offset), bid))
cx = offset + distance + 1
cy = i
cz = offset
if orient == "xy":
S.append(((cx, cy, cz), bid))
elif orient == "yz":
S.append(((cz, cy, cx), bid))
# Blocks corresponding to the stepped roof
for i in range(1, distance // 2 + 1):
cx_1 = offset + i
cy_1 = length + i - 1
cz_1 = offset
if orient == "xy":
S.append(((cx_1, cy_1, cz_1), bid))
elif orient == "yz":
S.append(((cz_1, cy_1, cx_1), bid))
cx_2 = offset + distance + 1 - i
cy_2 = length + i - 1
cz_2 = offset
if orient == "xy":
S.append(((cx_2, cy_2, cz_2), bid))
elif orient == "yz":
S.append(((cz_2, cy_2, cx_2), bid))
# topmost block
cx_top = offset + distance // 2 + 1
cy_top = length + distance // 2
cz_top = offset
if orient == "xy":
S.append(((cx_top, cy_top, cz_top), bid))
elif orient == "yz":
S.append(((cz_top, cy_top, cx_top), bid))
if not labelme:
return S
else:
return S, L, insts
def get_rect_instance_seg(bx, by, bz):
I = {}
I["top_corner"] = [((bx[i], by[1], bz[j]),) for i in range(2) for j in range(2)]
I["bottom_corner"] = [((bx[i], by[0], bz[j]),) for i in range(2) for j in range(2)]
I["vertical_edge"] = [
tuple((bx[i], s, bz[j]) for s in range(by[0], by[1] + 1))
for i in range(2)
for j in range(2)
]
I["top_edge"] = [
tuple((s, by[1], bz[i]) for s in range(bx[0], bx[1] + 1)) for i in range(2)
] + [tuple((bx[i], by[1], s) for s in range(bz[0], bz[1] + 1)) for i in range(2)]
I["bottom_edge"] = [
tuple((s, by[0], bz[i]) for s in range(bx[0], bx[1] + 1)) for i in range(2)
] + [tuple((bx[i], by[0], s) for s in range(bz[0], bz[1] + 1)) for i in range(2)]
I["face"] = [
tuple((s, t, bz[i]) for s in range(bx[0], bx[1] + 1) for t in range(by[0], by[1] + 1))
for i in range(2)
] + [
tuple((bx[i], t, s) for s in range(bz[0], bz[1] + 1) for t in range(by[0], by[1] + 1))
for i in range(2)
]
I["top"] = [
tuple((s, by[1], t) for s in range(bx[0], bx[1] + 1) for t in range(bz[0], bz[1] + 1))
]
I["bottom"] = [
tuple((s, by[0], t) for s in range(bx[0], bx[1] + 1) for t in range(bz[0], bz[1] + 1))
]
return I
def labels_from_instance_seg(I, L=None):
L = L or {}
for label in I:
for i in I[label]:
for p in i:
if L.get(p) is None:
L[p] = [label]
else:
if label not in L[p]:
L[p].append(label)
return L
# TODO: merge this with the one in build utils
def get_bounds(S):
"""
S should be a list of tuples, where each tuple is a pair of
(x,y,z) and ids
"""
x, y, z = list(zip(*list(zip(*S))[0]))
return min(x), max(x), min(y), max(y), min(z), max(z)
# TODO: vector direction?
def mirror(S, axis=0):
"""make a mirror of S"""
m = get_bounds(S)
out = []
aM = m[2 * axis + 1]
for b in S:
c = aM - b[0][axis]
loc = [b[0], b[1], b[2]]
loc[axis] = c
out.append(tuple(loc), b[1])
return out
# NOTE: arrangement will eventually be any of the shapes and
# arrangement will eventually be handled by relpos model
# for now it is either a 'circle' or a 'line'
# schematic is the thing to be built at each location
def arrange(arrangement, schematic=None, shapeparams={}):
"""This function arranges an Optional schematic in a given arrangement
and returns the offsets"""
N = shapeparams.get("N", 7)
extra_space = shapeparams.get("extra_space", 1)
if schematic is None:
bounds = [0, 1, 0, 1, 0, 1]
else:
bounds = get_bounds(schematic)
if N > 0:
if arrangement == "circle":
orient = shapeparams.get("orient", "xy")
encircled_object_radius = shapeparams.get("encircled_object_radius", 1)
b = max(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4])
radius = max(((b + extra_space) * N) / (2 * np.pi), encircled_object_radius + b + 1)
offsets = [
(radius * np.cos(2 * s * np.pi / N), 0, radius * np.sin(2 * s * np.pi / N))
for s in range(N)
]
if orient == "yz":
offsets = [np.round(np.asarray(0, offsets[i][0], offsets[i][2])) for i in range(N)]
if orient == "xz":
offsets = [
np.round(np.asarray((offsets[i][0], offsets[i][2], 0))) for i in range(N)
]
elif arrangement == "line":
orient = shapeparams.get("orient") # this is a vector here
b = max(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4])
b += extra_space + 1
offsets = [np.round(i * b * np.asarray(orient)) for i in range(N)]
if N <= 0:
raise NotImplementedError(
"TODO arrangement just based on extra space, need to specify number for now"
)
return offsets
| craftassist-master | python/craftassist/shapes.py |
import os
import sys
from mc_util import (
XYZ,
IDM,
to_block_pos,
pos_to_np,
euclid_dist,
diag_adjacent,
capped_line_of_sight,
)
from typing import Tuple, List
from block_data import BORING_BLOCKS
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.memory_nodes import PlayerNode, AttentionNode
from mc_memory_nodes import BlockObjectNode
class LowLevelMCPerception:
def __init__(self, agent, perceive_freq=5):
self.agent = agent
self.memory = agent.memory
self.pending_agent_placed_blocks = set()
self.perceive_freq = perceive_freq
def perceive(self, force=False):
# FIXME (low pri) remove these in code, get from sql
self.agent.pos = to_block_pos(pos_to_np(self.agent.get_player().pos))
if self.agent.count % self.perceive_freq == 0 or force:
for mob in self.agent.get_mobs():
if euclid_dist(self.agent.pos, pos_to_np(mob.pos)) < self.memory.perception_range:
self.memory.set_mob_position(mob)
item_stack_set = set()
for item_stack in self.agent.get_item_stacks():
item_stack_set.add(item_stack.entityId)
if (
euclid_dist(self.agent.pos, pos_to_np(item_stack.pos))
< self.memory.perception_range
):
self.memory.set_item_stack_position(item_stack)
old_item_stacks = self.memory.get_all_item_stacks()
if old_item_stacks:
for old_item_stack in old_item_stacks:
memid = old_item_stack[0]
eid = old_item_stack[1]
if eid not in item_stack_set:
self.memory.untag(memid, "_on_ground")
else:
self.memory.tag(memid, "_on_ground")
# note: no "force"; these run on every perceive call. assumed to be fast
self.update_self_memory()
self.update_other_players(self.agent.get_other_players())
# use safe_get_changed_blocks to deal with pointing
for (xyz, idm) in self.agent.safe_get_changed_blocks():
self.on_block_changed(xyz, idm)
def update_self_memory(self):
p = self.agent.get_player()
memid = self.memory.get_player_by_eid(p.entityId).memid
cmd = "UPDATE ReferenceObjects SET eid=?, name=?, x=?, y=?, z=?, pitch=?, yaw=? WHERE "
cmd = cmd + "uuid=?"
self.memory._db_write(
cmd, p.entityId, p.name, p.pos.x, p.pos.y, p.pos.z, p.look.pitch, p.look.yaw, memid
)
def update_other_players(self, player_list: List, force=False):
# input is a list of player_structs from agent
for p in player_list:
mem = self.memory.get_player_by_eid(p.entityId)
if mem is None:
memid = PlayerNode.create(self.memory, p)
else:
memid = mem.memid
cmd = (
"UPDATE ReferenceObjects SET eid=?, name=?, x=?, y=?, z=?, pitch=?, yaw=? WHERE "
)
cmd = cmd + "uuid=?"
self.memory._db_write(
cmd, p.entityId, p.name, p.pos.x, p.pos.y, p.pos.z, p.look.pitch, p.look.yaw, memid
)
loc = capped_line_of_sight(self.agent, p)
loc[1] += 1
memids = self.memory._db_read_one(
'SELECT uuid FROM ReferenceObjects WHERE ref_type="attention" AND type_name=?',
p.entityId,
)
if memids:
self.memory._db_write(
"UPDATE ReferenceObjects SET x=?, y=?, z=? WHERE uuid=?",
loc[0],
loc[1],
loc[2],
memids[0],
)
else:
AttentionNode.create(self.memory, loc, attender=p.entityId)
# TODO replace name by eid everywhere
def get_player_struct_by_name(self, name):
# returns a raw player struct, e.g. to use in agent.get_player_line_of_sight
for p in self.agent.get_other_players():
if p.name == name:
return p
return None
def on_block_changed(self, xyz: XYZ, idm: IDM):
# TODO don't need to do this for far away blocks if this is slowing down bot
self.maybe_remove_inst_seg(xyz)
self.maybe_remove_block_from_memory(xyz, idm)
self.maybe_add_block_to_memory(xyz, idm)
# TODO?
def clear_air_surrounded_negatives(self):
pass
# TODO move this somewhere more sensible
def maybe_remove_inst_seg(self, xyz):
# get all associated instseg nodes
info = self.memory.get_instseg_object_ids_by_xyz(xyz)
if not info or len(info) == 0:
pass
# first delete the InstSeg info on the loc of this block
self.memory._db_write(
'DELETE FROM VoxelObjects WHERE ref_type="inst_seg" AND x=? AND y=? AND z=?', *xyz
)
# then for each InstSeg, check if all blocks of same InstSeg node has
# already been deleted. if so, delete the InstSeg node entirely
for memid in info:
memid = memid[0]
xyzs = self.memory._db_read(
'SELECT x, y, z FROM VoxelObjects WHERE ref_type="inst_seg" AND uuid=?', memid
)
all_deleted = True
for xyz in xyzs:
r = self.memory._db_read(
'SELECT * FROM VoxelObjects WHERE ref_type="inst_seg" AND uuid=? AND x=? AND y=? AND z=?',
memid,
*xyz
)
if bool(r):
all_deleted = False
if all_deleted:
# TODO make an archive.
self.memory._db_write("DELETE FROM Memories WHERE uuid=?", memid)
# clean all this up...
# eventually some conditions for not committing air/negative blocks
def maybe_add_block_to_memory(self, xyz: XYZ, idm: IDM, agent_placed=False):
if not agent_placed:
interesting, player_placed, agent_placed = self.is_placed_block_interesting(
xyz, idm[0]
)
else:
interesting = True
player_placed = False
if not interesting:
return
# TODO remove this, clean up
if agent_placed:
try:
self.pending_agent_placed_blocks.remove(xyz)
except:
pass
adjacent = [
self.memory.get_object_info_by_xyz(a, "BlockObjects", just_memid=False)
for a in diag_adjacent(xyz)
]
if idm[0] == 0:
# block removed / air block added
adjacent_memids = [a[0][0] for a in adjacent if len(a) > 0 and a[0][1] == 0]
else:
# normal block added
adjacent_memids = [a[0][0] for a in adjacent if len(a) > 0 and a[0][1] > 0]
adjacent_memids = list(set(adjacent_memids))
if len(adjacent_memids) == 0:
# new block object
BlockObjectNode.create(self.agent.memory, [(xyz, idm)])
elif len(adjacent_memids) == 1:
# update block object
memid = adjacent_memids[0]
self.memory.upsert_block(
(xyz, idm), memid, "BlockObjects", player_placed, agent_placed
)
self.memory.set_memory_updated_time(memid)
self.memory.set_memory_attended_time(memid)
else:
chosen_memid = adjacent_memids[0]
self.memory.set_memory_updated_time(chosen_memid)
self.memory.set_memory_attended_time(chosen_memid)
# merge tags
where = " OR ".join(["subj=?"] * len(adjacent_memids))
self.memory._db_write(
"UPDATE Triples SET subj=? WHERE " + where, chosen_memid, *adjacent_memids
)
# merge multiple block objects (will delete old ones)
where = " OR ".join(["uuid=?"] * len(adjacent_memids))
cmd = "UPDATE VoxelObjects SET uuid=? WHERE "
self.memory._db_write(cmd + where, chosen_memid, *adjacent_memids)
# insert new block
self.memory.upsert_block(
(xyz, idm), chosen_memid, "BlockObjects", player_placed, agent_placed
)
def maybe_remove_block_from_memory(self, xyz: XYZ, idm: IDM):
tables = ["BlockObjects"]
for table in tables:
info = self.memory.get_object_info_by_xyz(xyz, table, just_memid=False)
if not info or len(info) == 0:
continue
assert len(info) == 1
memid, b, m = info[0]
delete = (b == 0 and idm[0] > 0) or (b > 0 and idm[0] == 0)
if delete:
self.memory.remove_voxel(*xyz, table)
self.agent.areas_to_perceive.append((xyz, 3))
# FIXME move removal of block to parent
def is_placed_block_interesting(self, xyz: XYZ, bid: int) -> Tuple[bool, bool, bool]:
"""Return three values:
- bool: is the placed block interesting?
- bool: is it interesting because it was placed by a player?
- bool: is it interesting because it was placed by the agent?
"""
interesting = False
player_placed = False
agent_placed = False
# TODO record *which* player placed it
if xyz in self.pending_agent_placed_blocks:
interesting = True
agent_placed = True
for player_struct in self.agent.get_other_players():
if (
euclid_dist(pos_to_np(player_struct.pos), xyz) < 5
and player_struct.mainHand.id == bid
):
interesting = True
if not agent_placed:
player_placed = True
if bid not in BORING_BLOCKS:
interesting = True
return interesting, player_placed, agent_placed
| craftassist-master | python/craftassist/low_level_perception.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
import os
import sys
import numpy as np
import time
from random import randint
from block_data import (
PASSABLE_BLOCKS,
BUILD_BLOCK_REPLACE_MAP,
BUILD_IGNORE_BLOCKS,
BUILD_INTERCHANGEABLE_PAIRS,
)
from build_utils import blocks_list_to_npy, npy_to_blocks_list
from entities import MOBS_BY_ID
import search
from heuristic_perception import ground_height
from mc_util import to_block_pos, manhat_dist, strip_idmeta
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.task import Task
from mc_memory_nodes import MobNode
# tasks should be interruptible; that is, if they
# store state, stopping the task and doing something
# else should not mess up their state and just the
# current state should be enough to do the task from
# any ob
class Dance(Task):
def __init__(self, agent, task_data):
super(Dance, self).__init__()
# movement should be a Movement object from dance.py
self.movement = task_data.get("movement")
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
super().step(agent)
if self.finished:
return
self.interrupted = False
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
mv = self.movement.get_move()
if mv is None:
self.finished = True
return
self.add_child_task(mv, agent)
class DanceMove(Task):
STEP_FNS = {
(1, 0, 0): "step_pos_x",
(-1, 0, 0): "step_neg_x",
(0, 1, 0): "step_pos_y",
(0, -1, 0): "step_neg_y",
(0, 0, 1): "step_pos_z",
(0, 0, -1): "step_neg_z",
}
def __init__(self, agent, task_data):
super(DanceMove, self).__init__()
self.relative_yaw = task_data.get("relative_yaw")
self.relative_pitch = task_data.get("relative_pitch")
# look_turn is (yaw, pitch). pitch = 0 is head flat
self.head_yaw_pitch = task_data.get("head_yaw_pitch")
self.head_xyz = task_data.get("head_xyz")
self.translate = task_data.get("translate")
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
if self.relative_yaw:
agent.turn_angle(self.relative_yaw)
if self.relative_pitch:
agent.relative_head_pitch(self.relative_pitch)
if self.head_xyz is not None:
agent.look_at(self.head_xyz[0], self.head_xyz[1], self.head_xyz[2])
elif self.head_yaw_pitch is not None:
# warning: pitch is flipped! client uses -pitch for up,
agent.set_look(self.head_yaw_pitch[0], -self.head_yaw_pitch[1])
if self.translate:
step = self.STEP_FNS[self.translate]
step_fn = getattr(agent, step)
step_fn()
else:
# FIXME... do this right with ticks/timing
time.sleep(0.1)
self.finished = True
class Point(Task):
def __init__(self, agent, task_data):
super(Point, self).__init__()
self.target = task_data.get("target")
self.start_time = agent.memory.get_time()
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
if self.target is not None:
agent.point_at(self.target)
self.target = None
if agent.memory.get_time() > self.start_time + 200:
self.finished = True
class Move(Task):
STEP_FNS = {
(1, 0, 0): "step_pos_x",
(-1, 0, 0): "step_neg_x",
(0, 1, 0): "step_pos_y",
(0, -1, 0): "step_neg_y",
(0, 0, 1): "step_pos_z",
(0, 0, -1): "step_neg_z",
}
def __init__(self, agent, task_data):
super(Move, self).__init__()
if self.finished:
return
self.target = to_block_pos(np.array(task_data["target"]))
self.approx = task_data.get("approx", 1)
self.path = None
self.replace = set()
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
super().step(agent)
if self.finished:
return
self.interrupted = False
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
# replace blocks if possible
R = self.replace.copy()
self.replace.clear()
for (pos, idm) in R:
agent.set_held_item(idm)
if agent.place_block(*pos):
logging.info("Move: replaced {}".format((pos, idm)))
else:
# try again later
self.replace.add((pos, idm))
if len(self.replace) > 0:
logging.info("Replace remaining: {}".format(self.replace))
# check if finished
if manhat_dist(tuple(agent.pos), self.target) <= self.approx:
if len(self.replace) > 0:
logging.error("Move finished with non-empty replace set: {}".format(self.replace))
self.finished = True
if self.memid is not None:
locmemid = agent.memory.add_location(self.target)
locmem = agent.memory.get_location_by_id(locmemid)
agent.memory.update_recent_entities(mems=[locmem])
agent.memory.add_triple(subj=self.memid, pred_text="task_effect_", obj=locmemid)
chat_mem_triples = agent.memory.get_triples(
subj=None, pred_text="chat_effect_", obj=self.memid
)
if len(chat_mem_triples) > 0:
chat_memid = chat_mem_triples[0][0]
agent.memory.add_triple(
subj=chat_memid, pred_text="chat_effect_", obj=locmemid
)
return
# get path
if self.path is None or tuple(agent.pos) != self.path[-1]:
self.path = search.astar(agent, self.target, self.approx)
if self.path is None:
self.handle_no_path(agent)
return
# take a step on the path
assert tuple(agent.pos) == self.path.pop()
step = tuple(self.path[-1] - agent.pos)
step_fn = getattr(agent, self.STEP_FNS[step])
step_fn()
self.last_stepped_time = agent.memory.get_time()
def handle_no_path(self, agent):
delta = self.target - agent.pos
for vec, step_fn_name in self.STEP_FNS.items():
if np.dot(delta, vec) > 0:
newpos = agent.pos + vec
x, y, z = newpos
newpos_blocks = agent.get_blocks(x, x, y, y + 1, z, z)
# dig if necessary
for (bp, idm) in npy_to_blocks_list(newpos_blocks, newpos):
self.replace.add((bp, idm))
agent.dig(*bp)
# move
step_fn = getattr(agent, step_fn_name)
step_fn()
break
def __repr__(self):
return "<Move {} ±{}>".format(self.target, self.approx)
class Build(Task):
def __init__(self, agent, task_data):
super(Build, self).__init__()
self.task_data = task_data
self.embed = task_data.get("embed", False)
self.schematic, _ = blocks_list_to_npy(task_data["blocks_list"])
self.origin = task_data["origin"]
self.verbose = task_data.get("verbose", True)
self.relations = task_data.get("relations", [])
self.default_behavior = task_data.get("default_behavior")
self.force = task_data.get("force", False)
self.attempts = 3 * np.ones(self.schematic.shape[:3], dtype=np.uint8)
self.fill_message = task_data.get("fill_message", False)
self.schematic_memid = task_data.get("schematic_memid", None)
self.schematic_tags = task_data.get("schematic_tags", [])
self.giving_up_message_sent = False
self.wait = False
self.old_blocks_list = None
self.old_origin = None
self.PLACE_REACH = task_data.get("PLACE_REACH", 3)
# negative schematic related
self.is_destroy_schm = task_data.get("is_destroy_schm", False)
self.dig_message = task_data.get("dig_message", False)
self.blockobj_memid = None
self.DIG_REACH = task_data.get("DIG_REACH", 3)
self.last_stepped_time = agent.memory.get_time()
if self.is_destroy_schm:
# is it destroying a whole block object? if so, save its tags
self.destroyed_block_object_triples = []
xyzs = set(strip_idmeta(task_data["blocks_list"]))
mem = agent.memory.get_block_object_by_xyz(next(iter(xyzs)))
# TODO what if there are several objects being destroyed?
if mem and all(xyz in xyzs for xyz in mem.blocks.keys()):
for pred in ["has_tag", "has_name", "has_colour"]:
self.destroyed_block_object_triples.extend(
agent.memory.get_triples(subj=mem.memid, pred_text=pred)
)
logging.info(
"Destroying block object {} tags={}".format(
mem.memid, self.destroyed_block_object_triples
)
)
# modify the schematic to avoid placing certain blocks
for bad, good in BUILD_BLOCK_REPLACE_MAP.items():
self.schematic[self.schematic[:, :, :, 0] == bad] = good
self.new_blocks = [] # a list of (xyz, idm) of newly placed blocks
# snap origin to ground if bottom level has dirt blocks
# NOTE(kavyasrinet): except for when we are rebuilding the old dirt blocks, we
# don't want to change the origin then, hence the self.force check.
if not self.force and not self.embed and np.isin(self.schematic[:, :, :, 0], (2, 3)).any():
h = ground_height(agent, self.origin, 0)
self.origin[1] = h[0, 0]
# get blocks occupying build area and save state for undo()
ox, oy, oz = self.origin
sy, sz, sx, _ = self.schematic.shape
current = agent.get_blocks(ox, ox + sx - 1, oy, oy + sy - 1, oz, oz + sz - 1)
self.old_blocks_list = npy_to_blocks_list(current, self.origin)
if len(self.old_blocks_list) > 0:
self.old_origin = np.min(strip_idmeta(self.old_blocks_list), axis=0)
def step(self, agent):
super().step(agent)
if self.finished:
return
self.interrupted = False
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
# get blocks occupying build area
ox, oy, oz = self.origin
sy, sz, sx, _ = self.schematic.shape
current = agent.get_blocks(ox, ox + sx - 1, oy, oy + sy - 1, oz, oz + sz - 1)
# are we done?
# TODO: diff ignores block meta right now because placing stairs and
# chests in the appropriate orientation is non-trivial
diff = (
(current[:, :, :, 0] != self.schematic[:, :, :, 0])
& (self.attempts > 0)
& np.isin(current[:, :, :, 0], BUILD_IGNORE_BLOCKS, invert=True)
)
# ignore negative blocks if there is already air there
diff &= (self.schematic[:, :, :, 0] + current[:, :, :, 0]) >= 0
if self.embed:
diff &= self.schematic[:, :, :, 0] != 0 # don't delete blocks if self.embed
for pair in BUILD_INTERCHANGEABLE_PAIRS:
diff &= np.isin(current[:, :, :, 0], pair, invert=True) | np.isin(
self.schematic[:, :, :, 0], pair, invert=True
)
if not np.any(diff):
self.finish(agent)
return
# blocks that would need to be removed
remove_mask = diff & (current[:, :, :, 0] != 0)
# destroy any blocks in the way (or any that are slated to be destroyed in schematic)
# first
rel_yzxs = np.argwhere(remove_mask)
xyzs = set(
[
(x + self.origin[0], y + self.origin[1], z + self.origin[2])
for (y, z, x) in rel_yzxs
]
)
if len(xyzs) != 0:
logging.info("Excavating {} blocks first".format(len(xyzs)))
target = self.get_next_destroy_target(agent, xyzs)
if target is None:
logging.info("No path from {} to {}".format(agent.pos, xyzs))
agent.send_chat("There's no path, so I'm giving up")
self.finished = True
return
if manhat_dist(agent.pos, target) <= self.DIG_REACH:
success = agent.dig(*target)
if success:
agent.perception_modules["low_level"].maybe_remove_inst_seg(target)
if self.is_destroy_schm:
agent.perception_modules["low_level"].maybe_remove_block_from_memory(
target, (0, 0)
)
else:
agent.perception_modules["low_level"].maybe_add_block_to_memory(
target, (0, 0), agent_placed=True
)
self.add_tags(agent, (target, (0, 0)))
agent.get_changed_blocks()
else:
mv = Move(agent, {"target": target, "approx": self.DIG_REACH})
self.add_child_task(mv, agent)
return
# for a build task with destroy schematic,
# it is done when all different blocks are removed
elif self.is_destroy_schm:
self.finish(agent)
return
# get next block to place
yzx = self.get_next_place_target(agent, current, diff)
idm = self.schematic[tuple(yzx)]
current_idm = current[tuple(yzx)]
# try placing block
target = yzx[[2, 0, 1]] + self.origin
logging.debug("trying to place {} @ {}".format(idm, target))
if tuple(target) in (tuple(agent.pos), tuple(agent.pos + [0, 1, 0])):
# can't place block where you're standing, so step out of the way
self.step_any_dir(agent)
return
if manhat_dist(agent.pos, target) <= self.PLACE_REACH:
# block is within reach
assert current_idm[0] != idm[0], "current={} idm={}".format(current_idm, idm)
if current_idm[0] != 0:
logging.debug(
"removing block {} @ {} from {}".format(current_idm, target, agent.pos)
)
agent.dig(*target)
if idm[0] > 0:
agent.set_held_item(idm)
logging.debug("placing block {} @ {} from {}".format(idm, target, agent.pos))
x, y, z = target
if agent.place_block(x, y, z):
B = agent.get_blocks(x, x, y, y, z, z)
if B[0, 0, 0, 0] == idm[0]:
agent.perception_modules["low_level"].maybe_add_block_to_memory(
(x, y, z), tuple(idm), agent_placed=True
)
changed_blocks = agent.get_changed_blocks()
self.new_blocks.append(((x, y, z), tuple(idm)))
self.add_tags(agent, ((x, y, z), tuple(idm)))
else:
logging.error(
"failed to place block {} @ {}, but place_block returned True. \
Got {} instead.".format(
idm, target, B[0, 0, 0, :]
)
)
else:
logging.warn("failed to place block {} from {}".format(target, agent.pos))
if idm[0] == 6: # hacky: all saplings have id 6
agent.set_held_item([351, 15]) # use bone meal on tree saplings
if len(changed_blocks) > 0:
sapling_pos = changed_blocks[0][0]
x, y, z = sapling_pos
for _ in range(6): # use at most 6 bone meal (should be enough)
agent.use_item_on_block(x, y, z)
changed_blocks = agent.get_changed_blocks()
changed_block_poss = {block[0] for block in changed_blocks}
# sapling has grown to a full tree, stop using bone meal
if (x, y, z) in changed_block_poss:
break
self.attempts[tuple(yzx)] -= 1
if self.attempts[tuple(yzx)] == 0 and not self.giving_up_message_sent:
agent.send_chat(
"I'm skipping a block because I can't place it. Maybe something is in the way."
)
self.giving_up_message_sent = True
else:
# too far to place; move first
task = Move(agent, {"target": target, "approx": self.PLACE_REACH})
self.add_child_task(task, agent)
def add_tags(self, agent, block):
# xyz, _ = npy_to_blocks_list(self.schematic, self.origin)[0]
xyz = block[0]
# this should not be an empty list- it is assumed the block passed in was just placed
try:
memid = agent.memory.get_block_object_ids_by_xyz(xyz)[0]
self.blockobj_memid = memid
except:
logging.debug(
"Warning: place block returned true, but no block in memory after update"
)
if self.schematic_memid:
agent.memory.tag_block_object_from_schematic(memid, self.schematic_memid)
if self.schematic_tags:
for pred, obj in self.schematic_tags:
agent.memory.add_triple(subj=memid, pred_text=pred, obj_text=obj)
# sooooorrry FIXME? when we handle triples better in interpreter_helper
if "has_" in pred:
agent.memory.tag(self.blockobj_memid, obj)
agent.memory.tag(memid, "_in_progress")
if self.dig_message:
agent.memory.tag(memid, "hole")
def finish(self, agent):
if self.blockobj_memid is not None:
agent.memory.untag(self.blockobj_memid, "_in_progress")
if self.verbose:
if self.is_destroy_schm:
agent.send_chat("I finished destroying this")
else:
agent.send_chat("I finished building this")
if self.fill_message:
agent.send_chat("I finished filling this")
if self.dig_message:
agent.send_chat("I finished digging this.")
self.finished = True
def get_next_place_target(self, agent, current, diff):
"""Return the next block that will be targeted for placing
In order:
1. don't build over your own body
2. build ground-up
3. try failed blocks again at the end
4. build closer blocks first
Args:
- current: yzxb-ordered current state of the region
- diff: a yzx-ordered boolean mask of blocks that need addressing
"""
relpos_yzx = (agent.pos - self.origin)[[1, 2, 0]]
diff_yzx = list(np.argwhere(diff))
diff_yzx.sort(key=lambda yzx: manhat_dist(yzx, relpos_yzx)) # 4
diff_yzx.sort(key=lambda yzx: -self.attempts[tuple(yzx)]) # 3
diff_yzx.sort(key=lambda yzx: yzx[0]) # 2
diff_yzx.sort(
key=lambda yzx: tuple(yzx) in (tuple(relpos_yzx), tuple(relpos_yzx + [1, 0, 0]))
) # 1
return diff_yzx[0]
def get_next_destroy_target(self, agent, xyzs):
p = agent.pos
for i, c in enumerate(sorted(xyzs, key=lambda c: manhat_dist(p, c))):
path = search.astar(agent, c, approx=2)
if path is not None:
if i > 0:
logging.debug("Destroy get_next_destroy_target wasted {} astars".format(i))
return c
# No path to any of the blocks
return None
def step_any_dir(self, agent):
px, py, pz = agent.pos
B = agent.get_blocks(px - 1, px + 1, py - 1, py + 2, pz - 1, pz + 1)
passable = np.isin(B[:, :, :, 0], PASSABLE_BLOCKS)
walkable = passable[:-1, :, :] & passable[1:, :, :] # head and feet passable
assert walkable.shape == (3, 3, 3)
relp = np.array([1, 1, 1]) # my pos is in the middle of the 3x3x3 cube
for step, fn in (
((0, 1, 0), agent.step_pos_z),
((0, -1, 0), agent.step_neg_z),
((0, 0, 1), agent.step_pos_x),
((0, 0, -1), agent.step_neg_x),
((1, 0, 0), agent.step_pos_y),
((-1, 0, 0), agent.step_neg_y),
):
if walkable[tuple(relp + step)]:
fn()
return
raise Exception("Can't step in any dir from pos={} B={}".format(agent.pos, B))
def undo(self, agent):
schematic_tags = []
if self.is_destroy_schm:
# if rebuilding an object, get old object tags
schematic_tags = [(pred, obj) for _, pred, obj in self.destroyed_block_object_triples]
agent.send_chat("ok I will build it back.")
else:
agent.send_chat("ok I will remove it.")
if self.old_blocks_list:
self.add_child_task(
Build(
agent,
{
"blocks_list": self.old_blocks_list,
"origin": self.old_origin,
"force": True,
"verbose": False,
"embed": self.embed,
"schematic_tags": schematic_tags,
},
),
agent,
pass_stop_condition=False,
)
if len(self.new_blocks) > 0:
self.add_child_task(
Destroy(agent, {"schematic": self.new_blocks}), agent, pass_child_task=False
)
def __repr__(self):
return "<Build {} @ {}>".format(len(self.schematic), self.origin)
class Fill(Task):
def __init__(self, agent, task_data):
super(Fill, self).__init__()
self.schematic = task_data["schematic"] # a list of xyz tuples
self.block_idm = task_data.get("block_idm", (2, 0)) # default 2: grass
self.build_task = None
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
origin = np.min(self.schematic, axis=0)
blocks_list = np.array([((x, y, z), self.block_idm) for (x, y, z) in self.schematic])
self.build_task = Build(
agent,
{
"blocks_list": blocks_list,
"origin": origin,
"force": True,
"verbose": False,
"embed": True,
"fill_message": True,
},
)
self.add_child_task(self.build_task, agent)
self.finished = True
def undo(self, agent):
if self.build_task is not None:
self.build_task.undo(agent)
class Destroy(Task):
def __init__(self, agent, task_data):
super(Destroy, self).__init__()
self.schematic = task_data["schematic"] # list[(xyz, idm)]
self.dig_message = True if "dig_message" in task_data else False
self.build_task = None
self.DIG_REACH = task_data.get("DIG_REACH", 3)
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
origin = np.min([(x, y, z) for ((x, y, z), (b, m)) in self.schematic], axis=0)
def to_destroy_schm(block_list):
"""Convert idm of block list to negative
For each block ((x, y, z), (b, m)), convert (b, m) to (-1, 0) indicating
it should be digged or destroyed.
Args:
- block_list: a list of ((x,y,z), (id, meta))
Returns:
- a block list of ((x,y,z), (-1, 0))
"""
destroy_schm = [((x, y, z), (-1, 0)) for ((x, y, z), (b, m)) in block_list]
return destroy_schm
destroy_schm = to_destroy_schm(self.schematic)
self.build_task = Build(
agent,
{
"blocks_list": destroy_schm,
"origin": origin,
"force": True,
"verbose": False,
"embed": True,
"dig_message": self.dig_message,
"is_destroy_schm": not self.dig_message,
"DIG_REACH": self.DIG_REACH,
},
)
self.add_child_task(self.build_task, agent)
self.finished = True
def undo(self, agent):
if self.build_task is not None:
self.build_task.undo(agent)
class Undo(Task):
def __init__(self, agent, task_data):
super(Undo, self).__init__()
self.to_undo_memid = task_data["memid"]
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
old_task_mem = agent.memory.get_task_by_id(self.to_undo_memid)
old_task_mem.task.undo(agent)
self.finished = True
def __repr__(self):
return "<Undo {}>".format(self.to_undo_memid)
class Spawn(Task):
def __init__(self, agent, task_data):
super(Spawn, self).__init__()
self.object_idm = task_data["object_idm"]
self.mobtype = MOBS_BY_ID[self.object_idm[1]]
self.pos = task_data["pos"]
self.PLACE_REACH = task_data.get("PLACE_REACH", 3)
self.last_stepped_time = agent.memory.get_time()
def find_nearby_new_mob(self, agent):
mindist = 1000000
near_new_mob = None
x, y, z = self.pos
y = y + 1
for mob in agent.get_mobs():
if MOBS_BY_ID[mob.mobType] == self.mobtype:
dist = manhat_dist((mob.pos.x, mob.pos.y, mob.pos.z), (x, y, z))
# hope this doesn;t take so long mob gets away...
if dist < mindist:
# print(MOBS_BY_ID[mob.mobType], dist)
if not agent.memory.get_entity_by_eid(mob.entityId):
mindist = dist
near_new_mob = mob
return mindist, near_new_mob
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
if manhat_dist(agent.pos, self.pos) > self.PLACE_REACH:
task = Move(agent, {"target": self.pos, "approx": self.PLACE_REACH})
self.add_child_task(task, agent)
else:
agent.set_held_item(self.object_idm)
if np.equal(self.pos, agent.pos).all():
agent.step_neg_z()
x, y, z = self.pos
y = y + 1
agent.place_block(x, y, z)
time.sleep(0.1)
mindist, placed_mob = self.find_nearby_new_mob(agent)
if mindist < 3:
memid = MobNode.create(agent.memory, placed_mob, agent_placed=True)
mobmem = agent.memory.get_mem_by_id(memid)
agent.memory.update_recent_entities(mems=[mobmem])
if self.memid is not None:
agent.memory.add_triple(
subj=self.memid, pred_text="task_effect_", obj=mobmem.memid
)
# the chat_effect_ triple was already made when the task is added if there was a chat...
# but it points to the task memory. link the chat to the mob memory:
chat_mem_triples = agent.memory.get_triples(
subj=None, pred_text="chat_effect_", obj=self.memid
)
if len(chat_mem_triples) > 0:
chat_memid = chat_mem_triples[0][0]
agent.memory.add_triple(
subj=chat_memid, pred_text="chat_effect_", obj=mobmem.memid
)
self.finished = True
class Dig(Task):
def __init__(self, agent, task_data):
super(Dig, self).__init__()
self.origin = task_data["origin"]
self.length = task_data["length"]
self.width = task_data["width"]
self.depth = task_data["depth"]
self.destroy_task = None
self.last_stepped_time = agent.memory.get_time()
def undo(self, agent):
if self.destroy_task is not None:
self.destroy_task.undo(agent)
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
mx, My, mz = self.origin
Mx = mx + (self.width - 1)
my = My - (self.depth - 1)
Mz = mz + (self.length - 1)
blocks = agent.get_blocks(mx, Mx, my, My, mz, Mz)
# if top row is above ground, make sure you are digging into the ground
if np.isin(blocks[-1, :, :, 0], PASSABLE_BLOCKS).all():
my -= 1
schematic = [
((x, y, z), (0, 0))
for x in range(mx, Mx + 1)
for y in range(my, My + 1)
for z in range(mz, Mz + 1)
]
# TODO ADS unwind this
# schematic = fill_idmeta(agent, poss)
self.destroy_task = Destroy(agent, {"schematic": schematic, "dig_message": True})
self.add_child_task(self.destroy_task, agent)
self.finished = True
class Get(Task):
def __init__(self, agent, task_data):
super(Get, self).__init__()
self.idm = task_data["idm"]
self.pos = task_data["pos"]
self.eid = task_data["eid"]
self.memid = task_data["memid"]
self.approx = 1
self.attempts = 10
self.item_count_before_get = agent.get_inventory_item_count(self.idm[0], self.idm[1])
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
delta = (
agent.get_inventory_item_count(self.idm[0], self.idm[1]) - self.item_count_before_get
)
if delta > 0:
agent.inventory.add_item_stack(self.idm, (self.memid, delta))
agent.send_chat("Got Item!")
agent.memory.tag(self.memid, "_in_inventory")
self.finished = True
return
if self.attempts == 0:
agent.send_chat("I can't get this item. Give up now")
self.finished = True
return
self.attempts -= 1
# walk through the area
target = (self.pos[0] + randint(-1, 1), self.pos[1], self.pos[2] + randint(-1, 1))
self.move_task = Move(agent, {"target": target, "approx": self.approx})
self.add_child_task(self.move_task, agent)
return
class Drop(Task):
def __init__(self, agent, task_data):
super(Drop, self).__init__()
self.eid = task_data["eid"]
self.idm = task_data["idm"]
self.memid = task_data["memid"]
def find_nearby_new_item_stack(self, agent, id, meta):
mindist = 3
near_new_item_stack = None
x, y, z = agent.get_player().pos
for item_stack in agent.get_item_stacks():
if item_stack.item.id == id and item_stack.item.meta == meta:
dist = manhat_dist(
(item_stack.pos.x, item_stack.pos.y, item_stack.pos.z), (x, y, z)
)
if dist < mindist:
if not agent.memory.get_entity_by_eid(item_stack.entityId):
mindist = dist
near_new_item_stack = item_stack
return mindist, near_new_item_stack
def step(self, agent):
super().step(agent)
if self.finished:
return
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
if not agent.inventory.contains(self.eid):
agent.send_chat("I can't find it in my inventory!")
self.finished = False
return
id, m = self.idm
count = self.inventory.get_item_stack_count_from_memid(self.memid)
agent.drop_inventory_item_stack(id, m, count)
agent.inventory.remove_item_stack(self.idm, self.memid)
mindist, dropped_item_stack = self.get_nearby_new_item_stack(agent, id, m)
if dropped_item_stack:
agent.memory.update_item_stack_eid(self.memid, dropped_item_stack.entityId)
agent.memory.set_item_stack_position(dropped_item_stack)
agent.memory.tag(self.memid, "_on_ground")
x, y, z = agent.get_player().pos
target = (x, y + 2, z)
self.move_task = Move(agent, {"target": target, "approx": 1})
self.add_child_task(self.move_task, agent)
self.finished = True
class Loop(Task):
def __init__(self, agent, task_data):
super(Loop, self).__init__()
self.new_tasks_fn = task_data["new_tasks_fn"]
self.stop_condition = task_data["stop_condition"]
self.last_stepped_time = agent.memory.get_time()
def step(self, agent):
# wait certain amount of ticks until issuing next step
# while not (agent.memory.get_time() - self.last_stepped_time) > self.throttling_tick:
# pass
if self.stop_condition.check():
self.finished = True
return
else:
for t in self.new_tasks_fn():
self.add_child_task(t, agent)
| craftassist-master | python/craftassist/tasks.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""This file contains functions to map strings representing abstract
sizes to ints and ranges"""
import numpy as np
RANGES = {
"tiny": (1, 3),
"small": (3, 4),
"medium": (4, 6),
"large": (6, 10),
"huge": (10, 16),
"gigantic": (16, 32),
}
MODIFIERS = ["very", "extremely", "really"]
WORD_SUBS = {"little": "small", "big": "large"}
def size_str_to_int(s, ranges=RANGES):
a, b = size_str_to_range(s, ranges=ranges)
return np.random.randint(a, b)
def size_str_to_range(s, ranges=RANGES):
words = s.split()
# replace words in WORD_SUBS
for i in range(len(words)):
if words[i] in WORD_SUBS:
words[i] = WORD_SUBS[words[i]]
is_modded = any(m in words for m in MODIFIERS)
med_idx = list(ranges.keys()).index("medium")
max_idx = len(ranges.keys())
for i, (word, rng) in enumerate(ranges.items()):
if word in words:
if is_modded and i < med_idx and i > 0:
return list(ranges.values())[i - 1]
elif is_modded and i > med_idx and i < max_idx - 1:
return list(ranges.values())[i + 1]
else:
return list(ranges.values())[i]
return ranges["medium"]
def size_int_to_str(x):
raise NotImplementedError()
| craftassist-master | python/craftassist/size_words.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
# TODO correct model paths
import os
import sys
import logging
import faulthandler
import signal
import random
import re
import sentry_sdk
import numpy as np
# FIXME
import time
from multiprocessing import set_start_method
import inventory
import mc_memory
from dialogue_objects import GetMemoryHandler, PutMemoryHandler, Interpreter
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
import dashboard
if __name__ == "__main__":
# this line has to go before any imports that contain @sio.on functions
# or else, those @sio.on calls become no-ops
print("starting dashboard...")
dashboard.start()
from base_agent.loco_mc_agent import LocoMCAgent
from argument_parser import ArgumentParser
from agent import Agent as MCAgent
from low_level_perception import LowLevelMCPerception
import heuristic_perception
from mc_util import cluster_areas, hash_user, MCTime
from voxel_models.subcomponent_classifier import SubcomponentClassifierWrapper
from voxel_models.geoscorer import Geoscorer
from base_agent.nsp_dialogue_manager import NSPDialogueManager
import default_behaviors
import subprocess
import rotation
faulthandler.register(signal.SIGUSR1)
random.seed(0)
log_formatter = logging.Formatter(
"%(asctime)s [%(filename)s:%(lineno)s - %(funcName)s() %(levelname)s]: %(message)s"
)
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().handlers.clear()
sentry_sdk.init() # enabled if SENTRY_DSN set in env
DEFAULT_BEHAVIOUR_TIMEOUT = 20
DEFAULT_FRAME = "SPEAKER"
class CraftAssistAgent(LocoMCAgent):
default_frame = DEFAULT_FRAME
coordinate_transforms = rotation
def __init__(self, opts):
super(CraftAssistAgent, self).__init__(opts)
self.no_default_behavior = opts.no_default_behavior
self.point_targets = []
self.last_chat_time = 0
# areas must be perceived at each step
# List of tuple (XYZ, radius), each defines a cube
self.areas_to_perceive = []
self.add_self_memory_node()
self.init_inventory()
def init_inventory(self):
self.inventory = inventory.Inventory()
logging.info("Initialized agent inventory")
def init_memory(self):
self.memory = mc_memory.MCAgentMemory(
db_file=os.environ.get("DB_FILE", ":memory:"),
db_log_path="agent_memory.{}.log".format(self.name),
agent_time=MCTime(self.get_world_time),
)
file_log_handler = logging.FileHandler("agent.{}.log".format(self.name))
file_log_handler.setFormatter(log_formatter)
logging.getLogger().addHandler(file_log_handler)
logging.info("Initialized agent memory")
def init_perception(self):
self.perception_modules = {}
self.perception_modules["low_level"] = LowLevelMCPerception(self)
self.perception_modules["heuristic"] = heuristic_perception.PerceptionWrapper(self)
# set up the SubComponentClassifier model
if self.opts.semseg_model_path:
self.perception_modules["semseg"] = SubcomponentClassifierWrapper(
self, self.opts.semseg_model_path, self.opts.semseg_vocab_path
)
# set up the Geoscorer model
self.geoscorer = (
Geoscorer(merger_model_path=self.opts.geoscorer_model_path)
if self.opts.geoscorer_model_path
else None
)
def init_controller(self):
dialogue_object_classes = {}
dialogue_object_classes["interpreter"] = Interpreter
dialogue_object_classes["get_memory"] = GetMemoryHandler
dialogue_object_classes["put_memory"] = PutMemoryHandler
self.dialogue_manager = NSPDialogueManager(self, dialogue_object_classes, self.opts)
def perceive(self, force=False):
self.areas_to_perceive = cluster_areas(self.areas_to_perceive)
for v in self.perception_modules.values():
v.perceive(force=force)
self.areas_to_perceive = []
def controller_step(self):
"""Process incoming chats and modify task stack"""
raw_incoming_chats = self.get_incoming_chats()
incoming_chats = []
for raw_chat in raw_incoming_chats:
match = re.search("^<([^>]+)> (.*)", raw_chat)
if match is None:
logging.info("Ignoring chat: {}".format(raw_chat))
continue
speaker, chat = match.group(1), match.group(2)
speaker_hash = hash_user(speaker)
logging.info("Incoming chat: ['{}' -> {}]".format(speaker_hash, chat))
if chat.startswith("/"):
continue
incoming_chats.append((speaker, chat))
self.memory.add_chat(self.memory.get_player_by_name(speaker).memid, chat)
if incoming_chats:
# force to get objects, speaker info
self.perceive(force=True)
# logging.info("Incoming chats: {}".format(raw_incoming_chats))
# change this to memory.get_time() format?
self.last_chat_time = time.time()
# for now just process the first incoming chat
self.dialogue_manager.step(incoming_chats[0])
else:
# Maybe add default task
if not self.no_default_behavior:
self.maybe_run_slow_defaults()
self.dialogue_manager.step((None, ""))
def maybe_run_slow_defaults(self):
"""Pick a default task task to run
with a low probability"""
if self.memory.task_stack_peek() or len(self.dialogue_manager.dialogue_stack) > 0:
return
# list of (prob, default function) pairs
visible_defaults = [
(0.001, default_behaviors.build_random_shape),
(0.005, default_behaviors.come_to_player),
]
# default behaviors of the agent not visible in the game
invisible_defaults = []
defaults = (
visible_defaults + invisible_defaults
if time.time() - self.last_chat_time > DEFAULT_BEHAVIOUR_TIMEOUT
else invisible_defaults
)
defaults = [(p, f) for (p, f) in defaults if f not in self.memory.banned_default_behaviors]
def noop(*args):
pass
defaults.append((1 - sum(p for p, _ in defaults), noop)) # noop with remaining prob
# weighted random choice of functions
p, fns = zip(*defaults)
fn = np.random.choice(fns, p=p)
if fn != noop:
logging.info("Default behavior: {}".format(fn))
fn(self)
def get_time(self):
# round to 100th of second, return as
# n hundreth of seconds since agent init
return self.memory.get_time()
def get_world_time(self):
# MC time is based on ticks, where 20 ticks happen every second.
# There are 24000 ticks in a day, making Minecraft days exactly 20 minutes long.
# The time of day in MC is based on the timestamp modulo 24000 (default).
# 0 is sunrise, 6000 is noon, 12000 is sunset, and 18000 is midnight.
return self.get_time_of_day()
def safe_get_changed_blocks(self):
blocks = self.cagent.get_changed_blocks()
safe_blocks = []
if len(self.point_targets) > 0:
for point_target in self.point_targets:
pt = point_target[0]
for b in blocks:
x, y, z = b[0]
xok = x < pt[0] or x > pt[3]
yok = y < pt[1] or y > pt[4]
zok = z < pt[2] or z > pt[5]
if xok and yok and zok:
safe_blocks.append(b)
else:
safe_blocks = blocks
return safe_blocks
def point_at(self, target, sleep=None):
"""Bot pointing.
Args:
target: list of x1 y1 z1 x2 y2 z2, where:
x1 <= x2,
y1 <= y2,
z1 <= z2.
"""
assert len(target) == 6
self.send_chat("/point {} {} {} {} {} {}".format(*target))
self.point_targets.append((target, time.time()))
# sleep before the bot can take any actions
# otherwise there might be bugs since the object is flashing
# deal with this in the task...
if sleep:
time.sleep(sleep)
def relative_head_pitch(self, angle):
# warning: pitch is flipped!
new_pitch = self.get_player().look.pitch - angle
self.set_look(self.get_player().look.yaw, new_pitch)
def send_chat(self, chat):
logging.info("Sending chat: {}".format(chat))
self.memory.add_chat(self.memory.self_memid, chat)
return self.cagent.send_chat(chat)
# TODO update client so we can just loop through these
# TODO rename things a bit- some perceptual things are here,
# but under current abstraction should be in init_perception
def init_physical_interfaces(self):
# For testing agent without cuberite server
if self.opts.port == -1:
return
logging.info("Attempting to connect to port {}".format(self.opts.port))
self.cagent = MCAgent("localhost", self.opts.port, self.name)
logging.info("Logged in to server")
self.dig = self.cagent.dig
self.drop_item_stack_in_hand = self.cagent.drop_item_stack_in_hand
self.drop_item_in_hand = self.cagent.drop_item_in_hand
self.drop_inventory_item_stack = self.cagent.drop_inventory_item_stack
self.set_inventory_slot = self.cagent.set_inventory_slot
self.get_player_inventory = self.cagent.get_player_inventory
self.get_inventory_item_count = self.cagent.get_inventory_item_count
self.get_inventory_items_counts = self.cagent.get_inventory_items_counts
# defined above...
# self.send_chat = self.cagent.send_chat
self.set_held_item = self.cagent.set_held_item
self.step_pos_x = self.cagent.step_pos_x
self.step_neg_x = self.cagent.step_neg_x
self.step_pos_z = self.cagent.step_pos_z
self.step_neg_z = self.cagent.step_neg_z
self.step_pos_y = self.cagent.step_pos_y
self.step_neg_y = self.cagent.step_neg_y
self.step_forward = self.cagent.step_forward
self.look_at = self.cagent.look_at
self.set_look = self.cagent.set_look
self.turn_angle = self.cagent.turn_angle
self.turn_left = self.cagent.turn_left
self.turn_right = self.cagent.turn_right
self.place_block = self.cagent.place_block
self.use_entity = self.cagent.use_entity
self.use_item = self.cagent.use_item
self.use_item_on_block = self.cagent.use_item_on_block
self.is_item_stack_on_ground = self.cagent.is_item_stack_on_ground
self.craft = self.cagent.craft
self.get_blocks = self.cagent.get_blocks
self.get_local_blocks = self.cagent.get_local_blocks
self.get_incoming_chats = self.cagent.get_incoming_chats
self.get_player = self.cagent.get_player
self.get_mobs = self.cagent.get_mobs
self.get_other_players = self.cagent.get_other_players
self.get_other_player_by_name = self.cagent.get_other_player_by_name
self.get_vision = self.cagent.get_vision
self.get_line_of_sight = self.cagent.get_line_of_sight
self.get_player_line_of_sight = self.cagent.get_player_line_of_sight
self.get_changed_blocks = self.cagent.get_changed_blocks
self.get_item_stacks = self.cagent.get_item_stacks
self.get_world_age = self.cagent.get_world_age
self.get_time_of_day = self.cagent.get_time_of_day
self.get_item_stack = self.cagent.get_item_stack
def add_self_memory_node(self):
# clean this up! FIXME!!!!! put in base_agent_memory?
# how/when to, memory is initialized before physical interfaces...
try:
p = self.get_player()
except: # this is for test/test_agent :(
return
self.memory._db_write(
"INSERT INTO ReferenceObjects(uuid, eid, name, ref_type, x, y, z, pitch, yaw) VALUES (?,?,?,?,?,?,?,?,?)",
self.memory.self_memid,
p.entityId,
p.name,
"player",
p.pos.x,
p.pos.y,
p.pos.z,
p.look.pitch,
p.look.yaw,
)
if __name__ == "__main__":
base_path = os.path.dirname(__file__)
parser = ArgumentParser("Minecraft", base_path)
opts = parser.parse()
# set up stdout logging
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG if opts.verbose else logging.INFO)
sh.setFormatter(log_formatter)
logging.getLogger().addHandler(sh)
logging.info("Info logging")
logging.debug("Debug logging")
# Check that models and datasets are up to date
rc = subprocess.call([opts.verify_hash_script_path, "craftassist"])
set_start_method("spawn", force=True)
sa = CraftAssistAgent(opts)
sa.start()
| craftassist-master | python/craftassist/craftassist_agent.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from typing import Dict, Callable
import shapes
# mapping from mob names to id
SPAWN_OBJECTS = {
"elder guardian": 4,
"wither skeleton": 5,
"stray": 6,
"husk": 23,
"zombie villager": 27,
"skeleton horse": 28,
"zombie horse": 29,
"donkey": 31,
"mule": 32,
"evoker": 34,
"vex": 35,
"vindicator": 36,
"creeper": 50,
"skeleton": 51,
"spider": 52,
"zombie": 54,
"slime": 55,
"ghast": 56,
"zombie pigman": 57,
"enderman": 58,
"cave spider": 59,
"silverfish": 60,
"blaze": 61,
"magma cube": 62,
"bat": 65,
"witch": 66,
"endermite": 67,
"guardian": 68,
"shulker": 69,
"pig": 90,
"sheep": 91,
"cow": 92,
"chicken": 93,
"squid": 94,
"wolf": 95,
"mooshroom": 96,
"ocelot": 98,
"horse": 100,
"rabbit": 101,
"polar bear": 102,
"llama": 103,
"parrot": 105,
"villager": 120,
}
# mapping from canonicalized shape names to the corresponding functions
SPECIAL_SHAPE_FNS: Dict[str, Callable] = {
"CUBE": shapes.cube,
"HOLLOW_CUBE": shapes.hollow_cube,
"RECTANGULOID": shapes.rectanguloid,
"HOLLOW_RECTANGULOID": shapes.hollow_rectanguloid,
"SPHERE": shapes.sphere,
"SPHERICAL_SHELL": shapes.spherical_shell,
"PYRAMID": shapes.square_pyramid,
"SQUARE": shapes.square,
"RECTANGLE": shapes.rectangle,
"CIRCLE": shapes.circle,
"DISK": shapes.disk,
"TRIANGLE": shapes.triangle,
"DOME": shapes.dome,
"ARCH": shapes.arch,
"ELLIPSOID": shapes.ellipsoid,
"TOWER": shapes.tower,
}
# mapping from shape names to canonicalized shape names
SPECIAL_SHAPES_CANONICALIZE = {
"rectanguloid": "RECTANGULOID",
"box": "HOLLOW_RECTANGULOID",
"empty box": "HOLLOW_RECTANGULOID",
"hollow box": "HOLLOW_RECTANGULOID",
"hollow rectanguloid": "HOLLOW_RECTANGULOID",
"cube": "CUBE",
"empty cube": "HOLLOW_CUBE",
"hollow cube": "HOLLOW_CUBE",
"ball": "SPHERE",
"sphere": "SPHERE",
"spherical shell": "SPHERICAL_SHELL",
"empty sphere": "SPHERICAL_SHELL",
"empty ball": "SPHERICAL_SHELL",
"hollow sphere": "SPHERICAL_SHELL",
"hollow ball": "SPHERICAL_SHELL",
"pyramid": "PYRAMID",
"rectangle": "RECTANGLE",
"wall": "RECTANGLE",
"slab": "RECTANGLE",
"platform": "RECTANGLE",
"square": "SQUARE",
"flat wedge": "TRIANGLE",
"triangle": "TRIANGLE",
"circle": "CIRCLE",
"disk": "DISK",
"ellipsoid": "ELLIPSOID",
"dome": "DOME",
"arch": "ARCH",
"archway": "ARCH",
"stack": "TOWER",
"tower": "TOWER",
}
| craftassist-master | python/craftassist/word_maps.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""This file has functions to implement different dances for the agent.
"""
import numpy as np
import tasks
import shapes
import search
from mc_util import ErrorWithResponse
# FIXME! actual jump on client
jump = [{"translate": (0, 1, 0)}, {"translate": (0, -1, 0)}]
konami_dance = [
{"translate": (0, 1, 0)},
{"translate": (0, 1, 0)},
{"translate": (0, -1, 0)},
{"translate": (0, -1, 0)},
{"translate": (0, 0, -1)},
{"translate": (0, 0, 1)},
{"translate": (0, 0, -1)},
{"translate": (0, 0, 1)},
]
# TODO relative to current
head_bob = [
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 90)},
{"head_yaw_pitch": (0, 0)},
{"head_yaw_pitch": (0, 0)},
]
def add_default_dances(memory):
memory.add_dance(generate_sequential_move_fn(jump), name="jump")
memory.add_dance(
generate_sequential_move_fn(konami_dance),
name="konami dance",
tags=["ornamental_dance", "konami"],
)
memory.add_dance(
generate_sequential_move_fn(head_bob), name="head bob", tags=["ornamental_dance"]
)
def generate_sequential_move_fn(sequence):
def move_fn(danceObj, agent):
if danceObj.tick >= len(sequence):
return None
else:
if danceObj.dance_location is not None and danceObj.tick == 0:
mv = tasks.Move(agent, {"target": danceObj.dance_location, "approx": 0})
danceObj.dance_location = None
else:
mv = tasks.DanceMove(agent, sequence[danceObj.tick])
danceObj.tick += 1
return mv
return move_fn
class Movement(object):
def __init__(self, agent, move_fn, dance_location=None):
self.agent = agent
self.move_fn = move_fn
self.dance_location = dance_location
self.tick = 0
def get_move(self):
# move_fn should output a tuple (dx, dy, dz) corresponding to a
# change in Movement or None
# if None then Movement is finished
# can output
return self.move_fn(self, self.agent)
# class HeadTurnInstant(Movement):
# TODO: class TimedDance(Movement): !!!!
# e.g. go around the x
# go through the x
# go over the x
# go across the x
class RefObjMovement(Movement):
def __init__(
self,
agent,
ref_object=None,
relative_direction="CLOCKWISE", # this is the memory of the object
):
self.agent = agent
self.tick = 0
if not ref_object:
x, y, z = agent.pos
bounds = (x, x, y, y, z, z)
center = (x, y, z)
else:
bounds = ref_object.get_bounds()
center = ref_object.get_pos()
d = max(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4])
if relative_direction == "CLOCKWISE" or relative_direction == "AROUND":
offsets = shapes.arrange(
"circle", schematic=None, shapeparams={"encircled_object_radius": d}
)
elif relative_direction == "ANTICLOCKWISE":
offsets = shapes.arrange(
"circle", schematic=None, shapeparams={"encircled_object_radius": d}
)
offsets = offsets[::-1]
else:
raise NotImplementedError("TODO other kinds of paths")
self.path = [np.round(np.add(center, o)) for o in offsets]
self.path.append(self.path[0])
# check each offset to find a nearby reachable point, see if a path
# is possible now, and error otherwise
for i in range(len(self.path) - 1):
path = search.astar(agent, self.path[i + 1], approx=2, pos=self.path[i])
if path is None:
raise ErrorWithResponse("I cannot find an appropriate path.")
def get_move(self):
if self.tick >= len(self.path):
return None
mv = tasks.Move(self.agent, {"target": self.path[self.tick], "approx": 2})
self.tick += 1
return mv
| craftassist-master | python/craftassist/dance.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
import os
import sys
import numpy as np
import random
import shape_helpers as sh
import tasks
from mc_util import pos_to_np
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.dialogue_objects import Say
from ttad.generation_dialogues.generate_utils import prepend_a_an
def build_random_shape(agent, rand_range=(10, 0, 10), no_chat=False):
"""Pick a random shape from shapes.py and build that"""
target_loc = agent.pos
for i in range(3):
target_loc[i] += np.random.randint(-rand_range[i], rand_range[i] + 1)
shape = random.choice(sh.SHAPE_NAMES)
opts = sh.SHAPE_HELPERS[shape]()
opts["bid"] = sh.bid()
schematic = sh.SHAPE_FNS[shape](**opts)
relations = [
{"pred": "has_name", "obj": shape.lower()},
{"pred": "has_tag", "obj": shape.lower()},
]
task_data = {
"blocks_list": schematic,
"origin": target_loc,
"verbose": False,
"schematic_tags": relations,
"default_behavior": "build_random_shape", # must == function name. Hacky and I hate it.
}
logging.info("Default behavior: building {}".format(shape))
agent.memory.task_stack_push(tasks.Build(agent, task_data))
if not no_chat:
shape_name = prepend_a_an(shape.lower())
agent.dialogue_manager.dialogue_stack.append_new(
Say, "I am building {} while you decide what you want me to do!".format(shape_name)
)
return schematic
def come_to_player(agent):
"""Go to where the player is."""
op = agent.get_other_players()
if len(op) == 0:
return
p = random.choice(agent.get_other_players())
agent.memory.task_stack_push(tasks.Move(agent, {"target": pos_to_np(p.pos), "approx": 3}))
| craftassist-master | python/craftassist/default_behaviors.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This is a utility script which allows the user to easily query the ttad model
At the prompt, try typing "build me a cube"
"""
import faulthandler
import fileinput
import json
import signal
from ttad.ttad_model.ttad_model_wrapper import ActionDictBuilder
faulthandler.register(signal.SIGUSR1)
if __name__ == "__main__":
print("Loading...")
# ttad_model_path = os.path.join(os.path.dirname(__file__), "models/ttad/ttad.pth")
# ttad_embedding_path = os.path.join(os.path.dirname(__file__), "models/ttad/ttad_ft_embeds.pth")
# ttad_model = ActionDictBuilder(ttad_model_path, ttad_embedding_path)
ttad_model = ActionDictBuilder()
print("> ", end="", flush=True)
for line in fileinput.input():
action_dict = ttad_model.parse([line.strip()])
print(json.dumps(action_dict))
print("\n> ", end="", flush=True)
| craftassist-master | python/craftassist/ttad_repl.py |
import os
import sys
sys.path.append(os.path.dirname(__file__))
| craftassist-master | python/craftassist/__init__.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import os
import random
import sys
from typing import Optional, List
from build_utils import npy_to_blocks_list
import minecraft_specs
import dance
PERCEPTION_RANGE = 64
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.base_util import XYZ, Block
from base_agent.sql_memory import AgentMemory
from base_agent.memory_nodes import ( # noqa
TaskNode,
PlayerNode,
MemoryNode,
ChatNode,
TimeNode,
LocationNode,
SetNode,
ReferenceObjectNode,
)
from mc_memory_nodes import ( # noqa
DanceNode,
VoxelObjectNode,
BlockObjectNode,
BlockTypeNode,
MobNode,
ItemStackNode,
MobTypeNode,
InstSegNode,
SchematicNode,
NODELIST,
)
from word_maps import SPAWN_OBJECTS
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
SCHEMAS = [
os.path.join(os.path.join(BASE_AGENT_ROOT, "base_agent"), "base_memory_schema.sql"),
os.path.join(os.path.dirname(__file__), "mc_memory_schema.sql"),
]
SCHEMA = os.path.join(os.path.dirname(__file__), "memory_schema.sql")
THROTTLING_TICK_UPPER_LIMIT = 64
THROTTLING_TICK_LOWER_LIMIT = 4
# TODO "snapshot" memory type (giving a what mob/object/player looked like at a fixed timestamp)
# TODO when a memory is removed, its last state should be snapshotted to prevent tag weirdness
class MCAgentMemory(AgentMemory):
def __init__(
self,
db_file=":memory:",
db_log_path=None,
schema_paths=SCHEMAS,
load_minecraft_specs=True,
load_block_types=True,
load_mob_types=True,
preception_range=PERCEPTION_RANGE,
agent_time=None,
):
super(MCAgentMemory, self).__init__(
db_file=db_file,
schema_paths=schema_paths,
db_log_path=db_log_path,
nodelist=NODELIST,
agent_time=agent_time,
)
self.banned_default_behaviors = [] # FIXME: move into triple store?
self._safe_pickle_saved_attrs = {}
self._load_schematics(load_minecraft_specs)
self._load_block_types(load_block_types)
self._load_mob_types(load_mob_types)
self.dances = {}
dance.add_default_dances(self)
self.perception_range = preception_range
########################
### ReferenceObjects ###
########################
def get_entity_by_eid(self, eid) -> Optional["ReferenceObjectNode"]:
r = self._db_read_one("SELECT uuid FROM ReferenceObjects WHERE eid=?", eid)
if r:
return self.get_mem_by_id(r[0])
else:
return None
###############
### Voxels ###
###############
# count updates are done by hand to not need to count all voxels every time
# use these functions, don't add/delete/modify voxels with raw sql
def update_voxel_count(self, memid, dn):
c = self._db_read_one("SELECT voxel_count FROM ReferenceObjects WHERE uuid=?", memid)
if c:
count = c[0] + dn
self._db_write("UPDATE ReferenceObjects SET voxel_count=? WHERE uuid=?", count, memid)
return count
else:
return None
def update_voxel_mean(self, memid, count, loc):
""" update the x, y, z entries in ReferenceObjects
to account for the removal or addition of a block.
count should be the number of voxels *after* addition if >0
and -count the number *after* removal if count < 0
count should not be 0- handle that outside
"""
old_loc = self._db_read_one("SELECT x, y, z FROM ReferenceObjects WHERE uuid=?", memid)
# TODO warn/error if no such memory?
assert count != 0
if old_loc:
b = 1 / count
if count > 0:
a = (count - 1) / count
else:
a = (1 - count) / (-count)
new_loc = (
old_loc[0] * a + loc[0] * b,
old_loc[1] * a + loc[1] * b,
old_loc[2] * a + loc[2] * b,
)
self._db_write(
"UPDATE ReferenceObjects SET x=?, y=?, z=? WHERE uuid=?", *new_loc, memid
)
return new_loc
def remove_voxel(self, x, y, z, ref_type):
memids = self._db_read_one(
"SELECT uuid FROM VoxelObjects WHERE x=? and y=? and z=? and ref_type=?",
x,
y,
z,
ref_type,
)
if not memids:
# TODO error/warning?
return
memid = memids[0]
c = self.update_voxel_count(memid, -1)
if c > 0:
self.update_voxel_mean(memid, c, (x, y, z))
self._db_write(
"DELETE FROM VoxelObjects WHERE x=? AND y=? AND z=? and ref_type=?", x, y, z, ref_type
)
if c == 0:
# if not self.memory.check_memid_exists(memid, "VoxelObjects"):
# object is gone now. TODO be more careful here... maybe want to keep some records?
self.remove_memid_triple(memid, role="both")
# this only upserts to the same ref_type- if the voxel is occupied by
# a different ref_type it will insert a new ref object even if update is True
def upsert_block(
self,
block: Block,
memid: str,
ref_type: str,
player_placed: bool = False,
agent_placed: bool = False,
update: bool = True, # if update is set to False, forces a write
):
((x, y, z), (b, m)) = block
old_memid = self._db_read_one(
"SELECT uuid FROM VoxelObjects WHERE x=? AND y=? AND z=? and ref_type=?",
x,
y,
z,
ref_type,
)
# add to voxel count
new_count = self.update_voxel_count(memid, 1)
assert new_count
self.update_voxel_mean(memid, new_count, (x, y, z))
if old_memid and update:
if old_memid != memid:
self.remove_voxel(x, y, z, ref_type)
cmd = "INSERT INTO VoxelObjects (uuid, bid, meta, updated, player_placed, agent_placed, ref_type, x, y, z) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
else:
cmd = "UPDATE VoxelObjects SET uuid=?, bid=?, meta=?, updated=?, player_placed=?, agent_placed=? WHERE ref_type=? AND x=? AND y=? AND z=?"
else:
cmd = "INSERT INTO VoxelObjects (uuid, bid, meta, updated, player_placed, agent_placed, ref_type, x, y, z) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
self._db_write(
cmd, memid, b, m, self.get_time(), player_placed, agent_placed, ref_type, x, y, z
)
######################
### BlockObjects ###
######################
# rename this... "object" is bad name
def get_object_by_id(self, memid: str, table="BlockObjects") -> "VoxelObjectNode":
if table == "BlockObjects":
return BlockObjectNode(self, memid)
elif table == "InstSeg":
return InstSegNode(self, memid)
else:
raise ValueError("Bad table={}".format(table))
# and rename this
def get_object_info_by_xyz(self, xyz: XYZ, ref_type: str, just_memid=True):
r = self._db_read(
"SELECT DISTINCT(uuid), bid, meta FROM VoxelObjects WHERE x=? AND y=? AND z=? and ref_type=?",
*xyz,
ref_type
)
if just_memid:
return [memid for (memid, bid, meta) in r]
else:
return r
# WARNING: these do not search archived/snapshotted block objects
# TODO replace all these all through the codebase with generic counterparts
def get_block_object_ids_by_xyz(self, xyz: XYZ) -> List[str]:
return self.get_object_info_by_xyz(xyz, "BlockObjects")
def get_block_object_by_xyz(self, xyz: XYZ) -> Optional["VoxelObjectNode"]:
memids = self.get_block_object_ids_by_xyz(xyz)
if len(memids) == 0:
return None
return self.get_block_object_by_id(memids[0])
def get_block_object_by_id(self, memid: str) -> "VoxelObjectNode":
return self.get_object_by_id(memid, "BlockObjects")
def tag_block_object_from_schematic(self, block_object_memid: str, schematic_memid: str):
self.add_triple(subj=block_object_memid, pred_text="_from_schematic", obj=schematic_memid)
#####################
### InstSegObject ###
#####################
def get_instseg_object_ids_by_xyz(self, xyz: XYZ) -> List[str]:
r = self._db_read(
'SELECT DISTINCT(uuid) FROM VoxelObjects WHERE ref_type="inst_seg" AND x=? AND y=? AND z=?',
*xyz
)
return r
####################
### Schematics ###
####################
def get_schematic_by_id(self, memid: str) -> "SchematicNode":
return SchematicNode(self, memid)
def get_schematic_by_property_name(self, name, table_name) -> Optional["SchematicNode"]:
r = self._db_read(
"""
SELECT {}.type_name
FROM {} INNER JOIN Triples as T ON T.subj={}.uuid
WHERE (T.pred_text="has_name" OR T.pred_text="has_tag") AND T.obj_text=?""".format(
table_name, table_name, table_name
),
name,
)
if not r:
return None
result = [] # noqa
for e in r:
schematic_name = e[0]
schematics = self._db_read(
"""
SELECT Schematics.uuid
FROM Schematics INNER JOIN Triples as T ON T.subj=Schematics.uuid
WHERE (T.pred_text="has_name" OR T.pred_text="has_tag") AND T.obj_text=?""",
schematic_name,
)
if schematics:
result.extend(schematics)
if result:
return self.get_schematic_by_id(random.choice(result)[0])
else:
return None
def get_mob_schematic_by_name(self, name: str) -> Optional["SchematicNode"]:
return self.get_schematic_by_property_name(name, "MobTypes")
# TODO call this in get_schematic_by_property_name
def get_schematic_by_name(self, name: str) -> Optional["SchematicNode"]:
r = self._db_read(
"""
SELECT Schematics.uuid
FROM Schematics INNER JOIN Triples as T ON T.subj=Schematics.uuid
WHERE (T.pred_text="has_name" OR T.pred_text="has_tag") AND T.obj_text=?""",
name,
)
if r: # if multiple exist, then randomly select one
return self.get_schematic_by_id(random.choice(r)[0])
# if no schematic with exact matched name exists, search for a schematic
# with matched property name instead
else:
return self.get_schematic_by_property_name(name, "BlockTypes")
def convert_block_object_to_schematic(self, block_object_memid: str) -> "SchematicNode":
r = self._db_read_one(
'SELECT subj FROM Triples WHERE pred_text="_source_block_object" AND obj=?',
block_object_memid,
)
if r:
# previously converted; return old schematic
return self.get_schematic_by_id(r[0])
else:
# get up to date BlockObject
block_object = self.get_block_object_by_id(block_object_memid)
# create schematic
memid = SchematicNode.create(self, list(block_object.blocks.items()))
# add triple linking the object to the schematic
self.add_triple(subj=memid, pred_text="_source_block_object", obj=block_object.memid)
return self.get_schematic_by_id(memid)
def _load_schematics(self, load_minecraft_specs=True):
if load_minecraft_specs:
for premem in minecraft_specs.get_schematics():
npy = premem["schematic"]
memid = SchematicNode.create(self, npy_to_blocks_list(npy))
if premem.get("name"):
for n in premem["name"]:
self.add_triple(subj=memid, pred_text="has_name", obj_text=n)
self.add_triple(subj=memid, pred_text="has_tag", obj_text=n)
if premem.get("tags"):
for t in premem["tags"]:
self.add_triple(subj=memid, pred_text="has_tag", obj_text=t)
# load single blocks as schematics
bid_to_name = minecraft_specs.get_block_data()["bid_to_name"]
for (d, m), name in bid_to_name.items():
if d >= 256:
continue
memid = SchematicNode.create(self, [((0, 0, 0), (d, m))])
self.add_triple(subj=memid, pred_text="has_name", obj_text=name)
if "block" in name:
self.add_triple(
subj=memid, pred_text="has_name", obj_text=name.strip("block").strip()
)
# tag single blocks with 'block'
self.add_triple(subj=memid, pred_text="has_name", obj_text="block")
def _load_block_types(
self,
load_block_types=True,
load_color=True,
load_block_property=True,
simple_color=False,
load_material=True,
):
if not load_block_types:
return
bid_to_name = minecraft_specs.get_block_data()["bid_to_name"]
color_data = minecraft_specs.get_colour_data()
if simple_color:
name_to_colors = color_data["name_to_simple_colors"]
else:
name_to_colors = color_data["name_to_colors"]
block_property_data = minecraft_specs.get_block_property_data()
block_name_to_properties = block_property_data["name_to_properties"]
for (b, m), type_name in bid_to_name.items():
if b >= 256:
continue
memid = BlockTypeNode.create(self, type_name, (b, m))
self.add_triple(subj=memid, pred_text="has_name", obj_text=type_name)
if "block" in type_name:
self.add_triple(
subj=memid, pred_text="has_name", obj_text=type_name.strip("block").strip()
)
if load_color:
if name_to_colors.get(type_name) is not None:
for color in name_to_colors[type_name]:
self.add_triple(subj=memid, pred_text="has_colour", obj_text=color)
if load_block_property:
if block_name_to_properties.get(type_name) is not None:
for property in block_name_to_properties[type_name]:
self.add_triple(subj_text=memid, pred_text="has_name", obj_text=property)
def _load_mob_types(self, load_mob_types=True):
if not load_mob_types:
return
mob_property_data = minecraft_specs.get_mob_property_data()
mob_name_to_properties = mob_property_data["name_to_properties"]
for (name, m) in SPAWN_OBJECTS.items():
type_name = "spawn " + name
# load single mob as schematics
memid = SchematicNode.create(self, [((0, 0, 0), (383, m))])
self.add_triple(subj=memid, pred_text="has_name", obj_text=type_name)
if "block" in type_name:
self.add_triple(
subj=memid, pred_text="has_name", obj_text=type_name.strip("block").strip()
)
# then load properties
memid = MobTypeNode.create(self, type_name, (383, m))
self.add_triple(subj=memid, pred_text="has_name", obj_text=type_name)
if mob_name_to_properties.get(type_name) is not None:
for property in mob_name_to_properties[type_name]:
self.add_triple(subj=memid, pred_text="has_name", obj_text=property)
##############
### Mobs ###
##############
def set_mob_position(self, mob) -> "MobNode":
r = self._db_read_one("SELECT uuid FROM ReferenceObjects WHERE eid=?", mob.entityId)
if r:
self._db_write(
"UPDATE ReferenceObjects SET x=?, y=?, z=?, yaw=?, pitch=? WHERE eid=?",
mob.pos.x,
mob.pos.y,
mob.pos.z,
mob.look.yaw,
mob.look.pitch,
mob.entityId,
)
(memid,) = r
else:
memid = MobNode.create(self, mob)
return self.get_mem_by_id(memid)
####################
### ItemStacks ###
####################
def update_item_stack_eid(self, memid, eid) -> "ItemStackNode":
r = self._db_read_one("SELECT * FROM ReferenceObjects WHERE uuid=?", memid)
if r:
self._db_write("UPDATE ReferenceObjects SET eid=? WHERE uuid=?", eid, memid)
return self.get_mem_by_id(memid)
def set_item_stack_position(self, item_stack) -> "ItemStackNode":
r = self._db_read_one("SELECT uuid FROM ReferenceObjects WHERE eid=?", item_stack.entityId)
if r:
self._db_write(
"UPDATE ReferenceObjects SET x=?, y=?, z=? WHERE eid=?",
item_stack.pos.x,
item_stack.pos.y,
item_stack.pos.z,
item_stack.entityId,
)
(memid,) = r
else:
memid = ItemStackNode.create(self, item_stack)
return self.get_mem_by_id(memid)
def get_all_item_stacks(self):
r = self._db_read("SELECT uuid, eid FROM ReferenceObjects WHERE ref_type=?", "item_stack")
return r
###############
### Dances ##
###############
def add_dance(self, dance_fn, name=None, tags=[]):
# a dance is movement determined as a sequence of steps, rather than by its destination
return DanceNode.create(self, dance_fn, name=name, tags=tags)
| craftassist-master | python/craftassist/mc_memory.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import heapq
import math
import numpy as np
from scipy.ndimage.filters import median_filter
from scipy.optimize import linprog
import logging
import minecraft_specs
from mc_util import (
manhat_dist,
get_locs_from_entity,
build_safe_diag_adjacent,
euclid_dist,
to_block_pos,
fill_idmeta,
)
from block_data import BORING_BLOCKS, PASSABLE_BLOCKS
from search import depth_first_search
from mc_memory_nodes import InstSegNode, BlockObjectNode
GROUND_BLOCKS = [1, 2, 3, 7, 8, 9, 12, 79, 80]
MAX_RADIUS = 20
BLOCK_DATA = minecraft_specs.get_block_data()
COLOUR_DATA = minecraft_specs.get_colour_data()
BLOCK_PROPERTY_DATA = minecraft_specs.get_block_property_data()
MOB_PROPERTY_DATA = minecraft_specs.get_mob_property_data()
BID_COLOR_DATA = minecraft_specs.get_bid_to_colours()
# Taken from : stackoverflow.com/questions/16750618/
# whats-an-efficient-way-to-find-if-a-point-lies-in-the-convex-hull-of-a-point-cl
def in_hull(points, x):
"""Check if x is in the convex hull of points"""
n_points = len(points)
c = np.zeros(n_points)
A = np.r_[points.T, np.ones((1, n_points))]
b = np.r_[x, np.ones(1)]
lp = linprog(c, A_eq=A, b_eq=b)
return lp.success
def all_nearby_objects(get_blocks, pos, max_radius=MAX_RADIUS):
"""Return a list of connected components near pos.
Each component is a list of ((x, y, z), (id, meta))
i.e. this function returns list[list[((x, y, z), (id, meta))]]
"""
pos = np.round(pos).astype("int32")
mask, off, blocks = all_close_interesting_blocks(get_blocks, pos, max_radius)
components = connected_components(mask)
logging.debug("all_nearby_objects found {} objects near {}".format(len(components), pos))
xyzbms = [
[((c[2] + off[2], c[0] + off[0], c[1] + off[1]), tuple(blocks[c])) for c in component_yzxs]
for component_yzxs in components
]
return xyzbms
def closest_nearby_object(get_blocks, pos):
"""Find the closest interesting object to pos
Returns a list of ((x,y,z), (id, meta)), or None if no interesting objects are nearby
"""
objects = all_nearby_objects(get_blocks, pos)
if len(objects) == 0:
return None
centroids = [np.mean([pos for (pos, idm) in obj], axis=0) for obj in objects]
dists = [manhat_dist(c, pos) for c in centroids]
return objects[np.argmin(dists)]
def all_close_interesting_blocks(get_blocks, pos, max_radius=MAX_RADIUS):
"""Find all "interesting" blocks close to pos, within a max_radius"""
mx, my, mz = pos[0] - max_radius, pos[1] - max_radius, pos[2] - max_radius
Mx, My, Mz = pos[0] + max_radius, pos[1] + max_radius, pos[2] + max_radius
yzxb = get_blocks(mx, Mx, my, My, mz, Mz)
relpos = pos - [mx, my, mz]
mask = accessible_interesting_blocks(yzxb[:, :, :, 0], relpos)
return mask, (my, mz, mx), yzxb
def accessible_interesting_blocks(blocks, pos):
"""Return a boolean mask of blocks that are accessible-interesting from pos.
A block b is accessible-interesting if it is
1. interesting, AND
2. there exists a path from pos to b through only passable or interesting blocks
"""
passable = np.isin(blocks, PASSABLE_BLOCKS)
interesting = np.isin(blocks, BORING_BLOCKS, invert=True)
passable_or_interesting = passable | interesting
X = np.zeros_like(passable)
def _fn(p):
if passable_or_interesting[p]:
X[p] = True
return True
return False
depth_first_search(blocks.shape[:3], pos, _fn)
return X & interesting
def find_closest_component(mask, relpos):
"""Find the connected component of nonzeros that is closest to loc
Args:
- mask is a 3d array
- relpos is a relative position in the mask, with the same ordering
Returns: a list of indices of the closest connected component, or None
"""
components = connected_components(mask)
if len(components) == 0:
return None
centroids = [np.mean(cs, axis=0) for cs in components]
dists = [manhat_dist(c, relpos) for c in centroids]
return components[np.argmin(dists)]
def connected_components(X, unique_idm=False):
"""Find all connected nonzero components in a array X.
X is either rank 3 (volume) or rank 4 (volume-idm)
If unique_idm == True, different block types are different
components
Returns a list of lists of indices of connected components
"""
visited = np.zeros((X.shape[0], X.shape[1], X.shape[2]), dtype="bool")
components = []
current_component = set()
diag_adj = build_safe_diag_adjacent([0, X.shape[0], 0, X.shape[1], 0, X.shape[2]])
if len(X.shape) == 3:
X = np.expand_dims(X, axis=3)
def is_air(X, i, j, k):
return X[i, j, k, 0] == 0
if not unique_idm:
def _build_fn(X, current_component, idm):
def _fn(p):
if X[p[0], p[1], p[2], 0]:
current_component.add(p)
return True
return _fn
else:
def _build_fn(X, current_component, idm):
def _fn(p):
if tuple(X[p]) == idm:
current_component.add(p)
return True
return _fn
for i in range(visited.shape[0]):
for j in range(visited.shape[1]):
for k in range(visited.shape[2]):
if visited[i, j, k]:
continue
visited[i, j, k] = True
if is_air(X, i, j, k):
continue
# found a new component
pos = (i, j, k)
_fn = _build_fn(X, current_component, tuple(X[i, j, k, :]))
visited |= depth_first_search(X.shape[:3], pos, _fn, diag_adj)
components.append(list(current_component))
current_component.clear()
return components
def check_between(entities, fat_scale=0.2):
""" Heuristic check if entities[0] is between entities[1] and entities[2]
by checking if the locs of enitity[0] are in the convex hull of
union of the max cardinal points of entity[1] and entity[2]"""
locs = []
means = []
for e in entities:
l = get_locs_from_entity(e)
if l is not None:
locs.append(l)
means.append(np.mean(l, axis=0))
else:
# this is not a thing we know how to assign 'between' to
return False
mean_separation = euclid_dist(means[1], means[2])
fat = fat_scale * mean_separation
bounding_locs = []
for l in locs:
if len(l) > 1:
bl = []
idx = np.argmax(l, axis=0)
for i in range(3):
f = np.zeros(3)
f[i] = fat
bl.append(np.array(l[idx[i]]) + fat)
idx = np.argmin(l, axis=0)
for i in range(3):
f = np.zeros(3)
f[i] = fat
bl.append(np.array(l[idx[i]]) - fat)
bounding_locs.append(np.vstack(bl))
else:
bounding_locs.append(np.array(l))
x = np.mean(bounding_locs[0], axis=0)
points = np.vstack([bounding_locs[1], bounding_locs[2]])
return in_hull(points, x)
def find_between(entities):
"""Heurisitc search for points between entities[0] and entities[1]
for now : just pick the point half way between their means
TODO: fuzz a bit if target is unreachable"""
for e in entities:
means = []
l = get_locs_from_entity(e)
if l is not None:
means.append(np.mean(l, axis=0))
else:
# this is not a thing we know how to assign 'between' to
return None
return (means[0] + means[1]) / 2
def check_inside(entities):
"""Heuristic check on whether an entity[0] is inside entity[1]
if in some 2d slice, cardinal rays cast from some point in
entity[0] all hit a block in entity[1], we say entity[0] is inside
entity[1]. This allows an entity to be inside a ring or
an open cylinder. This will fail for a "diagonal" ring.
TODO: "enclosed", where the object is inside in the topological sense"""
locs = []
for e in entities:
l = get_locs_from_entity(e)
if l is not None:
locs.append(l)
else:
# this is not a thing we know how to assign 'inside' to
return False
for b in locs[0]:
for i in range(3):
inside = True
coplanar = [c for c in locs[1] if c[i] == b[i]]
for j in range(2):
fixed = (i + 2 * j - 1) % 3
to_check = (i + 1 - 2 * j) % 3
colin = [c[to_check] for c in coplanar if c[fixed] == b[fixed]]
if len(colin) == 0:
inside = False
else:
if max(colin) <= b[to_check] or min(colin) >= b[to_check]:
inside = False
if inside:
return True
return False
def find_inside(entity):
"""Return a point inside the entity if it can find one.
TODO: heuristic quick check to find that there aren't any,
and maybe make this not d^3"""
# is this a negative object? if yes, just return its mean:
if hasattr(entity, "blocks"):
if all(b == (0, 0) for b in entity.blocks.values()):
m = np.mean(list(entity.blocks.keys()), axis=0)
return [to_block_pos(m)]
l = get_locs_from_entity(entity)
if l is None:
return []
m = np.round(np.mean(l, axis=0))
maxes = np.max(l, axis=0)
mins = np.min(l, axis=0)
inside = []
for x in range(mins[0], maxes[0] + 1):
for y in range(mins[1], maxes[1] + 1):
for z in range(mins[2], maxes[2] + 1):
if check_inside([(x, y, z), entity]):
inside.append((x, y, z))
return sorted(inside, key=lambda x: euclid_dist(x, m))
def label_top_bottom_blocks(block_list, top_heuristic=15, bottom_heuristic=25):
""" This function takes in a list of blocks, where each block is :
[[x, y, z], id] or [[x, y, z], [id, meta]]
and outputs a dict:
{
"top" : [list of blocks],
"bottom" : [list of blocks],
"neither" : [list of blocks]
}
The heuristic being used here is : The top blocks are within top_heuristic %
of the topmost block and the bottom blocks are within bottom_heuristic %
of the bottommost block.
Every other block in the list belongs to the category : "neither"
"""
if type(block_list) is tuple:
block_list = list(block_list)
# Sort the list on z, y, x in decreasing order, to order the list
# to top-down.
block_list.sort(key=lambda x: (x[0][2], x[0][1], x[0][0]), reverse=True)
num_blocks = len(block_list)
cnt_top = math.ceil((top_heuristic / 100) * num_blocks)
cnt_bottom = math.ceil((bottom_heuristic / 100) * num_blocks)
cnt_remaining = num_blocks - (cnt_top + cnt_bottom)
dict_top_bottom = {}
dict_top_bottom["top"] = block_list[:cnt_top]
dict_top_bottom["bottom"] = block_list[-cnt_bottom:]
dict_top_bottom["neither"] = block_list[cnt_top : cnt_top + cnt_remaining]
return dict_top_bottom
# heuristic method, can potentially be replaced with ml? can def make more sophisticated
# looks for the first stack of non-ground material hfilt high, can be fooled
# by e.g. a floating pile of dirt or a big buried object
def ground_height(agent, pos, radius, yfilt=5, xzfilt=5):
ground = np.array(GROUND_BLOCKS).astype("int32")
offset = yfilt // 2
yfilt = np.ones(yfilt, dtype="int32")
L = agent.get_blocks(
pos[0] - radius, pos[0] + radius, 0, pos[1] + 80, pos[2] - radius, pos[2] + radius
)
C = L.copy()
C = C[:, :, :, 0].transpose([2, 0, 1]).copy()
G = np.zeros((2 * radius + 1, 2 * radius + 1))
for i in range(C.shape[0]):
for j in range(C.shape[2]):
stack = C[i, :, j].squeeze()
inground = np.isin(stack, ground) * 1
inground = np.convolve(inground, yfilt, mode="same")
G[i, j] = np.argmax(inground == 0) # fixme what if there isn't one
G = median_filter(G, size=xzfilt)
return G - offset
def get_nearby_airtouching_blocks(agent, location, radius=15):
gh = ground_height(agent, location, 0)[0, 0]
x, y, z = location
ymin = int(max(y - radius, gh))
yzxb = agent.get_blocks(x - radius, x + radius, ymin, y + radius, z - radius, z + radius)
xyzb = yzxb.transpose([2, 0, 1, 3]).copy()
components = connected_components(xyzb, unique_idm=True)
blocktypes = []
for c in components:
tags = None
for loc in c:
idm = tuple(xyzb[loc[0], loc[1], loc[2], :])
for coord in range(3):
for d in [-1, 1]:
off = [0, 0, 0]
off[coord] = d
l = (loc[0] + off[0], loc[1] + off[1], loc[2] + off[2])
if l[coord] >= 0 and l[coord] < xyzb.shape[coord]:
if xyzb[l[0], l[1], l[2], 0] == 0:
try:
blocktypes.append(idm)
type_name = BLOCK_DATA["bid_to_name"][idm]
tags = [type_name]
tags.extend(COLOUR_DATA["name_to_colors"].get(type_name, []))
tags.extend(
BLOCK_PROPERTY_DATA["name_to_properties"].get(type_name, [])
)
except:
logging.debug(
"I see a weird block, ignoring: ({}, {})".format(
idm[0], idm[1]
)
)
if tags:
shifted_c = [(l[0] + x - radius, l[1] + ymin, l[2] + z - radius) for l in c]
if len(shifted_c) > 0:
InstSegNode.create(agent.memory, shifted_c, tags=tags)
return blocktypes
def get_all_nearby_holes(agent, location, radius=15, store_inst_seg=True):
"""Return a list of holes. Each hole is tuple(list[xyz], idm)"""
sx, sy, sz = location
max_height = sy + 5
map_size = radius * 2 + 1
height_map = [[sz] * map_size for i in range(map_size)]
hid_map = [[-1] * map_size for i in range(map_size)]
idm_map = [[(0, 0)] * map_size for i in range(map_size)]
visited = set([])
global current_connected_comp, current_idm
current_connected_comp = []
current_idm = (2, 0)
# helper functions
def get_block_info(x, z): # fudge factor 5
height = max_height
while True:
B = agent.get_blocks(x, x, height, height, z, z)
if (
(B[0, 0, 0, 0] != 0)
and (x != sx or z != sz or height != sy)
and (x != agent.pos[0] or z != agent.pos[2] or height != agent.pos[1])
and (B[0, 0, 0, 0] != 383)
): # if it's not a mobile block (agent, speaker, mobs)
return height, tuple(B[0, 0, 0])
height -= 1
gx = [0, 0, -1, 1]
gz = [1, -1, 0, 0]
def dfs(x, y, z):
""" Traverse current connected component and return minimum
height of all surrounding blocks """
build_height = 100000
if (x, y, z) in visited:
return build_height
global current_connected_comp, current_idm
current_connected_comp.append((x - radius + sx, y, z - radius + sz)) # absolute positions
visited.add((x, y, z))
for d in range(4):
nx = x + gx[d]
nz = z + gz[d]
if nx >= 0 and nz >= 0 and nx < map_size and nz < map_size:
if height_map[x][z] == height_map[nx][nz]:
build_height = min(build_height, dfs(nx, y, nz))
else:
build_height = min(build_height, height_map[nx][nz])
current_idm = idm_map[nx][nz]
else:
# bad ... hole is not within defined radius
return -100000
return build_height
# find all holes
blocks_queue = []
for i in range(map_size):
for j in range(map_size):
height_map[i][j], idm_map[i][j] = get_block_info(i - radius + sx, j - radius + sz)
heapq.heappush(blocks_queue, (height_map[i][j] + 1, (i, height_map[i][j] + 1, j)))
holes = []
while len(blocks_queue) > 0:
hxyz = heapq.heappop(blocks_queue)
h, (x, y, z) = hxyz # NB: relative positions
if (x, y, z) in visited or y > max_height:
continue
assert h == height_map[x][z] + 1, " h=%d heightmap=%d, x,z=%d,%d" % (
h,
height_map[x][z],
x,
z,
) # sanity check
current_connected_comp = []
current_idm = (2, 0)
build_height = dfs(x, y, z)
if build_height >= h:
holes.append((current_connected_comp.copy(), current_idm))
cur_hid = len(holes) - 1
for n, xyz in enumerate(current_connected_comp):
x, y, z = xyz
rx, ry, rz = x - sx + radius, y + 1, z - sz + radius
heapq.heappush(blocks_queue, (ry, (rx, ry, rz)))
height_map[rx][rz] += 1
if hid_map[rx][rz] != -1:
holes[cur_hid][0].extend(holes[hid_map[rx][rz]][0])
holes[hid_map[rx][rz]] = ([], (0, 0))
hid_map[rx][rz] = cur_hid
# A bug in the algorithm above produces holes that include non-air blocks.
# Just patch the problem here, since this function will eventually be
# performed by an ML model
for i, (xyzs, idm) in enumerate(holes):
blocks = fill_idmeta(agent, xyzs)
xyzs = [xyz for xyz, (d, _) in blocks if d == 0] # remove non-air blocks
holes[i] = (xyzs, idm)
# remove 0-length holes
holes = [h for h in holes if len(h[0]) > 0]
if store_inst_seg:
for hole in holes:
InstSegNode.create(agent.memory, hole[0], tags=["hole", "pit", "mine"])
return holes
class PerceptionWrapper:
def __init__(self, agent, perceive_freq=20, slow_perceive_freq_mult=8):
self.perceive_freq = perceive_freq
self.agent = agent
self.radius = 15
self.perceive_freq = perceive_freq
def perceive(self, force=False):
if self.perceive_freq == 0 and not force:
return
if self.agent.count % self.perceive_freq != 0 and not force:
return
if force or not self.agent.memory.task_stack_peek():
# perceive blocks in marked areas
for pos, radius in self.agent.areas_to_perceive:
for obj in all_nearby_objects(self.agent.get_blocks, pos, radius):
BlockObjectNode.create(self.agent.memory, obj)
get_all_nearby_holes(self.agent, pos, radius)
get_nearby_airtouching_blocks(self.agent, pos, radius)
# perceive blocks near the agent
for obj in all_nearby_objects(self.agent.get_blocks, self.agent.pos):
BlockObjectNode.create(self.agent.memory, obj)
get_all_nearby_holes(self.agent, self.agent.pos, radius=self.radius)
get_nearby_airtouching_blocks(self.agent, self.agent.pos, radius=self.radius)
| craftassist-master | python/craftassist/heuristic_perception.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from preprocess import word_tokenize
from ttad.generation_dialogues.generate_dialogue import action_type_map # Dict[str, Class]
from ttad.generation_dialogues.templates.templates import template_map # Dict[str, List[Template]]
from typing import Dict, List, Tuple, Sequence
def adtt(d: Dict) -> str:
"""Return a string that would produce the action dict `d`
d is post-process_span (i.e. its span values are replaced with strings)
d is pre-coref_resolve (i.e. its coref_resolve values are strings, not
memory objects or keywords)
"""
if d["dialogue_type"] != "HUMAN_GIVE_COMMAND":
raise NotImplementedError("can't handle {}".format(d["dialogue_type"]))
action_type = d["action"]["action_type"] # e.g. "MOVE"
action_type = action_type[0].upper() + action_type[1:].lower() # e.g. "Move"
for template in template_map[action_type]:
dialogue, gen_d = generate_from_template(action_type, template)
recurse_remove_keys(gen_d, ["has_attribute"])
if len(dialogue) != 1:
continue
if dicts_match(d, gen_d):
print(gen_d)
text = replace_spans(dialogue[0], gen_d, d)
print(dialogue[0])
return replace_relative_direction(text, gen_d, d)
raise ValueError("No matching template found for {}".format(d))
def replace_spans(text: str, gen_d: Dict, d: Dict) -> str:
"""Replace words in text with spans from d"""
words = word_tokenize(text).split()
# compile list of spans to replace via recursive search
replaces = []
to_consider = [(gen_d, d)]
while len(to_consider) > 0:
cur_gen_d, cur_d = to_consider.pop()
for k in cur_gen_d.keys():
if type(cur_d[k]) == dict:
to_consider.append((cur_gen_d[k], cur_d[k]))
elif type(cur_d[k]) == str and cur_d[k].upper() != cur_d[k]:
replaces.append((cur_gen_d[k], cur_d[k]))
# replace each span in words
replaces.sort(key=lambda r: r[0][1][0], reverse=True) # sort by L of span
for (sentence_idx, (L, R)), s in replaces:
assert sentence_idx == 0
words = words[:L] + word_tokenize(s).split() + words[(R + 1) :]
return " ".join(words)
def generate_from_template(action_type: str, template: List) -> Tuple[List[str], Dict]:
cls = action_type_map[action_type.lower()]
node = cls.generate(template)
dialogue = node.generate_description()
d = node.to_dict()
return dialogue, d
def dicts_match(
d: Dict,
e: Dict,
ignore_values_for_keys: Sequence[str] = ["relative_direction"],
ignore_keys: Sequence[str] = ["has_attribute"],
) -> bool:
if (set(d.keys()) - set(ignore_keys)) != (set(e.keys()) - set(ignore_keys)):
return False
for k, v in d.items():
if type(v) == dict and not dicts_match(v, e[k]):
return False
# allow values of certain keys to differ (e.g. relative_direction)
# allow spans (lowercase strings) to differ
if (
k not in ignore_keys
and k not in ignore_values_for_keys
and type(v) == str
and v == v.upper()
and v != e[k]
):
return False
return True
def recurse_remove_keys(d: Dict, keys: Sequence[str]):
# remove keys from dict
for x in keys:
if x in d:
del d[x]
# recurse
for k, v in d.items():
if type(v) == dict:
recurse_remove_keys(v, keys)
def replace_relative_direction(text: str, gen_d: Dict, d: Dict) -> str:
try:
rel_dir = d["action"]["location"]["relative_direction"]
agent_pos = False
try:
if (
d["action"]["location"]["reference_object"]["location"]["location_type"]
== "AGENT_POS"
):
agent_pos = True
except:
agent_pos = False
# generate direction dict
direction_dict = {}
if not agent_pos:
direction_dict["LEFT"] = ["to the left of", "towards the left of"]
direction_dict["RIGHT"] = ["to the right of", "towards the right of"]
direction_dict["UP"] = ["above", "on top of", "to the top of"]
direction_dict["DOWN"] = ["below", "under"]
direction_dict["FRONT"] = ["in front of"]
direction_dict["BACK"] = ["behind"]
direction_dict["AWAY"] = ["away from"]
direction_dict["INSIDE"] = ["inside"]
direction_dict["OUTSIDE"] = ["outside"]
direction_dict["NEAR"] = ["next to", "close to", "near"]
direction_dict["CLOCKWISE"] = ["clockwise"]
direction_dict["ANTICLOCKWISE"] = ["anticlockwise"]
else:
direction_dict["LEFT"] = ["to the left", "to your left", "east", "left"]
direction_dict["RIGHT"] = ["to the right", "to your right", "right", "west"]
direction_dict["UP"] = ["up", "north"]
direction_dict["DOWN"] = ["down", "south"]
direction_dict["FRONT"] = ["front", "forward", "to the front"]
direction_dict["BACK"] = ["back", "backwards", "to the back"]
direction_dict["AWAY"] = ["away"]
direction_dict["CLOCKWISE"] = ["clockwise"]
direction_dict["ANTICLOCKWISE"] = ["anticlockwise"]
# generate a list of the direction phrases and sort by longest to shortest
direction_list: List[str] = []
for k in direction_dict.keys():
direction_list = direction_list + direction_dict[k]
direction_list = sorted(direction_list, key=len, reverse=True)
# look for direction phrase in the text to replace
for dir_phrase in direction_list:
if dir_phrase in text:
text = text.replace(dir_phrase, direction_dict[rel_dir][0])
break
return text
except:
return text
if __name__ == "__main__":
d = {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action": {
"action_type": "BUILD",
"schematic": {"has_name": "barn"},
"location": {
"location_type": "REFERENCE_OBJECT",
"relative_direction": "LEFT",
"reference_object": {"has_name": "boat house"},
},
},
}
t = adtt(d)
print(t)
| craftassist-master | python/craftassist/adtt.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from base_sql_mock_environment import BaseSQLMockEnvironment
from typing import Dict
class SQLConverter(BaseSQLMockEnvironment):
"""A script with basic commands dealing with reference objects.
"""
def __init__(self):
super().__init__()
self.all_sql_queries = []
def run(self, action_dict):
self.agent.memory.sql_queries = []
self.convert_sql_query(action_dict)
self.all_sql_queries.append(self.agent.memory.sql_queries)
print(self.all_sql_queries)
def convert_sql_query(self, action_dict: Dict):
"""
Get SQL commands for an action dictionary.
"""
print(action_dict)
self.handle_logical_form(action_dict)
def process_input_dataset(self):
"""
Read annotated dataset and get action dictionaries.
"""
action_dict = {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action": {
"action_type": "DESTROY",
"reference_object": {
"has_name": "sphere",
"has_colour": "red",
"has_size": "small",
},
},
}
self.run(action_dict)
def main():
sql_converter = SQLConverter()
sql_converter.process_input_dataset()
if __name__ == "__main__":
main()
| craftassist-master | python/craftassist/sql_script.py |
import os
import sys
import numpy as np
import logging
from collections import Counter
from typing import cast, List, Sequence, Dict
# FIXME fix util imports
from mc_util import XYZ, LOOK, POINT_AT_TARGET, IDM, Block
import minecraft_specs
from entities import MOBS_BY_ID
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.memory_nodes import link_archive_to_mem, ReferenceObjectNode, MemoryNode, NODELIST
class VoxelObjectNode(ReferenceObjectNode):
"""this is a reference object that is distributed over
multiple voxels. uses VoxelObjects table to hold the
location of the voxels; and ReferenceObjects to hold 'global' info"""
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
ref = self.agent_memory._db_read("SELECT * FROM ReferenceObjects WHERE uuid=?", self.memid)
if len(ref) == 0:
raise Exception("no mention of this VoxelObject in ReferenceObjects Table")
self.ref_info = ref[0]
voxels = self.agent_memory._db_read("SELECT * FROM VoxelObjects WHERE uuid=?", self.memid)
self.locs: List[tuple] = []
self.blocks: Dict[tuple, tuple] = {}
self.update_times: Dict[tuple, int] = {}
self.player_placed: Dict[tuple, bool] = {}
self.agent_placed: Dict[tuple, bool] = {}
for v in voxels:
loc = (v[1], v[2], v[3])
self.locs.append(loc)
if v[4]:
assert v[5] is not None
self.blocks[loc] = (v[4], v[5])
else:
self.blocks[loc] = (None, None)
self.agent_placed[loc] = v[6]
self.player_placed[loc] = v[7]
self.update_times[loc] = v[8]
# TODO assert these all the same?
self.memtype = v[9]
def get_pos(self) -> XYZ:
return cast(XYZ, tuple(int(x) for x in np.mean(self.locs, axis=0)))
def get_point_at_target(self) -> POINT_AT_TARGET:
point_min = [int(x) for x in np.min(self.locs, axis=0)]
point_max = [int(x) for x in np.max(self.locs, axis=0)]
return cast(POINT_AT_TARGET, point_min + point_max)
def get_bounds(self):
M = np.max(self.locs, axis=0)
m = np.min(self.locs, axis=0)
return m[0], M[0], m[1], M[1], m[2], M[2]
def snapshot(self, agent_memory):
archive_memid = self.new(agent_memory, snapshot=True)
for loc in self.locs:
cmd = "INSERT INTO ArchivedVoxelObjects (uuid, x, y, z, bid, meta, agent_placed, player_placed, updated, ref_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
values = (
archive_memid,
loc[0],
loc[1],
loc[2],
self.blocks[loc][0],
self.blocks[loc][1],
self.agent_placed[loc],
self.player_placed[loc],
self.update_times[loc],
self.memtype,
)
agent_memory._db_write(cmd, *values)
archive_memid = self.new(agent_memory, snapshot=True)
cmd = "INSERT INTO ArchivedReferenceObjects (uuid, eid, x, y, z, yaw, pitch, name, type_name, ref_type, player_placed, agent_placed, created, updated, voxel_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
info = list(self.ref_info)
info[0] = archive_memid
agent_memory._db_write(cmd, *info)
link_archive_to_mem(agent_memory, self.memid, archive_memid)
return archive_memid
class BlockObjectNode(VoxelObjectNode):
""" this is a voxel object that represents a set of physically present blocks.
it is considered to be nonephemeral"""
TABLE_COLUMNS = [
"uuid",
"x",
"y",
"z",
"bid",
"meta",
"agent_placed",
"player_placed",
"updated",
]
TABLE = "ReferenceObjects"
NODE_TYPE = "BlockObject"
@classmethod
def create(cls, memory, blocks: Sequence[Block]) -> str:
# check if block object already exists in memory
for xyz, _ in blocks:
old_memids = memory.get_block_object_ids_by_xyz(xyz)
if old_memids:
return old_memids[0]
memid = cls.new(memory)
# TODO check/assert this isn't there...
cmd = "INSERT INTO ReferenceObjects (uuid, x, y, z, ref_type, voxel_count) VALUES ( ?, ?, ?, ?, ?, ?)"
# TODO this is going to cause a bug, need better way to initialize and track mean loc
memory._db_write(cmd, memid, 0, 0, 0, "BlockObjects", 0)
for block in blocks:
memory.upsert_block(block, memid, "BlockObjects")
memory.tag(memid, "_block_object")
memory.tag(memid, "_voxel_object")
memory.tag(memid, "_physical_object")
memory.tag(memid, "_destructible")
# this is a hack until memory_filters does "not"
memory.tag(memid, "_not_location")
logging.info(
"Added block object {} with {} blocks, {}".format(
memid, len(blocks), Counter([idm for _, idm in blocks])
)
)
return memid
def __repr__(self):
return "<BlockObject Node @ {}>".format(list(self.blocks.keys())[0])
# note: instance segmentation objects should not be tagged except by the creator
# build an archive if you want to tag permanently
class InstSegNode(VoxelObjectNode):
""" this is a voxel object that represents a region of space, and is considered ephemeral"""
TABLE_COLUMNS = ["uuid", "x", "y", "z", "ref_type"]
TABLE = "ReferenceObjects"
NODE_TYPE = "InstSeg"
@classmethod
def create(cls, memory, locs, tags=[]) -> str:
# TODO option to not overwrite
# check if instance segmentation object already exists in memory
inst_memids = {}
for xyz in locs:
m = memory._db_read(
'SELECT uuid from VoxelObjects WHERE ref_type="inst_seg" AND x=? AND y=? AND z=?',
*xyz
)
if len(m) > 0:
for memid in m:
inst_memids[memid[0]] = True
# FIXME just remember the locs in the first pass
for m in inst_memids.keys():
olocs = memory._db_read("SELECT x, y, z from VoxelObjects WHERE uuid=?", m)
# TODO maybe make an archive?
if len(set(olocs) - set(locs)) == 0:
memory._db_write("DELETE FROM Memories WHERE uuid=?", m)
memid = cls.new(memory)
loc = np.mean(locs, axis=0)
# TODO check/assert this isn't there...
cmd = "INSERT INTO ReferenceObjects (uuid, x, y, z, ref_type) VALUES ( ?, ?, ?, ?, ?)"
memory._db_write(cmd, memid, loc[0], loc[1], loc[2], "inst_seg")
for loc in locs:
cmd = "INSERT INTO VoxelObjects (uuid, x, y, z, ref_type) VALUES ( ?, ?, ?, ?, ?)"
memory._db_write(cmd, memid, loc[0], loc[1], loc[2], "inst_seg")
memory.tag(memid, "_voxel_object")
memory.tag(memid, "_inst_seg")
memory.tag(memid, "_destructible")
# this is a hack until memory_filters does "not"
memory.tag(memid, "_not_location")
for tag in tags:
memory.tag(memid, tag)
return memid
def __init__(self, memory, memid: str):
super().__init__(memory, memid)
r = memory._db_read("SELECT x, y, z FROM VoxelObjects WHERE uuid=?", self.memid)
self.locs = r
self.blocks = {l: (0, 0) for l in self.locs}
tags = memory.get_triples(subj=self.memid, pred_text="has_tag")
self.tags = [] # noqa: T484
for tag in tags:
if tag[2][0] != "_":
self.tags.append(tag[2])
def __repr__(self):
return "<InstSeg Node @ {} with tags {} >".format(self.locs, self.tags)
class MobNode(ReferenceObjectNode):
""" a memory node represneting a mob"""
TABLE_COLUMNS = [
"uuid",
"eid",
"x",
"y",
"z",
"yaw",
"pitch",
"ref_type",
"type_name",
"player_placed",
"agent_placed",
"created",
]
TABLE = "ReferenceObjects"
NODE_TYPE = "Mob"
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
eid, x, y, z, yaw, pitch = self.agent_memory._db_read_one(
"SELECT eid, x, y, z, yaw, pitch FROM ReferenceObjects WHERE uuid=?", self.memid
)
self.eid = eid
self.pos = (x, y, z)
self.look = (yaw, pitch)
@classmethod
def create(cls, memory, mob, player_placed=False, agent_placed=False) -> str:
# TODO warn/error if mob already in memory?
memid = cls.new(memory)
mobtype = MOBS_BY_ID[mob.mobType]
memory._db_write(
"INSERT INTO ReferenceObjects(uuid, eid, x, y, z, yaw, pitch, ref_type, type_name, player_placed, agent_placed, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
memid,
mob.entityId,
mob.pos.x,
mob.pos.y,
mob.pos.z,
mob.look.yaw,
mob.look.pitch,
"mob",
mobtype,
player_placed,
agent_placed,
memory.get_time(),
)
memory.tag(memid, "mob")
memory.tag(memid, "_physical_object")
memory.tag(memid, "_animate")
# this is a hack until memory_filters does "not"
memory.tag(memid, "_not_location")
memory.tag(memid, mobtype)
return memid
def get_pos(self) -> XYZ:
x, y, z = self.agent_memory._db_read_one(
"SELECT x, y, z FROM ReferenceObjects WHERE uuid=?", self.memid
)
self.pos = (x, y, z)
return self.pos
def get_look(self) -> LOOK:
yaw, pitch = self.agent_memory._db_read_one(
"SELECT yaw, pitch FROM ReferenceObjects WHERE uuid=?", self.memid
)
self.look = (yaw, pitch)
return self.look
# TODO: use a smarter way to get point_at_target
def get_point_at_target(self) -> POINT_AT_TARGET:
x, y, z = self.agent_memory._db_read_one(
"SELECT x, y, z FROM ReferenceObjects WHERE uuid=?", self.memid
)
# use the block above the mob as point_at_target
return cast(POINT_AT_TARGET, (x, y + 1, z, x, y + 1, z))
def get_bounds(self):
x, y, z = self.pos
return x, x, y, y, z, z
class ItemStackNode(ReferenceObjectNode):
TABLE_ROWS = ["uuid", "eid", "x", "y", "z", "type_name", "ref_type", "created"]
TABLE = "ReferenceObjects"
NODE_TYPE = "ItemStack"
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
eid, x, y, z = self.agent_memory._db_read_one(
"SELECT eid, x, y, z FROM ReferenceObjects WHERE uuid=?", self.memid
)
self.memid = memid
self.eid = eid
self.pos = (x, y, z)
@classmethod
def create(cls, memory, item_stack) -> str:
bid_to_name = minecraft_specs.get_block_data()["bid_to_name"]
type_name = bid_to_name[(item_stack.item.id, item_stack.item.meta)]
memid = cls.new(memory)
memory._db_write(
"INSERT INTO ReferenceObjects(uuid, eid, x, y, z, type_name, ref_type, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
memid,
item_stack.entityId,
item_stack.pos.x,
item_stack.pos.y,
item_stack.pos.z,
type_name,
"item_stack",
memory.get_time(),
)
memory.tag(memid, type_name)
memory.tag(memid, "_item_stack")
memory.tag(memid, "_on_ground")
memory.tag(memid, "_physical_object")
# this is a hack until memory_filters does "not"
memory.tag(memid, "_not_location")
return memid
def get_pos(self) -> XYZ:
x, y, z = self.agent_memory._db_read_one(
"SELECT x, y, z FROM ReferenceObjects WHERE uuid=?", self.memid
)
self.pos = (x, y, z)
return self.pos
# TODO: use a smarter way to get point_at_target
def get_point_at_target(self) -> POINT_AT_TARGET:
x, y, z = self.agent_memory._db_read_one(
"SELECT x, y, z FROM ReferenceObjects WHERE uuid=?", self.memid
)
# use the block above the item stack as point_at_target
return cast(POINT_AT_TARGET, (x, y + 1, z, x, y + 1, z))
def get_bounds(self):
x, y, z = self.pos
return x, x, y, y, z, z
class SchematicNode(MemoryNode):
""" a memory node representing a plan for an object that could be built"""
TABLE_COLUMNS = ["uuid", "x", "y", "z", "bid", "meta"]
TABLE = "Schematics"
NODE_TYPE = "Schematic"
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
r = self.agent_memory._db_read(
"SELECT x, y, z, bid, meta FROM Schematics WHERE uuid=?", self.memid
)
self.blocks = {(x, y, z): (b, m) for (x, y, z, b, m) in r}
@classmethod
def create(cls, memory, blocks: Sequence[Block]) -> str:
memid = cls.new(memory)
for ((x, y, z), (b, m)) in blocks:
memory._db_write(
"""
INSERT INTO Schematics(uuid, x, y, z, bid, meta)
VALUES (?, ?, ?, ?, ?, ?)""",
memid,
x,
y,
z,
b,
m,
)
return memid
class BlockTypeNode(MemoryNode):
TABLE_COLUMNS = ["uuid", "type_name", "bid", "meta"]
TABLE = "BlockTypes"
NODE_TYPE = "BlockType"
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
type_name, b, m = self.agent_memory._db_read(
"SELECT type_name, bid, meta FROM BlockTypes WHERE uuid=?", self.memid
)
self.type_name = type_name
self.b = b
self.m = m
@classmethod
def create(cls, memory, type_name: str, idm: IDM) -> str:
memid = cls.new(memory)
memory._db_write(
"INSERT INTO BlockTypes(uuid, type_name, bid, meta) VALUES (?, ?, ?, ?)",
memid,
type_name,
idm[0],
idm[1],
)
return memid
class MobTypeNode(MemoryNode):
TABLE_COLUMNS = ["uuid", "type_name", "bid", "meta"]
TABLE = "MobTypes"
NODE_TYPE = "MobType"
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
type_name, b, m = self.agent_memory._db_read(
"SELECT type_name, bid, meta FROM MobTypes WHERE uuid=?", self.memid
)
self.type_name = type_name
self.b = b
self.m = m
@classmethod
def create(cls, memory, type_name: str, idm: IDM) -> str:
memid = cls.new(memory)
memory._db_write(
"INSERT INTO MobTypes(uuid, type_name, bid, meta) VALUES (?, ?, ?, ?)",
memid,
type_name,
idm[0],
idm[1],
)
return memid
class DanceNode(MemoryNode):
TABLE_COLUMNS = ["uuid"]
TABLE = "Dances"
NODE_TYPE = "Dance"
def __init__(self, agent_memory, memid: str):
super().__init__(agent_memory, memid)
# TODO put in DB/pickle like tasks?
self.dance_fn = self.agent_memory[memid]
@classmethod
def create(cls, memory, dance_fn, name=None, tags=[]) -> str:
memid = cls.new(memory)
memory._db_write("INSERT INTO Dances(uuid) VALUES (?)", memid)
# TODO put in db via pickle like tasks?
memory.dances[memid] = dance_fn
if name is not None:
memory.add_triple(subj=memid, pred_text="has_name", obj_text=name)
if len(tags) > 0:
for tag in tags:
memory.add_triple(subj=memid, pred_text="has_tag", obj_text=tag)
return memid
class RewardNode(MemoryNode):
TABLE_COLUMNS = ["uuid", "value", "time"]
TABLE = "Rewards"
NODE_TYPE = "Reward"
def __init__(self, agent_memory, memid: str):
_, value, timestamp = agent_memory._db_read_one(
"SELECT * FROM Rewards WHERE uuid=?", memid
)
self.value = value
self.time = timestamp
@classmethod
def create(cls, agent_memory, reward_value: str) -> str:
memid = cls.new(agent_memory)
agent_memory._db_write(
"INSERT INTO Rewards(uuid, value, time) VALUES (?,?,?)",
memid,
reward_value,
agent_memory.get_time(),
)
return memid
NODELIST = NODELIST + [
RewardNode,
DanceNode,
BlockTypeNode,
SchematicNode,
MobNode,
ItemStackNode,
MobTypeNode,
InstSegNode,
BlockObjectNode,
] # noqa
| craftassist-master | python/craftassist/mc_memory_nodes.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import csv
import numpy as np
SHAPENET_PATH = "" # add path to shapenet csv here
def read_shapenet_csv(csvpath=SHAPENET_PATH + "metadata.csv"):
keyword_to_id = {}
id_to_keyword = {}
with open(csvpath, "r") as cfile:
cvs_metadata = csv.reader(cfile)
next(cvs_metadata)
for l in cvs_metadata:
bin_id = l[0][4:]
keywords = l[3].split(",")
if keywords[0] == "":
continue
id_to_keyword[bin_id] = keywords
for k in keywords:
if keyword_to_id.get(k) is None:
keyword_to_id[k] = []
else:
keyword_to_id[k].append(bin_id)
return keyword_to_id, id_to_keyword
def to_relative_pos(block_list):
"""Convert absolute block positions to their relative positions
Find the "origin", i.e. the minimum (x, y, z), and subtract this from all
block positions.
Args:
- block_list: a list of ((x,y,z), (id, meta))
Returns:
- a block list where positions are shifted by `origin`
- `origin`, the (x, y, z) offset by which the positions were shifted
"""
try:
locs, idms = zip(*block_list)
except ValueError:
raise ValueError("to_relative_pos invalid input: {}".format(block_list))
locs = np.array([loc for (loc, idm) in block_list])
origin = np.min(locs, axis=0)
locs -= origin
S = [(tuple(loc), idm) for (loc, idm) in zip(locs, idms)]
if type(block_list) is not list:
S = tuple(S)
if type(block_list) is frozenset:
S = frozenset(S)
return S, origin
def blocks_list_to_npy(blocks, xyz=False):
"""Convert a list of blockid meta (x, y, z), (id, meta) to numpy"""
xyzbm = np.array([(x, y, z, b, m) for ((x, y, z), (b, m)) in blocks])
mx, my, mz = np.min(xyzbm[:, :3], axis=0)
Mx, My, Mz = np.max(xyzbm[:, :3], axis=0)
npy = np.zeros((My - my + 1, Mz - mz + 1, Mx - mx + 1, 2), dtype="int32")
for x, y, z, b, m in xyzbm:
npy[y - my, z - mz, x - mx] = (b, m)
offsets = (my, mz, mx)
if xyz:
npy = np.swapaxes(np.swapaxes(npy, 1, 2), 0, 1)
offsets = (mx, my, mz)
return npy, offsets
def npy_to_blocks_list(npy, origin=(0, 0, 0)):
"""Convert a numpy array to block list ((x, y, z), (id, meta))"""
blocks = []
sy, sz, sx, _ = npy.shape
for ry in range(sy):
for rz in range(sz):
for rx in range(sx):
idm = tuple(npy[ry, rz, rx, :])
if idm[0] == 0:
continue
xyz = tuple(np.array([rx, ry, rz]) + origin)
blocks.append((xyz, idm))
return blocks
def blocks_list_add_offset(blocks, origin):
"""Offset all blocks in block list by a constant xyz
Args:
blocks: a list[(xyz, idm)]
origin: xyz
Returns list[(xyz, idm)]
"""
ox, oy, oz = origin
return [((x + ox, y + oy, z + oz), idm) for ((x, y, z), idm) in blocks]
| craftassist-master | python/craftassist/build_utils.py |
import logging
import socket
import json
import os
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 2557 # The port used by the server
dirname = os.path.dirname(__file__)
web_app_filename = os.path.join(dirname, "webapp_data.json")
# create a socket
s = socket.socket()
print("web app socket: created")
# s.bind(('', PORT)) specifies that the socket is reachable by any
# address the machine happens to have.
s.bind(("", PORT))
# become a server socket and queue as many as 5 requests before
# refusing connections
s.listen(5)
def convert(dictionary):
"""Recursively converts dictionary keys to strings."""
if not isinstance(dictionary, dict):
return dictionary
return dict((str(k), convert(v)) for k, v in dictionary.items())
while True:
conn, addr = s.accept()
print("web app socket: got connection from ", addr)
# receive bytes and decode to string
msgrec = conn.recv(10000).decode()
print("web app socket: received ", msgrec)
# here add hooks to decide what to do with the data / message
# 1. query dialogue_manager /
# read the file to return action dict
try:
with open(web_app_filename) as f:
data = json.load(f)
print(data)
try:
data = convert(data)
except Exception as e:
print(e)
print("sending")
print(data[msgrec])
if msgrec in data:
conn.send((json.dumps(data[msgrec])).encode())
else:
# send back empty data if not message not found
conn.send((str({})).encode())
except:
conn.send((str({})).encode())
logging.info("web app socket: closing")
conn.close()
| craftassist-master | python/craftassist/web_app_socket.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import heapq
import logging
import numpy as np
import time
from block_data import PASSABLE_BLOCKS
from mc_util import adjacent, manhat_dist
def depth_first_search(blocks_shape, pos, fn, adj_fn=adjacent):
"""Do depth-first search on array with blocks_shape starting
from pos
Calls fn(p) on each index `p` in DFS-order. If fn returns True,
continue searching. If False, do not add adjacent blocks.
Args:
- blocks_shape: a tuple giving the shape of the blocks
- pos: a relative position in blocks
- fn: a function called on each position in DFS-order. Return
True to continue searching from that node
- adj_fn: a function (pos) -> list[pos], of adjacent positions
Returns: visited, a bool array with blocks.shape
"""
visited = np.zeros(blocks_shape, dtype="bool")
q = [tuple(pos)]
visited[tuple(pos)] = True
i = 0
while i < len(q):
p = q.pop()
if fn(p):
for a in adj_fn(p):
try:
if not visited[a]:
visited[a] = True
q.append(a)
except IndexError:
pass
return visited
def astar(agent, target, approx=0, pos="agent"):
"""Find a path from the agent's pos to the target.
Args:
- agent: the Agent object
- target: an absolute (x, y, z)
- approx: proximity to target before search is complete (0 = exact)
- pos: (optional) checks path from specified tuple
Returns: a list of (x, y, z) positions from start to target
"""
t_start = time.time()
if type(pos) is str and pos == "agent":
pos = agent.pos
logging.debug("A* from {} -> {} ± {}".format(pos, target, approx))
corners = np.array([pos, target]).astype("int32")
mx, my, mz = corners.min(axis=0) - 10
Mx, My, Mz = corners.max(axis=0) + 10
my, My = max(my, 0), min(My, 255)
blocks = agent.get_blocks(mx, Mx, my, My, mz, Mz)
obstacles = np.isin(blocks[:, :, :, 0], PASSABLE_BLOCKS, invert=True)
obstacles = obstacles[:-1, :, :] | obstacles[1:, :, :] # check head and feet
start, goal = (corners - [mx, my, mz])[:, [1, 2, 0]]
path = _astar(obstacles, start, goal, approx)
if path is not None:
path = [(p[2] + mx, p[0] + my, p[1] + mz) for p in reversed(path)]
t_elapsed = time.time() - t_start
logging.debug("A* returned {}-len path in {}".format(len(path) if path else "None", t_elapsed))
return path
def _astar(X, start, goal, approx=0):
"""Find a path through X from start to goal.
Args:
- X: a 3d array of obstacles, i.e. False -> passable, True -> not passable
- start/goal: relative positions in X
- approx: proximity to goal before search is complete (0 = exact)
Returns: a list of relative positions, from start to goal
"""
start = tuple(start)
goal = tuple(goal)
visited = set()
came_from = {}
q = PriorityQueue()
q.push(start, manhat_dist(start, goal))
G = np.full_like(X, np.iinfo(np.uint32).max, "uint32")
G[start] = 0
while len(q) > 0:
_, p = q.pop()
if manhat_dist(p, goal) <= approx:
path = []
while p in came_from:
path.append(p)
p = came_from[p]
return [start] + list(reversed(path))
visited.add(p)
for a in adjacent(p):
if (
a in visited
or a[0] < 0
or a[0] >= X.shape[0]
or a[1] < 0
or a[1] >= X.shape[1]
or a[2] < 0
or a[2] >= X.shape[2]
or X[a]
):
continue
g = G[p] + 1
if g >= G[a]:
continue
came_from[a] = p
G[a] = g
f = g + manhat_dist(a, goal)
if q.contains(a):
q.replace(a, f)
else:
q.push(a, f)
return None
class PriorityQueue:
def __init__(self):
self.q = []
self.set = set()
def push(self, x, prio):
heapq.heappush(self.q, (prio, x))
self.set.add(x)
def pop(self):
prio, x = heapq.heappop(self.q)
self.set.remove(x)
return prio, x
def contains(self, x):
return x in self.set
def replace(self, x, newp):
for i in range(len(self.q)):
oldp, y = self.q[i]
if x == y:
self.q[i] = (newp, x)
heapq.heapify(self.q) # TODO: probably slow
return
raise ValueError("Not found: {}".format(x))
def __len__(self):
return len(self.q)
if __name__ == "__main__":
X = np.ones((5, 5, 5), dtype="bool")
X[3, :, :] = [
[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
start = (3, 4, 0)
goal = (3, 1, 0)
print(astar(X, start, goal))
| craftassist-master | python/craftassist/search.py |
import numpy as np
from collections import Counter
from build_utils import blocks_list_to_npy # , npy_to_blocks_list
##############################################
# WARNING: all npy arrays in this file are xyz
# not yzx
def maybe_convert_to_npy(blocks):
if type(blocks) is list:
blocks, _ = blocks_list_to_npy(blocks, xyz=True)
return blocks
else:
assert blocks.shape[-1] == 2
assert len(blocks.shape) == 4
return blocks.copy()
def maybe_convert_to_list(blocks):
if type(blocks) is list:
return blocks.copy()
else:
nz = np.transpose(blocks[:, :, :, 0].nonzero())
return [(tuple(loc), tuple(blocks[tuple(loc)])) for loc in nz]
def flint(x):
return int(np.floor(x))
def ceint(x):
return int(np.ceil(x))
def check_boundary(p, m, M):
if (
p[0] == m[0]
or p[0] == M[0] - 1
or p[1] == m[1]
or p[1] == M[1] - 1
or p[2] == m[2]
or p[2] == M[2] - 1
):
return True
else:
return False
def reshift(shape):
m = np.min([l[0] for l in shape], axis=0)
return [((b[0][0] - m[0], b[0][1] - m[1], b[0][2] - m[2]), b[1]) for b in shape]
def moment_at_center(npy, sl):
"""
shifts the object in the 4d numpy array so that the center of mass is at sl//2
in a sl x sl x sl x 2 array
warning, this will cut anything that is too big to fit in sl x sl x sl
and then the moment might not actually be in center.
"""
nz = np.transpose(npy[:, :, :, 0].nonzero())
mins = np.min(nz, axis=0)
shifted_nz = nz - mins
com = np.floor(np.array(shifted_nz.mean(axis=0)))
# this will fail if com is bigger than sl.
assert all(com < sl)
npy_out_center = np.array((sl // 2, sl // 2, sl // 2))
shifted_nz = (shifted_nz - com + npy_out_center).astype("int32")
npy_out = np.zeros((sl, sl, sl, 2), dtype="int32")
for i in range(nz.shape[0]):
if all(shifted_nz[i] >= 0) and all(shifted_nz[i] - sl < 0):
npy_out[tuple(shifted_nz[i])] = npy[tuple(nz[i])]
return npy_out
#############################################
## THICKEN
#############################################
# this doesn't preserve corners. should it?
# separate deltas per dim?
def thicker_blocks(blocks, delta=1):
newblocks = {l: idm for (l, idm) in blocks}
for b in blocks:
for dx in range(-delta, delta + 1):
for dy in range(-delta, delta + 1):
for dz in range(-delta, delta + 1):
l = b[0]
newblocks[(l[0] + dx, l[1] + dy, l[2] + dz)] = b[1]
return list(newblocks.items())
def thicker(blocks, delta=1):
blocks = maybe_convert_to_list(blocks)
newblocks = thicker_blocks(blocks, delta=delta)
npy, _ = blocks_list_to_npy(newblocks, xyz=True)
return npy
#############################################
## SCALE
#############################################
def get_loc_weight(idx, cell_size):
""" compute the scaled indices and amount in 1d they
extend on either side of the block boundary
"""
left = idx * cell_size
right = (idx + 1) * cell_size
lidx = int(np.floor(left))
ridx = int(np.floor(right))
if ridx > lidx:
right_weight = right - ridx
left_weight = ridx - left
else:
right_weight = 0
left_weight = 1
return (lidx, ridx), (left_weight, right_weight)
def get_cell_weights(idxs, cell_szs):
""" compute the amount of the cell in each of
the 8 cubes it might touch """
index = []
dw = []
for k in range(3):
i, w = get_loc_weight(idxs[k], cell_szs[k])
index.append(i)
dw.append(w)
cell_weights = np.zeros((2, 2, 2))
best_cell = None
big_weight = 0.0
total_weight = 0.0
for i in range(2):
for j in range(2):
for k in range(2):
w = dw[0][i] * dw[1][j] * dw[2][k]
cell_weights[i, j, k] = w
total_weight += w
if w > big_weight:
big_weight = w
best_cell = (index[0][i], index[1][j], index[2][k])
cell_weights = cell_weights / total_weight
return best_cell, index, cell_weights
def scale(blocks, lams=(1.0, 1.0, 1.0)):
""" scales the blockobject in the ith direction with factor lams[i]
algorithm is to first scale the blocks up (so each minecraft cube has
size lams), and then for each 1x1x1 block arranged in place assign it
the id, meta of the big block it most intersects
"""
assert lams[0] >= 1.0 # eventually FIXME?
assert lams[1] >= 1.0 # eventually FIXME?
assert lams[2] >= 1.0 # eventually FIXME?
inp = maybe_convert_to_npy(blocks)
szs = np.array(inp.shape[:3])
big_szs = np.ceil(szs * lams)
cell_szs = szs / big_szs
big_szs = big_szs.astype("int32")
big = np.zeros(tuple(big_szs) + (2,)).astype("int32")
for i in range(big_szs[0]):
for j in range(big_szs[1]):
for k in range(big_szs[2]):
best_cell, _, _ = get_cell_weights((i, j, k), cell_szs)
big[i, j, k, :] = inp[best_cell]
return big
def scale_sparse(blocks, lams=(1.0, 1.0, 1.0)):
""" scales the blockobject in the ith direction with factor lams[i]
algorithm is to first scale the blocks up (so each minecraft cube has
size lams), and then for each 1x1x1 block arranged in place assign it
the id, meta of the big block it most intersects
"""
assert lams[0] >= 1.0 # eventually FIXME?
assert lams[1] >= 1.0 # eventually FIXME?
assert lams[2] >= 1.0 # eventually FIXME?
inp = maybe_convert_to_list(blocks)
locs = [l for (l, idm) in inp]
m = np.min(locs, axis=0)
inp_dict = {(l[0] - m[0], l[1] - m[1], l[2] - m[2]): idm for (l, idm) in inp}
szs = np.max(locs, axis=0) - np.min(locs, axis=0) + 1
big_szs = np.ceil(szs * lams)
cell_szs = szs / big_szs
big_szs = big_szs.astype("int32")
big = np.zeros(tuple(big_szs) + (2,)).astype("int32")
for (x, y, z) in inp_dict.keys():
for i in range(flint(x * lams[0]), ceint(x * lams[0]) + 2):
for j in range(flint(y * lams[1]), ceint(y * lams[1]) + 2):
for k in range(flint(z * lams[2]), ceint(z * lams[2]) + 2):
if i < big_szs[0] and j < big_szs[1] and k < big_szs[2]:
best_cell, _, _ = get_cell_weights((i, j, k), cell_szs)
idm = inp_dict.get(best_cell)
if idm:
big[i, j, k, :] = idm
else:
big[i, j, k, :] = (0, 0)
return big
def shrink_sample(blocks, lams):
assert lams[0] <= 1.0
assert lams[1] <= 1.0
assert lams[2] <= 1.0
blocks = maybe_convert_to_npy(blocks)
szs = blocks.shape
xs = np.floor(np.arange(0, szs[0], 1 / lams[0])).astype("int32")
ys = np.floor(np.arange(0, szs[1], 1 / lams[1])).astype("int32")
zs = np.floor(np.arange(0, szs[2], 1 / lams[2])).astype("int32")
small = np.zeros((len(xs), len(ys), len(zs), 2), dtype="int32")
for i in range(len(xs)):
for j in range(len(ys)):
for k in range(len(zs)):
small[i, j, k] = blocks[xs[i], ys[j], zs[k]]
return small
#############################################
## ROTATE
#############################################
def rotate(blocks, angle=0, mirror=-1, plane="xz"):
inp = maybe_convert_to_npy(blocks)
if mirror > 0:
inp = np.flip(inp, mirror)
# maybe generalize?
assert angle % 90 == 0
i = angle // 90
if i < 0:
i = i % 4
if plane == "xz" or plane == "zx":
return np.rot90(inp, i, axes=(0, 2))
elif plane == "xy" or plane == "yx":
return np.rot90(inp, i, axes=(0, 1))
else:
return np.rot90(inp, i, axes=(1, 2))
#############################################
## REPLACE
#############################################
def hash_idm(npy):
return npy[:, :, :, 0] + 1000 * npy[:, :, :, 1]
def unhash_idm(npy):
npy = npy.astype("int32")
b = npy % 1000
m = (npy - b) // 1000
return np.stack((b, m), axis=3)
# TODO current_idm should be a list
def replace_by_blocktype(blocks, new_idm=(0, 0), current_idm=None, every_n=1, replace_every=False):
"""replace some blocks with a different kind
note that it is allowed that new_idm is (0,0)
"""
if current_idm is not None: # specifying a transformation of one blocktype to another
blocks = maybe_convert_to_npy(blocks)
h = hash_idm(blocks)
u = h.copy()
old_idm_hash = current_idm[0] + 1000 * current_idm[1]
new_idm_hash = new_idm[0] + 1000 * new_idm[1]
u[u == old_idm_hash] = new_idm_hash
out = unhash_idm(u)
else: # TODO FIXME need better algorithm here
if every_n == 1 and not replace_every:
lblocks = maybe_convert_to_list(blocks)
mode = Counter([idm for loc, idm in lblocks]).most_common(1)[0][0]
for b in lblocks:
if b[1] == mode:
b[1] = new_idm
return maybe_convert_to_npy(lblocks)
blocks = maybe_convert_to_npy(blocks)
out = blocks.copy()
if type(every_n) is int:
every_n = (every_n, every_n, every_n)
nzmask = blocks[:, :, :, 0] > 0
every_n_mask = nzmask.copy()
every_n_mask[:] = False
every_n_mask[:: every_n[0], :: every_n[0], :: every_n[0]] = True
mask = np.logical_and(every_n_mask, nzmask)
out_b = out[:, :, :, 0]
out_b[mask] = new_idm[0]
out_m = out[:, :, :, 1]
out_m[mask] = new_idm[1]
return out
def replace_by_halfspace(blocks, new_idm=(0, 0), geometry=None, replace_every=False):
"""replace some blocks with a different kind, chosen by
block at (i,j,k) is changed if
geometry['v']@((i,j,k) - geometry['offset']) > geometry['threshold']
note that it is allowed that new_idm is (0, 0)
"""
if not replace_every:
lblocks = maybe_convert_to_list(blocks)
mode = Counter([idm for loc, idm in lblocks]).most_common(1)[0][0]
else:
mode = None
blocks = maybe_convert_to_npy(blocks)
if not geometry:
geometry = {"v": np.ndarray((0, 1, 0)), "threshold": 0, "offset": blocks.shape // 2}
out = blocks.copy()
szs = blocks.shape
for i in range(szs[0]):
for j in range(szs[1]):
for k in range(szs[2]):
if blocks[i, j, k, 0] > 0:
if (np.array((i, j, k)) - geometry["offset"]) @ geometry["v"] > geometry[
"threshold"
]:
if replace_every or tuple(out[i, j, k, :]) == mode:
out[i, j, k, :] = new_idm
return out
#############################################
## FILL
#############################################
def maybe_update_extreme_loc(extremes, loc, axis):
""" given a non-air index loc into a block list, updates
a list of max and min values along axis at projections
given by the non-axis entries in loc
"""
other_indices = list(range(3))[:axis] + list(range(3))[axis + 1 :]
loc_in = (loc[other_indices[0]], loc[other_indices[1]])
loc_out = loc[axis]
current = extremes.get(loc_in)
if current is None:
extremes[loc_in] = (loc_out, loc_out)
else:
small, big = current
if loc_out < small:
small = loc_out
if loc_out > big:
big = loc_out
extremes[loc_in] = (small, big)
def get_index_from_proj(proj, proj_axes, i):
""" returns a tuple that can be used to index the rank-3 npy array
from the proj coords, proj_axes, and coordinate in the remaining dimension
"""
index = [0, 0, 0]
index[proj_axes[0]] = proj[0]
index[proj_axes[1]] = proj[1]
index[(set([0, 1, 2]) - set(proj_axes)).pop()] = i
return tuple(index)
def maybe_fill_line(old_npy, new_npy, proj, extremes, proj_axes, fill_material=None):
"""fill the line from starting from extremes[0] to extremes[1].
proj_axes is the gives the axes of the non-extreme coordinates
proj gives the coordinates in the proj_axes coordinates
if the extremes are different block types changes in the middle
"""
if (
extremes[0] < extremes[1] + 1
): # else no need to fill- extremes are the same block or touching
old_small = old_npy[get_index_from_proj(proj, proj_axes, extremes[0])]
old_big = old_npy[get_index_from_proj(proj, proj_axes, extremes[1])]
med = (extremes[1] + extremes[0]) // 2
for i in range(extremes[0], med + 1):
new_npy[get_index_from_proj(proj, proj_axes, i)] = old_small
for i in range(med + 1, extremes[1]):
new_npy[get_index_from_proj(proj, proj_axes, i)] = old_big
# TODO specify a slice or direction
def fill_flat(blocks, fill_material=None):
""" attempts to fill areas in a shape. basic algorithm: if two blocks in the shape
are connected by an x, y, or z only line, fills that line
"""
blocks = maybe_convert_to_npy(blocks)
szs = blocks.shape
# find the max and min in each plane
# this is kind of buggy, should instead find inner edge of most outer connected component...
# instead of plain extremes
xz_extremes = {}
yz_extremes = {}
xy_extremes = {}
for i in range(szs[0]):
for j in range(szs[1]):
for k in range(szs[2]):
if blocks[i, j, k, 0] > 0:
maybe_update_extreme_loc(xz_extremes, (i, j, k), 1)
maybe_update_extreme_loc(yz_extremes, (i, j, k), 0)
maybe_update_extreme_loc(xy_extremes, (i, j, k), 2)
old = blocks.copy()
# fill in the between blocks:
for proj, extremes in xz_extremes.items():
maybe_fill_line(old, blocks, proj, extremes, (0, 2), fill_material=fill_material)
for proj, extremes in yz_extremes.items():
maybe_fill_line(old, blocks, proj, extremes, (1, 2), fill_material=fill_material)
for proj, extremes in xy_extremes.items():
maybe_fill_line(old, blocks, proj, extremes, (0, 1), fill_material=fill_material)
return blocks
# fixme deal with 2D
def hollow(blocks):
# this is not the inverse of fill
filled_blocks = fill_flat(blocks)
schematic = filled_blocks.copy()
schematic[:] = 0
szs = filled_blocks.shape
for i in range(szs[0]):
for j in range(szs[1]):
for k in range(szs[2]):
idm = filled_blocks[i, j, k]
if check_boundary((i, j, k), (0, 0, 0), szs) and idm[0] != 0:
schematic[i, j, k] = idm
continue
airtouching = False
for r in [-1, 0, 1]:
for s in [-1, 0, 1]:
for t in [-1, 0, 1]:
if filled_blocks[i + r, j + s, k + t, 0] == 0:
airtouching = True
if airtouching and idm[0] != 0:
schematic[i, j, k] = idm
return schematic
if __name__ == "__main__":
import torch
import visdom
from shapes import *
from voxel_models.plot_voxels import SchematicPlotter
vis = visdom.Visdom(server="http://localhost")
sp = SchematicPlotter(vis)
b = hollow_triangle(size=5, thickness=1)
# b = hollow_rectangle(size = (10,7),thickness = 2)
a = torch.LongTensor(15, 15)
a.zero_()
for i in b:
a[i[0][0], i[0][1]] = 1
print(a)
c = reshift(thicker(b))
a.zero_()
for i in c:
a[i[0][0], i[0][1]] = 1
print(a)
b = hollow_cube(size=5, thickness=1)
Z = scale(b, (1.0, 1.5, 1.7))
| craftassist-master | python/craftassist/shape_transforms.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""This file has Minecraft entities"""
# TODO: pull from cuberite source?
# Map of mob id to mob name
MOBS_BY_ID = {
50: "creeper",
51: "skeleton",
52: "spider",
53: "giant",
54: "zombie",
55: "slime",
56: "ghast",
57: "pig zombie",
58: "enderman",
59: "cave spider",
60: "silverfish",
61: "blaze",
62: "lava slime",
63: "ender dragon",
64: "wither boss",
65: "bat",
66: "witch",
68: "guardian",
90: "pig",
91: "sheep",
92: "cow",
93: "chicken",
94: "squid",
95: "wolf",
96: "mushroom cow",
97: "snow man",
98: "ozelot",
99: "villager golem",
100: "entity horse",
101: "rabbit",
120: "villager",
}
| craftassist-master | python/craftassist/entities.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""This file has helper functions for shapes.py"""
import random
import numpy as np
import shapes
FORCE_SMALL = 10 # for debug
# Map shape name to function in shapes.py
SHAPE_FNS = {
"CUBE": shapes.cube,
"HOLLOW_CUBE": shapes.hollow_cube,
"RECTANGULOID": shapes.rectanguloid,
"HOLLOW_RECTANGULOID": shapes.hollow_rectanguloid,
"SPHERE": shapes.sphere,
"SPHERICAL_SHELL": shapes.spherical_shell,
"PYRAMID": shapes.square_pyramid,
"SQUARE": shapes.square,
"RECTANGLE": shapes.rectangle,
"CIRCLE": shapes.circle,
"DISK": shapes.disk,
"TRIANGLE": shapes.triangle,
"DOME": shapes.dome,
"ARCH": shapes.arch,
"ELLIPSOID": shapes.ellipsoid,
"HOLLOW_TRIANGLE": shapes.hollow_triangle,
"HOLLOW_RECTANGLE": shapes.hollow_rectangle,
"RECTANGULOID_FRAME": shapes.rectanguloid_frame,
}
# list of shape names
SHAPE_NAMES = [
"CUBE",
"HOLLOW_CUBE",
"RECTANGULOID",
"HOLLOW_RECTANGULOID",
"SPHERE",
"SPHERICAL_SHELL",
"PYRAMID",
"SQUARE",
"RECTANGLE",
"CIRCLE",
"DISK",
"TRIANGLE",
"DOME",
"ARCH",
"ELLIPSOID",
"HOLLOW_TRIANGLE",
"HOLLOW_RECTANGLE",
"RECTANGULOID_FRAME",
]
def bid():
allowed_blocks = {}
allowed_blocks[1] = list(range(7))
allowed_blocks[4] = [0]
allowed_blocks[5] = list(range(6))
allowed_blocks[12] = list(range(2))
allowed_blocks[17] = list(range(4))
allowed_blocks[18] = list(range(4))
allowed_blocks[20] = [0]
allowed_blocks[22] = [0]
allowed_blocks[24] = list(range(3))
allowed_blocks[34] = [0]
allowed_blocks[35] = list(range(16))
allowed_blocks[41] = [0]
allowed_blocks[42] = [0]
allowed_blocks[43] = list(range(8))
allowed_blocks[45] = [0]
allowed_blocks[48] = [0]
allowed_blocks[49] = [0]
allowed_blocks[57] = [0]
allowed_blocks[95] = list(range(16))
allowed_blocks[133] = [0]
allowed_blocks[155] = list(range(3))
allowed_blocks[159] = list(range(16))
allowed_blocks[169] = [0]
b = random.choice(list(allowed_blocks))
m = random.choice(allowed_blocks[b])
return (b, m)
def bernoulli(p=0.5):
return np.random.rand() > p
def slope(ranges=10):
return np.random.randint(1, ranges)
def sizes1(ranges=(1, 15)):
ranges = list(ranges)
ranges[1] = min(ranges[1], FORCE_SMALL)
return np.random.randint(ranges[0], ranges[1])
def sizes2(ranges=(15, 15)):
ranges = list(ranges)
for i in range(2):
ranges[i] = min(ranges[i], FORCE_SMALL)
return (np.random.randint(1, ranges[0]), np.random.randint(1, ranges[1]))
def sizes3(ranges=(15, 15, 15)):
ranges = list(ranges)
for i in range(3):
ranges[i] = min(ranges[i], FORCE_SMALL)
return (
np.random.randint(1, ranges[0]),
np.random.randint(1, ranges[1]),
np.random.randint(1, ranges[2]),
)
def orientation2():
return random.choice(["xy", "yz"])
def orientation3():
return random.choice(["xy", "yz", "xz"])
def options_rectangle():
return {"size": sizes2(), "orient": orientation3()}
def options_square():
return {"size": sizes1(), "orient": orientation3()}
def options_triangle():
return {"size": sizes1(), "orient": orientation3()}
def options_circle():
return {"radius": sizes1(), "orient": orientation3()}
def options_disk():
return {"radius": sizes1(), "orient": orientation3()}
def options_cube():
return {"size": sizes1(ranges=(1, 8))}
def options_hollow_cube():
return {"size": sizes1()}
def options_rectanguloid():
return {"size": sizes3(ranges=(8, 8, 8))}
def options_hollow_rectanguloid():
return {"size": sizes3()}
def options_sphere():
return {"radius": sizes1(ranges=(3, 5))}
def options_spherical_shell():
return {"radius": sizes1()}
def options_square_pyramid():
return {"slope": slope(), "radius": sizes1()}
def options_tower():
return {"height": sizes1(ranges=(1, 20)), "base": sizes1(ranges=(-3, 4))}
def options_ellipsoid():
return {"size": sizes3()}
def options_dome():
return {"radius": sizes1()}
def options_arch():
return {"size": sizes1(), "distance": 2 * sizes1(ranges=(2, 5)) + 1}
def options_hollow_triangle():
return {"size": sizes1() + 1, "orient": orientation3()}
def options_hollow_rectangle():
return {"size": sizes1() + 1, "orient": orientation3()}
def options_rectanguloid_frame():
return {"size": sizes3(), "only_corners": bernoulli()}
def shape_to_dicts(S):
blocks = [
{"x": s[0][0], "y": s[0][1], "z": s[0][2], "id": s[1][0], "meta": s[1][1]} for s in S
]
return blocks
def build_shape_scene():
offset_range = (14, 0, 14)
num_shapes = 5
blocks = []
block_xyz_set = set()
for t in range(num_shapes):
offsets = [0, 63, 0]
for i in range(3):
offsets[i] += np.random.randint(-offset_range[i], offset_range[i] + 1)
shape = random.choice(SHAPE_NAMES)
opts = SHAPE_HELPERS[shape]()
opts["bid"] = bid()
S = SHAPE_FNS[shape](**opts)
S = [
(
(x[0][0] + offsets[0], x[0][1] + offsets[1], x[0][2] + offsets[2]),
(x[1][0], x[1][1]),
)
for x in S
]
s = set([x[0] for x in S])
if not set.intersection(s, block_xyz_set):
block_xyz_set = set.union(block_xyz_set, s)
blocks.extend(shape_to_dicts(S))
return blocks
# Map shape name to option function
SHAPE_HELPERS = {
"CUBE": options_cube,
"HOLLOW_CUBE": options_hollow_cube,
"RECTANGULOID": options_rectanguloid,
"HOLLOW_RECTANGULOID": options_hollow_rectanguloid,
"SPHERE": options_sphere,
"SPHERICAL_SHELL": options_spherical_shell,
"PYRAMID": options_square_pyramid,
"SQUARE": options_square,
"RECTANGLE": options_rectangle,
"CIRCLE": options_circle,
"DISK": options_disk,
"TRIANGLE": options_triangle,
"DOME": options_dome,
"ARCH": options_arch,
"ELLIPSOID": options_ellipsoid,
"HOLLOW_TRIANGLE": options_hollow_triangle,
"HOLLOW_RECTANGLE": options_hollow_rectangle,
"RECTANGULOID_FRAME": options_rectanguloid_frame,
}
| craftassist-master | python/craftassist/shape_helpers.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import copy
import os
import sys
from math import sin, cos, pi
from typing import cast, Sequence
BASE_AGENT_ROOT = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(BASE_AGENT_ROOT)
from base_agent.base_util import *
import rotation
TICKS_PER_MC_DAY = 24000
LOOK = Tuple[float, float]
class MCTime(Time):
def __init__(self, get_world_time):
super().__init__()
self.get_world_time = get_world_time
def get_world_hour(self):
# returns a fraction of a day. 0 is sunrise, .5 is sunset, 1.0 is next day
return self.get_world_time() / TICKS_PER_MC_DAY
def adjacent(p):
"""Return the positions adjacent to position p"""
return (
(p[0] + 1, p[1], p[2]),
(p[0] - 1, p[1], p[2]),
(p[0], p[1] + 1, p[2]),
(p[0], p[1] - 1, p[2]),
(p[0], p[1], p[2] + 1),
(p[0], p[1], p[2] - 1),
)
def build_safe_diag_adjacent(bounds):
""" bounds is [mx, Mx, my, My, mz, Mz],
if nothing satisfies, returns empty list """
def a(p):
"""Return the adjacent positions to p including diagonal adjaceny, within the bounds"""
mx = max(bounds[0], p[0] - 1)
my = max(bounds[2], p[1] - 1)
mz = max(bounds[4], p[2] - 1)
Mx = min(bounds[1] - 1, p[0] + 1)
My = min(bounds[3] - 1, p[1] + 1)
Mz = min(bounds[5] - 1, p[2] + 1)
return [
(x, y, z)
for x in range(mx, Mx + 1)
for y in range(my, My + 1)
for z in range(mz, Mz + 1)
if (x, y, z) != p
]
return a
def capped_line_of_sight(agent, player_struct, cap=20):
"""Return the block directly in the entity's line of sight, or a point in the distance"""
xsect = agent.get_player_line_of_sight(player_struct)
if xsect is not None and euclid_dist(pos_to_np(xsect), pos_to_np(player_struct.pos)) <= cap:
return pos_to_np(xsect)
# default to cap blocks in front of entity
vec = rotation.look_vec(player_struct.look.yaw, player_struct.look.pitch)
return cap * np.array(vec) + to_block_pos(pos_to_np(player_struct.pos))
def cluster_areas(areas):
"""Cluster a list of areas so that intersected ones are unioned
areas: list of tuple ((x, y, z), radius), each defines a cube
where (x, y, z) is the center and radius is half the side length
"""
def expand_xyzs(pos, radius):
xmin, ymin, zmin = pos[0] - radius, pos[1] - radius, pos[2] - radius
xmax, ymax, zmax = pos[0] + radius, pos[1] + radius, pos[2] + radius
return xmin, xmax, ymin, ymax, zmin, zmax
def is_intersecting(area1, area2):
x1_min, x1_max, y1_min, y1_max, z1_min, z1_max = expand_xyzs(area1[0], area1[1])
x2_min, x2_max, y2_min, y2_max, z2_min, z2_max = expand_xyzs(area2[0], area2[1])
return (
(x1_min <= x2_max and x1_max >= x2_min)
and (y1_min <= y2_max and y1_max >= y2_min)
and (z1_min <= z2_max and z1_max >= z2_min)
)
def merge_area(area1, area2):
x1_min, x1_max, y1_min, y1_max, z1_min, z1_max = expand_xyzs(area1[0], area1[1])
x2_min, x2_max, y2_min, y2_max, z2_min, z2_max = expand_xyzs(area2[0], area2[1])
x_min, y_min, z_min = min(x1_min, x2_min), min(y1_min, y2_min), min(z1_min, z2_min)
x_max, y_max, z_max = max(x1_max, x2_max), max(y1_max, y2_max), max(z1_max, z2_max)
x, y, z = (x_min + x_max) // 2, (y_min + y_max) // 2, (z_min + z_max) // 2
radius = max(
(x_max - x_min + 1) // 2, max((y_max - y_min + 1) // 2, (z_max - z_min + 1) // 2)
)
return ((x, y, z), radius)
unclustered_areas = copy.deepcopy(areas)
clustered_areas = []
while len(unclustered_areas) > 0:
area = unclustered_areas[0]
del unclustered_areas[0]
finished = True
idx = 0
while idx < len(unclustered_areas) or not finished:
if idx >= len(unclustered_areas):
idx = 0
finished = True
continue
if is_intersecting(area, unclustered_areas[idx]):
area = merge_area(area, unclustered_areas[idx])
finished = False
del unclustered_areas[idx]
else:
idx += 1
clustered_areas.append(area)
return clustered_areas
def diag_adjacent(p):
"""Return the adjacent positions to p including diagonal adjaceny"""
return [
(x, y, z)
for x in range(p[0] - 1, p[0] + 2)
for y in range(p[1] - 1, p[1] + 2)
for z in range(p[2] - 1, p[2] + 2)
if (x, y, z) != p
]
def discrete_step_dir(agent):
"""Discretized unit vector in the direction of agent's yaw
agent pos + discrete_step_dir = block in front of agent
"""
yaw = agent.get_player().look.yaw
x = round(-sin(yaw * pi / 180))
z = round(cos(yaw * pi / 180))
return np.array([x, 0, z], dtype="int32")
def euclid_dist(a, b):
"""Return euclidean distance between a and b"""
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5
def fill_idmeta(agent, poss: List[XYZ]) -> List[Block]:
"""Add id_meta information to a a list of (xyz)s"""
if len(poss) == 0:
return []
mx, my, mz = np.min(poss, axis=0)
Mx, My, Mz = np.max(poss, axis=0)
B = agent.get_blocks(mx, Mx, my, My, mz, Mz)
idms = []
for x, y, z in poss:
idm = tuple(B[y - my, z - mz, x - mx])
idms.append(cast(IDM, idm))
return [(cast(XYZ, tuple(pos)), idm) for (pos, idm) in zip(poss, idms)]
def get_locs_from_entity(e):
"""Assumes input is either mob, memory, or tuple/list of coords
outputs a tuple of coordinate tuples"""
if hasattr(e, "pos"):
if type(e.pos) is list or type(e.pos) is tuple or hasattr(e.pos, "dtype"):
return (tuple(to_block_pos(e.pos)),)
else:
return tuple((tuple(to_block_pos(pos_to_np(e.pos))),))
if str(type(e)).find("memory") > 0:
if hasattr(e, "blocks"):
return strip_idmeta(e.blocks)
return None
elif type(e) is tuple or type(e) is list:
if len(e) > 0:
if type(e[0]) is tuple:
return e
else:
return tuple((e,))
return None
# this should eventually be replaced with sql query
def most_common_idm(idms):
""" idms is a list of tuples [(id, m) ,.... (id', m')]"""
counts = {}
for idm in idms:
if not counts.get(idm):
counts[idm] = 1
else:
counts[idm] += 1
return max(counts, key=counts.get)
# TODO move this to "reasoning"
def object_looked_at(
agent,
candidates: Sequence[Tuple[XYZ, T]],
player_struct,
limit=1,
max_distance=30,
loose=False,
) -> List[Tuple[XYZ, T]]:
"""Return the object that `player` is looking at
Args:
- agent: agent object, for API access
- candidates: list of (centroid, object) tuples
- player_struct: player struct whose POV to use for calculation
- limit: 'ALL' or int; max candidates to return
- loose: if True, don't filter candaidates behind agent
Returns: a list of (xyz, mem) tuples, max length `limit`
"""
if len(candidates) == 0:
return []
pos = pos_to_np(player_struct.pos)
yaw, pitch = player_struct.look.yaw, player_struct.look.pitch
# append to each candidate its relative position to player, rotated to
# player-centric coordinates
candidates_ = [(p, obj, rotation.transform(p - pos, yaw, pitch)) for (p, obj) in candidates]
FRONT = rotation.DIRECTIONS["FRONT"]
LEFT = rotation.DIRECTIONS["LEFT"]
UP = rotation.DIRECTIONS["UP"]
# reject objects behind player or not in cone of sight (but always include
# an object if it's directly looked at)
xsect = tuple(capped_line_of_sight(agent, player_struct, 25))
if not loose:
candidates_ = [
(p, o, r)
for (p, o, r) in candidates_
if xsect in getattr(o, "blocks", {})
or r @ FRONT > ((r @ LEFT) ** 2 + (r @ UP) ** 2) ** 0.5
]
# if looking directly at an object, sort by proximity to look intersection
if euclid_dist(pos, xsect) <= 25:
candidates_.sort(key=lambda c: euclid_dist(c[0], xsect))
else:
# otherwise, sort by closest to look vector
candidates_.sort(key=lambda c: ((c[2] @ LEFT) ** 2 + (c[2] @ UP) ** 2) ** 0.5)
# linit returns of things too far away
candidates_ = [c for c in candidates_ if euclid_dist(pos, c[0]) < max_distance]
# limit number of returns
if limit == "ALL":
limit = len(candidates_)
return [(p, o) for (p, o, r) in candidates_[:limit]]
def strip_idmeta(blockobj):
"""Return a list of (x, y, z) and drop the id_meta for blockobj"""
if blockobj is not None:
if type(blockobj) is dict:
return list(pos for (pos, id_meta) in blockobj.items())
else:
return list(pos for (pos, id_meta) in blockobj)
else:
return None
def to_block_center(array):
"""Return the array centered at [0.5, 0.5, 0.5]"""
return to_block_pos(array).astype("float") + [0.5, 0.5, 0.5]
def to_block_pos(array):
"""Convert array to block position"""
return np.floor(array).astype("int32")
| craftassist-master | python/craftassist/mc_util.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import numpy as np
from numpy import sin, cos, deg2rad
DIRECTIONS = {
"AWAY": np.array([0, 0, 1]),
"FRONT": np.array([0, 0, 1]),
"BACK": np.array([0, 0, -1]),
"LEFT": np.array([1, 0, 0]),
"RIGHT": np.array([-1, 0, 0]),
"DOWN": np.array([0, -1, 0]),
"UP": np.array([0, 1, 0]),
}
def transform(coords, yaw, pitch, inverted=False):
"""Coordinate transforms with respect to yaw/pitch of the viewer
coords should be relative to the viewer *before* pitch/yaw transform
If we want to transform any of DIRECTIONS back, then it would be inverted=True
"""
# our yaw and pitch are clockwise in the standard coordinate system
theta = deg2rad(-yaw)
gamma = deg2rad(-pitch)
# standard 3d coordinate system as in:
# http://planning.cs.uiuc.edu/node101.html#fig:yawpitchroll
# http://planning.cs.uiuc.edu/node102.html
# ^ z
# |
# |-----> y
# /
# V x
rtheta = np.array([[cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]])
rgamma = np.array([[cos(gamma), 0, sin(gamma)], [0, 1, 0], [-sin(gamma), 0, cos(gamma)]])
# Minecraft world:
# ^ y
# | ^ z
# | /
# x <----/
x, y, z = coords
# a b c is the standard coordinate system
if not inverted:
trans_mat = np.linalg.inv(rtheta @ rgamma)
else:
trans_mat = rtheta @ rgamma
a, b, c = trans_mat @ [-z, -x, y]
# transform back to Minecraft world
return [-b, c, -a]
def look_vec(yaw, pitch):
yaw = deg2rad(yaw)
pitch = deg2rad(pitch)
x = -cos(pitch) * sin(yaw)
y = -sin(pitch)
z = cos(pitch) * cos(yaw)
return np.array([x, y, z])
if __name__ == "__main__":
A = (4, 0, 1)
B = (4, 4, 4)
print(transform(DIRECTIONS["RIGHT"], 45, 0, inverted=True))
| craftassist-master | python/craftassist/rotation.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
NORMAL_BLOCKS_N = 454
PASSABLE_BLOCKS = (0, 8, 9, 31, 37, 38, 39, 40, 55, 106, 171, 175)
BORING_BLOCKS = (0, 1, 2, 3, 6, 12, 31, 32, 37, 38, 39, 40)
REMOVABLE_BLOCKS = BORING_BLOCKS + (106,)
# don't bother trying to remove vines, since they grow
BUILD_IGNORE_BLOCKS = (106,)
# don't care about the difference between grass and dirt; grass grows and
# messes things up
BUILD_INTERCHANGEABLE_PAIRS = [(2, 3)]
BUILD_BLOCK_REPLACE_MAP = {
8: (0, 0), # replace still water with air
9: (0, 0), # replace flowing water with air
13: (1, 0), # replace gravel with stone
}
# TODO map with all properties of blocks, and function to search
# e.g. see through/translucent, color, material (wood vs stone vs metal), etc.
"""Mapping from colour to blockid/ meta"""
COLOR_BID_MAP = {
"aqua": [(35, 3), (35, 9), (95, 3), (57, 0)],
"black": [(35, 15), (49, 0), (95, 15)],
"blue": [(35, 11), (22, 0), (57, 0), (79, 0)],
"fuchsia": [(35, 2)],
"green": [(133, 0), (35, 13), (95, 13), (159, 13)],
"gray": [(1, 0), (1, 6)],
"lime": [(159, 5), (95, 5)],
"maroon": [(112, 0)],
"navy": [(159, 11)],
"olive": [(159, 13)],
"purple": [(95, 10), (35, 10)],
"red": [(215, 0), (152, 0), (35, 14)],
"silver": [(155, 0)],
"teal": [(57, 0)],
"white": [(43, 7), (42, 0)],
"yellow": [(35, 4), (41, 0)],
"orange": [(35, 1), (95, 1), (159, 1)],
"brown": [(5, 5), (95, 12), (159, 12)],
"pink": [(35, 6), (95, 6), (159, 6)],
"gold": [(41, 0)],
}
BLOCK_GROUPS = {
"building_block": [
1,
5,
24,
43,
44,
45,
48,
98,
112,
125,
126,
133,
152,
155,
168,
179,
181,
182,
201,
202,
204,
205,
206,
214,
215,
216,
251,
],
"plant": [37, 38, 39, 40, 175],
"terracotta": [235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250],
"water": [8, 9],
"lava": [10, 11],
"stairs": [53, 108, 109, 128, 134, 135, 136, 156, 163, 164, 180, 114, 203],
"door": [64, 71, 193, 194, 195, 196, 197, 324, 330, 427, 428, 429, 430, 431],
"ore": [14, 15, 16, 21, 56, 73, 74, 129, 153],
"torch": [50, 75, 76],
"wood": [17, 162],
"shulkerbox": [219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234],
"glass": [20, 95, 102, 160],
"gate": [107, 183, 184, 185, 186, 187],
"fence": [85, 113, 188, 189, 190, 191, 192],
"disc": [2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267],
}
| craftassist-master | python/craftassist/block_data.py |
from typing import Tuple, List
from mc_util import IDM
ITEM_STACK_NODE = Tuple[str, int] # (memid, count)
ITEM_QUEUE = Tuple[
int, List[ITEM_STACK_NODE]
] # (queue_size, [item_stack_node_1, item_stack_node_2, ...])
class Inventory:
def __init__(self):
self.items_map = {}
def add_item_stack(self, idm: IDM, item_stack_node: ITEM_STACK_NODE):
if idm not in self.items_map:
self.items_map[idm] = [0, []]
self.items_map[idm][0] += item_stack_node[1]
self.items_map[idm][1].append(item_stack_node)
def remove_item_stack(self, idm: IDM, memid):
if idm not in self.items_map or memid not in self.items_map[idm][1]:
return
item_stack_node = next(i for i in self.items_map[idm][1] if i[0] == memid)
if item_stack_node:
self.items_map[idm][0] -= item_stack_node[1]
self.items_map[idm][1].remove(item_stack_node)
def get_idm_from_memid(self, memid):
for idm, item_q in self.items_map.items():
memids = [item_stack[0] for item_stack in item_q[1]]
if memid in memids:
return idm
return (0, 0)
def get_item_stack_count_from_memid(self, memid):
for idm, item_q in self.items_map.items():
for item_stack in item_q[1]:
if memid == item_stack[0]:
return item_stack[1]
return 0
def sync_inventory(self, inventory):
pass
| craftassist-master | python/craftassist/inventory.py |
from base_agent.nsp_dialogue_manager import NSPDialogueManager
from base_agent.loco_mc_agent import LocoMCAgent
import os
import unittest
import logging
from all_test_commands import *
class AttributeDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
class FakeAgent(LocoMCAgent):
def __init__(self, opts):
super(FakeAgent, self).__init__(opts)
self.opts = opts
def init_memory(self):
self.memory = "memory"
def init_physical_interfaces(self):
pass
def init_perception(self):
pass
def init_controller(self):
dialogue_object_classes = {}
self.dialogue_manager = NSPDialogueManager(self, dialogue_object_classes, self.opts)
# NOTE: The following commands in locobot_commands can't be supported
# right away but we'll attempt them in the next round:
# "push the chair",
# "find the closest red thing",
# "copy this motion",
# "topple the pile of notebooks",
locobot_commands = list(GROUND_TRUTH_PARSES) + [
"push the chair",
"find the closest red thing",
"copy this motion",
"topple the pile of notebooks",
]
class TestDialogueManager(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestDialogueManager, self).__init__(*args, **kwargs)
opts = AttributeDict(
{
"QA_nsp_model_path": "models/semantic_parser/ttad/ttad.pth",
"nsp_embeddings_path": "models/semantic_parser/ttad/ttad_ft_embeds.pth",
"nsp_grammar_path": "models/semantic_parser/ttad/dialogue_grammar.json",
"nsp_data_dir": "datasets/annotated_data/",
"nsp_model_dir": "models/semantic_parser/ttad_bert_updated/",
"ground_truth_data_dir": "datasets/ground_truth/",
"no_ground_truth": False,
"web_app": False,
}
)
def fix_path(opts):
base_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "craftassist"
)
for optname, optval in opts.items():
if "path" in optname or "dir" in optname:
if optval:
opts[optname] = os.path.join(base_path, optval)
fix_path(opts)
self.agent = FakeAgent(opts)
def test_parses(self):
logging.info(
"Printing semantic parsing for {} locobot commands".format(len(locobot_commands))
)
for command in locobot_commands:
ground_truth_parse = GROUND_TRUTH_PARSES.get(command, None)
model_prediction = self.agent.dialogue_manager.get_logical_form(
command, self.agent.dialogue_manager.model
)
logging.info(
"\nCommand -> '{}' \nGround truth -> {} \nParse -> {}\n".format(
command, ground_truth_parse, model_prediction
)
)
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_dialogue_manager.py |
import numpy as np
from typing import Sequence, Dict
from mc_util import Block, XYZ, IDM
from rotation import look_vec
from fake_mobs import make_mob_opts, MOB_META, SimpleMob
FLAT_GROUND_DEPTH = 8
class Opt:
pass
def flat_ground_generator_with_grass(world):
flat_ground_generator(world, grass=True)
def flat_ground_generator(world, grass=False, ground_depth=FLAT_GROUND_DEPTH):
r = world.to_world_coords((0, 62, 0))[1]
# r = world.sl // 2
world.blocks[:] = 0
world.blocks[:, 0:r, :, 0] = 7
world.blocks[:, r - ground_depth : r, :, 0] = 3
if grass:
world.blocks[:, r, :, 0] = 2
else:
world.blocks[:, r, :, 0] = 3
def shift_coords(p, shift):
if hasattr(p, "x"):
q = Opt()
q.x = p.x + shift[0]
q.y = p.y + shift[1]
q.z = p.z + shift[2]
return q
q = np.add(p, shift)
if type(p) is tuple:
q = tuple(q)
if type(p) is list:
q = list(q)
return q
def build_coord_shifts(coord_shift):
def to_world_coords(p):
dx = -coord_shift[0]
dy = -coord_shift[1]
dz = -coord_shift[2]
return shift_coords(p, (dx, dy, dz))
def from_world_coords(p):
return shift_coords(p, coord_shift)
return to_world_coords, from_world_coords
class World:
def __init__(self, opts, spec):
self.opts = opts
self.count = 0
self.sl = opts.sl
# to be subtracted from incoming coordinates and added to outgoing
self.coord_shift = spec.get("coord_shift", (0, 0, 0))
to_world_coords, from_world_coords = build_coord_shifts(self.coord_shift)
self.to_world_coords = to_world_coords
self.from_world_coords = from_world_coords
self.blocks = np.zeros((opts.sl, opts.sl, opts.sl, 2), dtype="int32")
if spec.get("ground_generator"):
ground_args = spec.get("ground_args", None)
if ground_args is None:
spec["ground_generator"](self)
else:
spec["ground_generator"](self, **ground_args)
else:
self.build_ground()
self.mobs = []
for m in spec["mobs"]:
m.add_to_world(self)
self.item_stacks = []
for i in spec["item_stacks"]:
i.add_to_world(self)
self.players = []
for p in spec["players"]:
self.players.append(p)
self.agent_data = spec["agent"]
self.chat_log = []
# FIXME
self.mob_opt_maker = make_mob_opts
self.mob_maker = SimpleMob
# TODO: Add item stack maker?
def step(self):
for m in self.mobs:
m.step()
self.count += 1
def build_ground(self):
if hasattr(self.opts, "avg_ground_height"):
avg_ground_height = self.opts.avg_ground_height
else:
avg_ground_height = 6.0
if hasattr(self.opts, "hill_scale"):
hill_scale = self.opts.hill_scale
else:
hill_scale = 5.0
p = hill_scale * np.random.randn(6)
g = np.mgrid[0 : self.sl, 0 : self.sl].astype("float32") / self.sl
ground_height = (
p[0] * np.sin(g[0])
+ p[1] * np.cos(g[0])
+ p[2] * np.cos(g[0]) * np.sin(g[0])
+ p[3] * np.sin(g[1])
+ p[4] * np.cos(g[1])
+ p[5] * np.cos(g[1]) * np.sin(g[1])
)
ground_height = ground_height - ground_height.mean() + avg_ground_height
for i in range(self.sl):
for j in range(self.sl):
height = min(31, max(0, int(ground_height[i, j])))
for k in range(int(height)):
self.blocks[i, k, j] = (3, 0)
# FIXME this is broken
if hasattr(self.opts, "ground_block_probs"):
ground_blocks = np.transpose(np.nonzero(self.blocks[:, :, :, 0] == 3))
num_ground_blocks = len(ground_blocks)
for idm, val in self.opts.ground_block_probs:
if idm != (3, 0):
num = np.random.rand() * val * 2 * num_ground_blocks
for i in range(num):
j = np.random.randint(num_ground_blocks)
self.blocks[
ground_blocks[j][0], ground_blocks[j][1], ground_blocks[j][2], :
] = idm
def place_block(self, block: Block, force=False):
loc, idm = block
if idm[0] == 383:
# its a mob...
try:
# FIXME handle unknown mobs/mobs not in list
m = SimpleMob(make_mob_opts(MOB_META[idm[1]]), start_pos=loc)
m.agent_built = True
m.add_to_world(self)
return True
except:
return False
# mobs keep loc in real coords, block objects we convert to the numpy index
loc = tuple(self.to_world_coords(loc))
if idm[0] == 0:
try:
if tuple(self.blocks[loc]) != (7, 0) or force:
self.blocks[loc] = (0, 0)
return True
else:
return False
except:
return False
else:
try:
if tuple(self.blocks[loc]) != (7, 0) or force:
self.blocks[loc] = idm
return True
else:
return False
except:
return False
def dig(self, loc: XYZ):
return self.place_block((loc, (0, 0)))
def blocks_to_dict(self):
d = {}
nz = np.transpose(self.blocks[:, :, :, 0].nonzero())
for loc in nz:
l = tuple(loc.tolist())
d[self.from_world_coords(l)] = tuple(self.blocks[l[0], l[1], l[2], :])
return d
def get_idm_at_locs(self, xyzs: Sequence[XYZ]) -> Dict[XYZ, IDM]:
"""Return the ground truth block state"""
d = {}
for (x, y, z) in xyzs:
B = self.get_blocks(x, x, y, y, z, z)
d[(x, y, z)] = tuple(B[0, 0, 0, :])
return d
def get_mobs(self):
return [m.get_info() for m in self.mobs]
def get_item_stacks(self):
return [i.get_info() for i in self.item_stacks]
def get_blocks(self, xa, xb, ya, yb, za, zb, transpose=True):
xa, ya, za = self.to_world_coords((xa, ya, za))
xb, yb, zb = self.to_world_coords((xb, yb, zb))
M = np.array((xb, yb, zb))
m = np.array((xa, ya, za))
szs = M - m + 1
B = np.zeros((szs[1], szs[2], szs[0], 2), dtype="uint8")
B[:, :, :, 0] = 7
xs, ys, zs = [0, 0, 0]
xS, yS, zS = szs
if xb < 0 or yb < 0 or zb < 0:
return B
if xa > self.sl - 1 or ya > self.sl - 1 or za > self.sl - 1:
return B
if xb > self.sl - 1:
xS = self.sl - xa
xb = self.sl - 1
if yb > self.sl - 1:
yS = self.sl - ya
yb = self.sl - 1
if zb > self.sl - 1:
zS = self.sl - za
zb = self.sl - 1
if xa < 0:
xs = -xa
xa = 0
if ya < 0:
ys = -ya
ya = 0
if za < 0:
zs = -za
za = 0
pre_B = self.blocks[xa : xb + 1, ya : yb + 1, za : zb + 1, :]
# pre_B = self.blocks[ya : yb + 1, za : zb + 1, xa : xb + 1, :]
B[ys:yS, zs:zS, xs:xS, :] = pre_B.transpose(1, 2, 0, 3)
if transpose:
return B
else:
return pre_B
def get_line_of_sight(self, pos, yaw, pitch):
# it is assumed lv is unit normalized
pos = tuple(self.to_world_coords(pos))
lv = look_vec(yaw, pitch)
dt = 1.0
for n in range(2 * self.sl):
p = tuple(np.round(np.add(pos, n * dt * lv)).astype("int32"))
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
sp = tuple(np.add(p, (i, j, k)))
if all([x >= 0 for x in sp]) and all([x < self.sl for x in sp]):
if tuple(self.blocks[sp]) != (0, 0):
# TODO: deal with close blocks artifacts,
# etc
return tuple(self.from_world_coords(sp))
return
def add_incoming_chat(self, chat: str, speaker_name: str):
"""Add a chat to memory as if it was just spoken by SPEAKER"""
self.chat_log.append("<" + speaker_name + ">" + " " + chat)
| craftassist-master | python/craftassist/test/world.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import os
from world import Opt
from base_craftassist_test_case import BaseCraftassistTestCase
GROUND_TRUTH_DATA_DIR = os.path.join(os.path.dirname(__file__), "../datasets/ground_truth/")
"""This class tests common greetings. Tests check whether the command executed successfully
without world state changes; for correctness inspect chat dialogues in logging.
"""
class GreetingTest(BaseCraftassistTestCase):
def setUp(self):
opts = Opt()
opts.ground_truth_data_dir = GROUND_TRUTH_DATA_DIR
opts.no_ground_truth = False
opts.nsp_model_dir = None
opts.nsp_data_dir = None
opts.nsp_embedding_path = None
opts.model_base_path = None
opts.QA_nsp_model_path = None
opts.web_app = False
super().setUp(agent_opts=opts)
def test_hello(self):
self.add_incoming_chat("hello", self.speaker)
changes = self.flush()
self.assertFalse(changes)
def test_goodbye(self):
self.add_incoming_chat("goodbye", self.speaker)
changes = self.flush()
self.assertFalse(changes)
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_greeting.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import shapes
from base_craftassist_test_case import BaseCraftassistTestCase
from all_test_commands import *
class GetMemoryTestCase(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.cube_right = self.add_object(shapes.cube(bid=(42, 0)), (9, 63, 4))
self.cube_left = self.add_object(shapes.cube(), (9, 63, 10))
self.set_looking_at(list(self.cube_right.blocks.keys())[0])
def test_get_name(self):
# set the name
name = "fluffball"
self.agent.memory.add_triple(
subj=self.cube_right.memid, pred_text="has_name", obj_text=name
)
# get the name
d = GET_MEMORY_COMMANDS["what is where I am looking"]
self.handle_logical_form(d, stop_on_chat=True)
# check that proper chat was sent
self.assertIn(name, self.last_outgoing_chat())
def test_what_are_you_doing(self):
# start building a cube
d = BUILD_COMMANDS["build a small cube"]
self.handle_logical_form(d, max_steps=5)
# what are you doing?
d = GET_MEMORY_COMMANDS["what are you doing"]
self.handle_logical_form(d, stop_on_chat=True)
# check that proper chat was sent
self.assertIn("building", self.last_outgoing_chat())
def test_what_are_you_building(self):
# start building a cube
d = BUILD_COMMANDS["build a small cube"]
self.handle_logical_form(d, max_steps=5)
# what are you building
d = GET_MEMORY_COMMANDS["what are you building"]
self.handle_logical_form(d, stop_on_chat=True)
# check that proper chat was sent
self.assertIn("cube", self.last_outgoing_chat())
def test_where_are_you_going(self):
# start moving
d = MOVE_COMMANDS["move to 42 65 0"]
self.handle_logical_form(d, max_steps=3)
# where are you going?
d = GET_MEMORY_COMMANDS["where are you going"]
self.handle_logical_form(d, stop_on_chat=True)
# check that proper chat was sent
self.assertIn("(42, 65, 0)", self.last_outgoing_chat())
def test_where_are_you(self):
# move to origin
d = MOVE_COMMANDS["move to 0 63 0"]
self.handle_logical_form(d)
# where are you?
d = GET_MEMORY_COMMANDS["where are you"]
self.handle_logical_form(d)
# check that proper chat was sent
self.assertIn("(0, 63, 0)", self.last_outgoing_chat())
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_get_memory.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
from craftassist_agent import CraftAssistAgent
class Opt:
pass
class BaseAgentTest(unittest.TestCase):
def test_init_agent(self):
opts = Opt()
opts.no_default_behavior = False
opts.semseg_model_path = None
opts.geoscorer_model_path = None
opts.nsp_model_dir = None
opts.nsp_data_dir = None
opts.nsp_embedding_path = None
opts.model_base_path = None
opts.QA_nsp_model_path = None
opts.ground_truth_data_dir = ""
opts.semseg_model_path = ""
opts.geoscorer_model_path = ""
opts.web_app = False
opts.no_ground_truth = True
# test does not instantiate cpp client
opts.port = -1
opts.no_default_behavior = False
CraftAssistAgent(opts)
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_agent.py |
from base_agent.dialogue_objects import SPEAKERLOOK, AGENTPOS
from copy import deepcopy
FILTERS = {
"that cow": {"has_name": "cow", "contains_coreference": "resolved", "location": SPEAKERLOOK},
"that cube": {"has_name": "cube", "contains_coreference": "resolved", "location": SPEAKERLOOK},
"a cow": {"has_name": "cow"},
"a cube": {"has_name": "cube"},
"where I am looking": {"location": SPEAKERLOOK},
"my location": {"location": AGENTPOS},
}
REFERENCE_OBJECTS = {
"where I am looking": {
"filters": FILTERS["where I am looking"],
"text_span": "where I'm looking",
},
"that cow": {"filters": FILTERS["that cow"]},
"a cow": {"filters": FILTERS["a cow"]},
"that cube": {"filters": FILTERS["that cube"]},
"a cube": {"filters": FILTERS["a cube"]},
"me": {"special_reference": "AGENT"},
}
INTERPRETER_POSSIBLE_ACTIONS = {
"destroy_speaker_look": {
"action_type": "DESTROY",
"reference_object": {
"filters": {"location": SPEAKERLOOK},
"text_span": "where I'm looking",
},
},
"spawn_5_sheep": {
"action_type": "SPAWN",
"reference_object": {"filters": {"has_name": "sheep"}, "text_span": "sheep"},
"repeat": {"repeat_key": "FOR", "repeat_count": "5"},
},
"copy_speaker_look_to_agent_pos": {
"action_type": "BUILD",
"reference_object": {
"filters": {"location": SPEAKERLOOK},
"text_span": "where I'm looking",
},
"location": {
"reference_object": {"special_reference": "AGENT"},
"text_span": "where I am",
},
},
"build_small_sphere": {
"action_type": "BUILD",
"schematic": {"has_name": "sphere", "has_size": "small", "text_span": "small sphere"},
},
"build_1x1x1_cube": {
"action_type": "BUILD",
"schematic": {"has_name": "cube", "has_size": "1 x 1 x 1", "text_span": "1 x 1 x 1 cube"},
},
"move_speaker_pos": {
"action_type": "MOVE",
"location": {"reference_object": {"special_reference": "SPEAKER"}, "text_span": "to me"},
},
"build_diamond": {
"action_type": "BUILD",
"schematic": {"has_name": "diamond", "text_span": "diamond"},
},
"build_gold_cube": {
"action_type": "BUILD",
"schematic": {"has_block_type": "gold", "has_name": "cube", "text_span": "gold cube"},
},
"build_red_cube": {
"action_type": "BUILD",
"location": {"reference_object": {"special_reference": "SPEAKER_LOOK"}},
"schematic": {"has_colour": "red", "has_name": "cube", "text_span": "red cube"},
},
"destroy_red_cube": {
"action_type": "DESTROY",
"reference_object": {
"filters": {"has_name": "cube", "has_colour": "red"},
"text_span": "red cube",
},
},
"fill_all_holes_speaker_look": {
"action_type": "FILL",
"reference_object": {
"filters": {"location": SPEAKERLOOK},
"text_span": "where I'm looking",
},
"repeat": {"repeat_key": "ALL"},
},
"go_to_tree": {
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "tree"}}, "text_span": "tree"},
},
"build_square_height_1": {
"action_type": "BUILD",
"schematic": {"has_name": "square", "has_height": "1", "text_span": "square height 1"},
},
"stop": {"action_type": "STOP"},
"fill_speaker_look": {
"action_type": "FILL",
"reference_object": {
"filters": {"location": SPEAKERLOOK},
"text_span": "where I'm looking",
},
},
"fill_speaker_look_gold": {
"action_type": "FILL",
"has_block_type": "gold",
"reference_object": {
"filters": {"location": SPEAKERLOOK},
"text_span": "where I'm looking",
},
},
}
BUILD_COMMANDS = {
"build a gold cube at 0 66 0": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "BUILD",
"schematic": {"has_name": "cube", "has_block_type": "gold"},
"location": {
"reference_object": {"special_reference": {"coordinates_span": "0 66 0"}}
},
}
],
},
"build a small cube": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{"action_type": "BUILD", "schematic": {"has_name": "cube", "has_size": "small"}}
],
},
"build a circle to the left of the circle": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "BUILD",
"location": {
"reference_object": {"filters": {"has_name": "circle"}},
"relative_direction": "LEFT",
"text_span": "to the left of the circle",
},
"schematic": {"has_name": "circle", "text_span": "circle"},
}
],
},
"copy where I am looking to here": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["copy_speaker_look_to_agent_pos"]],
},
"build a small sphere": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["build_small_sphere"]],
},
"build a 1x1x1 cube": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["build_1x1x1_cube"]],
},
"build a diamond": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["build_diamond"]],
},
"build a gold cube": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["build_gold_cube"]],
},
"build a 9 x 9 stone rectangle": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "BUILD",
"schematic": {
"has_block_type": "stone",
"has_name": "rectangle",
"has_height": "9",
"has_base": "9", # has_base doesn't belong in "rectangle"
"text_span": "9 x 9 stone rectangle",
},
}
],
},
"build a square with height 1": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["build_square_height_1"]],
},
"build a red cube": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["build_red_cube"]],
},
"build a fluffy here": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "BUILD",
"schematic": {"has_name": "fluffy"},
"location": {"reference_object": {"special_reference": "AGENT"}},
}
],
},
}
SPAWN_COMMANDS = {
"spawn 5 sheep": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["spawn_5_sheep"]],
}
}
DESTROY_COMMANDS = {
"destroy it": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "DESTROY",
"reference_object": {"filters": {"contains_coreference": "yes"}},
}
],
},
"destroy where I am looking": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["destroy_speaker_look"]],
},
"destroy the red cube": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["destroy_red_cube"]],
},
"destroy everything": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"reference_object": {
"repeat": {"repeat_key": "ALL"},
"filters": {},
"text_span": "everything",
},
"action_type": "DESTROY",
}
],
},
"destroy the fluff thing": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{"action_type": "DESTROY", "reference_object": {"filters": {"has_tag": "fluff"}}}
],
},
"destroy the fluffy object": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{"action_type": "DESTROY", "reference_object": {"filters": {"has_tag": "fluffy"}}}
],
},
}
MOVE_COMMANDS = {
"move to 42 65 0": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": {"coordinates_span": "42 65 0"}}
},
}
],
},
"move to 0 63 0": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": {"coordinates_span": "0 63 0"}}
},
}
],
},
"move to -7 63 -8": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": {"coordinates_span": "-7 63 -8"}},
"text_span": "-7 63 -8",
},
}
],
},
"go between the cubes": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"filters": {"has_name": "cube"}},
"relative_direction": "BETWEEN",
"text_span": "between the cubes",
},
}
],
},
"move here": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["move_speaker_pos"]],
},
"go to the tree": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["go_to_tree"]],
},
"move to 20 63 20": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": {"coordinates_span": "20 63 20"}},
"text_span": "20 63 20",
},
}
],
},
}
FILL_COMMANDS = {
"fill where I am looking": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["fill_speaker_look"]],
},
"fill where I am looking with gold": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["fill_speaker_look_gold"]],
},
"fill all holes where I am looking": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["fill_all_holes_speaker_look"]],
},
}
DANCE_COMMANDS = {
"dance": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [{"action_type": "DANCE", "dance_type": {"dance_type_span": "dance"}}],
}
}
COMBINED_COMMANDS = {
"build a small sphere then move here": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
INTERPRETER_POSSIBLE_ACTIONS["build_small_sphere"],
INTERPRETER_POSSIBLE_ACTIONS["move_speaker_pos"],
],
},
"copy where I am looking to here then build a 1x1x1 cube": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
INTERPRETER_POSSIBLE_ACTIONS["copy_speaker_look_to_agent_pos"],
INTERPRETER_POSSIBLE_ACTIONS["build_1x1x1_cube"],
],
},
"move to 3 63 2 then 7 63 7": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": {"coordinates_span": "3 63 2"}},
"text_span": "3 63 2",
},
},
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": {"coordinates_span": "7 63 7"}},
"text_span": "7 63 7",
},
},
],
},
}
GET_MEMORY_COMMANDS = {
"what is where I am looking": {
"dialogue_type": "GET_MEMORY",
"filters": {"type": "REFERENCE_OBJECT", "reference_object": {"location": SPEAKERLOOK}},
"answer_type": "TAG",
"tag_name": "has_name",
},
"what are you doing": {
"dialogue_type": "GET_MEMORY",
"filters": {"type": "ACTION"},
"answer_type": "TAG",
"tag_name": "action_name",
},
"what are you building": {
"dialogue_type": "GET_MEMORY",
"filters": {"type": "ACTION", "action_type": "BUILD"},
"answer_type": "TAG",
"tag_name": "action_reference_object_name",
},
"where are you going": {
"dialogue_type": "GET_MEMORY",
"filters": {"type": "ACTION", "action_type": "MOVE"},
"answer_type": "TAG",
"tag_name": "move_target",
},
"where are you": {
"dialogue_type": "GET_MEMORY",
"filters": {"type": "AGENT"},
"answer_type": "TAG",
"tag_name": "location",
},
}
PUT_MEMORY_COMMANDS = {
"that is fluff": {
"dialogue_type": "PUT_MEMORY",
"filters": {"reference_object": {"location": SPEAKERLOOK}},
"upsert": {"memory_data": {"memory_type": "TRIPLE", "has_tag": "fluff"}},
},
"good job": {
"dialogue_type": "PUT_MEMORY",
"upsert": {"memory_data": {"memory_type": "REWARD", "reward_value": "POSITIVE"}},
},
"that is fluffy": {
"dialogue_type": "PUT_MEMORY",
"filters": {"reference_object": {"location": SPEAKERLOOK}},
"upsert": {"memory_data": {"memory_type": "TRIPLE", "has_tag": "fluffy"}},
},
}
def append_output(filt, output):
new_filt = deepcopy(filt)
new_filt["output"] = output
return new_filt
ATTRIBUTES = {
"x": {"attribute": "x"},
"distance from me": {
"attribute": {
"linear_extent": {
"relative_direction": "AWAY",
"source": {"special_reference": "SPEAKER"},
}
}
},
"distance from that cube": {
"attribute": {
"linear_extent": {
"relative_direction": "AWAY",
"source": REFERENCE_OBJECTS["that cube"],
}
}
},
}
CONDITIONS = {
"a cow has x greater than 5": {
"condition_type": "COMPARATOR",
"condition": {
"input_left": {"value_extractor": append_output(FILTERS["a cow"], ATTRIBUTES["x"])},
"comparison_type": "GREATER_THAN",
"input_right": {"value_extractor": "5"},
},
},
"that cow has x greater than 5": {
"condition_type": "COMPARATOR",
"condition": {
"input_left": {"value_extractor": append_output(FILTERS["that cow"], ATTRIBUTES["x"])},
"comparison_type": "GREATER_THAN",
"input_right": {"value_extractor": "5"},
},
},
"that cow is closer than 2 steps to me": {
"condition_type": "COMPARATOR",
"condition": {
"input_left": {
"value_extractor": append_output(
FILTERS["that cow"], ATTRIBUTES["distance from me"]
)
},
"comparison_type": "LESS_THAN",
"input_right": {"value_extractor": "2"},
},
},
"2 minutes": {
"condition_type": "TIME",
"condition": {
"comparator": {
"comparison_measure": "minutes",
"input_left": {"value_extractor": "NULL"},
"comparison_type": "GREATER_THAN",
"input_right": {"value_extractor": "2"},
}
},
},
"18 seconds": {
"condition_type": "TIME",
"condition": {
"comparator": {
"comparison_measure": "seconds",
"input_left": {"value_extractor": "NULL"},
"comparison_type": "GREATER_THAN",
"input_right": {"value_extractor": "18"},
}
},
},
}
CONDITIONS["18 seconds after that cow has x greater than 5"] = {
"condition_type": "TIME",
"event": CONDITIONS["that cow has x greater than 5"],
"condition": {
"comparator": {
"comparison_measure": "seconds",
"input_left": {"value_extractor": "NULL"},
"comparison_type": "GREATER_THAN",
"input_right": {"value_extractor": "18"},
}
},
}
STOP_CONDITION_COMMANDS = {
"go left until that cow is closer than 2 steps to me": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "LEFT",
},
"stop_condition": CONDITIONS["that cow is closer than 2 steps to me"],
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"follow the cow for 2 minutes": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "cow"}}},
"stop_condition": CONDITIONS["2 minutes"],
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"follow the cow for 18 seconds": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "cow"}}},
"stop_condition": CONDITIONS["18 seconds"],
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"follow the cow for 18 seconds after it has x greater than 5": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "cow"}}},
"stop_condition": CONDITIONS["18 seconds after that cow has x greater than 5"],
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"follow the cow until it has x greater than 5": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "cow"}}},
"stop_condition": CONDITIONS["that cow has x greater than 5"],
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
}
OTHER_COMMANDS = {
"the weather is good": {"dialogue_type": "NOOP"},
"stop": {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [INTERPRETER_POSSIBLE_ACTIONS["stop"]],
},
"undo": {"dialogue_type": "HUMAN_GIVE_COMMAND", "action_sequence": [{"action_type": "UNDO"}]},
}
GROUND_TRUTH_PARSES = {
"go to the gray chair": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"filters": {"has_colour": "gray", "has_name": "chair"}}
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go to the chair": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "chair"}}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go forward 0.2 meters": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "FRONT",
"steps": "0.2",
"has_measure": "meters",
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go forward one meter": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "FRONT",
"steps": "one",
"has_measure": "meter",
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go left 3 feet": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "LEFT",
"steps": "3",
"has_measure": "feet",
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go left 3 meters": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "LEFT",
"steps": "3",
"has_measure": "meters",
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go forward 1 feet": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "FRONT",
"steps": "1",
"has_measure": "feet",
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go back 1 feet": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {
"reference_object": {"special_reference": "AGENT"},
"relative_direction": "BACK",
"steps": "1",
"has_measure": "feet",
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"turn right 90 degrees": {
"action_sequence": [
{
"action_type": "DANCE",
"dance_type": {"body_turn": {"relative_yaw": {"angle": "90"}}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"turn left 90 degrees": {
"action_sequence": [
{
"action_type": "DANCE",
"dance_type": {"body_turn": {"relative_yaw": {"angle": "-90"}}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"turn right 180 degrees": {
"action_sequence": [
{
"action_type": "DANCE",
"dance_type": {"body_turn": {"relative_yaw": {"angle": "180"}}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"turn right": {
"action_sequence": [
{
"action_type": "DANCE",
"dance_type": {"body_turn": {"relative_yaw": {"angle": "90"}}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"look at where I am pointing": {
"action_sequence": [
{
"action_type": "DANCE",
"dance_type": {
"look_turn": {
"location": {"reference_object": {"special_reference": "SPEAKER_LOOK"}}
}
},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"wave": {
"action_sequence": [{"action_type": "DANCE", "dance_type": {"dance_type_name": "wave"}}],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"follow the chair": {
"action_sequence": [
{
"action_type": "MOVE",
"location": {"reference_object": {"filters": {"has_name": "chair"}}},
"stop_condition": {"condition_type": "NEVER"},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"find Laurens": {
"action_sequence": [
{"action_type": "SCOUT", "reference_object": {"filters": {"has_name": "Laurens"}}}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"bring the cup to Mary": {
"action_sequence": [
{
"action_type": "GET",
"receiver": {"reference_object": {"filters": {"has_name": "Mary"}}},
"reference_object": {"filters": {"has_name": "cup"}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
"go get me lunch": {
"action_sequence": [
{
"action_type": "GET",
"receiver": {"reference_object": {"special_reference": "SPEAKER"}},
"reference_object": {"filters": {"has_name": "lunch"}},
}
],
"dialogue_type": "HUMAN_GIVE_COMMAND",
},
}
| craftassist-master | python/craftassist/test/all_test_commands.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
from unittest.mock import Mock
import tasks
from base_agent.dialogue_objects import BotStackStatus
from dialogue_stack import DialogueStack
from mc_memory import MCAgentMemory
class BotStackStatusTest(unittest.TestCase):
def setUp(self):
self.agent = Mock(["send_chat"])
self.memory = MCAgentMemory()
self.agent.memory = self.memory
self.dialogue_stack = DialogueStack(self.agent, self.memory)
self.dialogue_stack.append(
BotStackStatus(
agent=self.agent, memory=self.memory, dialogue_stack=self.dialogue_stack
)
)
def test_move(self):
self.memory.task_stack_push(tasks.Move(self.agent, {"target": (42, 42, 42)}))
self.memory.add_chat("test_agent", "test chat: where are you going?")
self.dialogue_stack.step()
self.agent.send_chat.assert_called()
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_dialogue_objects.py |
import numpy as np
from utils import Pos, Look
from entities import MOBS_BY_ID
FLAT_GROUND_DEPTH = 8
FALL_SPEED = 1
# TODO make these prettier
MOB_COLORS = {
"rabbit": (0.3, 0.3, 0.3),
"cow": (0.9, 0.9, 0.9),
"pig": (0.9, 0.5, 0.5),
"chicken": (0.9, 0.9, 0.0),
"sheep": (0.6, 0.6, 0.6),
}
MOB_META = {101: "rabbit", 92: "cow", 90: "pig", 93: "chicken", 91: "sheep"}
MOB_SPEED = {"rabbit": 1, "cow": 0.3, "pig": 0.5, "chicken": 1, "sheep": 0.3}
MOB_LOITER_PROB = {"rabbit": 0.3, "cow": 0.5, "pig": 0.3, "chicken": 0.1, "sheep": 0.5}
MOB_LOITER_TIME = {"rabbit": 2, "cow": 2, "pig": 2, "chicken": 1, "sheep": 2}
MOB_STEP_HEIGHT = {"rabbit": 1, "cow": 1, "pig": 1, "chicken": 2, "sheep": 2}
MOB_DIRECTION_CHANGE_PROB = {"rabbit": 0.1, "cow": 0.1, "pig": 0.2, "chicken": 0.3, "sheep": 0.2}
class Opt:
pass
class MobInfo:
pass
def make_mob_opts(mobname):
opts = Opt()
opts.mobname = mobname
opts.direction_change_prob = MOB_DIRECTION_CHANGE_PROB[mobname]
opts.color = MOB_COLORS[mobname]
opts.speed = MOB_SPEED[mobname]
opts.loiter_prob = MOB_LOITER_PROB[mobname]
opts.loiter_time = MOB_LOITER_TIME[mobname]
opts.step_height = MOB_STEP_HEIGHT[mobname]
opts.mobType = list(MOBS_BY_ID.keys())[list(MOBS_BY_ID.values()).index(mobname)]
return opts
def check_bounds(p, sl):
if p >= sl or p < 0:
return -1
return 1
class SimpleMob:
def __init__(self, opts, start_pos=None, start_look=(0.0, 0.0)):
self.mobname = opts.mobname
self.color = opts.color
self.direction_change_prob = opts.direction_change_prob
self.loiter_prob = opts.loiter_prob
self.loiter_time = opts.loiter_time
self.speed = opts.speed
self.step_height = opts.step_height
self.pos = start_pos
self.look = start_look
self.loitering = -1
self.new_direction()
self.entityId = str(np.random.randint(0, 100000))
self.mobType = opts.mobType
self.agent_built = False
def add_to_world(self, world):
self.world = world
if self.pos is None:
xz = np.random.randint(0, world.sl, (2,))
slice = self.world.blocks[xz[0], :, xz[1], 0]
nz = np.flatnonzero(slice)
if len(nz) == 0:
# mob will be floating, but why no floor here?
h = 0
else:
# if top block is nonzero mob will be trapped
h = nz[-1]
off = self.world.coord_shift
self.pos = (float(xz[0]) + off[0], float(h + 1) + off[1], float(xz[1]) + off[2])
self.world.mobs.append(self)
def get_info(self):
info = MobInfo()
info.entityId = self.entityId
info.pos = Pos(*self.pos)
info.look = Look(*self.look)
info.mobType = self.mobType
info.color = self.color
info.mobname = self.mobname
return info
def new_direction(self):
new_direction = np.random.randn(2)
self.direction = new_direction / np.linalg.norm(new_direction)
# self.look ##NOT IMPLEMENTED
def step(self):
# check if falling:
x, y, z = self.world.to_world_coords(self.pos)
fy = int(np.floor(y))
rx = int(np.round(x))
rz = int(np.round(z))
if y > 0:
if self.world.blocks[rx, fy - 1, rz, 0] == 0:
self.pos = (self.pos[0], self.pos[1] - FALL_SPEED, self.pos[2])
return
# TODO when look implemented: change looks when loitering
if self.loitering >= 0:
self.loitering += 1
if self.loitering > self.loiter_time:
self.loitering = -1
return
if np.random.rand() < self.loiter_prob:
self.loitering = 0
return
if np.random.rand() < self.direction_change_prob:
self.new_direction()
step = self.direction * self.speed
bx = check_bounds(int(np.round(x + step[0])), self.world.sl)
bz = check_bounds(int(np.round(z + step[1])), self.world.sl)
# if hitting boundary, reverse...
self.direction[0] = bx * self.direction[0]
self.direction[1] = bz * self.direction[1]
step = self.direction * self.speed
new_x = step[0] + x
new_z = step[1] + z
# is there a block in new location? if no go there, if yes go up
for i in range(self.step_height):
if fy + i >= self.world.sl:
self.new_direction()
return
if self.world.blocks[int(np.round(new_x)), fy + i, int(np.round(new_z)), 0] == 0:
self.pos = self.world.from_world_coords((new_x, y + i, new_z))
return
# couldn't get past a wall of blocks, try a different dir
self.new_direction()
return
class LoopMob(SimpleMob):
def __init__(self, opts, move_sequence):
# move sequence is a list of ((x, y, z), (yaw, pitch)) tuples
super().__init__(opts)
self.move_sequence = move_sequence
self.pos = move_sequence[0][0]
self.count = 0
def step(self):
c = self.count % len(self.move_sequence)
self.pos = self.move_sequence[c][0]
# print("in loopmob step, pos is " + str(self.pos))
self.look = self.move_sequence[c][1]
self.count += 1
| craftassist-master | python/craftassist/test/fake_mobs.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
from base_craftassist_test_case import BaseCraftassistTestCase
from world import Opt
import os
GROUND_TRUTH_DATA_DIR = os.path.join(os.path.dirname(__file__), "../datasets/ground_truth/")
"""This class tests safety checks using a preset list of blacklisted words.
"""
class SafetyTest(BaseCraftassistTestCase):
def setUp(self):
opts = Opt()
opts.ground_truth_data_dir = GROUND_TRUTH_DATA_DIR
opts.no_ground_truth = False
opts.nsp_model_dir = None
opts.nsp_data_dir = None
opts.nsp_embedding_path = None
opts.model_base_path = None
opts.QA_nsp_model_path = None
opts.web_app = False
super().setUp(agent_opts=opts)
def test_unsafe_word(self):
is_safe = self.agent.dialogue_manager.is_safe("bad Clinton")
self.assertFalse(is_safe)
def test_safe_word(self):
is_safe = self.agent.dialogue_manager.is_safe("build a house")
self.assertTrue(is_safe)
def test_dialogue_manager(self):
self.add_incoming_chat("bad Clinton", self.speaker)
changes = self.flush()
self.assertFalse(changes)
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_safety.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import shapes
from base_craftassist_test_case import BaseCraftassistTestCase
from all_test_commands import *
class PutMemoryTestCase(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.cube_right = self.add_object(shapes.cube(bid=(42, 0)), (9, 63, 4))
self.cube_left = self.add_object(shapes.cube(), (9, 63, 10))
self.set_looking_at(list(self.cube_right.blocks.keys())[0])
def test_good_job(self):
d = PUT_MEMORY_COMMANDS["good job"]
self.handle_logical_form(d)
def test_tag(self):
d = PUT_MEMORY_COMMANDS["that is fluffy"]
self.handle_logical_form(d)
# destroy it
d = DESTROY_COMMANDS["destroy the fluffy object"]
changes = self.handle_logical_form(d, answer="yes")
# ensure it was destroyed
self.assertEqual(changes, {k: (0, 0) for k in self.cube_right.blocks.keys()})
def test_tag_and_build(self):
d = PUT_MEMORY_COMMANDS["that is fluffy"]
self.handle_logical_form(d)
# build a fluffy
d = BUILD_COMMANDS["build a fluffy here"]
changes = self.handle_logical_form(d, answer="yes")
self.assert_schematics_equal(changes.items(), self.cube_right.blocks.items())
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_put_memory.py |
import numpy as np
import pickle
from world import build_coord_shifts
# TODO replay instantiates world, replays in world
class Recorder:
def __init__(self, agent=None, filepath=None):
assert agent or filepath
self.agent = agent
self.tape = {}
if filepath:
self.load_from_file(filepath)
else:
self.initial_blocks = agent.world.blocks.copy()
self.coord_shift = agent.world.coord_shift
self.current_blocks = self.initial_blocks.copy()
self.replay_step = 0
_, from_world_coords = build_coord_shifts(self.coord_shift)
self.from_world_coords = from_world_coords
def load_from_file(self, filepath):
with open(filepath, "rb") as f:
d = pickle.load(f)
self.last_entry = d["last_entry"]
self.tape = d["tape"]
self.initial_blocks = d["initial_blocks"]
self.coord_shift = d["coord_shift"]
def save_to_file(self, filepath):
d = {}
d["last_entry"] = self.last_entry
d["tape"] = self.tape
d["initial_blocks"] = self.initial_blocks
d["coord_shift"] = self.coord_shift
with open(filepath, "wb") as f:
pickle.dump(d, f)
def maybe_add_entry(self):
if self.tape.get(self.agent.count) is None:
self.last_entry = self.agent.count
self.tape[self.agent.count] = {}
def record_action(self, a):
self.maybe_add_entry()
if self.tape[self.agent.count].get("actions") is None:
self.tape[self.agent.count]["actions"] = []
self.tape[self.agent.count]["actions"].append(a)
def record_mobs(self):
self.maybe_add_entry()
self.tape[self.agent.count]["mobs"] = self.agent.get_mobs()
def record_players(self):
self.maybe_add_entry()
player_list = self.agent.get_other_players()
self.tape[self.agent.count]["players"] = []
for player_struct in player_list:
loc = self.agent.get_player_line_of_sight(player_struct)
self.tape[self.agent.count]["players"].append((player_struct, loc))
def record_agent(self):
self.maybe_add_entry()
self.tape[self.agent.count]["agent"] = self.agent.get_player()
self.tape[self.agent.count]["logical_form"] = self.agent.logical_form
def record_block_changes(self):
d = self.agent.world.blocks - self.current_blocks
if d.any():
diff_idx = np.transpose(d.nonzero())
self.maybe_add_entry()
self.tape[self.agent.count]["block_changes"] = []
for idx in diff_idx:
loc = tuple(idx[:3])
idm = tuple(self.agent.world.blocks[loc[0], loc[1], loc[2], :])
self.current_blocks[loc[0], loc[1], loc[2], :] = idm
self.tape[self.agent.count]["block_changes"].append((loc, idm))
def record_world(self):
self.record_mobs()
self.record_agent()
self.record_players()
self.record_block_changes()
def get_last_record(self):
if self.tape.get(self.last_entry):
return self.tape[self.last_entry]
else:
return {}
def rewind(self):
self.replay_step = 0
self.current_blocks = self.initial_blocks.copy()
def __iter__(self):
return self
def __next__(self):
if self.replay_step > self.last_entry:
raise StopIteration
r = self.tape.get(self.replay_step, {})
if r.get("blocks_changes"):
for loc, idm in r["block_changes"]:
self.current_blocks[loc[0], loc[1], loc[2], :] = idm
self.replay_step += 1
return {
"step": self.replay_step,
"logical_form": r.get("logical_form"),
"blocks": self.current_blocks,
"block_changes": r.get("block_changes"),
"mobs": r.get("mobs"),
"agent": r.get("agent"),
"players": r.get("players"),
"actions": r.get("actions"),
}
| craftassist-master | python/craftassist/test/recorder.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
from base_craftassist_test_case import BaseCraftassistTestCase
from all_test_commands import *
from fake_mobs import LoopMob, make_mob_opts
from base_agent.base_util import TICKS_PER_SEC
def add_sequence_mob(test, mobname, sequence):
m = LoopMob(make_mob_opts(mobname), sequence)
m.add_to_world(test.world)
class MoveDirectionUntilTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
def test_move_till_condition(self):
cow_look = (0.0, 0.0)
x = -5
z = -5
cow_move_sequence = [((x, 63, z), cow_look)]
# speaker_pos = [5, 63, 5]
for i in range(20):
while x < 10:
x += 1
cow_move_sequence.append(((x, 63, z), cow_look))
z += 1
cow_move_sequence.append(((x, 63, z), cow_look))
while x > 1:
x -= 1
cow_move_sequence.append(((x, 63, z), cow_look))
z -= 1
cow_move_sequence.append(((x, 63, z), cow_look))
add_sequence_mob(self, "cow", cow_move_sequence)
cow = self.agent.world.mobs[0]
self.set_looking_at((1, 63, -2))
d = STOP_CONDITION_COMMANDS["go left until that cow is closer than 2 steps to me"]
self.handle_logical_form(d, max_steps=1000)
self.assertLessEqual(((5 - cow.pos[0]) ** 2 + (5 - cow.pos[2]) ** 2) ** 0.5, 2)
self.assertLessEqual(self.agent.pos[2], -10)
self.assertLessEqual(abs(self.agent.pos[0]), 1)
# self.assertLessEqual(abs(self.agent.pos[0] - 5), 1.01)
class FollowUntilTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
def test_move_till_condition(self):
cow_look = (0.0, 0.0)
cow_move_sequence = [((0, 63, 0), cow_look)]
x = 0
for i in range(20):
while x < 10:
x += 1
for j in [-2, -3, -2, -3]:
cow_move_sequence.append(((x, 63, j), cow_look))
while x > 1:
x -= 1
for j in [-2, -3, -2, -3]:
cow_move_sequence.append(((x, 63, j), cow_look))
add_sequence_mob(self, "cow", cow_move_sequence)
cow = self.agent.world.mobs[0]
self.set_looking_at((1, 63, -2))
print(self.agent.memory._db_read("SELECT * FROM ReferenceObjects WHERE ref_type=?", "mob"))
print("initial mob pos " + str(self.agent.world.mobs[0].pos))
d = STOP_CONDITION_COMMANDS["follow the cow until it has x greater than 5"]
self.handle_logical_form(d, max_steps=1000)
self.assertLessEqual(abs(self.agent.pos[0] - 5), 1.01)
d = STOP_CONDITION_COMMANDS["follow the cow for 18 seconds"]
start_time = self.agent.get_time()
self.handle_logical_form(d, max_steps=5000)
end_time = self.agent.get_time()
time_elapsed = (end_time - start_time) / TICKS_PER_SEC
self.assertLessEqual(
abs(self.agent.pos[0] - cow.pos[0]) + abs(self.agent.pos[2] - cow.pos[2]), 1.01
)
self.assertLessEqual(time_elapsed, 20)
self.assertGreaterEqual(time_elapsed, 16)
d = STOP_CONDITION_COMMANDS["follow the cow for 2 minutes"]
start_time = self.agent.get_time()
self.handle_logical_form(d, max_steps=5000)
end_time = self.agent.get_time()
time_elapsed = (end_time - start_time) / TICKS_PER_SEC
self.assertLessEqual(
abs(self.agent.pos[0] - cow.pos[0]) + abs(self.agent.pos[2] - cow.pos[2]), 1.01
)
self.assertLessEqual(time_elapsed, 130)
self.assertGreaterEqual(time_elapsed, 110)
# TODO make sure cow is moving in x positive direction from below 5 when the test starts
# it is now if everything else works, but should force it
d = STOP_CONDITION_COMMANDS["follow the cow for 18 seconds after it has x greater than 5"]
start_time = self.agent.get_time()
self.handle_logical_form(d, max_steps=5000)
end_time = self.agent.get_time()
time_elapsed = (end_time - start_time) / TICKS_PER_SEC
self.assertEqual(cow_move_sequence[self.agent.world.count - 1 - 18][0][0], 6)
self.assertLessEqual(
abs(self.agent.pos[0] - cow.pos[0]) + abs(self.agent.pos[2] - cow.pos[2]), 1.01
)
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_conditions.py |
import os
import sys
dir_test = os.path.dirname(__file__)
dir_craftassist = os.path.join(dir_test, "..")
dir_root = os.path.join(dir_craftassist, "..")
sys.path.append(dir_craftassist)
sys.path.append(dir_root)
sys.path.insert(0, dir_test) # insert 0 so that Agent is pulled from here
print("sys path {}".format(sys.path))
| craftassist-master | python/craftassist/test/__init__.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import shapes
from base_craftassist_test_case import BaseCraftassistTestCase
from all_test_commands import *
class CorefResolveTestCase(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.cube_right = self.add_object(shapes.cube(bid=(42, 0)), (9, 63, 4))
self.cube_left = self.add_object(shapes.cube(), (9, 63, 10))
self.set_looking_at(list(self.cube_right.blocks.keys())[0])
def test_destroy_it(self):
# build a gold cube
d = BUILD_COMMANDS["build a gold cube at 0 66 0"]
changes = self.handle_logical_form(d)
# assert cube was built
self.assertGreater(len(changes), 0)
self.assertEqual(set(changes.values()), set([(41, 0)]))
cube_xyzs = set(changes.keys())
# destroy it
d = DESTROY_COMMANDS["destroy it"]
changes = self.handle_logical_form(d, chatstr="destroy it")
# assert cube was destroyed
self.assertEqual(cube_xyzs, set(changes.keys()))
self.assertEqual(set(changes.values()), {(0, 0)})
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_coref_resolve.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import time
import shapes
from base_agent.dialogue_objects import AwaitResponse
from base_craftassist_test_case import BaseCraftassistTestCase
from all_test_commands import *
class UndoTest(BaseCraftassistTestCase):
def test_undo_destroy(self):
tag = "fluffy"
# Build something
obj = self.add_object(shapes.cube(bid=(41, 0)), (0, 63, 0))
self.set_looking_at(list(obj.blocks.keys())[0])
# Tag it
d = PUT_MEMORY_COMMANDS["that is fluffy"]
self.handle_logical_form(d)
self.assertIn(tag, obj.get_tags())
# Destroy it
d = DESTROY_COMMANDS["destroy where I am looking"]
self.handle_logical_form(d)
self.assertIsNone(self.agent.memory.get_block_object_by_xyz(list(obj.blocks.keys())[0]))
# Undo destroy (will ask confirmation)
d = OTHER_COMMANDS["undo"]
self.handle_logical_form(d)
self.assertIsInstance(self.agent.dialogue_manager.dialogue_stack.peek(), AwaitResponse)
# confirm undo
# TODO change tests to record different speakers to avoid the sleep?
time.sleep(0.02)
self.add_incoming_chat("yes", self.speaker)
self.flush()
# Check that block object has tag
newobj = self.agent.memory.get_block_object_by_xyz(list(obj.blocks.keys())[0])
self.assertIsNotNone(newobj)
self.assertIn(tag, newobj.get_tags())
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_undo.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from collections import namedtuple
from unittest.mock import Mock
Player = namedtuple("Player", "entityId, name, pos, look, mainHand")
Mob = namedtuple("Mob", "entityId, mobType, pos, look")
Pos = namedtuple("Pos", "x, y, z")
Look = namedtuple("Look", "yaw, pitch")
Item = namedtuple("Item", "id, meta")
class PickleMock(Mock):
"""Mocks cannot be pickled. This Mock class can."""
def __reduce__(self):
return (Mock, ())
| craftassist-master | python/craftassist/test/utils.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
"""Minimal agent stub only used to test CraftAssistAgent's __init__ function. It must be called "Agent" to mimic the agent.so import.
For a full-featured test agent to import in other unit tests, use FakeAgent.
"""
class Agent(object):
def __init__(self, host, port, name):
pass
def send_chat(self, chat):
pass
| craftassist-master | python/craftassist/test/agent.py |
# Adapted from Michael Fogleman (https://github.com/fogleman/Minecraft)
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import math
import time
import pickle
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse
import os
import sys
sys.path.append(os.path.dirname(__file__))
TICKS_PER_SEC = 60
PLAYER_HEIGHT = 2
FLYING_SPEED = 20
def cube_vertices(x, y, z, n):
""" Return the vertices of the cube at position x, y, z with size 2*n.
"""
return [
x - n,
y + n,
z - n,
x - n,
y + n,
z + n,
x + n,
y + n,
z + n,
x + n,
y + n,
z - n, # top
x - n,
y - n,
z - n,
x + n,
y - n,
z - n,
x + n,
y - n,
z + n,
x - n,
y - n,
z + n, # bottom
x - n,
y - n,
z - n,
x - n,
y - n,
z + n,
x - n,
y + n,
z + n,
x - n,
y + n,
z - n, # left
x + n,
y - n,
z + n,
x + n,
y - n,
z - n,
x + n,
y + n,
z - n,
x + n,
y + n,
z + n, # right
x - n,
y - n,
z + n,
x + n,
y - n,
z + n,
x + n,
y + n,
z + n,
x - n,
y + n,
z + n, # front
x + n,
y - n,
z - n,
x - n,
y - n,
z - n,
x - n,
y + n,
z - n,
x + n,
y + n,
z - n, # back
]
def tex_coord(x, y, n=4):
""" Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
def tex_coords(top, bottom, side):
""" Return a list of the texture squares for the top, bottom and side.
"""
top = tex_coord(*top, n=32)
bottom = tex_coord(*bottom, n=32)
side = tex_coord(*side, n=32)
result = []
result.extend(top)
result.extend(bottom)
result.extend(side * 4)
return result
def idm_to_tex_coords(idm):
return tex_coords(tidx[idm]["top"], tidx[idm]["bottom"], tidx[idm]["side"])
with open("texture_index.pkl", "rb") as f:
tidx = pickle.load(f)
TEXTURE_PATH = "block_textures.png"
FACES = [(0, 1, 0), (0, -1, 0), (-1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, -1)]
def normalize(position):
""" Accepts `position` of arbitrary precision and returns the block
containing that position.
Parameters
----------
position : tuple of len 3
Returns
-------
block_position : tuple of ints of len 3
"""
x, y, z = position
x, y, z = (int(round(x)), int(round(y)), int(round(z)))
return (x, y, z)
class Model(object):
def __init__(self, recorder, agent=None):
self.started = False
if agent:
self.agent = agent
self.recorder = agent.recorder
else:
self.agent = None
self.recorder = recorder
self.batch = pyglet.graphics.Batch()
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
# A mapping from position to the texture of the block at that position.
# This defines all the blocks that are currently in the world.
self.world = {}
# Same mapping as `world` but only contains blocks that are shown.
self.shown = {}
# Mapping from position to a pyglet `VertextList` for all shown blocks.
self._shown = {}
# Simple function queue implementation. The queue is populated with
# _show_block() and _hide_block() calls
self.queue = deque()
def hit_test(self, position, vector, max_distance=8):
""" Line of sight search from current position. If a block is
intersected it is returned, along with the block previously in the line
of sight. If no block is found, return None, None.
Parameters
----------
position : tuple of len 3
The (x, y, z) position to check visibility from.
vector : tuple of len 3
The line of sight vector.
max_distance : int
How many blocks away to search for a hit.
"""
m = 8
x, y, z = position
dx, dy, dz = vector
previous = None
for _ in range(max_distance * m):
key = normalize((x, y, z))
if key != previous and key in self.world:
return key, previous
previous = key
x, y, z = x + dx / m, y + dy / m, z + dz / m
return None, None
def exposed(self, position):
""" Returns False is given `position` is surrounded on all 6 sides by
blocks, True otherwise.
"""
x, y, z = position
for dx, dy, dz in FACES:
if (x + dx, y + dy, z + dz) not in self.world:
return True
return False
def add_block(self, position, texture, immediate=True):
""" Add a block with the given `texture` and `position` to the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to add.
texture : list of len 3
The coordinates of the texture squares. Use `tex_coords()` to
generate.
immediate : bool
Whether or not to draw the block immediately.
"""
if position in self.world:
self.remove_block(position, immediate)
self.world[position] = texture
if immediate:
if self.exposed(position):
self.show_block(position)
self.check_neighbors(position)
def remove_block(self, position, immediate=True):
""" Remove the block at the given `position`.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to remove.
immediate : bool
Whether or not to immediately remove block from canvas.
"""
del self.world[position]
if immediate:
if position in self.shown:
self.hide_block(position)
self.check_neighbors(position)
def check_neighbors(self, position):
""" Check all blocks surrounding `position` and ensure their visual
state is current. This means hiding blocks that are not exposed and
ensuring that all exposed blocks are shown. Usually used after a block
is added or removed.
"""
x, y, z = position
for dx, dy, dz in FACES:
key = (x + dx, y + dy, z + dz)
if key not in self.world:
continue
if self.exposed(key):
if key not in self.shown:
self.show_block(key)
else:
if key in self.shown:
self.hide_block(key)
def show_block(self, position, immediate=True):
""" Show the block at the given `position`. This method assumes the
block has already been added with add_block()
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to show.
immediate : bool
Whether or not to show the block immediately.
"""
texture = self.world[position]
self.shown[position] = texture
if immediate:
self._show_block(position, texture)
else:
self._enqueue(self._show_block, position, texture)
def _show_block(self, position, texture):
""" Private implementation of the `show_block()` method.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to show.
texture : list of len 3
The coordinates of the texture squares. Use `tex_coords()` to
generate.
"""
x, y, z = position
vertex_data = cube_vertices(x, y, z, 0.5)
texture_data = list(texture)
# create vertex list
# FIXME Maybe `add_indexed()` should be used instead
self._shown[position] = self.batch.add(
24, GL_QUADS, self.group, ("v3f/static", vertex_data), ("t2f/static", texture_data)
)
def hide_block(self, position, immediate=True):
""" Hide the block at the given `position`. Hiding does not remove the
block from the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to hide.
immediate : bool
Whether or not to immediately remove the block from the canvas.
"""
self.shown.pop(position)
if immediate:
self._hide_block(position)
else:
self._enqueue(self._hide_block, position)
def _hide_block(self, position):
""" Private implementation of the 'hide_block()` method.
"""
self._shown.pop(position).delete()
def _enqueue(self, func, *args):
""" Add `func` to the internal queue.
"""
self.queue.append((func, args))
def _dequeue(self):
""" Pop the top function from the internal queue and call it.
"""
func, args = self.queue.popleft()
func(*args)
def process_queue(self):
""" Process the entire queue while taking periodic breaks. This allows
the game loop to run smoothly. The queue contains calls to
_show_block() and _hide_block() so this method should be called if
add_block() or remove_block() was called with immediate=False
"""
start = time.clock()
while self.queue and time.clock() - start < 1.0 / TICKS_PER_SEC:
self._dequeue()
def process_entire_queue(self):
""" Process the entire queue with no breaks.
"""
while self.queue:
self._dequeue()
def clear_world(self):
locs = list(self.world.keys())
for loc in locs:
self.remove_block(loc)
def clone_agent_world(self):
npy_blocks = self.recorder.initial_blocks
W, H, D, ch = npy_blocks.shape
for i in range(npy_blocks.shape[0]):
for j in range(npy_blocks.shape[1]):
for k in range(npy_blocks.shape[2]):
idm = tuple(npy_blocks[i, j, k])
if idm[0] != 0:
loc = self.recorder.from_world_coords((i, j, k))
self.add_block(loc, idm_to_tex_coords(idm), immediate=False)
def show_world(self):
for position in self.world:
if position not in self.shown and self.exposed(position):
self.show_block(position, False)
class Window(pyglet.window.Window):
def __init__(
self, width=800, height=600, caption="Pyglet", resizable=True, recorder=None, agent=None
):
super(Window, self).__init__(width=800, height=600, caption="Pyglet", resizable=True)
# Whether or not the window exclusively captures the mouse.
self.exclusive = False
self.immaterial = True
# Strafing is moving lateral to the direction you are facing,
# e.g. moving to the left or right while continuing to face forward.
#
# First element is -1 when moving forward, 1 when moving back, and 0
# otherwise. The second element is -1 when moving left, 1 when moving
# right, and 0 otherwise.
self.strafe = [0, 0, 0]
# First element is rotation of the player in the x-z plane (ground
# plane) measured from the z-axis down. The second is the rotation
# angle from the ground plane up. Rotation is in degrees.
#
# The vertical plane rotation ranges from -90 (looking straight down) to
# 90 (looking straight up). The horizontal rotation range is unbounded.
self.rotation = (0, 0)
# The crosshairs at the center of the screen.
self.reticle = None
# Velocity in the y (upward) direction.
self.dy = 0
# A list of blocks the player can place. Hit num keys to cycle.
# self.inventory = [BRICK, GRASS, SAND]
self.inventory = [0]
# The current block the user can place. Hit num keys to cycle.
self.block = self.inventory[0]
# Convenience list of num keys.
self.num_keys = [
key._1,
key._2,
key._3,
key._4,
key._5,
key._6,
key._7,
key._8,
key._9,
key._0,
]
# Instance of the model that handles the world.
self.model = Model(recorder, agent=agent)
# Current (x, y, z) position in the world, specified with floats. Note
# that, perhaps unlike in math class, the y-axis is the vertical axis.
self.position = (-4, 63, -4)
# The label that is displayed in the top left of the canvas.
self.label = pyglet.text.Label(
"",
font_name="Arial",
font_size=10,
x=10,
y=self.height - 10,
anchor_x="left",
anchor_y="top",
color=(0, 0, 0, 255),
)
self.steplabel = pyglet.text.Label(
"",
font_name="Arial",
font_size=10,
x=10,
y=self.height - 30,
anchor_x="left",
anchor_y="top",
color=(0, 0, 0, 255),
)
self.lflabel = pyglet.text.Label(
"",
font_name="Arial",
font_size=10,
x=10,
y=self.height - 50,
anchor_x="left",
anchor_y="top",
color=(0, 0, 0, 255),
)
# This call schedules the `update()` method to be called
# TICKS_PER_SEC. This is the main game event loop.
pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC)
self.autostep = False
self.loop = False
self.count = 0
self.current_record = {}
def set_exclusive_mouse(self, exclusive):
""" If `exclusive` is True, the game will capture the mouse, if False
the game will ignore the mouse.
"""
super(Window, self).set_exclusive_mouse(exclusive)
self.exclusive = exclusive
def get_sight_vector(self):
""" Returns the current line of sight vector indicating the direction
the player is looking.
"""
x, y = self.rotation
# y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and
# is 1 when looking ahead parallel to the ground and 0 when looking
# straight up or down.
m = math.cos(math.radians(y))
# dy ranges from -1 to 1 and is -1 when looking straight down and 1 when
# looking straight up.
dy = math.sin(math.radians(y))
dx = math.cos(math.radians(x - 90)) * m
dz = math.sin(math.radians(x - 90)) * m
return (dx, dy, dz)
def get_motion_vector(self):
""" Returns the current motion vector indicating the velocity of the
player.
Returns
-------
vector : tuple of len 3
Tuple containing the velocity in x, y, and z respectively.
"""
dx = 0.0
dy = self.strafe[2]
dz = 0.0
if self.strafe[0] or self.strafe[1]:
x, y = self.rotation
strafe_deg = math.degrees(math.atan2(self.strafe[0], self.strafe[1]))
x_angle = math.radians(x + strafe_deg)
dx = math.cos(x_angle)
dz = math.sin(x_angle)
return (dx, dy, dz)
def update(self, dt):
""" This method is scheduled to be called repeatedly by the pyglet
clock.
Parameters
----------
dt : float
The change in time since the last call.
"""
if self.model.started:
self.model.process_queue()
else:
self.model.clone_agent_world()
self.model.show_world()
self.model.process_entire_queue()
self.model.started = True
if self.autostep and self.model.agent is not None:
self.model.agent.step()
self.current_record = self.model.recorder.get_last_record()
else:
# self.current_record = {}
if self.loop:
if self.count % 10 == 0:
try:
self.current_record = next(self.tape)
except:
self.model.recorder.rewind()
self.tape = iter(self.model.recorder)
self.current_record = next(self.tape)
self.model.clear_world()
self.model.clone_agent_world()
self.model.show_world()
self.model.process_entire_queue()
block_changes = self.current_record.get("block_changes")
if block_changes:
for loc, idm in block_changes:
loc = self.model.recorder.from_world_coords(loc)
if idm[0] == 0:
try:
self.model.remove_block(loc, immediate=True)
except:
pass
else:
self.model.add_block(loc, idm_to_tex_coords(idm), immediate=True)
m = 8
dt = min(dt, 0.2)
for _ in range(m):
self._update(dt / m)
self.count += 1
def _update(self, dt):
""" Private implementation of the `update()` method. This is where most
of the motion logic lives, along with gravity and collision detection.
Parameters
----------
dt : float
The change in time since the last call.
"""
speed = FLYING_SPEED
d = dt * speed # distance covered this tick.
dx, dy, dz = self.get_motion_vector()
# New position in space, before accounting for gravity.
dx, dy, dz = dx * d, dy * d, dz * d
# collisions
x, y, z = self.position
x = x + dx
y = y + dy
z = z + dz
if not self.immaterial:
x, y, z = self.collide((x, y, z), PLAYER_HEIGHT)
self.position = (x, y, z)
def collide(self, position, height):
""" Checks to see if the player at the given `position` and `height`
is colliding with any blocks in the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position to check for collisions at.
height : int or float
The height of the player.
Returns
-------
position : tuple of len 3
The new position of the player taking into account collisions.
"""
# How much overlap with a dimension of a surrounding block you need to
# have to count as a collision. If 0, touching terrain at all counts as
# a collision. If .49, you sink into the ground, as if walking through
# tall grass. If >= .5, you'll fall through the ground.
pad = 0.25
p = list(position)
np = normalize(position)
for face in FACES: # check all surrounding blocks
for i in range(3): # check each dimension independently
if not face[i]:
continue
# How much overlap you have with this dimension.
d = (p[i] - np[i]) * face[i]
if d < pad:
continue
for dy in range(height): # check each height
op = list(np)
op[1] -= dy
op[i] += face[i]
if tuple(op) not in self.model.world:
continue
p[i] -= (d - pad) * face[i]
if face == (0, -1, 0) or face == (0, 1, 0):
# You are colliding with the ground or ceiling, so stop
# falling / rising.
self.dy = 0
break
return tuple(p)
def on_mouse_press(self, x, y, button, modifiers):
""" Called when a mouse button is pressed. See pyglet docs for button
amd modifier mappings.
Parameters
----------
x, y : int
The coordinates of the mouse click. Always center of the screen if
the mouse is captured.
button : int
Number representing mouse button that was clicked. 1 = left button,
4 = right button.
modifiers : int
Number representing any modifying keys that were pressed when the
mouse button was clicked.
"""
if self.exclusive:
vector = self.get_sight_vector()
block, previous = self.model.hit_test(self.position, vector)
if (button == mouse.RIGHT) or ((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)):
# ON OSX, control + left click = right click.
if previous:
self.model.add_block(previous, self.block)
elif button == pyglet.window.mouse.LEFT and block:
texture = self.model.world[block]
if texture != STONE:
self.model.remove_block(block)
else:
self.set_exclusive_mouse(True)
def on_mouse_motion(self, x, y, dx, dy):
""" Called when the player moves the mouse.
Parameters
----------
x, y : int
The coordinates of the mouse click. Always center of the screen if
the mouse is captured.
dx, dy : float
The movement of the mouse.
"""
if self.exclusive:
m = 0.15
x, y = self.rotation
x, y = x + dx * m, y + dy * m
y = max(-90, min(90, y))
self.rotation = (x, y)
def on_key_press(self, symbol, modifiers):
""" Called when the player presses a key. See pyglet docs for key
mappings.
Parameters
----------
symbol : int
Number representing the key that was pressed.
modifiers : int
Number representing any modifying keys that were pressed.
"""
if symbol == key.W:
self.strafe[0] -= 1
elif symbol == key.S:
self.strafe[0] += 1
elif symbol == key.A:
self.strafe[1] -= 1
elif symbol == key.D:
self.strafe[1] += 1
elif symbol == key.SPACE:
self.strafe[2] += 1
elif symbol == key.RSHIFT:
self.strafe[2] -= 1
elif symbol == key.ESCAPE:
self.set_exclusive_mouse(False)
elif symbol == key.P:
self.autostep = True
elif symbol == key.M:
self.autostep = False
elif symbol == key.L:
self.loop = True
elif symbol == key.K:
self.loop = False
elif symbol == key.N:
if self.model.agent:
self.model.agent.step()
elif symbol in self.num_keys:
index = (symbol - self.num_keys[0]) % len(self.inventory)
self.block = self.inventory[index]
def on_key_release(self, symbol, modifiers):
""" Called when the player releases a key. See pyglet docs for key
mappings.
Parameters
----------
symbol : int
Number representing the key that was pressed.
modifiers : int
Number representing any modifying keys that were pressed.
"""
if symbol == key.W:
self.strafe[0] += 1
elif symbol == key.S:
self.strafe[0] -= 1
elif symbol == key.A:
self.strafe[1] += 1
elif symbol == key.D:
self.strafe[1] -= 1
elif symbol == key.SPACE:
self.strafe[2] -= 1
elif symbol == key.RSHIFT:
self.strafe[2] += 1
def on_resize(self, width, height):
""" Called when the window is resized to a new `width` and `height`.
"""
# label
self.label.y = height - 10
# reticle
if self.reticle:
self.reticle.delete()
x, y = self.width // 2, self.height // 2
n = 10
self.reticle = pyglet.graphics.vertex_list(
4, ("v2i", (x - n, y, x + n, y, x, y - n, x, y + n))
)
def set_2d(self):
""" Configure OpenGL to draw in 2d.
"""
width, height = self.get_size()
glDisable(GL_DEPTH_TEST)
viewport = self.get_viewport_size()
glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, max(1, width), 0, max(1, height), -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def set_3d(self):
""" Configure OpenGL to draw in 3d.
"""
width, height = self.get_size()
glEnable(GL_DEPTH_TEST)
viewport = self.get_viewport_size()
glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(65.0, width / float(height), 0.1, 60.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
x, y = self.rotation
glRotatef(x, 0, 1, 0)
glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
x, y, z = self.position
glTranslatef(-x, -y, -z)
def on_draw(self):
""" Called by pyglet to draw the canvas.
"""
self.clear()
self.set_3d()
glColor3d(1, 1, 1)
self.model.batch.draw()
self.draw_focused_block()
self.draw_speaker_look()
self.draw_characters()
self.set_2d()
self.draw_label()
self.draw_reticle()
# self.show_block(tuple(self.agent.pos), True)
def draw_characters(self):
def draw_cube(loc, color):
vertex_data = cube_vertices(loc[0], loc[1], loc[2], 0.51)
glColor3d(color[0], color[1], color[2])
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
pyglet.graphics.draw(24, GL_QUADS, ("v3f/static", vertex_data))
r = self.current_record
mobs = r.get("mobs", [])
for m in mobs:
draw_cube((m.pos.x, m.pos.y, m.pos.z), (m.color[0], m.color[1], m.color[2]))
players = r.get("players", [])
for player in players:
p = player[0]
draw_cube((p.pos.x, p.pos.y, p.pos.z), (0.0, 1.0, 1.0))
draw_cube((p.pos.x, p.pos.y + 1, p.pos.z), (0.0, 1.0, 1.0))
a = r.get("agent")
if a:
draw_cube((a.pos.x, a.pos.y, a.pos.z), (1.0, 0.0, 0.0))
draw_cube((a.pos.x, a.pos.y + 1, a.pos.z), (1.0, 0.0, 0.0))
def draw_speaker_look(self):
r = self.current_record
players = r.get("players", [])
if len(players) > 0:
player = players[0]
vertex_data = cube_vertices(player[1].x, player[1].y, player[1].z, 0.51)
glColor3d(1, 0, 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
pyglet.graphics.draw(24, GL_QUADS, ("v3f/static", vertex_data))
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def draw_focused_block(self):
""" Draw black edges around the block that is currently under the
crosshairs.
"""
vector = self.get_sight_vector()
block = self.model.hit_test(self.position, vector)[0]
if block:
x, y, z = block
vertex_data = cube_vertices(x, y, z, 0.51)
glColor3d(0, 0, 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
pyglet.graphics.draw(24, GL_QUADS, ("v3f/static", vertex_data))
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def draw_label(self):
""" Draw the label in the top left of the screen.
"""
x, y, z = self.position
self.label.text = "%02d (%.2f, %.2f, %.2f) %d / %d" % (
pyglet.clock.get_fps(),
x,
y,
z,
len(self.model._shown),
len(self.model.world),
)
self.label.draw()
if self.current_record:
self.steplabel.text = "step " + str(self.current_record["step"])
self.steplabel.draw()
# self.lflabel.draw()
if self.current_record.get("logical_form"):
self.lflabel.text = str(self.current_record.get("logical_form"))
def draw_reticle(self):
""" Draw the crosshairs in the center of the screen.
"""
glColor3d(0, 0, 0)
self.reticle.draw(GL_LINES)
def setup_fog():
""" Configure the OpenGL fog properties.
"""
# Enable fog. Fog "blends a fog color with each rasterized pixel fragment's
# post-texturing color."
glEnable(GL_FOG)
# Set the fog color.
glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 1))
# Say we have no preference between rendering speed and quality.
glHint(GL_FOG_HINT, GL_DONT_CARE)
# Specify the equation used to compute the blending factor.
glFogi(GL_FOG_MODE, GL_LINEAR)
# How close and far away fog starts and ends. The closer the start and end,
# the denser the fog in the fog range.
glFogf(GL_FOG_START, 20.0)
glFogf(GL_FOG_END, 60.0)
def setup():
""" Basic OpenGL configuration.
"""
# Set the color of "clear", i.e. the sky, in rgba.
glClearColor(0.5, 0.69, 1.0, 1)
# Enable culling (not rendering) of back-facing facets -- facets that aren't
# visible to you.
glEnable(GL_CULL_FACE)
# Set the texture minification/magnification function to GL_NEAREST (nearest
# in Manhattan distance) to the specified texture coordinates. GL_NEAREST
# "is generally faster than GL_LINEAR, but it can produce textured images
# with sharper edges because the transition between texture elements is not
# as smooth."
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
setup_fog()
def main():
window = Window(width=800, height=600, caption="Pyglet", resizable=True)
# Hide the mouse cursor and prevent the mouse from leaving the window.
window.set_exclusive_mouse(True)
setup()
pyglet.app.run()
| craftassist-master | python/craftassist/test/world_visualizer.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import shapes
from mc_memory import MCAgentMemory
from utils import Mob, Pos, Look
from entities import MOBS_BY_ID
from base_craftassist_test_case import BaseCraftassistTestCase
from all_test_commands import *
class ObjectsTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
# add two objects
self.obj_a = self.add_object([((0, 0, z), (41, 0)) for z in [0, -1, -2]])
self.obj_b = self.add_object([((0, 0, z), (41, 0)) for z in [-4, -5]])
# give them unique tags
self.agent.memory.tag(self.obj_a.memid, "tag_A")
self.agent.memory.tag(self.obj_b.memid, "tag_B")
def test_merge_tags(self):
obj = self.add_object([((0, 0, -3), (41, 0))])
self.assertIn("tag_A", obj.get_tags())
self.assertIn("tag_B", obj.get_tags())
class TriggersTests(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.cube_right = self.add_object(shapes.cube(bid=(42, 0)), (9, 63, 4))
self.cube_left = self.add_object(shapes.cube(), (9, 63, 10))
self.set_looking_at(list(self.cube_right.blocks.keys())[0])
def test_workspace_cleared_on_object_delete(self):
# Tag object
tag = "fluff"
d = PUT_MEMORY_COMMANDS["that is fluff"]
self.handle_logical_form(d)
self.assertIn(tag, self.cube_right.get_tags())
# Destroy it
d = DESTROY_COMMANDS["destroy the fluff thing"]
changes = self.handle_logical_form(d)
self.assertEqual(set(changes.keys()), set(self.cube_right.blocks.keys()))
# Ensure it is not in recent entities
recent_memids = [m.memid for m in self.agent.memory.get_recent_entities("BlockObjects")]
self.assertNotIn(self.cube_right.memid, recent_memids)
class MethodsTests(unittest.TestCase):
def setUp(self):
self.memory = MCAgentMemory()
def test_peek_empty(self):
self.assertEqual(self.memory.task_stack_peek(), None)
def test_add_mob(self):
# add mob
chicken = {v: k for k, v in MOBS_BY_ID.items()}["chicken"]
mob_id, mob_type, pos, look = 42, chicken, Pos(3, 4, 5), Look(0.0, 0.0)
self.memory.set_mob_position(Mob(mob_id, mob_type, pos, look))
# get mob
self.assertIsNotNone(self.memory.get_entity_by_eid(mob_id))
# update mob
pos = Pos(6, 7, 8)
look = Look(120.0, 50.0)
self.memory.set_mob_position(Mob(mob_id, mob_type, pos, look))
# get mob
mob_node = self.memory.get_entity_by_eid(mob_id)
self.assertIsNotNone(mob_node)
self.assertEqual(mob_node.pos, (6, 7, 8), (120.0, 50.0))
def test_add_guardian_mob(self):
guardian = {v: k for k, v in MOBS_BY_ID.items()}["guardian"]
mob_id, mob_type, pos, look = 42, guardian, Pos(3, 4, 5), Look(0.0, 0.0)
self.memory.set_mob_position(Mob(mob_id, mob_type, pos, look))
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_memory.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
import numpy as np
from typing import List
from mc_util import XYZ, IDM, Block
from utils import Look, Pos, Item, Player
from base_agent.loco_mc_agent import LocoMCAgent
from base_agent.base_util import TICKS_PER_SEC
from mc_memory import MCAgentMemory
from mc_memory_nodes import VoxelObjectNode
from craftassist_agent import CraftAssistAgent
from base_agent.base_util import Time
from base_agent.nsp_dialogue_manager import NSPDialogueManager
from dialogue_objects import GetMemoryHandler, PutMemoryHandler, Interpreter
from low_level_perception import LowLevelMCPerception
import heuristic_perception
from rotation import look_vec
# how many internal, non-world-interacting steps agent takes before world steps:
WORLD_STEP = 10
WORLD_STEPS_PER_DAY = 480
class Opt:
pass
class FakeMCTime(Time):
def __init__(self, world):
self.world = world
def get_world_hour(self):
return (self.world.count % WORLD_STEPS_PER_DAY) / WORLD_STEPS_PER_DAY
# converts from "seconds" to internal tick
def round_time(self, t):
return int(TICKS_PER_SEC * t)
def get_time(self):
return self.world.count * TICKS_PER_SEC
def add_tick(self, ticks=1):
for i in range(ticks):
self.world.step()
class FakeCPPAction:
NAME = "NULL"
def __init__(self, agent):
self.agent = agent
def action(self, *args):
self.agent.world_interaction_occurred = True
def __call__(self, *args):
if hasattr(self.agent, "recorder"):
self.agent.recorder.record_action({"name": self.NAME, "args": list(args)})
return self.action(*args)
class Dig(FakeCPPAction):
NAME = "dig"
def action(self, x, y, z):
self.agent.world_interaction_occurred = True
dug = self.agent.world.dig((x, y, z))
if dug:
self.agent._changed_blocks.append(((x, y, z), (0, 0)))
return True
else:
return False
class SendChat(FakeCPPAction):
NAME = "send_chat"
def action(self, chat):
self.agent.world_interaction_occurred = True
logging.info("FakeAgent.send_chat: {}".format(chat))
self.agent._outgoing_chats.append(chat)
class SetHeldItem(FakeCPPAction):
NAME = "set_held_item"
def action(self, arg):
self.agent.world_interaction_occurred = True
try:
d, m = arg
self.agent._held_item = (d, m)
except TypeError:
self.agent._held_item = (arg, 0)
class StepPosX(FakeCPPAction):
NAME = "step_pos_x"
def action(self):
self.agent.world_interaction_occurred = True
self.agent.pos += (1, 0, 0)
class StepNegX(FakeCPPAction):
NAME = "step_neg_x"
def action(self):
self.agent.world_interaction_occurred = True
self.agent.pos += (-1, 0, 0)
class StepPosZ(FakeCPPAction):
NAME = "step_pos_z"
def action(self):
self.agent.world_interaction_occurred = True
self.agent.pos += (0, 0, 1)
class StepNegZ(FakeCPPAction):
NAME = "step_neg_z"
def action(self):
self.agent.world_interaction_occurred = True
self.agent.pos += (0, 0, -1)
class StepPosY(FakeCPPAction):
NAME = "step_pos_y"
def action(self):
self.agent.world_interaction_occurred = True
self.agent.pos += (0, 1, 0)
class StepNegY(FakeCPPAction):
NAME = "step_neg_y"
def action(self):
self.agent.world_interaction_occurred = True
self.agent.pos += (0, -1, 0)
class StepForward(FakeCPPAction):
NAME = "step_forward"
def action(self):
self.agent.world_interaction_occurred = True
dx, dy, dz = self.agent._look_vec
self.agent.pos += (dx, 0, dz)
class TurnAngle(FakeCPPAction):
NAME = "turn_angle"
def action(self, angle):
self.agent.world_interaction_occurred = True
if angle == 90:
self.agent.turn_left()
elif angle == -90:
self.agent.turn_right()
else:
raise ValueError("bad angle={}".format(angle))
class TurnLeft(FakeCPPAction):
NAME = "turn_left"
def action(self):
self.agent.world_interaction_occurred = True
old_l = (self.agent._look_vec[0], self.agent._look_vec[1])
idx = self.agent.CCW_LOOK_VECS.index(old_l)
new_l = self.agent.CCW_LOOK_VECS[(idx + 1) % len(self.agent.CCW_LOOK_VECS)]
self.agent._look_vec[0] = new_l[0]
self.agent._look_vec[2] = new_l[2]
class TurnRight(FakeCPPAction):
NAME = "turn_right"
def action(self):
self.agent.world_interaction_occurred = True
old_l = (self.agent._look_vec[0], self.agent._look_vec[1])
idx = self.agent.CCW_LOOK_VECS.index(old_l)
new_l = self.agent.CCW_LOOK_VECS[(idx - 1) % len(self.agent.CCW_LOOK_VECS)]
self.agent._look_vec[0] = new_l[0]
self.agent._look_vec[2] = new_l[2]
class PlaceBlock(FakeCPPAction):
NAME = "place_block"
def action(self, x, y, z):
self.agent.world_interaction_occurred = True
block = ((x, y, z), self.agent._held_item)
self.agent.world.place_block(block)
self.agent._changed_blocks.append(block)
return True
class LookAt(FakeCPPAction):
NAME = "look_at"
def action(self, x, y, z):
raise NotImplementedError()
class SetLook(FakeCPPAction):
NAME = "set_look"
def action(self, yaw, pitch):
self.agent.world_interaction_occurred = True
a = look_vec(yaw, pitch)
self._look_vec = [a[0], a[1], a[2]]
class Craft(FakeCPPAction):
NAME = "craft"
def action(self):
raise NotImplementedError()
class FakeAgent(LocoMCAgent):
CCW_LOOK_VECS = [(1, 0), (0, 1), (-1, 0), (0, -1)]
default_frame = CraftAssistAgent.default_frame
coordinate_transforms = CraftAssistAgent.default_frame
def __init__(self, world, opts=None, do_heuristic_perception=False):
self.world = world
self.chat_count = 0
if not opts:
opts = Opt()
opts.nsp_model_dir = None
opts.nsp_data_dir = None
opts.nsp_embedding_path = None
opts.model_base_path = None
opts.QA_nsp_model_path = None
opts.ground_truth_data_dir = ""
opts.web_app = False
opts.no_ground_truth = True
super(FakeAgent, self).__init__(opts)
self.do_heuristic_perception = do_heuristic_perception
self.no_default_behavior = True
self.last_task_memid = None
pos = (0, 63, 0)
if hasattr(self.world, "agent_data"):
pos = self.world.agent_data["pos"]
self.pos = np.array(pos, dtype="int")
self.logical_form = None
self.world_interaction_occurred = False
self._held_item: IDM = (0, 0)
self._look_vec = (1, 0, 0)
self._changed_blocks: List[Block] = []
self._outgoing_chats: List[str] = []
CraftAssistAgent.add_self_memory_node(self)
def init_perception(self):
self.geoscorer = None
self.perception_modules = {}
self.perception_modules["low_level"] = LowLevelMCPerception(self, perceive_freq=1)
self.perception_modules["heuristic"] = heuristic_perception.PerceptionWrapper(self)
def init_physical_interfaces(self):
self.dig = Dig(self)
self.send_chat = SendChat(self)
self.set_held_item = SetHeldItem(self)
self.step_pos_x = StepPosX(self)
self.step_neg_x = StepNegX(self)
self.step_pos_z = StepPosZ(self)
self.step_neg_z = StepNegZ(self)
self.step_pos_y = StepPosY(self)
self.step_neg_y = StepNegY(self)
self.step_forward = StepForward(self)
self.turn_angle = TurnAngle(self)
self.turn_left = TurnLeft(self)
self.turn_right = TurnRight(self)
self.set_look = SetLook(self)
self.place_block = PlaceBlock(self)
def init_memory(self):
T = FakeMCTime(self.world)
self.memory = MCAgentMemory(load_minecraft_specs=False, agent_time=T)
def init_controller(self):
dialogue_object_classes = {}
dialogue_object_classes["interpreter"] = Interpreter
dialogue_object_classes["get_memory"] = GetMemoryHandler
dialogue_object_classes["put_memory"] = PutMemoryHandler
self.dialogue_manager = NSPDialogueManager(self, dialogue_object_classes, self.opts)
def set_logical_form(self, lf, chatstr, speaker):
self.logical_form = {"logical_form": lf, "chatstr": chatstr, "speaker": speaker}
def step(self):
if hasattr(self.world, "step"):
if self.world_interaction_occurred or self.count % WORLD_STEP == 0:
self.world.step()
self.world_interaction_occurred = False
if hasattr(self, "recorder"):
self.recorder.record_world()
super().step()
#### use the CraftassistAgent.controller_step()
def controller_step(self):
if self.logical_form is None:
pass
CraftAssistAgent.controller_step(self)
else: # logical form given directly:
# clear the chat buffer
self.get_incoming_chats()
# use the logical form as given...
d = self.logical_form["logical_form"]
chatstr = self.logical_form["chatstr"]
speaker_name = self.logical_form["speaker"]
self.memory.add_chat(self.memory.get_player_by_name(speaker_name).memid, chatstr)
# force to get objects, speaker info
self.perceive(force=True)
obj = self.dialogue_manager.handle_logical_form(speaker_name, d, chatstr)
if obj is not None:
self.dialogue_manager.dialogue_stack.append(obj)
self.logical_form = None
def setup_test(self):
self.task_steps_count = 0
def clear_outgoing_chats(self):
self._outgoing_chats.clear()
def get_last_outgoing_chat(self):
try:
return self._outgoing_chats[-1]
except IndexError:
return None
########################
## FAKE .PY METHODS ##
########################
def task_step(self):
CraftAssistAgent.task_step(self, sleep_time=0)
def point_at(*args):
pass
def perceive(self, force=False):
self.perception_modules["low_level"].perceive(force=force)
if self.do_heuristic_perception:
self.perception_modules["heuristic"].perceive()
###################################
## FAKE C++ PERCEPTION METHODS ##
###################################
def get_blocks(self, xa, xb, ya, yb, za, zb):
return self.world.get_blocks(xa, xb, ya, yb, za, zb)
def get_local_blocks(self, r):
x, y, z = self.pos
return self.get_blocks(x - r, x + r, y - r, y + r, z - r, z + r)
def get_incoming_chats(self):
c = self.chat_count
self.chat_count = len(self.world.chat_log)
return self.world.chat_log[c:].copy()
def get_player(self):
return Player(1, "fake_agent", Pos(*self.pos), self.get_look(), Item(*self._held_item))
def get_mobs(self):
return self.world.get_mobs()
def get_item_stacks(self):
return self.world.get_item_stacks()
def get_other_players(self):
return self.world.players.copy()
def get_other_player_by_name(self):
raise NotImplementedError()
def get_vision(self):
raise NotImplementedError()
def get_line_of_sight(self):
raise NotImplementedError()
def get_look(self):
pitch = -np.rad2deg(np.arcsin(self._look_vec[1]))
yaw = -np.rad2deg(np.arctan2(self._look_vec[0], self._look_vec[2]))
return Look(pitch, yaw)
def get_player_line_of_sight(self, player_struct):
if hasattr(self.world, "get_line_of_sight"):
pos = (player_struct.pos.x, player_struct.pos.y, player_struct.pos.z)
pitch = player_struct.look.pitch
yaw = player_struct.look.yaw
xsect = self.world.get_line_of_sight(pos, yaw, pitch)
if xsect is not None:
return Pos(*xsect)
else:
raise NotImplementedError()
def get_changed_blocks(self) -> List[Block]:
# need a better solution here
r = self._changed_blocks.copy()
self._changed_blocks.clear()
return r
def safe_get_changed_blocks(self) -> List[Block]:
return self.get_changed_blocks()
######################################
## World setup
######################################
def set_blocks(self, xyzbms: List[Block], origin: XYZ = (0, 0, 0)):
"""Change the state of the world, block by block,
store in memory"""
for xyz, idm in xyzbms:
abs_xyz = tuple(np.array(xyz) + origin)
self.perception_modules["low_level"].pending_agent_placed_blocks.add(abs_xyz)
# TODO add force option so we don't need to make it as if agent placed
self.perception_modules["low_level"].on_block_changed(abs_xyz, idm)
self.world.place_block((abs_xyz, idm))
def add_object(
self, xyzbms: List[Block], origin: XYZ = (0, 0, 0), relations={}
) -> VoxelObjectNode:
"""Add an object to memory as if it was placed block by block
Args:
- xyzbms: a list of relative (xyz, idm)
- origin: (x, y, z) of the corner
Returns an VoxelObjectNode
"""
self.set_blocks(xyzbms, origin)
abs_xyz = tuple(np.array(xyzbms[0][0]) + origin)
memid = self.memory.get_block_object_ids_by_xyz(abs_xyz)[0]
for pred, obj in relations.items():
self.memory.add_triple(subj=memid, pred_text=pred, obj_text=obj)
# sooooorrry FIXME? when we handle triples better in interpreter_helper
if "has_" in pred:
self.memory.tag(memid, obj)
return self.memory.get_object_by_id(memid)
######################################
## visualization
######################################
def draw_slice(self, h=None, r=5, c=None):
if not h:
h = self.pos[1]
if c:
c = [c[0], h, c[1]]
else:
c = [self.pos[0], h, self.pos[2]]
C = self.world.to_world_coords(c)
A = self.world.to_world_coords(self.pos)
shifted_agent_pos = [A[0] - C[0] + r, A[2] - C[2] + r]
npy = self.world.get_blocks(
c[0] - r, c[0] + r, c[1], c[1], c[2] - r, c[2] + r, transpose=False
)
npy = npy[:, 0, :, 0]
try:
npy[shifted_agent_pos[0], shifted_agent_pos[1]] = 1024
except:
pass
mobnums = {"rabbit": -1, "cow": -2, "pig": -3, "chicken": -4, "sheep": -5}
nummobs = {-1: "rabbit", -2: "cow", -3: "pig", -4: "chicken", -5: "sheep"}
for mob in self.world.mobs:
# todo only in the plane?
p = np.round(np.array(self.world.to_world_coords(mob.pos)))
p = p - C
try:
npy[p[0] + r, p[1] + r] = mobnums[mob.mobname]
except:
pass
mapslice = ""
height = npy.shape[0]
width = npy.shape[1]
def xs(x):
return x + int(self.pos[0]) - r
def zs(z):
return z + int(self.pos[2]) - r
mapslice = mapslice + " " * (width + 2) * 3 + "\n"
for i in reversed(range(height)):
mapslice = mapslice + str(xs(i)).center(3)
for j in range(width):
if npy[i, j] > 0:
if npy[i, j] == 1024:
mapslice = mapslice + " A "
else:
mapslice = mapslice + str(npy[i, j]).center(3)
elif npy[i, j] == 0:
mapslice = mapslice + " * "
else:
npy[i, j] = mapslice + " " + nummobs[npy[i, j]][0] + " "
mapslice = mapslice + "\n"
mapslice = mapslice + " "
for j in range(width):
mapslice = mapslice + " * "
mapslice = mapslice + "\n"
mapslice = mapslice + " "
for j in range(width):
mapslice = mapslice + str(zs(j)).center(3)
return mapslice
| craftassist-master | python/craftassist/test/fake_agent.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
from unittest.mock import Mock
import heuristic_perception
import shapes
from base_agent.dialogue_objects import SPEAKERLOOK
from base_craftassist_test_case import BaseCraftassistTestCase
from dialogue_objects.interpreter_helper import NextDialogueStep
from typing import List
from mc_util import Block, strip_idmeta, euclid_dist
from all_test_commands import *
def add_two_cubes(test):
triples = {"has_name": "cube", "has_shape": "cube"}
test.cube_right: List[Block] = list(
test.add_object(
xyzbms=shapes.cube(bid=(42, 0)), origin=(9, 63, 4), relations=triples
).blocks.items()
)
test.cube_left: List[Block] = list(
test.add_object(xyzbms=shapes.cube(), origin=(9, 63, 10), relations=triples).blocks.items()
)
test.set_looking_at(test.cube_right[0][0])
class TwoCubesInterpreterTest(BaseCraftassistTestCase):
"""A basic general-purpose test suite in a world which begins with two cubes.
N.B. by default, the agent is looking at cube_right
"""
def setUp(self):
super().setUp()
add_two_cubes(self)
def test_noop(self):
d = OTHER_COMMANDS["the weather is good"]
changes = self.handle_logical_form(d)
self.assertEqual(len(changes), 0)
def test_destroy_that(self):
d = DESTROY_COMMANDS["destroy where I am looking"]
self.handle_logical_form(d)
# Check that cube_right is destroyed
self.assertEqual(
set(self.get_idm_at_locs(strip_idmeta(self.cube_right)).values()), set([(0, 0)])
)
def test_copy_that(self):
d = BUILD_COMMANDS["copy where I am looking to here"]
changes = self.handle_logical_form(d)
# check that another gold cube was built
self.assert_schematics_equal(list(changes.items()), self.cube_right)
def test_build_small_sphere(self):
d = BUILD_COMMANDS["build a small sphere"]
changes = self.handle_logical_form(d)
# check that a small object was built
self.assertGreater(len(changes), 0)
self.assertLess(len(changes), 30)
def test_build_1x1x1_cube(self):
d = BUILD_COMMANDS["build a 1x1x1 cube"]
changes = self.handle_logical_form(d)
# check that a single block will be built
self.assertEqual(len(changes), 1)
def test_move_coordinates(self):
d = MOVE_COMMANDS["move to -7 63 -8"]
self.handle_logical_form(d)
# check that agent moved
self.assertLessEqual(euclid_dist(self.agent.pos, (-7, 63, -8)), 1)
def test_move_here(self):
d = MOVE_COMMANDS["move here"]
self.handle_logical_form(d)
# check that agent moved
self.assertLessEqual(euclid_dist(self.agent.pos, self.get_speaker_pos()), 1)
def test_build_diamond(self):
d = BUILD_COMMANDS["build a diamond"]
changes = self.handle_logical_form(d)
# check that a Build was added with a single diamond block
self.assertEqual(len(changes), 1)
self.assertEqual(list(changes.values())[0], (57, 0))
def test_build_gold_cube(self):
d = BUILD_COMMANDS["build a gold cube"]
changes = self.handle_logical_form(d)
# check that a Build was added with a gold blocks
self.assertGreater(len(changes), 0)
self.assertEqual(set(changes.values()), set([(41, 0)]))
def test_fill_all_holes_no_holes(self):
d = FILL_COMMANDS["fill all holes where I am looking"]
heuristic_perception.get_all_nearby_holes = Mock(return_value=[]) # no holes
self.handle_logical_form(d)
def test_go_to_the_tree(self):
d = MOVE_COMMANDS["go to the tree"]
try:
self.handle_logical_form(d)
except NextDialogueStep:
pass
def test_build_has_base(self):
d = BUILD_COMMANDS["build a 9 x 9 stone rectangle"]
self.handle_logical_form(d)
def test_build_square_has_height(self):
d = BUILD_COMMANDS["build a square with height 1"]
changes = self.handle_logical_form(d)
ys = set([y for (x, y, z) in changes.keys()])
self.assertEqual(len(ys), 1) # height 1
def test_action_sequence_order(self):
d = COMBINED_COMMANDS["move to 3 63 2 then 7 63 7"]
self.handle_logical_form(d)
self.assertLessEqual(euclid_dist(self.agent.pos, (7, 63, 7)), 1)
def test_stop(self):
# start moving
target = (20, 63, 20)
d = MOVE_COMMANDS["move to 20 63 20"]
self.handle_logical_form(d, max_steps=5)
# stop
d = OTHER_COMMANDS["stop"]
self.handle_logical_form(d)
# assert that move did not complete
self.assertGreater(euclid_dist(self.agent.pos, target), 1)
def test_build_sphere_move_here(self):
d = COMBINED_COMMANDS["build a small sphere then move here"]
changes = self.handle_logical_form(d)
# check that a small object was built
self.assertGreater(len(changes), 0)
self.assertLess(len(changes), 30)
# check that agent moved
self.assertLessEqual(euclid_dist(self.agent.pos, self.get_speaker_pos()), 1)
def test_copy_that_and_build_cube(self):
d = COMBINED_COMMANDS["copy where I am looking to here then build a 1x1x1 cube"]
changes = self.handle_logical_form(d)
# check that the cube_right is rebuilt and an additional block is built
self.assertEqual(len(changes), len(self.cube_right) + 1)
# doesn't actually check if the bot dances, just if it crashes FIXME!
# use recorder class from e2e_env
class DanceTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.set_looking_at((0, 63, 0))
def test_dance(self):
d = DANCE_COMMANDS["dance"]
self.handle_logical_form(d)
@unittest.skip("these just check if the modifies run, not if they are accurate")
class ModifyTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.cube_right: List[Block] = list(
self.add_object(shapes.cube(bid=(42, 0)), (9, 63, 4)).blocks.items()
)
self.set_looking_at(self.cube_right[0][0])
def gen_modify(self, modify_dict):
d = {
"dialogue_type": "HUMAN_GIVE_COMMAND",
"action_sequence": [
{
"action_type": "MODIFY",
"reference_object": {"filters": {"location": SPEAKERLOOK}},
"modify_dict": modify_dict,
}
],
}
return d
def test_modify(self):
bigger = {"modify_type": "SCALE", "categorical_scale_factor": "BIGGER"}
d = self.gen_modify(bigger)
self.handle_logical_form(d)
replace_bygeom = {
"modify_type": "REPLACE",
"new_block": {"has_colour": "green"},
"replace_geometry": {"relative_direction": "LEFT", "amount": "QUARTER"},
}
d = self.gen_modify(replace_bygeom)
self.handle_logical_form(d)
shorter = {"modify_type": "SCALE", "categorical_scale_factor": "SHORTER"}
d = self.gen_modify(shorter)
self.handle_logical_form(d)
# need to replace has_block_type by FILTERS....
replace_byblock = {
"modify_type": "REPLACE",
"old_block": {"has_block_type": "iron"},
"new_block": {"has_block_type": "diamond"},
}
d = self.gen_modify(replace_byblock)
self.handle_logical_form(d)
replace_bygeom = {
"modify_type": "REPLACE",
"new_block": {"has_block_type": "orange wool"},
"replace_geometry": {"relative_direction": "LEFT", "amount": "QUARTER"},
}
d = self.gen_modify(replace_bygeom)
self.handle_logical_form(d)
class SpawnSheep(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.set_looking_at((0, 63, 0))
def test_spawn_5_sheep(self):
d = SPAWN_COMMANDS["spawn 5 sheep"]
self.handle_logical_form(d)
self.assertEqual(len(self.agent.get_mobs()), 5)
# TODO ignore build outside of boundary in all tests
# TODO check its a circle
class CirclesLeftOfCircleTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
triples = {"has_name": "circle", "has_shape": "circle"}
self.circle_right: List[Block] = list(
self.add_object(
xyzbms=shapes.circle(bid=(42, 0)), origin=(2, 63, 4), relations=triples
).blocks.items()
)
self.set_looking_at(self.circle_right[0][0])
def test_build_other_circle(self):
d = BUILD_COMMANDS["build a circle to the left of the circle"]
changes = self.handle_logical_form(d)
self.assertGreater(len(changes), 0)
class MoveBetweenTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
add_two_cubes(self)
def test_between_cubes(self):
d = MOVE_COMMANDS["go between the cubes"]
self.handle_logical_form(d)
assert heuristic_perception.check_between(
[
self.agent,
[loc for loc, idm in self.cube_right],
[loc for loc, idm in self.cube_left],
]
)
# TODO class BuildInsideTest(BaseCraftassistTestCase):
class DestroyRedCubeTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.set_looking_at((0, 63, 0))
def test_destroy_red_cube(self):
d = BUILD_COMMANDS["build a red cube"]
changes = self.handle_logical_form(d)
self.assertGreater(len(changes), 0) # TODO check its red
# TODO also build a blue one
# TODO test where fake player also builds one
(loc, idm) = list(changes.items())[0]
self.set_looking_at(loc)
d = DESTROY_COMMANDS["destroy the red cube"]
self.handle_logical_form(d)
self.assertEqual((self.agent.world.blocks[:, :, :, 0] == idm[0]).sum(), 0)
class DestroyEverythingTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
add_two_cubes(self)
def test_destroy_everything(self):
d = DESTROY_COMMANDS["destroy everything"]
self.handle_logical_form(d)
self.assertEqual((self.agent.world.blocks[:, :, :, 0] == 42).sum(), 0)
self.assertEqual((self.agent.world.blocks[:, :, :, 0] == 41).sum(), 0)
class FillTest(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
self.hole_poss = [(x, 62, z) for x in (8, 9) for z in (10, 11)]
self.set_blocks([(pos, (0, 0)) for pos in self.hole_poss])
self.set_looking_at(self.hole_poss[0])
self.assertEqual(set(self.get_idm_at_locs(self.hole_poss).values()), set([(0, 0)]))
def test_fill_that(self):
d = FILL_COMMANDS["fill where I am looking"]
self.handle_logical_form(d)
# Make sure hole is filled
self.assertEqual(set(self.get_idm_at_locs(self.hole_poss).values()), set([(3, 0)]))
def test_fill_with_block_type(self):
d = FILL_COMMANDS["fill where I am looking with gold"]
self.handle_logical_form(d)
# Make sure hole is filled with gold
self.assertEqual(set(self.get_idm_at_locs(self.hole_poss).values()), set([(41, 0)]))
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_interpreter.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import size_words
class TestSizeWords(unittest.TestCase):
def assert_in_range(self, x, rng):
a, b = rng
self.assertTrue(a <= x < b)
def test_str_to_int(self):
x = size_words.size_str_to_int("big")
self.assert_in_range(x, size_words.RANGES["large"])
def test_str_to_int_mod(self):
x = size_words.size_str_to_int("really big")
self.assert_in_range(x, size_words.RANGES["huge"])
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_size_words.py |
from world import World, SimpleMob, make_mob_opts, Opt
from utils import Player, Pos, Look, Item
from fake_agent import FakeAgent
from world_visualizer import Window, setup
from recorder import Recorder
import pyglet
import logging
if __name__ == "__main__":
log_formatter = logging.Formatter(
"%(asctime)s [%(filename)s:%(lineno)s - %(funcName)s() %(levelname)s]: %(message)s"
)
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger().handlers.clear()
# set up stdout logging
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
sh.setFormatter(log_formatter)
logging.getLogger().addHandler(sh)
opts = Opt()
opts.sl = 32
spec = {
"players": [Player(42, "SPEAKER", Pos(0, 68, 0), Look(270, 80), Item(0, 0))],
"mobs": [SimpleMob(make_mob_opts("cow")), SimpleMob(make_mob_opts("chicken"))],
"agent": {"pos": (1, 68, 1)},
"coord_shift": (-opts.sl // 2, 63 - opts.sl // 2, -opts.sl // 2),
}
world = World(opts, spec)
agent = FakeAgent(world, opts=None)
speaker_name = agent.get_other_players()[0].name
move_speaker_pos = {"action_type": "MOVE", "location": {"location_type": "SPEAKER_POS"}}
build_small_sphere = {
"action_type": "BUILD",
"schematic": {"has_name": "sphere", "has_size": "small"},
}
build_medium_sphere = {
"action_type": "BUILD",
"schematic": {"has_name": "sphere", "has_size": "medium"},
}
build_small_sphere_here = {
"action_type": "BUILD",
"schematic": {"has_name": "sphere", "has_size": "small"},
"location": {"location_type": "SPEAKER_POS"},
}
lf = {"dialogue_type": "HUMAN_GIVE_COMMAND", "action": build_medium_sphere}
# lf = {
# "dialogue_type": "HUMAN_GIVE_COMMAND",
# "action": move_speaker_pos,
# }
dummy_chat = "TEST {}".format(lf)
agent.set_logical_form(lf, dummy_chat, speaker_name)
agent.recorder = Recorder(agent=agent)
for i in range(100):
agent.step()
FNAME = "test_record.pkl"
agent.recorder.save_to_file(FNAME)
new_recorder = Recorder(filepath=FNAME)
W = Window(recorder=new_recorder)
#
# W = Window(agent.recorder, agent=agent)
## # Hide the mouse cursor and prevent the mouse from leaving the window.
## W.set_exclusive_mouse(True)
setup()
pyglet.app.run()
| craftassist-master | python/craftassist/test/visualize_scenario.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import shapes
from base_craftassist_test_case import BaseCraftassistTestCase
from typing import List
from mc_util import Block
from all_test_commands import * # noqa
def add_two_cubes(test):
triples = {"has_name": "cube", "has_shape": "cube"}
test.cube_right: List[Block] = list(
test.add_object(
xyzbms=shapes.cube(bid=(42, 0)), origin=(9, 63, 4), relations=triples
).blocks.items()
)
test.cube_left: List[Block] = list(
test.add_object(xyzbms=shapes.cube(), origin=(9, 63, 10), relations=triples).blocks.items()
)
test.set_looking_at(test.cube_right[0][0])
class MemoryExplorer(BaseCraftassistTestCase):
def setUp(self):
super().setUp()
add_two_cubes(self)
if __name__ == "__main__":
import memory_filters as mf # noqa
M = MemoryExplorer()
M.setUp()
a = M.agent
m = M.agent.memory
| craftassist-master | python/craftassist/test/interactive_memory_explorer.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import os
import unittest
import shapes
from mc_util import euclid_dist
from base_craftassist_test_case import BaseCraftassistTestCase
class Opt:
pass
TTAD_MODEL_DIR = os.path.join(
os.path.dirname(__file__), "../models/semantic_parser/ttad_bert_updated/"
)
TTAD_BERT_DATA_DIR = os.path.join(os.path.dirname(__file__), "../datasets/annotated_data/")
class PutMemoryTestCase(BaseCraftassistTestCase):
def setUp(self):
opts = Opt()
opts.nsp_model_dir = TTAD_MODEL_DIR
opts.nsp_data_dir = TTAD_BERT_DATA_DIR
opts.nsp_embedding_path = None
opts.model_base_path = None
opts.QA_nsp_model_path = None
opts.ground_truth_data_dir = ""
opts.no_ground_truth = True
opts.web_app = False
super().setUp(agent_opts=opts)
self.cube_right = self.add_object(shapes.cube(bid=(42, 0)), (9, 63, 4))
self.cube_left = self.add_object(shapes.cube(), (9, 63, 10))
self.set_looking_at(list(self.cube_right.blocks.keys())[0])
def test_come_here(self):
chat = "come here"
self.add_incoming_chat(chat, self.speaker)
self.flush()
self.assertLessEqual(euclid_dist(self.agent.pos, self.get_speaker_pos()), 1)
def test_stop(self):
chat = "stop"
self.add_incoming_chat(chat, self.speaker)
self.flush()
if __name__ == "__main__":
unittest.main()
| craftassist-master | python/craftassist/test/test_with_model.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
# import sys
# import os
# BASE_DIR = os.path.join(os.path.dirname(__file__), "../../")
# sys.path.append(BASE_DIR)
import unittest
from unittest.mock import Mock
from build_utils import to_relative_pos
from base_agent.dialogue_objects import AwaitResponse
from fake_agent import FakeAgent
from mc_memory_nodes import VoxelObjectNode
from typing import List, Sequence, Dict
from mc_util import XYZ, Block, IDM
from utils import Player, Pos, Look, Item
from world import World, Opt, flat_ground_generator
class BaseCraftassistTestCase(unittest.TestCase):
def setUp(self, agent_opts=None):
spec = {
"players": [Player(42, "SPEAKER", Pos(5, 63, 5), Look(270, 0), Item(0, 0))],
"mobs": [],
"item_stacks": [],
"ground_generator": flat_ground_generator,
"agent": {"pos": (0, 63, 0)},
"coord_shift": (-16, 54, -16),
}
world_opts = Opt()
world_opts.sl = 32
self.world = World(world_opts, spec)
self.agent = FakeAgent(self.world, opts=agent_opts)
self.set_looking_at((0, 63, 0))
self.speaker = self.agent.get_other_players()[0].name
self.agent.perceive()
def handle_logical_form(
self, d, chatstr: str = "", answer: str = None, stop_on_chat=False, max_steps=10000
) -> Dict[XYZ, IDM]:
"""Handle a logical form and call self.flush()
If "answer" is specified and a question is asked by the agent, respond
with this string.
If "stop_on_chat" is specified, stop iterating if the agent says anything
"""
chatstr = chatstr or "TEST {}".format(d)
self.add_incoming_chat(chatstr, self.speaker)
self.agent.set_logical_form(d, chatstr, self.speaker)
changes = self.flush(max_steps, stop_on_chat=stop_on_chat)
if len(self.agent.dialogue_manager.dialogue_stack) != 0 and answer is not None:
self.add_incoming_chat(answer, self.speaker)
changes.update(self.flush(max_steps, stop_on_chat=stop_on_chat))
return changes
def flush(self, max_steps=10000, stop_on_chat=False) -> Dict[XYZ, IDM]:
"""Run the agant's step until task and dialogue stacks are empty
If "stop_on_chat" is specified, stop iterating if the agent says anything
Return the set of blocks that were changed.
"""
if stop_on_chat:
self.agent.clear_outgoing_chats()
world_before = self.agent.world.blocks_to_dict()
for _ in range(max_steps):
self.agent.step()
if self.agent_should_stop(stop_on_chat):
break
# get changes
world_after = self.world.blocks_to_dict()
changes = dict(set(world_after.items()) - set(world_before.items()))
changes.update({k: (0, 0) for k in set(world_before.keys()) - set(world_after.keys())})
return changes
def agent_should_stop(self, stop_on_chat=False):
stop = False
if (
len(self.agent.dialogue_manager.dialogue_stack) == 0
and not self.agent.memory.task_stack_peek()
):
stop = True
# stuck waiting for answer?
if (
isinstance(self.agent.dialogue_manager.dialogue_stack.peek(), AwaitResponse)
and not self.agent.dialogue_manager.dialogue_stack.peek().finished
):
stop = True
if stop_on_chat and self.agent.get_last_outgoing_chat():
stop = True
return stop
def set_looking_at(self, xyz: XYZ):
"""Set the return value for C++ call to get_player_line_of_sight"""
self.agent.get_player_line_of_sight = Mock(return_value=Pos(*xyz))
def set_blocks(self, xyzbms: List[Block], origin: XYZ = (0, 0, 0)):
self.agent.set_blocks(xyzbms, origin)
def add_object(
self, xyzbms: List[Block], origin: XYZ = (0, 0, 0), relations={}
) -> VoxelObjectNode:
return self.agent.add_object(xyzbms=xyzbms, origin=origin, relations=relations)
def add_incoming_chat(self, chat: str, speaker_name: str):
"""Add a chat to memory as if it was just spoken by SPEAKER"""
self.world.chat_log.append("<" + speaker_name + ">" + " " + chat)
# self.agent.memory.add_chat(self.agent.memory.get_player_by_name(self.speaker).memid, chat)
def assert_schematics_equal(self, a, b):
"""Check equality between two list[(xyz, idm)] schematics
N.B. this compares the shapes and idms, but ignores absolute position offsets.
"""
a, _ = to_relative_pos(a)
b, _ = to_relative_pos(b)
self.assertEqual(set(a), set(b))
def get_idm_at_locs(self, xyzs: Sequence[XYZ]) -> Dict[XYZ, IDM]:
return self.world.get_idm_at_locs(xyzs)
def last_outgoing_chat(self) -> str:
return self.agent.get_last_outgoing_chat()
def get_speaker_pos(self) -> XYZ:
return self.agent.memory.get_player_by_name(self.speaker).pos
| craftassist-master | python/craftassist/test/base_craftassist_test_case.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import fileinput
from ttad_annotate import MAX_WORDS
print("command", *["word{}".format(i) for i in range(MAX_WORDS)], sep=",")
for line in fileinput.input():
command = line.replace(",", "").strip()
words = command.split()
print(command, *words, *([""] * (MAX_WORDS - len(words))), sep=",")
| craftassist-master | python/craftassist/ttad-annotate/make_input_csv.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
MAX_WORDS = 30
CSS_SCRIPT = """
<script>
var node = document.createElement('style');
"""
for i in range(MAX_WORDS):
CSS_SCRIPT += """
if (! "${{word{i}}}") {{
node.innerHTML += '.word{i} {{ display: none }} '
}}
""".format(
i=i
)
CSS_SCRIPT += """
document.body.appendChild(node);
</script>
"""
JS_SCRIPT = """
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
"""
BEFORE = """
<!-- Bootstrap v3.0.3 -->
<link href="https://s3.amazonaws.com/mturk-public/bs30/css/bootstrap.min.css" rel="stylesheet" />
<section class="container" id="Other" style="margin-bottom:15px; padding: 10px 10px;
font-family: Verdana, Geneva, sans-serif; color:#333333; font-size:0.9em;">
<div class="row col-xs-12 col-md-12">
<!-- Instructions -->
<div class="panel panel-primary">
<div class="panel-heading"><strong>Instructions</strong></div>
<div class="panel-body">
<p>Each of these sentences is spoken to an assistant
who is tasked with helping the speaker.
We are looking to determine the meaning of the commands given to the assistant.</p>
<p>For each command, answer a series of questions. Each question is either multiple-choice,
or requires you to select which words in the sentence
correspond to which part of the command.</p>
<p>For example, given the command <b>"Build a house next to the river"</b>
<ul>
<li>For "What action is being instructed?", the answer is "Build"</li>
<li>For "What should be built?", select the button for "house"</li>
<li>For "Where should it be built?", the answer is "Relative to other object(s)"
<li>For "What other object(s)?", select the buttons for "the river"</li>
<li>etc.</li>
</ul>
<p>There may not be a suitable answer that captures the meaning of a sentence.
Don't be afraid to select "Other" if there is no good answer.</p>
</div>
</div>
<div class="well" style="position:sticky;position:-webkit-sticky;top:0;z-index:9999">
<b>Command: </b>${command}</div>
<!-- Content Body -->
<section>
"""
AFTER = """
</section>
<!-- End Content Body -->
</div>
</section>
<style type="text/css">
fieldset {{
padding: 10px;
background: #fbfbfb;
border-radius: 5px;
margin-bottom: 5px;
}}
</style>
{CSS_SCRIPT}
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script>{JS_SCRIPT}</script>
""".format(
CSS_SCRIPT=CSS_SCRIPT, JS_SCRIPT=JS_SCRIPT
)
if __name__ == "__main__":
import render_flows
from flows import *
print(
BEFORE,
render_flows.render_q(Q_ACTION, "root", show=True),
render_flows.render_q(Q_ACTION_LOOP, "root", show=True),
AFTER,
)
| craftassist-master | python/craftassist/ttad-annotate/ttad_annotate.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import csv
import argparse
import json
from collections import defaultdict, Counter
import re
from ttad_annotate import MAX_WORDS
def process_result(full_d):
worker_id = full_d["WorkerId"]
d = with_prefix(full_d, "Answer.root.")
try:
action = d["action"]
except KeyError:
return None, None, None
action_dict = {action: process_dict(with_prefix(d, "action.{}.".format(action)))}
##############
# repeat dict
##############
if d.get("loop") not in [None, "Other"]:
repeat_dict = process_repeat_dict(d)
# Some turkers annotate a repeat dict for a repeat_count of 1.
# Don't include the repeat dict if that's the case
if repeat_dict.get("repeat_count"):
a, b = repeat_dict["repeat_count"]
repeat_count_str = " ".join(
[full_d["Input.word{}".format(x)] for x in range(a, b + 1)]
)
if repeat_count_str not in ("a", "an", "one", "1"):
action_val = list(action_dict.values())[0]
if action_val.get("schematic"):
action_val["schematic"]["repeat"] = repeat_dict
elif action_val.get("action_reference_object"):
action_val["action_reference_object"]["repeat"] = repeat_dict
else:
action_dict["repeat"] = repeat_dict
##################
# post-processing
##################
# Fix Build/Freebuild mismatch
if action_dict.get("Build", {}).get("Freebuild") == "Freebuild":
action_dict["FreeBuild"] = action_dict["Build"]
del action_dict["Build"]
action_dict.get("Build", {}).pop("Freebuild", None)
action_dict.get("FreeBuild", {}).pop("Freebuild", None)
# Fix empty words messing up spans
words = [full_d["Input.word{}".format(x)] for x in range(MAX_WORDS)]
action_dict, words = fix_spans_due_to_empty_words(action_dict, words)
return worker_id, action_dict, words
def process_dict(d):
r = {}
# remove key prefixes
d = remove_key_prefixes(d, ["copy.yes.", "copy.no."])
if "location" in d:
r["location"] = {"location_type": d["location"]}
if r["location"]["location_type"] == "location_reference_object":
r["location"]["location_type"] = "BlockObject"
r["location"]["relative_direction"] = d.get(
"location.location_reference_object.relative_direction"
)
if r["location"]["relative_direction"] in ("EXACT", "NEAR", "Other"):
del r["location"]["relative_direction"]
d["location.location_reference_object.relative_direction"] = None
r["location"].update(process_dict(with_prefix(d, "location.")))
for k, v in d.items():
if (
k == "location"
or k.startswith("location.")
or k == "copy"
or (k == "relative_direction" and v in ("EXACT", "NEAR", "Other"))
):
continue
# handle span
if re.match("[^.]+.span#[0-9]+", k):
prefix, rest = k.split(".", 1)
idx = int(rest.split("#")[-1])
if prefix in r:
a, b = r[prefix]
r[prefix] = [min(a, idx), max(b, idx)] # expand span to include idx
else:
r[prefix] = [idx, idx]
# handle nested dict
elif "." in k:
prefix, rest = k.split(".", 1)
prefix_snake = snake_case(prefix)
r[prefix_snake] = r.get(prefix_snake, {})
r[prefix_snake].update(process_dict(with_prefix(d, prefix + ".")))
# handle const value
else:
r[k] = v
return r
def process_repeat_dict(d):
if d["loop"] == "ntimes":
return {
"repeat_key": "FOR",
"repeat_count": process_dict(with_prefix(d, "loop.ntimes."))["repeat_for"],
}
if d["loop"] == "repeat_all":
return {"repeat_key": "ALL"}
if d["loop"] == "forever":
return {"stop_condition": {"condition_type": "NEVER"}}
raise NotImplementedError("Bad repeat dict option: {}".format(d["loop"]))
def with_prefix(d, prefix):
return {
k.split(prefix)[1]: v
for k, v in d.items()
if k.startswith(prefix) and v not in ("", None, "None")
}
def snake_case(s):
return re.sub("([a-z])([A-Z])", "\\1_\\2", s).lower()
def remove_key_prefixes(d, ps):
d = d.copy()
rm_keys = []
add_items = []
for p in ps:
for k, v in d.items():
if k.startswith(p):
rm_keys.append(k)
add_items.append((k[len(p) :], v))
for k in rm_keys:
del d[k]
for k, v in add_items:
d[k] = v
return d
def fix_spans_due_to_empty_words(action_dict, words):
"""Return modified (action_dict, words)"""
def reduce_span_vals_gte(d, i):
for k, v in d.items():
if type(v) == dict:
reduce_span_vals_gte(v, i)
continue
try:
a, b = v
if a >= i:
a -= 1
if b >= i:
b -= 1
d[k] = [a, b]
except ValueError:
pass
except TypeError:
pass
# remove trailing empty strings
while words[-1] == "":
del words[-1]
# fix span
i = 0
while i < len(words):
if words[i] == "":
reduce_span_vals_gte(action_dict, i)
del words[i]
else:
i += 1
return action_dict, words
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("results_csv")
parser.add_argument(
"--min-votes", type=int, default=1, help="Required # of same answers, defaults to 2/3"
)
parser.add_argument(
"--only-show-disagreements",
action="store_true",
help="Only show commands that did not meet the --min-votes requirement",
)
parser.add_argument("--debug", action="store_true", help="Show debug information")
parser.add_argument(
"--tsv", action="store_true", help="Show each result with worker id in tsv format"
)
args = parser.parse_args()
result_counts = defaultdict(Counter) # map[command] -> Counter(dict)
with open(args.results_csv, "r") as f:
r = csv.DictReader(f)
for d in r:
command = d["Input.command"]
try:
worker_id, action_dict, words = process_result(d)
except:
continue
if action_dict is None:
continue
command = " ".join(words)
result = json.dumps(action_dict)
result_counts[command][result] += 1
if args.debug:
for k, v in with_prefix(d, "Answer.").items():
print((k, v))
# show each result with worker info
if args.tsv:
print(command, worker_id, result, "", sep="\t")
# results by command
if not args.tsv:
for command, counts in sorted(result_counts.items()):
if not any(v >= args.min_votes for v in counts.values()):
if args.only_show_disagreements:
print(command)
continue
elif args.only_show_disagreements:
continue
print(command)
for result, count in counts.items():
if count >= args.min_votes:
print(result)
print()
| craftassist-master | python/craftassist/ttad-annotate/process_results.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from collections import Counter, defaultdict
import fileinput
import json
import os
right_answer_count = Counter()
wrong_answer_count = Counter()
# compile sets of allowed answers
allowed_answers = defaultdict(set)
command = None
with open(os.path.join(os.path.dirname(__file__), "data/qualtest.answers.txt"), "r") as f:
for line in f:
line = line.strip()
if line == "":
continue
if line.startswith("{"):
try:
json.loads(line)
allowed_answers[command].add(line)
except:
print("Bad allowed answer:", line)
raise
else:
command = line
# validate answers
for line in fileinput.input():
command, worker_id, answer = line.strip().split("\t")
action_dict = json.loads(answer)
if not any(action_dict == json.loads(d) for d in allowed_answers[command]):
wrong_answer_count[worker_id] += 1
else:
right_answer_count[worker_id] += 1
for worker_id in right_answer_count:
print(
right_answer_count[worker_id],
"/",
right_answer_count[worker_id] + wrong_answer_count[worker_id],
worker_id,
)
| craftassist-master | python/craftassist/ttad-annotate/qualtest.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import re
def render_q(q, parent_id, show=True):
"""Return a fieldset for the given question"""
assert "key" in q, "Missing key for q: {}".format(q)
q_id = "{}.{}".format(parent_id, q["key"])
r = ""
r += '<fieldset id="{}" style="display:{}">'.format(q_id, "block" if show else "none")
r += label_tag(tooltip=q.get("tooltip")) + q["text"] + "</label>"
if "radio" in q:
r += render_radios(q["radio"], q_id, add_other_opt=q.get("add_radio_other", True))
if "span" in q:
r += render_span(q_id, q.get("optional"))
r += "</fieldset>"
return r
def render_span(parent_id, optional=False):
r = ""
group_id = "{}.span".format(parent_id)
if optional:
onclick = """var x = document.getElementById('{}');
x.style.display = x.style.display == 'block' ? 'none' : 'block';""".format(
group_id
)
r += """<label class="btn btn-primary btn-sm" onclick="{}"
style="margin-left:10px">Click if specified</label>""".format(
onclick
)
r += '<div id="{}" class="btn-group" data-toggle="buttons" style="display:{}">'.format(
group_id, "none" if optional else "block"
)
for i in range(25):
input_id = "{}#{}".format(group_id, i)
r += """<label class="btn btn-default word{i}"
name="{input_id}">""".format(
input_id=input_id, i=i
)
r += '<input type="checkbox" autocomplete="off" id="{input_id}" \
name="{input_id}">${{word{i}}}'.format(
input_id=input_id, i=i
)
r += "</label>"
r += "</div>"
return r
def render_radios(opts, parent_id, add_other_opt=True):
if add_other_opt:
opts = opts + [{"text": "Other", "key": "Other"}]
r = ""
suffix = ""
for opt in opts:
opt_id = "{}.{}".format(parent_id, opt["key"])
nexts = opt.get("next", [])
# render child questions
suffix += (
'<div id="{}.next" style="display:none">'.format(opt_id)
+ "\n".join([render_q(n, opt_id) for n in nexts])
+ "</div>"
)
# get onchange function
sibling_ids = ["{}.{}".format(parent_id, o["key"]) for o in opts]
# child_ids = ["{}.{}".format(opt_id, n["key"]) for n in nexts]
onchange = "\n".join(
[
"""
console.log('Toggling {sid}');
if (document.getElementById('{sid}.next')) {{
document.getElementById('{sid}.next').style.display = \
document.getElementById('{sid}').checked ? 'block' : 'none';
}}
""".format(
sid=sid
)
for sid in sibling_ids
]
)
# produce div for single option
r += '<div class="radio">' + label_tag(opt.get("tooltip"))
r += """<input name="{}"
id="{}"
type="radio"
value="{}"
onchange="{}"
/>""".format(
parent_id, opt_id, opt["key"], onchange
)
r += opt["text"]
r += "</label></div>"
return r + suffix
def label_tag(tooltip=None):
if tooltip:
return '<label data-toggle="tooltip" data-placement="right" title="{}">'.format(tooltip)
else:
return "<label>"
def child_id(parent_id, text):
return parent_id + "." + re.sub(r"[^a-z]+", "-", text.lower().strip()).strip("-")
| craftassist-master | python/craftassist/ttad-annotate/render_flows.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
LOCATION_RADIO = [
{"text": "Not specified", "key": None},
{
"text": "Where the speaker is looking (e.g. 'that thing', 'over there')",
"key": "SPEAKER_LOOK",
},
{"text": "Where the speaker is standing (e.g. 'here', 'by me')", "key": "SpeakerPos"},
{
"text": "Where the assistant is standing (e.g. 'by you', 'where you are')",
"key": "AGENT_POS",
},
{
"text": "To a specific object or area, or somewhere relative to other object(s)",
"key": "REFERENCE_OBJECT",
"next": [
{"text": "What other object(s) or area?", "key": "has_name", "span": True},
{
"text": "Where in relation to the other object(s)?",
"key": "relative_direction",
"radio": [
{"text": "Left", "key": "LEFT"},
{"text": "Right", "key": "RIGHT"},
{"text": "Above", "key": "UP"},
{"text": "Below", "key": "DOWN"},
{"text": "In front", "key": "FRONT"},
{"text": "Behind", "key": "BACK"},
{"text": "Away from", "key": "AWAY"},
{"text": "Nearby", "key": "NEAR"},
{"text": "Exactly at", "key": "EXACT"},
],
},
],
},
]
REF_OBJECT_OPTIONALS = [
{
"text": "What is the building material?",
"key": "reference_object.has_block_type",
"span": True,
"optional": True,
},
{
"text": "What is the color?",
"key": "reference_object.has_colour",
"span": True,
"optional": True,
},
{
"text": "What is the size?",
"key": "reference_object.has_size",
"span": True,
"optional": True,
},
{
"text": "What is the width?",
"key": "reference_object.has_width",
"span": True,
"optional": True,
},
{
"text": "What is the height?",
"key": "reference_object.has_height",
"span": True,
"optional": True,
},
{
"text": "What is the depth?",
"key": "reference_object.has_depth",
"span": True,
"optional": True,
},
]
Q_ACTION = {
"text": 'What action is being instructed? If multiple separate actions are being instructed (e.g. "do X and then do Y"), select "Multiple separate actions"',
"key": "action_type",
"add_radio_other": False,
"radio": [
# BUILD
{
"text": "Build or create something",
"key": "BUILD",
"next": [
{
"text": "Is this a copy or duplicate of an existing object?",
"key": "COPY",
"radio": [
# COPY
{
"text": "Yes",
"key": "yes",
"next": [
{
"text": "What object should be copied?",
"key": "reference_object.has_name",
"span": True,
},
*REF_OBJECT_OPTIONALS,
{
"text": "What is the location of the object to be copied?",
"key": "location",
"radio": LOCATION_RADIO,
},
],
},
# BUILD
{
"text": "No",
"key": "no",
"next": [
{
"text": "What should be built?",
"key": "schematic.has_name",
"span": True,
},
{
"text": "What is the building material?",
"key": "schematic.has_block_type",
"span": True,
"optional": True,
},
{
"text": "What is the size?",
"key": "schematic.has_size",
"span": True,
"optional": True,
},
{
"text": "What is the width?",
"key": "schematic.has_width",
"span": True,
"optional": True,
},
{
"text": "What is the height?",
"key": "schematic.has_height",
"span": True,
"optional": True,
},
{
"text": "What is the depth?",
"key": "schematic.has_depth",
"span": True,
"optional": True,
},
{
"text": "Is the assistant being asked to...",
"key": "FREEBUILD",
"add_radio_other": False,
"radio": [
{
"text": "Build a complete, specific object",
"key": "BUILD",
},
{
"text": "Help complete or finish an existing object",
"key": "FREEBUILD",
},
],
},
],
},
],
},
{"text": "Where should it be built?", "key": "location", "radio": LOCATION_RADIO},
],
},
# MOVE
{
"text": "Move somewhere",
"key": "MOVE",
"next": [
{
"text": "Where should the assistant move to?",
"key": "location",
"radio": LOCATION_RADIO,
}
],
},
# DESTROY
{
"text": "Destroy, remove, or kill something",
"key": "DESTROY",
"next": [
{
"text": "What object should the assistant destroy?",
"key": "reference_object.has_name",
"span": True,
},
*REF_OBJECT_OPTIONALS,
{
"text": "What is the location of the object to be removed?",
"key": "location",
"radio": LOCATION_RADIO,
},
],
},
# DIG
{
"text": "Dig a hole",
"key": "DIG",
"next": [
{
"text": "Where should the hole be dug?",
"key": "location",
"radio": LOCATION_RADIO,
},
{"text": "What is the size?", "key": "has_size", "span": True, "optional": True},
{"text": "What is the width?", "key": "has_width", "span": True, "optional": True},
{
"text": "What is the height?",
"key": "has_height",
"span": True,
"optional": True,
},
{"text": "What is the depth?", "key": "has_depth", "span": True, "optional": True},
],
},
# FILL
{
"text": "Fill a hole",
"key": "FILL",
"next": [
{
"text": "Where should the hole be dug?",
"key": "location",
"radio": LOCATION_RADIO,
},
*REF_OBJECT_OPTIONALS,
],
},
# TAG
{
"text": "Assign a description, name, or tag to an object",
"key": "TAG",
"tooltip": "e.g. 'That thing is fluffy' or 'The blue building is my house'",
"next": [
{
"text": "What is the description, name, or tag being assigned?",
"key": "tag",
"span": True,
},
{
"text": "What object is being assigned a description, name, or tag?",
"key": "reference_object",
},
*REF_OBJECT_OPTIONALS,
{
"text": "What is the location of the object to be described, named, or tagged?",
"key": "location",
"radio": LOCATION_RADIO,
},
],
},
# STOP
{
"text": "Stop current action",
"key": "STOP",
"next": [
{
"text": "Is this a command to stop a particular action?",
"key": "target_action_type",
"radio": [
{"text": "Building", "key": "BUILD"},
{"text": "Moving", "key": "MOVE"},
{"text": "Destroying", "key": "DESTROY"},
{"text": "Digging", "key": "DIG"},
{"text": "Filling", "key": "FILL"},
],
}
],
},
# RESUME
{"text": "Resume previous action", "key": "RESUME"},
# UNDO
{"text": "Undo previous action", "key": "UNDO"},
# ANSWER QUESTION
{
"text": "Answer a question",
"key": "ANSWER",
"tooltip": "e.g. 'How many trees are there?' or 'Tell me how deep that tunnel goes'",
},
# OTHER ACTION NOT LISTED
{
"text": "Another action not listed here",
"key": "OtherAction",
"tooltip": "The sentence is a command, but not one of the actions listed here",
"next": [
{
"text": "What object (if any) is the target of this action? e.g. for the sentence 'Sharpen this axe', select the word 'axe'",
"key": "reference_object.has_name",
"span": True,
},
*REF_OBJECT_OPTIONALS,
{
"text": "Where should the action take place?",
"key": "location",
"radio": LOCATION_RADIO,
},
],
},
# NOT ACTION
{
"text": "This sentence is not a command or request to do something",
"key": "NOOP",
"tooltip": "e.g. 'Yes', 'Hello', or 'What a nice day it is today'",
},
# MULTIPLE ACTIONS
{
"text": "Multiple separate actions",
"key": "COMPOSITE_ACTION",
"tooltip": "e.g. 'Build a cube and then run around'. Do not select this for a single repeated action, e.g. 'Build 5 cubes'",
},
],
}
REPEAT_DIR = {
"text": "In which direction should the action be repeated?",
"key": "repeat_dir",
"radio": [
{"text": "Not specified", "key": None},
{"text": "Forward", "key": "FRONT"},
{"text": "Backward", "key": "BACK"},
{"text": "Left", "key": "LEFT"},
{"text": "Right", "key": "RIGHT"},
{"text": "Up", "key": "UP"},
{"text": "Down", "key": "DOWN"},
],
}
Q_ACTION_LOOP = {
"text": "How many times should this action be performed?",
"key": "loop",
"radio": [
{"text": "Just once, or not specified", "key": None},
{
"text": "Repeatedly, a specific number of times",
"key": "ntimes",
"next": [{"text": "How many times?", "span": True, "key": "repeat_for"}],
},
{
"text": "Repeatedly, once for each object",
"key": "repeat_all",
"tooltip": "e.g. 'Destroy the red blocks', or 'Build a shed in front of each house'",
},
{
"text": "Repeated forever",
"key": "forever",
"tooltip": "e.g. 'Keep building railroad tracks in that direction' or 'Collect diamonds until I tell you to stop'",
},
],
}
| craftassist-master | python/craftassist/ttad-annotate/flows.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import csv
def any_two(a, b, c):
return a == b or a == c or b == c
with open("Batch_3449808_batch_results.csv", "r") as f:
r = csv.DictReader(f)
r = [d for d in r]
whittled = [
{k: v for k, v in d.items() if (k.startswith("Answer.") or k == "Input.command") and v != ""}
for d in r
]
with open("results.tmp", "r") as f:
processed = f.readlines()
assert len(processed) == len(whittled)
faulty_processed_idxs = []
for i in range(181):
if not any_two(processed[3 * i], processed[3 * i + 1], processed[3 * i + 2]):
print(i)
print(whittled[3 * i])
# print(processed[3*i], processed[3*i+1], processed[3*i+2], '', sep='\n')
faulty_processed_idxs.append(i)
# for i in faulty_processed_idxs:
# print(whittled[3*i], whittled[3*i], whittled[3*i], '', sep='\n')
| craftassist-master | python/craftassist/ttad-annotate/analyze_outputs.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
from typing import Dict, Tuple, Any, Optional
from base_agent.dialogue_objects import DialogueObject
from mc_memory_nodes import VoxelObjectNode, RewardNode
from .interpreter_helper import interpret_reference_object, ErrorWithResponse
######FIXME TEMPORARY:
from base_agent import post_process_logical_form
class PutMemoryHandler(DialogueObject):
def __init__(self, speaker_name: str, action_dict: Dict, **kwargs):
super().__init__(**kwargs)
self.provisional: Dict = {}
self.speaker_name = speaker_name
self.action_dict = action_dict
def step(self) -> Tuple[Optional[str], Any]:
r = self._step()
self.finished = True
return r
def _step(self) -> Tuple[Optional[str], Any]:
assert self.action_dict["dialogue_type"] == "PUT_MEMORY"
memory_type = self.action_dict["upsert"]["memory_data"]["memory_type"]
if memory_type == "REWARD":
return self.handle_reward()
elif memory_type == "TRIPLE":
return self.handle_triple()
else:
raise NotImplementedError
def handle_reward(self) -> Tuple[Optional[str], Any]:
reward_value = self.action_dict["upsert"]["memory_data"]["reward_value"]
assert reward_value in ("POSITIVE", "NEGATIVE"), self.action_dict
RewardNode.create(self.memory, reward_value)
if reward_value == "POSITIVE":
return "Thank you!", None
else:
return "I'll try to do better in the future.", None
def handle_triple(self) -> Tuple[Optional[str], Any]:
# ref_obj_d = self.action_dict["filters"]["reference_object"]
##### FIXME short term
ref_obj_d = post_process_logical_form.fix_reference_object_with_filters(
self.action_dict["filters"]
)
if not ref_obj_d.get("reference_object"):
import ipdb
ipdb.set_trace()
r = interpret_reference_object(
self, self.speaker_name, ref_obj_d["reference_object"], only_physical=True
)
if len(r) == 0:
raise ErrorWithResponse("I don't know what you're referring to")
mem = r[0]
name = "it"
triples = self.memory.get_triples(subj=mem.memid, pred_text="has_tag")
if len(triples) > 0:
name = triples[0][2].strip("_")
memory_data = self.action_dict["upsert"]["memory_data"]
schematic_memid = (
self.memory.convert_block_object_to_schematic(mem.memid).memid
if isinstance(mem, VoxelObjectNode)
else None
)
for k, v in memory_data.items():
if k.startswith("has_"):
logging.info("Tagging {} {} {}".format(mem.memid, k, v))
self.memory.add_triple(subj=mem.memid, pred_text=k, obj_text=v)
if schematic_memid:
self.memory.add_triple(subj=schematic_memid, pred_text=k, obj_text=v)
point_at_target = mem.get_point_at_target()
self.agent.send_chat("OK I'm tagging this %r as %r " % (name, v))
self.agent.point_at(list(point_at_target))
return "Done!", None
| craftassist-master | python/craftassist/dialogue_objects/put_memory_handler.py |
import random
import Levenshtein
import block_data
import minecraft_specs
from mc_util import IDM
# TODO FILTERS!
def get_block_type(s) -> IDM:
"""string -> (id, meta)
or {"has_x": span} -> (id, meta) """
name_to_bid = minecraft_specs.get_block_data()["name_to_bid"]
if type(s) is str:
s_aug = s + " block"
_, closest_match = min(
[(name, id_meta) for (name, id_meta) in name_to_bid.items() if id_meta[0] < 256],
key=lambda x: min(Levenshtein.distance(x[0], s), Levenshtein.distance(x[0], s_aug)),
)
else:
if "has_colour" in s:
c = block_data.COLOR_BID_MAP.get(s["has_colour"])
if c is not None:
closest_match = random.choice(c)
if "has_block_type" in s:
_, closest_match = min(
[(name, id_meta) for (name, id_meta) in name_to_bid.items() if id_meta[0] < 256],
key=lambda x: min(
Levenshtein.distance(x[0], s), Levenshtein.distance(x[0], s_aug)
),
)
return closest_match
| craftassist-master | python/craftassist/dialogue_objects/block_helpers.py |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import numpy as np
import rotation
import shapes
import heuristic_perception
from mc_util import pos_to_np, to_block_center, to_block_pos, ErrorWithResponse
def post_process_loc(loc, interpreter):
return to_block_pos(loc)
def compute_locations(
interpreter,
speaker,
mems,
steps,
reldir,
repeat_num=1,
repeat_dir=None,
objects=[],
padding=(1, 1, 1),
enable_geoscorer=False,
):
agent = interpreter.agent
repeat_num = max(repeat_num, len(objects))
player_look = agent.perception_modules["low_level"].get_player_struct_by_name(speaker).look
player_pos = pos_to_np(agent.get_player().pos)
origin = compute_location_heuristic(player_look, player_pos, mems, steps, reldir)
if (
enable_geoscorer
and agent.geoscorer is not None
and agent.geoscorer.use(steps, repeat_num, reldir)
):
r = agent.geoscorer.radius
brc = (origin[0] - r, origin[1] - r, origin[2] - r)
tlc = (brc[0] + 2 * r - 1, brc[1] + 2 * r - 1, brc[2] + 2 * r - 1)
context = agent.get_blocks(brc[0], tlc[0], brc[1], tlc[1], brc[2], tlc[2])
segment = objects[0][0]
origin = agent.geoscorer.produce_segment_pos_in_context(segment, context, brc)
offsets = [(0, 0, 0)]
else:
if repeat_num > 1:
schematic = None if len(objects) == 0 else objects[0][0]
offsets = get_repeat_arrangement(
player_look, repeat_num, repeat_dir, mems, schematic, padding
)
else:
offsets = [(0, 0, 0)]
origin = post_process_loc(origin, interpreter)
offsets = [post_process_loc(o, interpreter) for o in offsets]
return origin, offsets
# There will be at least one mem in mems
def compute_location_heuristic(player_look, player_pos, mems, steps, reldir):
loc = mems[0].get_pos()
if reldir is not None:
steps = steps or 5
if reldir == "BETWEEN":
loc = (np.add(mems[0].get_pos(), mems[1].get_pos())) / 2
loc = (loc[0], loc[1], loc[2])
elif reldir == "INSIDE":
for i in range(len(mems)):
mem = mems[i]
locs = heuristic_perception.find_inside(mem)
if len(locs) > 0:
break
if len(locs) == 0:
raise ErrorWithResponse("I don't know how to go inside there")
else:
loc = locs[0]
elif reldir == "AWAY":
dir_vec = (player_pos - loc) / np.linalg.norm(player_pos - loc)
loc = steps * np.array(dir_vec) + to_block_center(loc)
elif reldir == "NEAR":
pass
elif reldir == "AROUND":
pass
else: # LEFT, RIGHT, etc...
reldir_vec = rotation.DIRECTIONS[reldir]
# this should be an inverse transform so we set inverted=True
dir_vec = rotation.transform(reldir_vec, player_look.yaw, 0, inverted=True)
loc = steps * np.array(dir_vec) + to_block_center(loc)
elif steps is not None:
loc = to_block_center(loc) + [0, 0, steps]
return to_block_pos(loc)
def get_repeat_arrangement(
player_look, repeat_num, repeat_dir, ref_mems, schematic=None, padding=(1, 1, 1)
):
shapeparams = {}
# default repeat dir is LEFT
if not repeat_dir:
repeat_dir = "LEFT"
# eventually fix this to allow number based on shape
shapeparams["N"] = repeat_num
if repeat_dir == "AROUND":
# TODO vertical "around"
shapeparams["orient"] = "xy"
shapeparams["extra_space"] = max(padding)
central_object = ref_mems[0]
bounds = central_object.get_bounds()
b = max(bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4])
shapeparams["encircled_object_radius"] = b
offsets = shapes.arrange("circle", schematic, shapeparams)
else:
reldir_vec = rotation.DIRECTIONS[repeat_dir]
# this should be an inverse transform so we set inverted=True
dir_vec = rotation.transform(reldir_vec, player_look.yaw, 0, inverted=True)
max_ind = np.argmax(dir_vec)
shapeparams["extra_space"] = padding[max_ind]
shapeparams["orient"] = dir_vec
offsets = shapes.arrange("line", schematic, shapeparams)
offsets = [tuple(to_block_pos(o)) for o in offsets]
return offsets
| craftassist-master | python/craftassist/dialogue_objects/reference_object_helpers.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.