python_code
stringlengths
0
187k
repo_name
stringlengths
8
46
file_path
stringlengths
6
135
import pytest from allennlp.data.dataset_readers import SequenceTaggingDatasetReader from allennlp.common.util import ensure_list from allennlp.common.testing import AllenNlpTestCase class TestSequenceTaggingDatasetReader: @pytest.mark.parametrize("lazy", (True, False)) def test_default_format(self, lazy): ...
allennlp-master
tests/data/dataset_readers/sequence_tagging_test.py
from typing import Iterable, List from allennlp.data.fields import TextField from allennlp.data.instance import Instance from allennlp.data.dataset_readers import DatasetReader from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data.tokenizers import Token from allennlp.common.testing import A...
allennlp-master
tests/data/dataset_readers/lazy_dataset_reader_test.py
from collections import deque import os import shutil from typing import Optional, NamedTuple, List from filelock import FileLock import pytest import torch.distributed as dist from allennlp.common.testing import AllenNlpTestCase from allennlp.common import util as common_util from allennlp.common.checks import Confi...
allennlp-master
tests/data/dataset_readers/dataset_reader_test.py
allennlp-master
tests/data/dataset_readers/__init__.py
import pytest from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp.data.dataset_readers import BabiReader from allennlp.common.testing import AllenNlpTestCase class TestBAbIReader: @pytest.mark.parametrize( "keep_sentences, lazy", [(False, False), (False, True), (...
allennlp-master
tests/data/dataset_readers/babi_reader_test.py
import pytest from typing import List from allennlp.data.dataset_readers import TextClassificationJsonReader from allennlp.common.util import ensure_list from allennlp.common.testing import AllenNlpTestCase from allennlp.data.tokenizers.sentence_splitter import SpacySentenceSplitter from allennlp.common.util import ge...
allennlp-master
tests/data/dataset_readers/text_classification_json_test.py
import glob import os import tarfile from collections import Counter from typing import Tuple import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data.dataset_readers import ( SequenceTaggingDatasetReader, ShardedDatasetReader, DatasetReader, ) from allennlp.data.instance impo...
allennlp-master
tests/data/dataset_readers/sharded_dataset_reader_test.py
from typing import List import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data.dataset_readers.dataset_utils import span_utils from allennlp.data.tokenizers import Token, SpacyTokenizer class SpanUtilsTest(AllenNlpTestCase): def test_bio_tags_to_spans_extracts_correct_spans(self): ...
allennlp-master
tests/data/dataset_readers/dataset_utils/span_utils_test.py
from allennlp.common.testing import AllenNlpTestCase from allennlp.data.token_indexers.spacy_indexer import SpacyTokenIndexer from allennlp.data.fields.text_field import TextField from allennlp.common.util import get_spacy_model from allennlp.data.vocabulary import Vocabulary class TestSpacyTokenIndexer(AllenNlpTestC...
allennlp-master
tests/data/token_indexers/spacy_indexer_test.py
allennlp-master
tests/data/token_indexers/__init__.py
import numpy as np import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary, Instance from allennlp.data.batch import Batch from allennlp.data.token_indexers import ELMoTokenCharactersIndexer from allennlp.data.fields import ListField, TextField class TestELMoTok...
allennlp-master
tests/data/token_indexers/elmo_indexer_test.py
from allennlp.common import cached_transformers from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary from allennlp.data.token_indexers import PretrainedTransformerMismatchedIndexer class TestPretrainedTransformerMismatchedIndexer(AllenNlpTestCase): def test_bert(self): ...
allennlp-master
tests/data/token_indexers/pretrained_transformer_mismatched_indexer_test.py
from collections import defaultdict import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary from allennlp.data.token_indexers import TokenCharactersIndexer from allennlp.data.tokenizers.character_tokenizer import CharacterTokenizer class CharacterTokenIndexerTe...
allennlp-master
tests/data/token_indexers/character_token_indexer_test.py
from collections import defaultdict from dataclasses import dataclass import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data.tokenizers import SpacyTokenizer @dataclass(init=False...
allennlp-master
tests/data/token_indexers/single_id_token_indexer_test.py
import pytest from allennlp.common import cached_transformers from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Vocabulary from allennlp.data.token_indexers import PretrainedTransformerIndexer from allennlp.data.tokenizers import PretrainedTransformerTokenizer class TestPretrainedTransfo...
allennlp-master
tests/data/token_indexers/pretrained_transformer_indexer_test.py
from allennlp.common import Params from allennlp.data import Instance, Token from allennlp.data.batch import Batch from allennlp.data.fields import TextField from allennlp.data.samplers import MaxTokensBatchSampler from allennlp.data.dataset_readers.dataset_reader import AllennlpDataset from allennlp.data.dataloader im...
allennlp-master
tests/data/samplers/max_tokens_batch_sampler_test.py
allennlp-master
tests/data/samplers/__init__.py
from typing import List, Iterable, Dict, Union from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Vocabulary, Instance, Token, Batch from allennlp.data.fields import TextField from allennlp.data.token_indexers import SingleIdTokenIndexer class LazyIterable: def __init__(self, instance...
allennlp-master
tests/data/samplers/sampler_test.py
from allennlp.common import Params from allennlp.data import Instance, Token from allennlp.data.batch import Batch from allennlp.data.fields import TextField from allennlp.data.samplers import BucketBatchSampler from allennlp.data.dataset_readers.dataset_reader import AllennlpDataset from allennlp.data.dataloader impor...
allennlp-master
tests/data/samplers/bucket_batch_sampler_test.py
import numpy import pytest from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token from allennlp.data.fields import TextField, IndexField from allennlp.data.token_indexers import SingleIdTokenIndexer class TestIndexField(AllenNlpTestC...
allennlp-master
tests/data/fields/index_field_test.py
import numpy import torch from allennlp.common.testing.test_case import AllenNlpTestCase from allennlp.data.fields import ArrayField, ListField class TestArrayField(AllenNlpTestCase): def test_get_padding_lengths_correctly_returns_ordered_shape(self): shape = [3, 4, 5, 6] array = numpy.zeros(shap...
allennlp-master
tests/data/fields/array_field_test.py
from typing import Dict import numpy import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary, Instance from allennlp.data.fields import TextField, LabelField, ListField, IndexField, SequenceLabelField from allennlp.data.token_indexers import SingleIdTokenIndexer, ...
allennlp-master
tests/data/fields/list_field_test.py
from collections import defaultdict from typing import Dict, List import numpy import pytest from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary from allennlp.data.fields import TextField from allennlp.data.token_indexe...
allennlp-master
tests/data/fields/text_field_test.py
allennlp-master
tests/data/fields/__init__.py
import logging import numpy import pytest from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data.fields import MultiLabelField from allennlp.data.vocabulary import Vocabulary class TestMultiLabelField(AllenNlpTestCase): def test_as_tensor_re...
allennlp-master
tests/data/fields/multilabel_field_test.py
import logging import pytest from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data.fields import LabelField from allennlp.data import Vocabulary class TestLabelField(AllenNlpTestCase): def test_as_tensor_returns_integer_tensor(self): ...
allennlp-master
tests/data/fields/label_field_test.py
import pytest import numpy from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data.fields import AdjacencyField, TextField from allennlp.data.token_indexers import SingleIdTokenIndexer from allennlp.data import Vocabulary, Token class TestAdjacency...
allennlp-master
tests/data/fields/adjacency_field_test.py
import numpy import pytest from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token from allennlp.data.fields import TextField, SpanField from allennlp.data.token_indexers import SingleIdTokenIndexer class TestSpanField(AllenNlpTestCase): def setup_method(self): super().setup_...
allennlp-master
tests/data/fields/span_field_test.py
from allennlp.data.fields import Field def test_eq_with_inheritance(): class SubField(Field): __slots__ = ["a"] def __init__(self, a): self.a = a class SubSubField(SubField): __slots__ = ["b"] def __init__(self, a, b): super().__init__(a) ...
allennlp-master
tests/data/fields/field_test.py
from collections import defaultdict import logging import pytest import numpy from allennlp.common.checks import ConfigurationError from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Token, Vocabulary from allennlp.data.fields import TextField, SequenceLabelField from allennlp.data.token_i...
allennlp-master
tests/data/fields/sequence_label_field_test.py
import pytest from allennlp.common.testing.test_case import AllenNlpTestCase from allennlp.data.fields import MetadataField class TestMetadataField(AllenNlpTestCase): def test_mapping_works_with_dict(self): field = MetadataField({"a": 1, "b": [0]}) assert "a" in field assert field["a"] =...
allennlp-master
tests/data/fields/metadata_field_test.py
import pytest from allennlp.common.testing.test_case import AllenNlpTestCase from allennlp.data.fields import FlagField class TestFlagField(AllenNlpTestCase): def test_get_padding_lengths_returns_nothing(self): flag_field = FlagField(True) assert flag_field.get_padding_lengths() == {} def te...
allennlp-master
tests/data/fields/flag_field_test.py
allennlp-master
benchmarks/__init__.py
import torch from allennlp.nn import util from allennlp.common.testing import requires_gpu @requires_gpu def bench_add_sentence_boundary_token_ids(benchmark): device = torch.device("cuda") # shape: (32, 50) tensor = torch.tensor([[3] * 50] * 32, device=device) # shape: (32, 50) mask = torch.tenso...
allennlp-master
benchmarks/nn/util_bench.py
allennlp-master
benchmarks/data/__init__.py
allennlp-master
benchmarks/data/tokenizers/__init__.py
from allennlp.data.tokenizers import CharacterTokenizer tokenizer = CharacterTokenizer() passage = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut...
allennlp-master
benchmarks/data/tokenizers/character_tokenizer_bench.py
# encoding: utf-8 """ Prepares markdown release notes for GitHub releases. """ import os from typing import List from allennlp.version import VERSION TAG = os.environ["TAG"] ADDED_HEADER = "### Added 🎉" CHANGED_HEADER = "### Changed ⚠️" FIXED_HEADER = "### Fixed ✅" REMOVED_HEADER = "### Removed 👋" def get_cha...
allennlp-master
scripts/release_notes.py
#!/usr/bin/env python """ This script is used to populate the table of contents for the API in the mkdocs config file. """ import argparse from pathlib import Path from typing import Any, List from ruamel.yaml import YAML from allennlp.version import VERSION API_TOC_KEY = "API" def parse_args(): parser = ar...
allennlp-master
scripts/build_docs_config.py
#!/usr/bin/env python import glob import logging import os import re import shutil import sys import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) from allennlp.commands.test_install import _get_module_root from allennlp.commands.train import train_model_from_file, t...
allennlp-master
scripts/train_fixtures.py
#!/usr/bin/env python # encoding: UTF-8 """ Goes through all the inline-links in markdown files and reports the breakages. """ import re import sys import pathlib import os from multiprocessing.dummy import Pool from typing import Tuple, NamedTuple, Optional import requests OK_STATUS_CODES = ( 200, 401, #...
allennlp-master
scripts/check_links.py
from datetime import datetime as dt import os from github import Github def main(): g = Github(os.environ["GITHUB_TOKEN"]) repo = g.get_repo("allenai/allennlp") open_issues = repo.get_issues(state="open") for issue in open_issues: if ( issue.milestone is None and issu...
allennlp-master
scripts/ping_issue_assignees.py
#!/usr/bin/env python import argparse from typing import Dict import requests def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("version_type", choices=["stable", "latest", "current"]) return parser.parse_args() def get_current_version() -> str: VERSION: Dict[str, str] = {} ...
allennlp-master
scripts/get_version.py
from datetime import datetime as dt import os from github import Github LABELS_TO_EXEMPT = ["contributions welcome", "merge when ready", "under development", "help wanted"] def main(): g = Github(os.environ["GITHUB_TOKEN"]) repo = g.get_repo("allenai/allennlp") open_issues = repo.get_issues(state="open...
allennlp-master
scripts/close_stale_issues.py
#!/usr/bin/env python """ Turn docstrings from a single module into a markdown file. We do this with PydocMarkdown, using custom processors and renderers defined here. """ import argparse from collections import OrderedDict from dataclasses import dataclass from enum import Enum import logging from multiprocessing i...
allennlp-master
scripts/py2md.py
from typing import Optional import pytest from allennlp.common.testing import AllenNlpTestCase from scripts.py2md import py2md, Param, DocstringError class TestPy2md(AllenNlpTestCase): def test_basic_example(self, capsys): py2md("scripts.tests.py2md.basic_example") captured = capsys.readouterr()...
allennlp-master
scripts/tests/py2md/py2md_test.py
""" This is a docstring. And this is a multi-line line: [http://example.com] (https://example.com/blah/blah/blah.html). """ from dataclasses import dataclass SOME_GLOBAL_VAR = "Ahhhh I'm a global var!!" """ This is a global var. """ def func_with_no_args(): """ This function has no args. """ return...
allennlp-master
scripts/tests/py2md/basic_example.py
import pytest import sqlite3 from unittest.mock import call, Mock from allennlp.common.testing import AllenNlpTestCase from scripts.ai2_internal.resume_daemon import ( BeakerStatus, create_table, handler, logger, resume, start_autoresume, ) # Don't spam the log in tests. logger.removeHandler(...
allennlp-master
scripts/tests/ai2_internal/resume_daemon_test.py
#! /usr/bin/env python3 # Tool to automatically resume preemptible beaker experiments created with run_with_beaker.py. # # Examples # -------- # # Ensure an experiment will be resumed: # resume_daemon.py --action=start --experiment-id=$YOUR_EXPERIMENT_ID # # Stop resuming an experiment: # resume_daemon.py --action=sto...
allennlp-master
scripts/ai2_internal/resume_daemon.py
#! /usr/bin/env python # Script to launch AllenNLP Beaker jobs. import argparse import os import json import random import tempfile import subprocess import sys # This has to happen before we import spacy (even indirectly), because for some crazy reason spacy # thought it was a good idea to set the random seed on im...
allennlp-master
scripts/ai2_internal/run_with_beaker.py
from setuptools import setup, find_packages import sys import os # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Release ...
allennlp-hub-master
setup.py
import pytest import spacy from allennlp.common.testing import AllenNlpTestCase from allennlp_hub import pretrained class AllenNlpSemparsePretrainedTest(AllenNlpTestCase): def test_wikitables_parser(self): predictor = pretrained.wikitables_parser_dasigi_2019() table = """# Event Year Season Flag ...
allennlp-hub-master
tests/pretrained/allennlp_semparse_pretrained_test.py
import pytest import spacy from allennlp.common.testing import AllenNlpTestCase from allennlp_hub import pretrained class AllenNlpPretrainedTest(AllenNlpTestCase): def test_machine_comprehension(self): predictor = pretrained.bidirectional_attention_flow_seo_2017() passage = """The Matrix is a 19...
allennlp-hub-master
tests/pretrained/allennlp_pretrained_test.py
_MAJOR = "0" _MINOR = "0" _REVISION = "1-unreleased" VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR) VERSION = "{0}.{1}.{2}".format(_MAJOR, _MINOR, _REVISION)
allennlp-hub-master
allennlp_hub/version.py
allennlp-hub-master
allennlp_hub/__init__.py
from allennlp_hub.pretrained.helpers import _load_predictor from allennlp_semparse import predictors as semparse_predictors import allennlp_semparse.models import allennlp_semparse.dataset_readers # AllenNLP Semparse models def wikitables_parser_dasigi_2019() -> semparse_predictors.WikiTablesParserPredictor: pre...
allennlp-hub-master
allennlp_hub/pretrained/allennlp_semparse_pretrained.py
from allennlp_hub.pretrained.allennlp_pretrained import * from allennlp_hub.pretrained.allennlp_semparse_pretrained import *
allennlp-hub-master
allennlp_hub/pretrained/__init__.py
from allennlp import predictors from allennlp_rc import predictors as rc_predictors from allennlp_hub.pretrained.helpers import _load_predictor import allennlp.models # Models in the main repo def srl_with_elmo_luheng_2018() -> predictors.SemanticRoleLabelerPredictor: """ Semantic Role Labeling Based o...
allennlp-hub-master
allennlp_hub/pretrained/allennlp_pretrained.py
from allennlp.predictors import Predictor from allennlp.models.archival import load_archive def _load_predictor(archive_file: str, predictor_name: str) -> Predictor: """ Helper to load the desired predictor from the given archive. """ archive = load_archive(archive_file) return Predictor.from_arch...
allennlp-hub-master
allennlp_hub/pretrained/helpers.py
import ai2thor.controller import ai2thor.robot_controller import random import time import numpy as np from pprint import pprint fps = ["FloorPlan311"] runs = [ {"id": "unity", "port": 8200, "controller": ai2thor.controller.Controller()}, {"id": "robot", "port": 9200, "controller": ai2thor.robot_controller.Co...
ai2thor-main
test_controllers.py
import os import signal import sys if os.name != "nt": import fcntl import datetime import json import re import time import zipfile import threading import hashlib import shutil import subprocess import pprint import random from typing import Dict from invoke import task import boto3 import botocore.exceptions i...
ai2thor-main
tasks.py
from setuptools import setup, find_packages import os __version__ = "0.0.1" if os.path.isfile("ai2thor/_version.py"): exec(open("ai2thor/_version.py").read()) this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f: long_descript...
ai2thor-main
setup.py
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth import os import requests import json from ai2thor.util import makedirs import ai2thor.downloader import zipfile import logging from ai2thor.util.lock import LockSh, LockEx from ai2thor.util import atomic_write import io from ai2thor.platform import STR_PLATF...
ai2thor-main
ai2thor/build.py
# Copyright Allen Institute for Artificial Intelligence 2017 """ ai2thor.server Handles all communication with Unity through a Flask service. Messages are sent to the controller using a pair of request/response queues. """ import json import subprocess import warnings from abc import abstractmethod, ABC from collecti...
ai2thor-main
ai2thor/server.py
from flask import Flask, request, make_response import numpy as np import random import msgpack import werkzeug import werkzeug.serving import werkzeug.http def random_image(height, width): img = np.zeros(height * width * 3, dtype=np.uint8).reshape(height, width, 3) img[:, :, 0] = random.randint(0, 255) i...
ai2thor-main
ai2thor/mock_real_server.py
# Copyright Allen Institute for Artificial Intelligence 2017 """ ai2thor.controller Primary entrypoint into the Thor API. Provides all the high-level functions needed to control the in-game agent through ai2thor.server. """ import atexit import copy import json import logging import math import numbers import os impo...
ai2thor-main
ai2thor/controller.py
# Copyright Allen Institute for Artificial Intelligence 2017 import requests from progressbar import ProgressBar, Bar, Percentage, FileTransferSpeed import hashlib import logging import ai2thor.build logger = logging.getLogger(__name__) def download(url, sha256_digest, include_private_scenes=False): auth = None...
ai2thor-main
ai2thor/downloader.py
import os import msgpack import numpy as np import requests import cv2 import warnings from pprint import pprint import shutil import copy from ai2thor.server import Event, MultiAgentEvent, DepthFormat from ai2thor.interact import InteractiveControllerPrompt, DefaultActions class Controller(object): def __init__...
ai2thor-main
ai2thor/robot_controller.py
# Copyright Allen Institute for Artificial Intelligence 2017 __version__ = None try: from ai2thor._version import __version__ except ImportError: pass
ai2thor-main
ai2thor/__init__.py
import subprocess import os.path import re import tempfile from ai2thor.build import COMMIT_ID import shlex import shutil def pci_records(): records = [] command = shlex.split("lspci -vmm") output = subprocess.check_output(command).decode() for devices in output.strip().split("\n\n"): record ...
ai2thor-main
ai2thor/docker.py
import Xlib.display import glob import warnings import os import ctypes.util import xml.etree.ElementTree class Request: def __init__(self, system, width, height, x_display, headless): self.system = system self.width = width self.height = height self.x_display = x_display s...
ai2thor-main
ai2thor/platform.py
ai2thor-main
ai2thor/camera.py
class UnityCrashException(Exception): pass class RestartError(RuntimeError): pass
ai2thor-main
ai2thor/exceptions.py
import copy import glob import shutil import json import pickle import ai2thor.controller from collections import defaultdict import os MOVE_AHEAD_MAP = { 0: dict(x=0, z=1), 90: dict(x=1, z=0), 180: dict(x=0, z=-1), 270: dict(x=-1, z=0), } class Controller(object): def __init__(self, base_dir, g...
ai2thor-main
ai2thor/offline_controller.py
# GENERATED FILE - DO NOT EDIT DEFAULT_QUALITY = 'Ultra' QUALITY_SETTINGS = {'DONOTUSE': 0, 'High': 5, 'High WebGL': 8, 'Low': 2, 'Medium': 3, 'MediumCloseFitShadows': 4, 'Ultra': 7, 'Very High': 6, 'Very Low': 1}
ai2thor-main
ai2thor/_quality_settings.py
# Copyright Allen Institute for Artificial Intelligence 2017 """ ai2thor.server Handles all communication with Unity through a Flask service. Messages are sent to the controller using a pair of request/response queues. """ import json import os import select import struct import tempfile import time from collections ...
ai2thor-main
ai2thor/fifo_server.py
# Copyright Allen Institute for Artificial Intelligence 2017 """ ai2thor.server Handles all communication with Unity through a Flask service. Messages are sent to the controller using a pair of request/response queues. """ import json import logging import math import os import threading from typing import Optional ...
ai2thor-main
ai2thor/wsgi_server.py
import sys import numpy as np import os from enum import Enum import json class DefaultActions(Enum): MoveRight = (0,) MoveLeft = (1,) MoveAhead = (2,) MoveBack = (3,) LookUp = (4,) LookDown = (5,) RotateRight = (8,) RotateLeft = 9 # TODO tie this with actions # class ObjectActions(...
ai2thor-main
ai2thor/interact.py
""" A video controller for ai2thor Basic example: from ai2thor.controller import VideoController with VideoController() as vc: vc.play(vc.MoveAhead()) vc.wait(5) vc.play(vc.MoveAhead()) vc.export_video('thor.mp4') Known issues: - Multi agent rotations don't work (since TeleportFull breaks when passing i...
ai2thor-main
ai2thor/video_controller.py
from abc import abstractmethod, ABC from collections import defaultdict from functools import reduce from operator import itemgetter import ai2thor.controller import copy import functools import inspect import itertools import json import logging import numpy as np import operator import os import platform import rando...
ai2thor-main
ai2thor/benchmarking.py
import json import math import copy def vector_distance(v0, v1): dx = v0["x"] - v1["x"] dy = v0["y"] - v1["y"] dz = v0["z"] - v1["z"] return math.sqrt(dx * dx + dy * dy + dz * dz) def path_distance(path): distance = 0 for i in range(0, len(path) - 1): distance += vector_distance(path...
ai2thor-main
ai2thor/util/metrics.py
import numpy as np REAL_2_SIM_TRANSFORM = np.array( [[1.00854301, -0.0111386, 0.51920809], [0.00316833, 0.97336625, -1.15532594]] ) def transform_real_2_sim(real_position): """ Transforms a position from the 'real' coordinate system to the 'sim' coordinate system. :param real_position: dictionary wit...
ai2thor-main
ai2thor/util/transforms.py
import numpy as np import math class TrialMetric(object): def init_trials(self, num_trials, metadata): ... def update_with_trial(self, trial_index, metadata): ... class ObjectPositionVarianceAverage(TrialMetric): """ Metric that computes the average of the variance of all objects in...
ai2thor-main
ai2thor/util/trials.py
import re def scene_names_key_func(scene_name): """ Key function for sorting scenes with the naming convention that was used """ m = re.search("FloorPlan[_]?([a-zA-Z\-]*)([0-9]+)_?([0-9]+)?.*$", scene_name) last_val = m.group(3) if m.group(3) is not None else -1 return m.group(1), int(m.group(...
ai2thor-main
ai2thor/util/scene_utils.py
from pprint import pprint from unityparser import UnityDocument # Requires unity parser, run: # pip install unityparser def updateNavMeshParamsForScene(scene_file_name): pprint("Updating file '{}'...".format(scene_file_name)) doc = UnityDocument.load_yaml(scene_file_name) for entry in doc.entries: ...
ai2thor-main
ai2thor/util/scene_yaml_edit.py
import os import random import time def makedirs(directory): os.makedirs(directory, exist_ok=True) def atomic_write(path, data): tmp_path = "-".join([path, str(time.time()), str(random.random())]) mode = "w" if type(data) is bytes: mode = "wb" with open(tmp_path, mode) as f: f....
ai2thor-main
ai2thor/util/__init__.py
import os import numpy as np dir_path = os.path.dirname(os.path.realpath(__file__)) def generate_noise_indices(img_size): img_size = int(img_size) default_size = 300 corners = np.load(os.path.join(dir_path, "depth_noise.npy"), allow_pickle=True) indices = [] for j, corner in enumerate(corners): ...
ai2thor-main
ai2thor/util/depth.py
import os from platform import system if system() == "Windows": class fcntl: LOCK_UN = 0 LOCK_SH = 0 LOCK_NB = 0 LOCK_EX = 0 @staticmethod def fcntl(fd, op, arg=0): return 0 @staticmethod def ioctl(fd, op, arg=0, mutable_flag=True): ...
ai2thor-main
ai2thor/util/lock.py
import os from pathlib import Path TEST_SCENE = "FloorPlan28_physics" TESTS_DIR = os.path.abspath(os.path.dirname(Path(__file__))) TESTS_DATA_DIR = os.path.join(TESTS_DIR, "data")
ai2thor-main
ai2thor/tests/constants.py
ai2thor-main
ai2thor/tests/__init__.py
import ai2thor.fifo_server import pytest import numpy as np import msgpack from ai2thor.tests.test_event import metadata_simple from ai2thor.tests.fifo_client import FifoClient from io import BytesIO import copy def test_multi_agent_train(): s = ai2thor.fifo_server.FifoServer(width=300, height=300) s.send(di...
ai2thor-main
ai2thor/tests/test_fifo_server.py
import ai2thor.fifo_server import struct import json class FifoClient: def __init__(self, server_pipe_path, client_pipe_path): self.server_pipe = None self.client_pipe = None self.server_pipe_path = server_pipe_path self.client_pipe_path = client_pipe_path def send(self, field...
ai2thor-main
ai2thor/tests/fifo_client.py
import os from ai2thor.server import Event, DepthFormat import warnings import json import numpy as np import pytest from ai2thor.tests.constants import TESTS_DATA_DIR, TEST_SCENE metadata_complex = { "agent": { "bounds3D": [], "cameraHorizon": 0.0, "distance": 0.0, "isopen": Fals...
ai2thor-main
ai2thor/tests/test_event.py
import ai2thor.wsgi_server import pytest import numpy as np import json from ai2thor.wsgi_server import Queue from ai2thor.tests.test_event import metadata_simple from io import BytesIO import copy def generate_multi_agent_form(metadata, sequence_id=1): agent2 = copy.deepcopy(metadata) agent2["agentId"] = 1 ...
ai2thor-main
ai2thor/tests/test_server.py
# import pytest import copy import glob import json import os import random import re import string import time import shutil import warnings import jsonschema import numpy as np import pytest from PIL import ImageChops, ImageFilter, Image from ai2thor.controller import Controller from ai2thor.build import TEST_OUTPU...
ai2thor-main
ai2thor/tests/test_unity.py
# import pytest import json import os import cv2 import numpy as np import pytest from ai2thor.fifo_server import FifoServer from ai2thor.wsgi_server import WsgiServer from .test_unity import build_controller, depth_images_near, images_near DATA_PATH = "ai2thor/tests/data/" IMAGE_FOLDER_PATH = os.path.join(DATA_PAT...
ai2thor-main
ai2thor/tests/test_unity_procedural.py
import ai2thor.controller from ai2thor.server import Event from ai2thor.platform import CloudRendering, Linux64 import pytest import numpy as np import warnings import os import math def fake_linux64_exists(self): if self.platform.name() == "Linux64": return True else: return False @classmet...
ai2thor-main
ai2thor/tests/test_controller.py
import datetime import json import pdb import os import sys root_dir = os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/..") sys.path.insert(0, root_dir) import ai2thor.controller import math import ai2thor import random import copy MAX_TESTS = 20 MAX_EP_LEN = 100 scene_names = ["FloorPlan{}_physics"....
ai2thor-main
arm_test/check_determinism_event_collision_different_machines.py
import datetime import json import pdb import math import os import sys root_dir = os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/..") sys.path.insert(0, root_dir) import ai2thor.controller import ai2thor import random import copy MAX_TESTS = 20 MAX_EP_LEN = 100 scene_names = ["FloorPlan{}_physics"....
ai2thor-main
arm_test/check_determinism_different_machines.py
import os import sys root_dir = os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/..") sys.path.insert(0, root_dir) import ai2thor.controller c = ai2thor.controller.Controller( scene="FloorPlan1_physics", gridSize=0.25, width=900, height=900, agentMode="arm", fieldOfView=100, ...
ai2thor-main
arm_test/arm_counter_30fps_fixed_update.py